Make SimplMonad warning-free
[ghc-hetmet.git] / compiler / simplCore / SimplMonad.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[SimplMonad]{The simplifier Monad}
5
6 \begin{code}
7 module SimplMonad (
8         -- The monad
9         SimplM,
10         initSmpl,
11         getDOptsSmpl, getRules, getFamEnvs,
12
13         -- Unique supply
14         MonadUnique(..), newId,
15
16         -- Counting
17         SimplCount, Tick(..),
18         tick, freeTick,
19         getSimplCount, zeroSimplCount, pprSimplCount, 
20         plusSimplCount, isZeroSimplCount,
21
22         -- Switch checker
23         SwitchChecker, SwitchResult(..), getSimplIntSwitch,
24         isAmongSimpl, intSwitchSet, switchIsOn
25     ) where
26
27 import Id               ( Id, mkSysLocal )
28 import Type             ( Type )
29 import FamInstEnv       ( FamInstEnv )
30 import Rules            ( RuleBase )
31 import UniqSupply
32 import DynFlags         ( SimplifierSwitch(..), DynFlags, DynFlag(..), dopt )
33 import StaticFlags      ( opt_PprStyle_Debug, opt_HistorySize )
34 import Maybes           ( expectJust )
35 import FiniteMap        ( FiniteMap, emptyFM, isEmptyFM, lookupFM, addToFM, plusFM_C, fmToList )
36 import FastString
37 import Outputable
38 import FastTypes
39
40 import Data.Array
41 import Data.Array.Base (unsafeAt)
42 \end{code}
43
44 %************************************************************************
45 %*                                                                      *
46 \subsection{Monad plumbing}
47 %*                                                                      *
48 %************************************************************************
49
50 For the simplifier monad, we want to {\em thread} a unique supply and a counter.
51 (Command-line switches move around through the explicitly-passed SimplEnv.)
52
53 \begin{code}
54 newtype SimplM result
55   =  SM  { unSM :: SimplTopEnv  -- Envt that does not change much
56                 -> UniqSupply   -- We thread the unique supply because
57                                 -- constantly splitting it is rather expensive
58                 -> SimplCount 
59                 -> (result, UniqSupply, SimplCount)}
60
61 data SimplTopEnv = STE  { st_flags :: DynFlags 
62                         , st_rules :: RuleBase
63                         , st_fams  :: (FamInstEnv, FamInstEnv) }
64 \end{code}
65
66 \begin{code}
67 initSmpl :: DynFlags -> RuleBase -> (FamInstEnv, FamInstEnv) 
68          -> UniqSupply          -- No init count; set to 0
69          -> SimplM a
70          -> (a, SimplCount)
71
72 initSmpl dflags rules fam_envs us m
73   = case unSM m env us (zeroSimplCount dflags) of 
74         (result, _, count) -> (result, count)
75   where
76     env = STE { st_flags = dflags, st_rules = rules, st_fams = fam_envs }
77
78 {-# INLINE thenSmpl #-}
79 {-# INLINE thenSmpl_ #-}
80 {-# INLINE returnSmpl #-}
81
82 instance Monad SimplM where
83    (>>)   = thenSmpl_
84    (>>=)  = thenSmpl
85    return = returnSmpl
86
87 returnSmpl :: a -> SimplM a
88 returnSmpl e = SM (\_st_env us sc -> (e, us, sc))
89
90 thenSmpl  :: SimplM a -> (a -> SimplM b) -> SimplM b
91 thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
92
93 thenSmpl m k 
94   = SM (\ st_env us0 sc0 ->
95           case (unSM m st_env us0 sc0) of 
96                 (m_result, us1, sc1) -> unSM (k m_result) st_env us1 sc1 )
97
98 thenSmpl_ m k 
99   = SM (\st_env us0 sc0 ->
100          case (unSM m st_env us0 sc0) of 
101                 (_, us1, sc1) -> unSM k st_env us1 sc1)
102
103 -- TODO: this specializing is not allowed
104 {-# -- SPECIALIZE mapM         :: (a -> SimplM b) -> [a] -> SimplM [b] #-}
105 {-# -- SPECIALIZE mapAndUnzipM :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c]) #-}
106 {-# -- SPECIALIZE mapAccumLM   :: (acc -> b -> SimplM (acc,c)) -> acc -> [b] -> SimplM (acc, [c]) #-}
107 \end{code}
108
109
110 %************************************************************************
111 %*                                                                      *
112 \subsection{The unique supply}
113 %*                                                                      *
114 %************************************************************************
115
116 \begin{code}
117 instance MonadUnique SimplM where
118     getUniqueSupplyM
119        = SM (\_st_env us sc -> case splitUniqSupply us of
120                                 (us1, us2) -> (us1, us2, sc))
121
122     getUniqueM
123        = SM (\_st_env us sc -> case splitUniqSupply us of
124                                 (us1, us2) -> (uniqFromSupply us1, us2, sc))
125
126     getUniquesM
127         = SM (\_st_env us sc -> case splitUniqSupply us of
128                                 (us1, us2) -> (uniqsFromSupply us1, us2, sc))
129
130 getDOptsSmpl :: SimplM DynFlags
131 getDOptsSmpl = SM (\st_env us sc -> (st_flags st_env, us, sc))
132
133 getRules :: SimplM RuleBase
134 getRules = SM (\st_env us sc -> (st_rules st_env, us, sc))
135
136 getFamEnvs :: SimplM (FamInstEnv, FamInstEnv)
137 getFamEnvs = SM (\st_env us sc -> (st_fams st_env, us, sc))
138
139 newId :: FastString -> Type -> SimplM Id
140 newId fs ty = do uniq <- getUniqueM
141                  return (mkSysLocal fs uniq ty)
142 \end{code}
143
144
145 %************************************************************************
146 %*                                                                      *
147 \subsection{Counting up what we've done}
148 %*                                                                      *
149 %************************************************************************
150
151 \begin{code}
152 getSimplCount :: SimplM SimplCount
153 getSimplCount = SM (\_st_env us sc -> (sc, us, sc))
154
155 tick :: Tick -> SimplM ()
156 tick t 
157    = SM (\_st_env us sc -> let sc' = doTick t sc 
158                            in sc' `seq` ((), us, sc'))
159
160 freeTick :: Tick -> SimplM ()
161 -- Record a tick, but don't add to the total tick count, which is
162 -- used to decide when nothing further has happened
163 freeTick t 
164    = SM (\_st_env us sc -> let sc' = doFreeTick t sc
165                            in sc' `seq` ((), us, sc'))
166 \end{code}
167
168 \begin{code}
169 verboseSimplStats :: Bool
170 verboseSimplStats = opt_PprStyle_Debug          -- For now, anyway
171
172 zeroSimplCount     :: DynFlags -> SimplCount
173 isZeroSimplCount   :: SimplCount -> Bool
174 pprSimplCount      :: SimplCount -> SDoc
175 doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
176 plusSimplCount     :: SimplCount -> SimplCount -> SimplCount
177 \end{code}
178
179 \begin{code}
180 data SimplCount = VerySimplZero         -- These two are used when 
181                 | VerySimplNonZero      -- we are only interested in 
182                                         -- termination info
183
184                 | SimplCount    {
185                         ticks   :: !Int,                -- Total ticks
186                         details :: !TickCounts,         -- How many of each type
187                         n_log   :: !Int,                -- N
188                         log1    :: [Tick],              -- Last N events; <= opt_HistorySize
189                         log2    :: [Tick]               -- Last opt_HistorySize events before that
190                   }
191
192 type TickCounts = FiniteMap Tick Int
193
194 zeroSimplCount dflags
195                 -- This is where we decide whether to do
196                 -- the VerySimpl version or the full-stats version
197   | dopt Opt_D_dump_simpl_stats dflags
198   = SimplCount {ticks = 0, details = emptyFM,
199                 n_log = 0, log1 = [], log2 = []}
200   | otherwise
201   = VerySimplZero
202
203 isZeroSimplCount VerySimplZero              = True
204 isZeroSimplCount (SimplCount { ticks = 0 }) = True
205 isZeroSimplCount _                          = False
206
207 doFreeTick tick sc@SimplCount { details = dts } 
208   = dts' `seqFM` sc { details = dts' }
209   where
210     dts' = dts `addTick` tick 
211 doFreeTick _ sc = sc 
212
213 -- Gross hack to persuade GHC 3.03 to do this important seq
214 seqFM :: FiniteMap key elt -> t -> t
215 seqFM fm x | isEmptyFM fm = x
216            | otherwise    = x
217
218 doTick tick sc@SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1 }
219   | nl >= opt_HistorySize = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
220   | otherwise             = sc1 { n_log = nl+1, log1 = tick : l1 }
221   where
222     sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
223
224 doTick _ _ = VerySimplNonZero -- The very simple case
225
226
227 -- Don't use plusFM_C because that's lazy, and we want to 
228 -- be pretty strict here!
229 addTick :: TickCounts -> Tick -> TickCounts
230 addTick fm tick = case lookupFM fm tick of
231                         Nothing -> addToFM fm tick 1
232                         Just n  -> n1 `seq` addToFM fm tick n1
233                                 where
234                                    n1 = n+1
235
236
237 plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
238                sc2@(SimplCount { ticks = tks2, details = dts2 })
239   = log_base { ticks = tks1 + tks2, details = plusFM_C (+) dts1 dts2 }
240   where
241         -- A hackish way of getting recent log info
242     log_base | null (log1 sc2) = sc1    -- Nothing at all in sc2
243              | null (log2 sc2) = sc2 { log2 = log1 sc1 }
244              | otherwise       = sc2
245
246 plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
247 plusSimplCount _             _             = VerySimplNonZero
248
249 pprSimplCount VerySimplZero    = ptext (sLit "Total ticks: ZERO!")
250 pprSimplCount VerySimplNonZero = ptext (sLit "Total ticks: NON-ZERO!")
251 pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
252   = vcat [ptext (sLit "Total ticks:    ") <+> int tks,
253           text "",
254           pprTickCounts (fmToList dts),
255           if verboseSimplStats then
256                 vcat [text "",
257                       ptext (sLit "Log (most recent first)"),
258                       nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
259           else empty
260     ]
261
262 pprTickCounts :: [(Tick,Int)] -> SDoc
263 pprTickCounts [] = empty
264 pprTickCounts ((tick1,n1):ticks)
265   = vcat [int tot_n <+> text (tickString tick1),
266           pprTCDetails real_these,
267           pprTickCounts others
268     ]
269   where
270     tick1_tag           = tickToTag tick1
271     (these, others)     = span same_tick ticks
272     real_these          = (tick1,n1):these
273     same_tick (tick2,_) = tickToTag tick2 == tick1_tag
274     tot_n               = sum [n | (_,n) <- real_these]
275
276 pprTCDetails :: [(Tick, Int)] -> SDoc
277 pprTCDetails ticks@((tick,_):_)
278   | verboseSimplStats || isRuleFired tick
279   = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
280   | otherwise
281   = empty
282 pprTCDetails [] = panic "pprTCDetails []"
283 \end{code}
284
285 %************************************************************************
286 %*                                                                      *
287 \subsection{Ticks}
288 %*                                                                      *
289 %************************************************************************
290
291 \begin{code}
292 data Tick
293   = PreInlineUnconditionally    Id
294   | PostInlineUnconditionally   Id
295
296   | UnfoldingDone               Id
297   | RuleFired                   FastString      -- Rule name
298
299   | LetFloatFromLet
300   | EtaExpansion                Id      -- LHS binder
301   | EtaReduction                Id      -- Binder on outer lambda
302   | BetaReduction               Id      -- Lambda binder
303
304
305   | CaseOfCase                  Id      -- Bndr on *inner* case
306   | KnownBranch                 Id      -- Case binder
307   | CaseMerge                   Id      -- Binder on outer case
308   | AltMerge                    Id      -- Case binder
309   | CaseElim                    Id      -- Case binder
310   | CaseIdentity                Id      -- Case binder
311   | FillInCaseDefault           Id      -- Case binder
312
313   | BottomFound         
314   | SimplifierDone              -- Ticked at each iteration of the simplifier
315
316 isRuleFired :: Tick -> Bool
317 isRuleFired (RuleFired _) = True
318 isRuleFired _             = False
319
320 instance Outputable Tick where
321   ppr tick = text (tickString tick) <+> pprTickCts tick
322
323 instance Eq Tick where
324   a == b = case a `cmpTick` b of
325            EQ -> True
326            _ -> False
327
328 instance Ord Tick where
329   compare = cmpTick
330
331 tickToTag :: Tick -> Int
332 tickToTag (PreInlineUnconditionally _)  = 0
333 tickToTag (PostInlineUnconditionally _) = 1
334 tickToTag (UnfoldingDone _)             = 2
335 tickToTag (RuleFired _)                 = 3
336 tickToTag LetFloatFromLet               = 4
337 tickToTag (EtaExpansion _)              = 5
338 tickToTag (EtaReduction _)              = 6
339 tickToTag (BetaReduction _)             = 7
340 tickToTag (CaseOfCase _)                = 8
341 tickToTag (KnownBranch _)               = 9
342 tickToTag (CaseMerge _)                 = 10
343 tickToTag (CaseElim _)                  = 11
344 tickToTag (CaseIdentity _)              = 12
345 tickToTag (FillInCaseDefault _)         = 13
346 tickToTag BottomFound                   = 14
347 tickToTag SimplifierDone                = 16
348 tickToTag (AltMerge _)                  = 17
349
350 tickString :: Tick -> String
351 tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
352 tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
353 tickString (UnfoldingDone _)            = "UnfoldingDone"
354 tickString (RuleFired _)                = "RuleFired"
355 tickString LetFloatFromLet              = "LetFloatFromLet"
356 tickString (EtaExpansion _)             = "EtaExpansion"
357 tickString (EtaReduction _)             = "EtaReduction"
358 tickString (BetaReduction _)            = "BetaReduction"
359 tickString (CaseOfCase _)               = "CaseOfCase"
360 tickString (KnownBranch _)              = "KnownBranch"
361 tickString (CaseMerge _)                = "CaseMerge"
362 tickString (AltMerge _)                 = "AltMerge"
363 tickString (CaseElim _)                 = "CaseElim"
364 tickString (CaseIdentity _)             = "CaseIdentity"
365 tickString (FillInCaseDefault _)        = "FillInCaseDefault"
366 tickString BottomFound                  = "BottomFound"
367 tickString SimplifierDone               = "SimplifierDone"
368
369 pprTickCts :: Tick -> SDoc
370 pprTickCts (PreInlineUnconditionally v) = ppr v
371 pprTickCts (PostInlineUnconditionally v)= ppr v
372 pprTickCts (UnfoldingDone v)            = ppr v
373 pprTickCts (RuleFired v)                = ppr v
374 pprTickCts LetFloatFromLet              = empty
375 pprTickCts (EtaExpansion v)             = ppr v
376 pprTickCts (EtaReduction v)             = ppr v
377 pprTickCts (BetaReduction v)            = ppr v
378 pprTickCts (CaseOfCase v)               = ppr v
379 pprTickCts (KnownBranch v)              = ppr v
380 pprTickCts (CaseMerge v)                = ppr v
381 pprTickCts (AltMerge v)                 = ppr v
382 pprTickCts (CaseElim v)                 = ppr v
383 pprTickCts (CaseIdentity v)             = ppr v
384 pprTickCts (FillInCaseDefault v)        = ppr v
385 pprTickCts _                            = empty
386
387 cmpTick :: Tick -> Tick -> Ordering
388 cmpTick a b = case (tickToTag a `compare` tickToTag b) of
389                 GT -> GT
390                 EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
391                    | otherwise                          -> EQ
392                 LT -> LT
393         -- Always distinguish RuleFired, so that the stats
394         -- can report them even in non-verbose mode
395
396 cmpEqTick :: Tick -> Tick -> Ordering
397 cmpEqTick (PreInlineUnconditionally a)  (PreInlineUnconditionally b)    = a `compare` b
398 cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b)   = a `compare` b
399 cmpEqTick (UnfoldingDone a)             (UnfoldingDone b)               = a `compare` b
400 cmpEqTick (RuleFired a)                 (RuleFired b)                   = a `compare` b
401 cmpEqTick (EtaExpansion a)              (EtaExpansion b)                = a `compare` b
402 cmpEqTick (EtaReduction a)              (EtaReduction b)                = a `compare` b
403 cmpEqTick (BetaReduction a)             (BetaReduction b)               = a `compare` b
404 cmpEqTick (CaseOfCase a)                (CaseOfCase b)                  = a `compare` b
405 cmpEqTick (KnownBranch a)               (KnownBranch b)                 = a `compare` b
406 cmpEqTick (CaseMerge a)                 (CaseMerge b)                   = a `compare` b
407 cmpEqTick (AltMerge a)                  (AltMerge b)                    = a `compare` b
408 cmpEqTick (CaseElim a)                  (CaseElim b)                    = a `compare` b
409 cmpEqTick (CaseIdentity a)              (CaseIdentity b)                = a `compare` b
410 cmpEqTick (FillInCaseDefault a)         (FillInCaseDefault b)           = a `compare` b
411 cmpEqTick _                             _                               = EQ
412 \end{code}
413
414
415 %************************************************************************
416 %*                                                                      *
417 \subsubsection{Command-line switches}
418 %*                                                                      *
419 %************************************************************************
420
421 \begin{code}
422 type SwitchChecker = SimplifierSwitch -> SwitchResult
423
424 data SwitchResult
425   = SwBool      Bool            -- on/off
426   | SwString    FastString      -- nothing or a String
427   | SwInt       Int             -- nothing or an Int
428
429 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
430 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
431                                         -- in the list; defaults right at the end.
432   = let
433         tidied_on_switches = foldl rm_dups [] on_switches
434                 -- The fold*l* ensures that we keep the latest switches;
435                 -- ie the ones that occur earliest in the list.
436
437         sw_tbl :: Array Int SwitchResult
438         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
439                         all_undefined)
440                  // defined_elems
441
442         all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
443
444         defined_elems = map mk_assoc_elem tidied_on_switches
445     in
446     -- (avoid some unboxing, bounds checking, and other horrible things:)
447     \ switch -> unsafeAt sw_tbl $ iBox (tagOf_SimplSwitch switch)
448   where
449     mk_assoc_elem k@(MaxSimplifierIterations lvl)
450         = (iBox (tagOf_SimplSwitch k), SwInt lvl)
451     mk_assoc_elem k
452         = (iBox (tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
453
454     -- cannot have duplicates if we are going to use the array thing
455     rm_dups switches_so_far switch
456       = if switch `is_elem` switches_so_far
457         then switches_so_far
458         else switch : switches_so_far
459       where
460         _  `is_elem` []     = False
461         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) ==# (tagOf_SimplSwitch s)
462                             || sw `is_elem` ss
463 \end{code}
464
465 \begin{code}
466 getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
467 getSimplIntSwitch chkr switch
468   = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
469
470 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
471
472 switchIsOn lookup_fn switch
473   = case (lookup_fn switch) of
474       SwBool False -> False
475       _            -> True
476
477 intSwitchSet :: (switch -> SwitchResult)
478              -> (Int -> switch)
479              -> Maybe Int
480
481 intSwitchSet lookup_fn switch
482   = case (lookup_fn (switch (panic "intSwitchSet"))) of
483       SwInt int -> Just int
484       _         -> Nothing
485 \end{code}
486
487
488 These things behave just like enumeration types.
489
490 \begin{code}
491 instance Eq SimplifierSwitch where
492     a == b = tagOf_SimplSwitch a ==# tagOf_SimplSwitch b
493
494 instance Ord SimplifierSwitch where
495     a <  b  = tagOf_SimplSwitch a <# tagOf_SimplSwitch b
496     a <= b  = tagOf_SimplSwitch a <=# tagOf_SimplSwitch b
497
498
499 tagOf_SimplSwitch :: SimplifierSwitch -> FastInt
500 tagOf_SimplSwitch (MaxSimplifierIterations _)   = _ILIT(1)
501 tagOf_SimplSwitch NoCaseOfCase                  = _ILIT(2)
502
503 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
504
505 lAST_SIMPL_SWITCH_TAG :: Int
506 lAST_SIMPL_SWITCH_TAG = 2
507 \end{code}
508