2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplMonad]{The simplifier Monad}
11 getDOptsSmpl, getRules, getFamEnvs,
14 MonadUnique(..), newId,
19 getSimplCount, zeroSimplCount, pprSimplCount,
20 plusSimplCount, isZeroSimplCount,
23 SwitchChecker, SwitchResult(..), getSimplIntSwitch,
24 isAmongSimpl, intSwitchSet, switchIsOn
27 import Id ( Id, mkSysLocal )
29 import FamInstEnv ( FamInstEnv )
30 import Rules ( RuleBase )
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 )
41 import Data.Array.Base (unsafeAt)
44 %************************************************************************
46 \subsection{Monad plumbing}
48 %************************************************************************
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.)
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
59 -> (result, UniqSupply, SimplCount)}
61 data SimplTopEnv = STE { st_flags :: DynFlags
62 , st_rules :: RuleBase
63 , st_fams :: (FamInstEnv, FamInstEnv) }
67 initSmpl :: DynFlags -> RuleBase -> (FamInstEnv, FamInstEnv)
68 -> UniqSupply -- No init count; set to 0
72 initSmpl dflags rules fam_envs us m
73 = case unSM m env us (zeroSimplCount dflags) of
74 (result, _, count) -> (result, count)
76 env = STE { st_flags = dflags, st_rules = rules, st_fams = fam_envs }
78 {-# INLINE thenSmpl #-}
79 {-# INLINE thenSmpl_ #-}
80 {-# INLINE returnSmpl #-}
82 instance Monad SimplM where
87 returnSmpl :: a -> SimplM a
88 returnSmpl e = SM (\_st_env us sc -> (e, us, sc))
90 thenSmpl :: SimplM a -> (a -> SimplM b) -> SimplM b
91 thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
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 )
99 = SM (\st_env us0 sc0 ->
100 case (unSM m st_env us0 sc0) of
101 (_, us1, sc1) -> unSM k st_env us1 sc1)
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]) #-}
110 %************************************************************************
112 \subsection{The unique supply}
114 %************************************************************************
117 instance MonadUnique SimplM where
119 = SM (\_st_env us sc -> case splitUniqSupply us of
120 (us1, us2) -> (us1, us2, sc))
123 = SM (\_st_env us sc -> case splitUniqSupply us of
124 (us1, us2) -> (uniqFromSupply us1, us2, sc))
127 = SM (\_st_env us sc -> case splitUniqSupply us of
128 (us1, us2) -> (uniqsFromSupply us1, us2, sc))
130 getDOptsSmpl :: SimplM DynFlags
131 getDOptsSmpl = SM (\st_env us sc -> (st_flags st_env, us, sc))
133 getRules :: SimplM RuleBase
134 getRules = SM (\st_env us sc -> (st_rules st_env, us, sc))
136 getFamEnvs :: SimplM (FamInstEnv, FamInstEnv)
137 getFamEnvs = SM (\st_env us sc -> (st_fams st_env, us, sc))
139 newId :: FastString -> Type -> SimplM Id
140 newId fs ty = do uniq <- getUniqueM
141 return (mkSysLocal fs uniq ty)
145 %************************************************************************
147 \subsection{Counting up what we've done}
149 %************************************************************************
152 getSimplCount :: SimplM SimplCount
153 getSimplCount = SM (\_st_env us sc -> (sc, us, sc))
155 tick :: Tick -> SimplM ()
157 = SM (\_st_env us sc -> let sc' = doTick t sc
158 in sc' `seq` ((), us, sc'))
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
164 = SM (\_st_env us sc -> let sc' = doFreeTick t sc
165 in sc' `seq` ((), us, sc'))
169 verboseSimplStats :: Bool
170 verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
172 zeroSimplCount :: DynFlags -> SimplCount
173 isZeroSimplCount :: SimplCount -> Bool
174 pprSimplCount :: SimplCount -> SDoc
175 doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
176 plusSimplCount :: SimplCount -> SimplCount -> SimplCount
180 data SimplCount = VerySimplZero -- These two are used when
181 | VerySimplNonZero -- we are only interested in
185 ticks :: !Int, -- Total ticks
186 details :: !TickCounts, -- How many of each type
188 log1 :: [Tick], -- Last N events; <= opt_HistorySize
189 log2 :: [Tick] -- Last opt_HistorySize events before that
192 type TickCounts = FiniteMap Tick Int
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 = []}
203 isZeroSimplCount VerySimplZero = True
204 isZeroSimplCount (SimplCount { ticks = 0 }) = True
205 isZeroSimplCount _ = False
207 doFreeTick tick sc@SimplCount { details = dts }
208 = dts' `seqFM` sc { details = dts' }
210 dts' = dts `addTick` tick
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
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 }
222 sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
224 doTick _ _ = VerySimplNonZero -- The very simple case
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
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 }
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 }
246 plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
247 plusSimplCount _ _ = VerySimplNonZero
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,
254 pprTickCounts (fmToList dts),
255 if verboseSimplStats then
257 ptext (sLit "Log (most recent first)"),
258 nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
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,
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]
276 pprTCDetails :: [(Tick, Int)] -> SDoc
277 pprTCDetails ticks@((tick,_):_)
278 | verboseSimplStats || isRuleFired tick
279 = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
282 pprTCDetails [] = panic "pprTCDetails []"
285 %************************************************************************
289 %************************************************************************
293 = PreInlineUnconditionally Id
294 | PostInlineUnconditionally Id
297 | RuleFired FastString -- Rule name
300 | EtaExpansion Id -- LHS binder
301 | EtaReduction Id -- Binder on outer lambda
302 | BetaReduction Id -- Lambda binder
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
314 | SimplifierDone -- Ticked at each iteration of the simplifier
316 isRuleFired :: Tick -> Bool
317 isRuleFired (RuleFired _) = True
318 isRuleFired _ = False
320 instance Outputable Tick where
321 ppr tick = text (tickString tick) <+> pprTickCts tick
323 instance Eq Tick where
324 a == b = case a `cmpTick` b of
328 instance Ord Tick where
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
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"
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
387 cmpTick :: Tick -> Tick -> Ordering
388 cmpTick a b = case (tickToTag a `compare` tickToTag b) of
390 EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
393 -- Always distinguish RuleFired, so that the stats
394 -- can report them even in non-verbose mode
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
415 %************************************************************************
417 \subsubsection{Command-line switches}
419 %************************************************************************
422 type SwitchChecker = SimplifierSwitch -> SwitchResult
425 = SwBool Bool -- on/off
426 | SwString FastString -- nothing or a String
427 | SwInt Int -- nothing or an Int
429 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
430 isAmongSimpl on_switches -- Switches mentioned later occur *earlier*
431 -- in the list; defaults right at the end.
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.
437 sw_tbl :: Array Int SwitchResult
438 sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
442 all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
444 defined_elems = map mk_assoc_elem tidied_on_switches
446 -- (avoid some unboxing, bounds checking, and other horrible things:)
447 \ switch -> unsafeAt sw_tbl $ iBox (tagOf_SimplSwitch switch)
449 mk_assoc_elem k@(MaxSimplifierIterations lvl)
450 = (iBox (tagOf_SimplSwitch k), SwInt lvl)
452 = (iBox (tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
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
458 else switch : switches_so_far
460 _ `is_elem` [] = False
461 sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) ==# (tagOf_SimplSwitch s)
466 getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
467 getSimplIntSwitch chkr switch
468 = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
470 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
472 switchIsOn lookup_fn switch
473 = case (lookup_fn switch) of
474 SwBool False -> False
477 intSwitchSet :: (switch -> SwitchResult)
481 intSwitchSet lookup_fn switch
482 = case (lookup_fn (switch (panic "intSwitchSet"))) of
483 SwInt int -> Just int
488 These things behave just like enumeration types.
491 instance Eq SimplifierSwitch where
492 a == b = tagOf_SimplSwitch a ==# tagOf_SimplSwitch b
494 instance Ord SimplifierSwitch where
495 a < b = tagOf_SimplSwitch a <# tagOf_SimplSwitch b
496 a <= b = tagOf_SimplSwitch a <=# tagOf_SimplSwitch b
499 tagOf_SimplSwitch :: SimplifierSwitch -> FastInt
500 tagOf_SimplSwitch (MaxSimplifierIterations _) = _ILIT(1)
501 tagOf_SimplSwitch NoCaseOfCase = _ILIT(2)
503 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
505 lAST_SIMPL_SWITCH_TAG :: Int
506 lAST_SIMPL_SWITCH_TAG = 2