2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplMonad]{The simplifier Monad}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
18 getDOptsSmpl, getRules, getFamEnvs,
21 MonadUnique(..), newId,
26 getSimplCount, zeroSimplCount, pprSimplCount,
27 plusSimplCount, isZeroSimplCount,
30 SwitchChecker, SwitchResult(..), getSimplIntSwitch,
31 isAmongSimpl, intSwitchSet, switchIsOn
34 #include "HsVersions.h"
36 import Id ( Id, mkSysLocal )
38 import FamInstEnv ( FamInstEnv )
39 import Rules ( RuleBase )
41 import DynFlags ( SimplifierSwitch(..), DynFlags, DynFlag(..), dopt )
42 import StaticFlags ( opt_PprStyle_Debug, opt_HistorySize )
43 import Unique ( Unique )
44 import Maybes ( expectJust )
45 import FiniteMap ( FiniteMap, emptyFM, isEmptyFM, lookupFM, addToFM, plusFM_C, fmToList )
46 import FastString ( FastString )
51 import Data.Array.Base (unsafeAt)
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)
113 -- TODO: this specializing is not allowed
114 {-# -- SPECIALIZE mapM :: (a -> SimplM b) -> [a] -> SimplM [b] #-}
115 {-# -- SPECIALIZE mapAndUnzipM :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c]) #-}
116 {-# -- SPECIALIZE mapAccumLM :: (acc -> b -> SimplM (acc,c)) -> acc -> [b] -> SimplM (acc, [c]) #-}
120 %************************************************************************
122 \subsection{The unique supply}
124 %************************************************************************
127 instance MonadUnique SimplM where
129 = SM (\st_env us sc -> case splitUniqSupply us of
130 (us1, us2) -> (us1, us2, sc))
133 = SM (\st_env us sc -> case splitUniqSupply us of
134 (us1, us2) -> (uniqFromSupply us1, us2, sc))
137 = SM (\st_env us sc -> case splitUniqSupply us of
138 (us1, us2) -> (uniqsFromSupply us1, us2, sc))
140 getDOptsSmpl :: SimplM DynFlags
141 getDOptsSmpl = SM (\st_env us sc -> (st_flags st_env, us, sc))
143 getRules :: SimplM RuleBase
144 getRules = SM (\st_env us sc -> (st_rules st_env, us, sc))
146 getFamEnvs :: SimplM (FamInstEnv, FamInstEnv)
147 getFamEnvs = SM (\st_env us sc -> (st_fams st_env, us, sc))
149 newId :: FastString -> Type -> SimplM Id
150 newId fs ty = do uniq <- getUniqueM
151 return (mkSysLocal fs uniq ty)
155 %************************************************************************
157 \subsection{Counting up what we've done}
159 %************************************************************************
162 getSimplCount :: SimplM SimplCount
163 getSimplCount = SM (\st_env us sc -> (sc, us, sc))
165 tick :: Tick -> SimplM ()
167 = SM (\st_env us sc -> let sc' = doTick t sc
168 in sc' `seq` ((), us, sc'))
170 freeTick :: Tick -> SimplM ()
171 -- Record a tick, but don't add to the total tick count, which is
172 -- used to decide when nothing further has happened
174 = SM (\st_env us sc -> let sc' = doFreeTick t sc
175 in sc' `seq` ((), us, sc'))
179 verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
181 zeroSimplCount :: DynFlags -> SimplCount
182 isZeroSimplCount :: SimplCount -> Bool
183 pprSimplCount :: SimplCount -> SDoc
184 doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
185 plusSimplCount :: SimplCount -> SimplCount -> SimplCount
189 data SimplCount = VerySimplZero -- These two are used when
190 | VerySimplNonZero -- we are only interested in
194 ticks :: !Int, -- Total ticks
195 details :: !TickCounts, -- How many of each type
197 log1 :: [Tick], -- Last N events; <= opt_HistorySize
198 log2 :: [Tick] -- Last opt_HistorySize events before that
201 type TickCounts = FiniteMap Tick Int
203 zeroSimplCount dflags
204 -- This is where we decide whether to do
205 -- the VerySimpl version or the full-stats version
206 | dopt Opt_D_dump_simpl_stats dflags
207 = SimplCount {ticks = 0, details = emptyFM,
208 n_log = 0, log1 = [], log2 = []}
212 isZeroSimplCount VerySimplZero = True
213 isZeroSimplCount (SimplCount { ticks = 0 }) = True
214 isZeroSimplCount other = False
216 doFreeTick tick sc@SimplCount { details = dts }
217 = dts' `seqFM` sc { details = dts' }
219 dts' = dts `addTick` tick
220 doFreeTick tick sc = sc
222 -- Gross hack to persuade GHC 3.03 to do this important seq
223 seqFM fm x | isEmptyFM fm = x
226 doTick tick sc@SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1, log2 = l2 }
227 | nl >= opt_HistorySize = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
228 | otherwise = sc1 { n_log = nl+1, log1 = tick : l1 }
230 sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
232 doTick tick sc = VerySimplNonZero -- The very simple case
235 -- Don't use plusFM_C because that's lazy, and we want to
236 -- be pretty strict here!
237 addTick :: TickCounts -> Tick -> TickCounts
238 addTick fm tick = case lookupFM fm tick of
239 Nothing -> addToFM fm tick 1
240 Just n -> n1 `seq` addToFM fm tick n1
245 plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
246 sc2@(SimplCount { ticks = tks2, details = dts2 })
247 = log_base { ticks = tks1 + tks2, details = plusFM_C (+) dts1 dts2 }
249 -- A hackish way of getting recent log info
250 log_base | null (log1 sc2) = sc1 -- Nothing at all in sc2
251 | null (log2 sc2) = sc2 { log2 = log1 sc1 }
254 plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
255 plusSimplCount sc1 sc2 = VerySimplNonZero
257 pprSimplCount VerySimplZero = ptext SLIT("Total ticks: ZERO!")
258 pprSimplCount VerySimplNonZero = ptext SLIT("Total ticks: NON-ZERO!")
259 pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
260 = vcat [ptext SLIT("Total ticks: ") <+> int tks,
262 pprTickCounts (fmToList dts),
263 if verboseSimplStats then
265 ptext SLIT("Log (most recent first)"),
266 nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
270 pprTickCounts :: [(Tick,Int)] -> SDoc
271 pprTickCounts [] = empty
272 pprTickCounts ((tick1,n1):ticks)
273 = vcat [int tot_n <+> text (tickString tick1),
274 pprTCDetails real_these,
278 tick1_tag = tickToTag tick1
279 (these, others) = span same_tick ticks
280 real_these = (tick1,n1):these
281 same_tick (tick2,_) = tickToTag tick2 == tick1_tag
282 tot_n = sum [n | (_,n) <- real_these]
284 pprTCDetails ticks@((tick,_):_)
285 | verboseSimplStats || isRuleFired tick
286 = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
291 %************************************************************************
295 %************************************************************************
299 = PreInlineUnconditionally Id
300 | PostInlineUnconditionally Id
303 | RuleFired FastString -- Rule name
306 | EtaExpansion Id -- LHS binder
307 | EtaReduction Id -- Binder on outer lambda
308 | BetaReduction Id -- Lambda binder
311 | CaseOfCase Id -- Bndr on *inner* case
312 | KnownBranch Id -- Case binder
313 | CaseMerge Id -- Binder on outer case
314 | AltMerge Id -- Case binder
315 | CaseElim Id -- Case binder
316 | CaseIdentity Id -- Case binder
317 | FillInCaseDefault Id -- Case binder
320 | SimplifierDone -- Ticked at each iteration of the simplifier
322 isRuleFired (RuleFired _) = True
323 isRuleFired other = False
325 instance Outputable Tick where
326 ppr tick = text (tickString tick) <+> pprTickCts tick
328 instance Eq Tick where
329 a == b = case a `cmpTick` b of { EQ -> True; other -> False }
331 instance Ord Tick where
334 tickToTag :: Tick -> Int
335 tickToTag (PreInlineUnconditionally _) = 0
336 tickToTag (PostInlineUnconditionally _) = 1
337 tickToTag (UnfoldingDone _) = 2
338 tickToTag (RuleFired _) = 3
339 tickToTag LetFloatFromLet = 4
340 tickToTag (EtaExpansion _) = 5
341 tickToTag (EtaReduction _) = 6
342 tickToTag (BetaReduction _) = 7
343 tickToTag (CaseOfCase _) = 8
344 tickToTag (KnownBranch _) = 9
345 tickToTag (CaseMerge _) = 10
346 tickToTag (CaseElim _) = 11
347 tickToTag (CaseIdentity _) = 12
348 tickToTag (FillInCaseDefault _) = 13
349 tickToTag BottomFound = 14
350 tickToTag SimplifierDone = 16
351 tickToTag (AltMerge _) = 17
353 tickString :: Tick -> String
354 tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
355 tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
356 tickString (UnfoldingDone _) = "UnfoldingDone"
357 tickString (RuleFired _) = "RuleFired"
358 tickString LetFloatFromLet = "LetFloatFromLet"
359 tickString (EtaExpansion _) = "EtaExpansion"
360 tickString (EtaReduction _) = "EtaReduction"
361 tickString (BetaReduction _) = "BetaReduction"
362 tickString (CaseOfCase _) = "CaseOfCase"
363 tickString (KnownBranch _) = "KnownBranch"
364 tickString (CaseMerge _) = "CaseMerge"
365 tickString (AltMerge _) = "AltMerge"
366 tickString (CaseElim _) = "CaseElim"
367 tickString (CaseIdentity _) = "CaseIdentity"
368 tickString (FillInCaseDefault _) = "FillInCaseDefault"
369 tickString BottomFound = "BottomFound"
370 tickString SimplifierDone = "SimplifierDone"
372 pprTickCts :: Tick -> SDoc
373 pprTickCts (PreInlineUnconditionally v) = ppr v
374 pprTickCts (PostInlineUnconditionally v)= ppr v
375 pprTickCts (UnfoldingDone v) = ppr v
376 pprTickCts (RuleFired v) = ppr v
377 pprTickCts LetFloatFromLet = empty
378 pprTickCts (EtaExpansion v) = ppr v
379 pprTickCts (EtaReduction v) = ppr v
380 pprTickCts (BetaReduction v) = ppr v
381 pprTickCts (CaseOfCase v) = ppr v
382 pprTickCts (KnownBranch v) = ppr v
383 pprTickCts (CaseMerge v) = ppr v
384 pprTickCts (AltMerge v) = ppr v
385 pprTickCts (CaseElim v) = ppr v
386 pprTickCts (CaseIdentity v) = ppr v
387 pprTickCts (FillInCaseDefault v) = ppr v
388 pprTickCts other = empty
390 cmpTick :: Tick -> Tick -> Ordering
391 cmpTick a b = case (tickToTag a `compare` tickToTag b) of
393 EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
396 -- Always distinguish RuleFired, so that the stats
397 -- can report them even in non-verbose mode
399 cmpEqTick :: Tick -> Tick -> Ordering
400 cmpEqTick (PreInlineUnconditionally a) (PreInlineUnconditionally b) = a `compare` b
401 cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b) = a `compare` b
402 cmpEqTick (UnfoldingDone a) (UnfoldingDone b) = a `compare` b
403 cmpEqTick (RuleFired a) (RuleFired b) = a `compare` b
404 cmpEqTick (EtaExpansion a) (EtaExpansion b) = a `compare` b
405 cmpEqTick (EtaReduction a) (EtaReduction b) = a `compare` b
406 cmpEqTick (BetaReduction a) (BetaReduction b) = a `compare` b
407 cmpEqTick (CaseOfCase a) (CaseOfCase b) = a `compare` b
408 cmpEqTick (KnownBranch a) (KnownBranch b) = a `compare` b
409 cmpEqTick (CaseMerge a) (CaseMerge b) = a `compare` b
410 cmpEqTick (AltMerge a) (AltMerge b) = a `compare` b
411 cmpEqTick (CaseElim a) (CaseElim b) = a `compare` b
412 cmpEqTick (CaseIdentity a) (CaseIdentity b) = a `compare` b
413 cmpEqTick (FillInCaseDefault a) (FillInCaseDefault b) = a `compare` b
414 cmpEqTick other1 other2 = EQ
418 %************************************************************************
420 \subsubsection{Command-line switches}
422 %************************************************************************
425 type SwitchChecker = SimplifierSwitch -> SwitchResult
428 = SwBool Bool -- on/off
429 | SwString FastString -- nothing or a String
430 | SwInt Int -- nothing or an Int
432 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
433 isAmongSimpl on_switches -- Switches mentioned later occur *earlier*
434 -- in the list; defaults right at the end.
436 tidied_on_switches = foldl rm_dups [] on_switches
437 -- The fold*l* ensures that we keep the latest switches;
438 -- ie the ones that occur earliest in the list.
440 sw_tbl :: Array Int SwitchResult
441 sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
445 all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
447 defined_elems = map mk_assoc_elem tidied_on_switches
449 -- (avoid some unboxing, bounds checking, and other horrible things:)
450 \ switch -> unsafeAt sw_tbl $ iBox (tagOf_SimplSwitch switch)
452 mk_assoc_elem k@(MaxSimplifierIterations lvl)
453 = (iBox (tagOf_SimplSwitch k), SwInt lvl)
455 = (iBox (tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
457 -- cannot have duplicates if we are going to use the array thing
458 rm_dups switches_so_far switch
459 = if switch `is_elem` switches_so_far
461 else switch : switches_so_far
463 sw `is_elem` [] = False
464 sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) ==# (tagOf_SimplSwitch s)
469 getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
470 getSimplIntSwitch chkr switch
471 = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
473 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
475 switchIsOn lookup_fn switch
476 = case (lookup_fn switch) of
477 SwBool False -> False
480 intSwitchSet :: (switch -> SwitchResult)
484 intSwitchSet lookup_fn switch
485 = case (lookup_fn (switch (panic "intSwitchSet"))) of
486 SwInt int -> Just int
491 These things behave just like enumeration types.
494 instance Eq SimplifierSwitch where
495 a == b = tagOf_SimplSwitch a ==# tagOf_SimplSwitch b
497 instance Ord SimplifierSwitch where
498 a < b = tagOf_SimplSwitch a <# tagOf_SimplSwitch b
499 a <= b = tagOf_SimplSwitch a <=# tagOf_SimplSwitch b
502 tagOf_SimplSwitch (MaxSimplifierIterations _) = _ILIT(1)
503 tagOf_SimplSwitch NoCaseOfCase = _ILIT(2)
505 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
507 lAST_SIMPL_SWITCH_TAG = 2