4ad6d53e8d0a0d30fab0f583c7fc611f28ae039e
[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 Data.Array
49 import Data.Array.Base (unsafeAt)
50
51 infixr 0  `thenSmpl`, `thenSmpl_`
52 \end{code}
53
54 %************************************************************************
55 %*                                                                      *
56 \subsection{Monad plumbing}
57 %*                                                                      *
58 %************************************************************************
59
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.)
62
63 \begin{code}
64 newtype SimplM result
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
68                 -> SimplCount 
69                 -> (result, UniqSupply, SimplCount)}
70
71 data SimplTopEnv = STE  { st_flags :: DynFlags 
72                         , st_rules :: RuleBase
73                         , st_fams  :: (FamInstEnv, FamInstEnv) }
74 \end{code}
75
76 \begin{code}
77 initSmpl :: DynFlags -> RuleBase -> (FamInstEnv, FamInstEnv) 
78          -> UniqSupply          -- No init count; set to 0
79          -> SimplM a
80          -> (a, SimplCount)
81
82 initSmpl dflags rules fam_envs us m
83   = case unSM m env us (zeroSimplCount dflags) of 
84         (result, _, count) -> (result, count)
85   where
86     env = STE { st_flags = dflags, st_rules = rules, st_fams = fam_envs }
87
88 {-# INLINE thenSmpl #-}
89 {-# INLINE thenSmpl_ #-}
90 {-# INLINE returnSmpl #-}
91
92 instance Monad SimplM where
93    (>>)   = thenSmpl_
94    (>>=)  = thenSmpl
95    return = returnSmpl
96
97 returnSmpl :: a -> SimplM a
98 returnSmpl e = SM (\ st_env us sc -> (e, us, sc))
99
100 thenSmpl  :: SimplM a -> (a -> SimplM b) -> SimplM b
101 thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
102
103 thenSmpl m k 
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 )
107
108 thenSmpl_ m k 
109   = SM (\st_env us0 sc0 ->
110          case (unSM m st_env us0 sc0) of 
111                 (_, us1, sc1) -> unSM k st_env us1 sc1)
112 \end{code}
113
114
115 \begin{code}
116 mapSmpl         :: (a -> SimplM b) -> [a] -> SimplM [b]
117 mapAndUnzipSmpl :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c])
118
119 mapSmpl f [] = returnSmpl []
120 mapSmpl f (x:xs)
121   = f x             `thenSmpl` \ x'  ->
122     mapSmpl f xs    `thenSmpl` \ xs' ->
123     returnSmpl (x':xs')
124
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)
130
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')
136 \end{code}
137
138
139 %************************************************************************
140 %*                                                                      *
141 \subsection{The unique supply}
142 %*                                                                      *
143 %************************************************************************
144
145 \begin{code}
146 getUniqSupplySmpl :: SimplM UniqSupply
147 getUniqSupplySmpl 
148    = SM (\st_env us sc -> case splitUniqSupply us of
149                                 (us1, us2) -> (us1, us2, sc))
150
151 getUniqueSmpl :: SimplM Unique
152 getUniqueSmpl 
153    = SM (\st_env us sc -> case splitUniqSupply us of
154                                 (us1, us2) -> (uniqFromSupply us1, us2, sc))
155
156 getUniquesSmpl :: SimplM [Unique]
157 getUniquesSmpl 
158    = SM (\st_env us sc -> case splitUniqSupply us of
159                                 (us1, us2) -> (uniqsFromSupply us1, us2, sc))
160
161 getDOptsSmpl :: SimplM DynFlags
162 getDOptsSmpl = SM (\st_env us sc -> (st_flags st_env, us, sc))
163
164 getRules :: SimplM RuleBase
165 getRules = SM (\st_env us sc -> (st_rules st_env, us, sc))
166
167 getFamEnvs :: SimplM (FamInstEnv, FamInstEnv)
168 getFamEnvs = SM (\st_env us sc -> (st_fams st_env, us, sc))
169
170 newId :: FastString -> Type -> SimplM Id
171 newId fs ty = getUniqueSmpl     `thenSmpl` \ uniq ->
172               returnSmpl (mkSysLocal fs uniq ty)
173 \end{code}
174
175
176 %************************************************************************
177 %*                                                                      *
178 \subsection{Counting up what we've done}
179 %*                                                                      *
180 %************************************************************************
181
182 \begin{code}
183 getSimplCount :: SimplM SimplCount
184 getSimplCount = SM (\st_env us sc -> (sc, us, sc))
185
186 tick :: Tick -> SimplM ()
187 tick t 
188    = SM (\st_env us sc -> let sc' = doTick t sc 
189                           in sc' `seq` ((), us, sc'))
190
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
194 freeTick t 
195    = SM (\st_env us sc -> let sc' = doFreeTick t sc
196                           in sc' `seq` ((), us, sc'))
197 \end{code}
198
199 \begin{code}
200 verboseSimplStats = opt_PprStyle_Debug          -- For now, anyway
201
202 zeroSimplCount     :: DynFlags -> SimplCount
203 isZeroSimplCount   :: SimplCount -> Bool
204 pprSimplCount      :: SimplCount -> SDoc
205 doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
206 plusSimplCount     :: SimplCount -> SimplCount -> SimplCount
207 \end{code}
208
209 \begin{code}
210 data SimplCount = VerySimplZero         -- These two are used when 
211                 | VerySimplNonZero      -- we are only interested in 
212                                         -- termination info
213
214                 | SimplCount    {
215                         ticks   :: !Int,                -- Total ticks
216                         details :: !TickCounts,         -- How many of each type
217                         n_log   :: !Int,                -- N
218                         log1    :: [Tick],              -- Last N events; <= opt_HistorySize
219                         log2    :: [Tick]               -- Last opt_HistorySize events before that
220                   }
221
222 type TickCounts = FiniteMap Tick Int
223
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 = []}
230   | otherwise
231   = VerySimplZero
232
233 isZeroSimplCount VerySimplZero              = True
234 isZeroSimplCount (SimplCount { ticks = 0 }) = True
235 isZeroSimplCount other                      = False
236
237 doFreeTick tick sc@SimplCount { details = dts } 
238   = dts' `seqFM` sc { details = dts' }
239   where
240     dts' = dts `addTick` tick 
241 doFreeTick tick sc = sc 
242
243 -- Gross hack to persuade GHC 3.03 to do this important seq
244 seqFM fm x | isEmptyFM fm = x
245            | otherwise    = x
246
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 }
250   where
251     sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
252
253 doTick tick sc = VerySimplNonZero       -- The very simple case
254
255
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
262                                 where
263                                    n1 = n+1
264
265
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 }
269   where
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 }
273              | otherwise       = sc2
274
275 plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
276 plusSimplCount sc1           sc2           = VerySimplNonZero
277
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,
282           text "",
283           pprTickCounts (fmToList dts),
284           if verboseSimplStats then
285                 vcat [text "",
286                       ptext SLIT("Log (most recent first)"),
287                       nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
288           else empty
289     ]
290
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,
296           pprTickCounts others
297     ]
298   where
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]
304
305 pprTCDetails ticks@((tick,_):_)
306   | verboseSimplStats || isRuleFired tick
307   = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
308   | otherwise
309   = empty
310 \end{code}
311
312 %************************************************************************
313 %*                                                                      *
314 \subsection{Ticks}
315 %*                                                                      *
316 %************************************************************************
317
318 \begin{code}
319 data Tick
320   = PreInlineUnconditionally    Id
321   | PostInlineUnconditionally   Id
322
323   | UnfoldingDone               Id
324   | RuleFired                   FastString      -- Rule name
325
326   | LetFloatFromLet
327   | EtaExpansion                Id      -- LHS binder
328   | EtaReduction                Id      -- Binder on outer lambda
329   | BetaReduction               Id      -- Lambda binder
330
331
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
339
340   | BottomFound         
341   | SimplifierDone              -- Ticked at each iteration of the simplifier
342
343 isRuleFired (RuleFired _) = True
344 isRuleFired other         = False
345
346 instance Outputable Tick where
347   ppr tick = text (tickString tick) <+> pprTickCts tick
348
349 instance Eq Tick where
350   a == b = case a `cmpTick` b of { EQ -> True; other -> False }
351
352 instance Ord Tick where
353   compare = cmpTick
354
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
373
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"
392
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
410
411 cmpTick :: Tick -> Tick -> Ordering
412 cmpTick a b = case (tickToTag a `compare` tickToTag b) of
413                 GT -> GT
414                 EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
415                    | otherwise                          -> EQ
416                 LT -> LT
417         -- Always distinguish RuleFired, so that the stats
418         -- can report them even in non-verbose mode
419
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
436 \end{code}
437
438
439 %************************************************************************
440 %*                                                                      *
441 \subsubsection{Command-line switches}
442 %*                                                                      *
443 %************************************************************************
444
445 \begin{code}
446 type SwitchChecker = SimplifierSwitch -> SwitchResult
447
448 data SwitchResult
449   = SwBool      Bool            -- on/off
450   | SwString    FastString      -- nothing or a String
451   | SwInt       Int             -- nothing or an Int
452
453 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
454 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
455                                         -- in the list; defaults right at the end.
456   = let
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.
460
461         sw_tbl :: Array Int SwitchResult
462         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
463                         all_undefined)
464                  // defined_elems
465
466         all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
467
468         defined_elems = map mk_assoc_elem tidied_on_switches
469     in
470     -- (avoid some unboxing, bounds checking, and other horrible things:)
471     \ switch -> unsafeAt sw_tbl $ iBox (tagOf_SimplSwitch switch)
472   where
473     mk_assoc_elem k@(MaxSimplifierIterations lvl)
474         = (iBox (tagOf_SimplSwitch k), SwInt lvl)
475     mk_assoc_elem k
476         = (iBox (tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
477
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
481         then switches_so_far
482         else switch : switches_so_far
483       where
484         sw `is_elem` []     = False
485         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) ==# (tagOf_SimplSwitch s)
486                             || sw `is_elem` ss
487 \end{code}
488
489 \begin{code}
490 getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
491 getSimplIntSwitch chkr switch
492   = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
493
494 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
495
496 switchIsOn lookup_fn switch
497   = case (lookup_fn switch) of
498       SwBool False -> False
499       _            -> True
500
501 intSwitchSet :: (switch -> SwitchResult)
502              -> (Int -> switch)
503              -> Maybe Int
504
505 intSwitchSet lookup_fn switch
506   = case (lookup_fn (switch (panic "intSwitchSet"))) of
507       SwInt int -> Just int
508       _         -> Nothing
509 \end{code}
510
511
512 These things behave just like enumeration types.
513
514 \begin{code}
515 instance Eq SimplifierSwitch where
516     a == b = tagOf_SimplSwitch a ==# tagOf_SimplSwitch b
517
518 instance Ord SimplifierSwitch where
519     a <  b  = tagOf_SimplSwitch a <# tagOf_SimplSwitch b
520     a <= b  = tagOf_SimplSwitch a <=# tagOf_SimplSwitch b
521
522
523 tagOf_SimplSwitch (MaxSimplifierIterations _)   = _ILIT(1)
524 tagOf_SimplSwitch NoCaseOfCase                  = _ILIT(2)
525
526 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
527
528 lAST_SIMPL_SWITCH_TAG = 2
529 \end{code}
530