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