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