2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplMonad]{The simplifier Monad}
10 initSmpl, returnSmpl, thenSmpl, thenSmpl_,
11 mapSmpl, mapAndUnzipSmpl, mapAccumLSmpl,
12 getDOptsSmpl, getRules, getFamEnvs,
15 getUniqueSmpl, getUniquesSmpl, getUniqSupplySmpl, newId,
20 getSimplCount, zeroSimplCount, pprSimplCount,
21 plusSimplCount, isZeroSimplCount,
24 SwitchChecker, SwitchResult(..), getSimplIntSwitch,
25 isAmongSimpl, intSwitchSet, switchIsOn
28 #include "HsVersions.h"
30 import Id ( Id, mkSysLocal )
32 import FamInstEnv ( FamInstEnv )
33 import Rules ( RuleBase )
34 import UniqSupply ( uniqsFromSupply, uniqFromSupply, splitUniqSupply,
37 import DynFlags ( SimplifierSwitch(..), DynFlags, DynFlag(..), dopt )
38 import StaticFlags ( opt_PprStyle_Debug, opt_HistorySize )
39 import Unique ( Unique )
40 import Maybes ( expectJust )
41 import FiniteMap ( FiniteMap, emptyFM, isEmptyFM, lookupFM, addToFM, plusFM_C, fmToList )
42 import FastString ( FastString )
46 import GHC.Exts ( indexArray# )
49 import Data.Array.Base (unsafeAt)
51 infixr 0 `thenSmpl`, `thenSmpl_`
54 %************************************************************************
56 \subsection{Monad plumbing}
58 %************************************************************************
60 For the simplifier monad, we want to {\em thread} a unique supply and a counter.
61 (Command-line switches move around through the explicitly-passed SimplEnv.)
65 = SM { unSM :: SimplTopEnv -- Envt that does not change much
66 -> UniqSupply -- We thread the unique supply because
67 -- constantly splitting it is rather expensive
69 -> (result, UniqSupply, SimplCount)}
71 data SimplTopEnv = STE { st_flags :: DynFlags
72 , st_rules :: RuleBase
73 , st_fams :: (FamInstEnv, FamInstEnv) }
77 initSmpl :: DynFlags -> RuleBase -> (FamInstEnv, FamInstEnv)
78 -> UniqSupply -- No init count; set to 0
82 initSmpl dflags rules fam_envs us m
83 = case unSM m env us (zeroSimplCount dflags) of
84 (result, _, count) -> (result, count)
86 env = STE { st_flags = dflags, st_rules = rules, st_fams = fam_envs }
88 {-# INLINE thenSmpl #-}
89 {-# INLINE thenSmpl_ #-}
90 {-# INLINE returnSmpl #-}
92 instance Monad SimplM where
97 returnSmpl :: a -> SimplM a
98 returnSmpl e = SM (\ st_env us sc -> (e, us, sc))
100 thenSmpl :: SimplM a -> (a -> SimplM b) -> SimplM b
101 thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
104 = SM (\ st_env us0 sc0 ->
105 case (unSM m st_env us0 sc0) of
106 (m_result, us1, sc1) -> unSM (k m_result) st_env us1 sc1 )
109 = SM (\st_env us0 sc0 ->
110 case (unSM m st_env us0 sc0) of
111 (_, us1, sc1) -> unSM k st_env us1 sc1)
116 mapSmpl :: (a -> SimplM b) -> [a] -> SimplM [b]
117 mapAndUnzipSmpl :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c])
119 mapSmpl f [] = returnSmpl []
121 = f x `thenSmpl` \ x' ->
122 mapSmpl f xs `thenSmpl` \ xs' ->
125 mapAndUnzipSmpl f [] = returnSmpl ([],[])
126 mapAndUnzipSmpl f (x:xs)
127 = f x `thenSmpl` \ (r1, r2) ->
128 mapAndUnzipSmpl f xs `thenSmpl` \ (rs1, rs2) ->
129 returnSmpl (r1:rs1, r2:rs2)
131 mapAccumLSmpl :: (acc -> b -> SimplM (acc,c)) -> acc -> [b] -> SimplM (acc, [c])
132 mapAccumLSmpl f acc [] = returnSmpl (acc, [])
133 mapAccumLSmpl f acc (x:xs) = f acc x `thenSmpl` \ (acc', x') ->
134 mapAccumLSmpl f acc' xs `thenSmpl` \ (acc'', xs') ->
135 returnSmpl (acc'', x':xs')
139 %************************************************************************
141 \subsection{The unique supply}
143 %************************************************************************
146 getUniqSupplySmpl :: SimplM UniqSupply
148 = SM (\st_env us sc -> case splitUniqSupply us of
149 (us1, us2) -> (us1, us2, sc))
151 getUniqueSmpl :: SimplM Unique
153 = SM (\st_env us sc -> case splitUniqSupply us of
154 (us1, us2) -> (uniqFromSupply us1, us2, sc))
156 getUniquesSmpl :: SimplM [Unique]
158 = SM (\st_env us sc -> case splitUniqSupply us of
159 (us1, us2) -> (uniqsFromSupply us1, us2, sc))
161 getDOptsSmpl :: SimplM DynFlags
162 getDOptsSmpl = SM (\st_env us sc -> (st_flags st_env, us, sc))
164 getRules :: SimplM RuleBase
165 getRules = SM (\st_env us sc -> (st_rules st_env, us, sc))
167 getFamEnvs :: SimplM (FamInstEnv, FamInstEnv)
168 getFamEnvs = SM (\st_env us sc -> (st_fams st_env, us, sc))
170 newId :: FastString -> Type -> SimplM Id
171 newId fs ty = getUniqueSmpl `thenSmpl` \ uniq ->
172 returnSmpl (mkSysLocal fs uniq ty)
176 %************************************************************************
178 \subsection{Counting up what we've done}
180 %************************************************************************
183 getSimplCount :: SimplM SimplCount
184 getSimplCount = SM (\st_env us sc -> (sc, us, sc))
186 tick :: Tick -> SimplM ()
188 = SM (\st_env us sc -> let sc' = doTick t sc
189 in sc' `seq` ((), us, sc'))
191 freeTick :: Tick -> SimplM ()
192 -- Record a tick, but don't add to the total tick count, which is
193 -- used to decide when nothing further has happened
195 = SM (\st_env us sc -> let sc' = doFreeTick t sc
196 in sc' `seq` ((), us, sc'))
200 verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
202 zeroSimplCount :: DynFlags -> SimplCount
203 isZeroSimplCount :: SimplCount -> Bool
204 pprSimplCount :: SimplCount -> SDoc
205 doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
206 plusSimplCount :: SimplCount -> SimplCount -> SimplCount
210 data SimplCount = VerySimplZero -- These two are used when
211 | VerySimplNonZero -- we are only interested in
215 ticks :: !Int, -- Total ticks
216 details :: !TickCounts, -- How many of each type
218 log1 :: [Tick], -- Last N events; <= opt_HistorySize
219 log2 :: [Tick] -- Last opt_HistorySize events before that
222 type TickCounts = FiniteMap Tick Int
224 zeroSimplCount dflags
225 -- This is where we decide whether to do
226 -- the VerySimpl version or the full-stats version
227 | dopt Opt_D_dump_simpl_stats dflags
228 = SimplCount {ticks = 0, details = emptyFM,
229 n_log = 0, log1 = [], log2 = []}
233 isZeroSimplCount VerySimplZero = True
234 isZeroSimplCount (SimplCount { ticks = 0 }) = True
235 isZeroSimplCount other = False
237 doFreeTick tick sc@SimplCount { details = dts }
238 = dts' `seqFM` sc { details = dts' }
240 dts' = dts `addTick` tick
241 doFreeTick tick sc = sc
243 -- Gross hack to persuade GHC 3.03 to do this important seq
244 seqFM fm x | isEmptyFM fm = x
247 doTick tick sc@SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1, log2 = l2 }
248 | nl >= opt_HistorySize = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
249 | otherwise = sc1 { n_log = nl+1, log1 = tick : l1 }
251 sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
253 doTick tick sc = VerySimplNonZero -- The very simple case
256 -- Don't use plusFM_C because that's lazy, and we want to
257 -- be pretty strict here!
258 addTick :: TickCounts -> Tick -> TickCounts
259 addTick fm tick = case lookupFM fm tick of
260 Nothing -> addToFM fm tick 1
261 Just n -> n1 `seq` addToFM fm tick n1
266 plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
267 sc2@(SimplCount { ticks = tks2, details = dts2 })
268 = log_base { ticks = tks1 + tks2, details = plusFM_C (+) dts1 dts2 }
270 -- A hackish way of getting recent log info
271 log_base | null (log1 sc2) = sc1 -- Nothing at all in sc2
272 | null (log2 sc2) = sc2 { log2 = log1 sc1 }
275 plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
276 plusSimplCount sc1 sc2 = VerySimplNonZero
278 pprSimplCount VerySimplZero = ptext SLIT("Total ticks: ZERO!")
279 pprSimplCount VerySimplNonZero = ptext SLIT("Total ticks: NON-ZERO!")
280 pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
281 = vcat [ptext SLIT("Total ticks: ") <+> int tks,
283 pprTickCounts (fmToList dts),
284 if verboseSimplStats then
286 ptext SLIT("Log (most recent first)"),
287 nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
291 pprTickCounts :: [(Tick,Int)] -> SDoc
292 pprTickCounts [] = empty
293 pprTickCounts ((tick1,n1):ticks)
294 = vcat [int tot_n <+> text (tickString tick1),
295 pprTCDetails real_these,
299 tick1_tag = tickToTag tick1
300 (these, others) = span same_tick ticks
301 real_these = (tick1,n1):these
302 same_tick (tick2,_) = tickToTag tick2 == tick1_tag
303 tot_n = sum [n | (_,n) <- real_these]
305 pprTCDetails ticks@((tick,_):_)
306 | verboseSimplStats || isRuleFired tick
307 = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
312 %************************************************************************
316 %************************************************************************
320 = PreInlineUnconditionally Id
321 | PostInlineUnconditionally Id
324 | RuleFired FastString -- Rule name
327 | EtaExpansion Id -- LHS binder
328 | EtaReduction Id -- Binder on outer lambda
329 | BetaReduction Id -- Lambda binder
332 | CaseOfCase Id -- Bndr on *inner* case
333 | KnownBranch Id -- Case binder
334 | CaseMerge Id -- Binder on outer case
335 | AltMerge Id -- Case binder
336 | CaseElim Id -- Case binder
337 | CaseIdentity Id -- Case binder
338 | FillInCaseDefault Id -- Case binder
341 | SimplifierDone -- Ticked at each iteration of the simplifier
343 isRuleFired (RuleFired _) = True
344 isRuleFired other = False
346 instance Outputable Tick where
347 ppr tick = text (tickString tick) <+> pprTickCts tick
349 instance Eq Tick where
350 a == b = case a `cmpTick` b of { EQ -> True; other -> False }
352 instance Ord Tick where
355 tickToTag :: Tick -> Int
356 tickToTag (PreInlineUnconditionally _) = 0
357 tickToTag (PostInlineUnconditionally _) = 1
358 tickToTag (UnfoldingDone _) = 2
359 tickToTag (RuleFired _) = 3
360 tickToTag LetFloatFromLet = 4
361 tickToTag (EtaExpansion _) = 5
362 tickToTag (EtaReduction _) = 6
363 tickToTag (BetaReduction _) = 7
364 tickToTag (CaseOfCase _) = 8
365 tickToTag (KnownBranch _) = 9
366 tickToTag (CaseMerge _) = 10
367 tickToTag (CaseElim _) = 11
368 tickToTag (CaseIdentity _) = 12
369 tickToTag (FillInCaseDefault _) = 13
370 tickToTag BottomFound = 14
371 tickToTag SimplifierDone = 16
372 tickToTag (AltMerge _) = 17
374 tickString :: Tick -> String
375 tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
376 tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
377 tickString (UnfoldingDone _) = "UnfoldingDone"
378 tickString (RuleFired _) = "RuleFired"
379 tickString LetFloatFromLet = "LetFloatFromLet"
380 tickString (EtaExpansion _) = "EtaExpansion"
381 tickString (EtaReduction _) = "EtaReduction"
382 tickString (BetaReduction _) = "BetaReduction"
383 tickString (CaseOfCase _) = "CaseOfCase"
384 tickString (KnownBranch _) = "KnownBranch"
385 tickString (CaseMerge _) = "CaseMerge"
386 tickString (AltMerge _) = "AltMerge"
387 tickString (CaseElim _) = "CaseElim"
388 tickString (CaseIdentity _) = "CaseIdentity"
389 tickString (FillInCaseDefault _) = "FillInCaseDefault"
390 tickString BottomFound = "BottomFound"
391 tickString SimplifierDone = "SimplifierDone"
393 pprTickCts :: Tick -> SDoc
394 pprTickCts (PreInlineUnconditionally v) = ppr v
395 pprTickCts (PostInlineUnconditionally v)= ppr v
396 pprTickCts (UnfoldingDone v) = ppr v
397 pprTickCts (RuleFired v) = ppr v
398 pprTickCts LetFloatFromLet = empty
399 pprTickCts (EtaExpansion v) = ppr v
400 pprTickCts (EtaReduction v) = ppr v
401 pprTickCts (BetaReduction v) = ppr v
402 pprTickCts (CaseOfCase v) = ppr v
403 pprTickCts (KnownBranch v) = ppr v
404 pprTickCts (CaseMerge v) = ppr v
405 pprTickCts (AltMerge v) = ppr v
406 pprTickCts (CaseElim v) = ppr v
407 pprTickCts (CaseIdentity v) = ppr v
408 pprTickCts (FillInCaseDefault v) = ppr v
409 pprTickCts other = empty
411 cmpTick :: Tick -> Tick -> Ordering
412 cmpTick a b = case (tickToTag a `compare` tickToTag b) of
414 EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
417 -- Always distinguish RuleFired, so that the stats
418 -- can report them even in non-verbose mode
420 cmpEqTick :: Tick -> Tick -> Ordering
421 cmpEqTick (PreInlineUnconditionally a) (PreInlineUnconditionally b) = a `compare` b
422 cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b) = a `compare` b
423 cmpEqTick (UnfoldingDone a) (UnfoldingDone b) = a `compare` b
424 cmpEqTick (RuleFired a) (RuleFired b) = a `compare` b
425 cmpEqTick (EtaExpansion a) (EtaExpansion b) = a `compare` b
426 cmpEqTick (EtaReduction a) (EtaReduction b) = a `compare` b
427 cmpEqTick (BetaReduction a) (BetaReduction b) = a `compare` b
428 cmpEqTick (CaseOfCase a) (CaseOfCase b) = a `compare` b
429 cmpEqTick (KnownBranch a) (KnownBranch b) = a `compare` b
430 cmpEqTick (CaseMerge a) (CaseMerge b) = a `compare` b
431 cmpEqTick (AltMerge a) (AltMerge b) = a `compare` b
432 cmpEqTick (CaseElim a) (CaseElim b) = a `compare` b
433 cmpEqTick (CaseIdentity a) (CaseIdentity b) = a `compare` b
434 cmpEqTick (FillInCaseDefault a) (FillInCaseDefault b) = a `compare` b
435 cmpEqTick other1 other2 = EQ
439 %************************************************************************
441 \subsubsection{Command-line switches}
443 %************************************************************************
446 type SwitchChecker = SimplifierSwitch -> SwitchResult
449 = SwBool Bool -- on/off
450 | SwString FastString -- nothing or a String
451 | SwInt Int -- nothing or an Int
453 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
454 isAmongSimpl on_switches -- Switches mentioned later occur *earlier*
455 -- in the list; defaults right at the end.
457 tidied_on_switches = foldl rm_dups [] on_switches
458 -- The fold*l* ensures that we keep the latest switches;
459 -- ie the ones that occur earliest in the list.
461 sw_tbl :: Array Int SwitchResult
462 sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
466 all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
468 defined_elems = map mk_assoc_elem tidied_on_switches
470 -- (avoid some unboxing, bounds checking, and other horrible things:)
471 \ switch -> unsafeAt sw_tbl $ iBox (tagOf_SimplSwitch switch)
473 mk_assoc_elem k@(MaxSimplifierIterations lvl)
474 = (iBox (tagOf_SimplSwitch k), SwInt lvl)
476 = (iBox (tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
478 -- cannot have duplicates if we are going to use the array thing
479 rm_dups switches_so_far switch
480 = if switch `is_elem` switches_so_far
482 else switch : switches_so_far
484 sw `is_elem` [] = False
485 sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) ==# (tagOf_SimplSwitch s)
490 getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
491 getSimplIntSwitch chkr switch
492 = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
494 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
496 switchIsOn lookup_fn switch
497 = case (lookup_fn switch) of
498 SwBool False -> False
501 intSwitchSet :: (switch -> SwitchResult)
505 intSwitchSet lookup_fn switch
506 = case (lookup_fn (switch (panic "intSwitchSet"))) of
507 SwInt int -> Just int
512 These things behave just like enumeration types.
515 instance Eq SimplifierSwitch where
516 a == b = tagOf_SimplSwitch a ==# tagOf_SimplSwitch b
518 instance Ord SimplifierSwitch where
519 a < b = tagOf_SimplSwitch a <# tagOf_SimplSwitch b
520 a <= b = tagOf_SimplSwitch a <=# tagOf_SimplSwitch b
523 tagOf_SimplSwitch (MaxSimplifierIterations _) = _ILIT(1)
524 tagOf_SimplSwitch NoCaseOfCase = _ILIT(2)
526 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
528 lAST_SIMPL_SWITCH_TAG = 2