PageRenderTime 53ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/simplCore/CoreMonad.lhs

https://bitbucket.org/carter/ghc
Haskell | 1059 lines | 776 code | 184 blank | 99 comment | 12 complexity | bc4ebadb9f35b67874ff6d3898054bfd MD5 | raw file
  1. %
  2. % (c) The AQUA Project, Glasgow University, 1993-1998
  3. %
  4. \section[CoreMonad]{The core pipeline monad}
  5. \begin{code}
  6. {-# OPTIONS -fno-warn-tabs #-}
  7. -- The above warning supression flag is a temporary kludge.
  8. -- While working on this module you are encouraged to remove it and
  9. -- detab the module (please do the detabbing in a separate patch). See
  10. -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
  11. -- for details
  12. {-# LANGUAGE UndecidableInstances #-}
  13. module CoreMonad (
  14. -- * Configuration of the core-to-core passes
  15. CoreToDo(..), runWhen, runMaybe,
  16. SimplifierMode(..),
  17. FloatOutSwitches(..),
  18. dumpSimplPhase, pprPassDetails,
  19. -- * Plugins
  20. PluginPass, Plugin(..), CommandLineOption,
  21. defaultPlugin, bindsOnlyPass,
  22. -- * Counting
  23. SimplCount, doSimplTick, doFreeSimplTick, simplCountN,
  24. pprSimplCount, plusSimplCount, zeroSimplCount,
  25. isZeroSimplCount, hasDetailedCounts, Tick(..),
  26. -- * The monad
  27. CoreM, runCoreM,
  28. -- ** Reading from the monad
  29. getHscEnv, getRuleBase, getModule,
  30. getDynFlags, getOrigNameCache,
  31. -- ** Writing to the monad
  32. addSimplCount,
  33. -- ** Lifting into the monad
  34. liftIO, liftIOWithCount,
  35. liftIO1, liftIO2, liftIO3, liftIO4,
  36. -- ** Global initialization
  37. reinitializeGlobals,
  38. -- ** Dealing with annotations
  39. getAnnotations, getFirstAnnotations,
  40. -- ** Debug output
  41. showPass, endPass, dumpPassResult, lintPassResult, dumpIfSet,
  42. -- ** Screen output
  43. putMsg, putMsgS, errorMsg, errorMsgS,
  44. fatalErrorMsg, fatalErrorMsgS,
  45. debugTraceMsg, debugTraceMsgS,
  46. dumpIfSet_dyn,
  47. #ifdef GHCI
  48. -- * Getting 'Name's
  49. thNameToGhcName
  50. #endif
  51. ) where
  52. #ifdef GHCI
  53. import Name( Name )
  54. #endif
  55. import CoreSyn
  56. import PprCore
  57. import CoreUtils
  58. import CoreLint ( lintCoreBindings )
  59. import HscTypes
  60. import Module ( Module )
  61. import DynFlags
  62. import StaticFlags
  63. import Rules ( RuleBase )
  64. import BasicTypes ( CompilerPhase(..) )
  65. import Annotations
  66. import Id ( Id )
  67. import IOEnv hiding ( liftIO, failM, failWithM )
  68. import qualified IOEnv ( liftIO )
  69. import TcEnv ( tcLookupGlobal )
  70. import TcRnMonad ( initTcForLookup )
  71. import Outputable
  72. import FastString
  73. import qualified ErrUtils as Err
  74. import Bag
  75. import Maybes
  76. import SrcLoc
  77. import UniqSupply
  78. import UniqFM ( UniqFM, mapUFM, filterUFM )
  79. import MonadUtils
  80. import Util ( split )
  81. import ListSetOps ( runs )
  82. import Data.List
  83. import Data.Ord
  84. import Data.Dynamic
  85. import Data.IORef
  86. import Data.Map (Map)
  87. import qualified Data.Map as Map
  88. import Data.Word
  89. import Control.Monad
  90. import Prelude hiding ( read )
  91. #ifdef GHCI
  92. import Control.Concurrent.MVar (MVar)
  93. import Linker ( PersistentLinkerState, saveLinkerGlobals, restoreLinkerGlobals )
  94. import {-# SOURCE #-} TcSplice ( lookupThName_maybe )
  95. import qualified Language.Haskell.TH as TH
  96. #else
  97. saveLinkerGlobals :: IO ()
  98. saveLinkerGlobals = return ()
  99. restoreLinkerGlobals :: () -> IO ()
  100. restoreLinkerGlobals () = return ()
  101. #endif
  102. \end{code}
  103. %************************************************************************
  104. %* *
  105. Debug output
  106. %* *
  107. %************************************************************************
  108. These functions are not CoreM monad stuff, but they probably ought to
  109. be, and it makes a conveneint place. place for them. They print out
  110. stuff before and after core passes, and do Core Lint when necessary.
  111. \begin{code}
  112. showPass :: DynFlags -> CoreToDo -> IO ()
  113. showPass dflags pass = Err.showPass dflags (showPpr dflags pass)
  114. endPass :: DynFlags -> CoreToDo -> CoreProgram -> [CoreRule] -> IO ()
  115. endPass dflags pass binds rules
  116. = do { dumpPassResult dflags mb_flag (ppr pass) (pprPassDetails pass) binds rules
  117. ; lintPassResult dflags pass binds }
  118. where
  119. mb_flag = case coreDumpFlag pass of
  120. Just dflag | dopt dflag dflags -> Just dflag
  121. | dopt Opt_D_verbose_core2core dflags -> Just dflag
  122. _ -> Nothing
  123. dumpIfSet :: DynFlags -> Bool -> CoreToDo -> SDoc -> SDoc -> IO ()
  124. dumpIfSet dflags dump_me pass extra_info doc
  125. = Err.dumpIfSet dflags dump_me (showSDoc dflags (ppr pass <+> extra_info)) doc
  126. dumpPassResult :: DynFlags
  127. -> Maybe DynFlag -- Just df => show details in a file whose
  128. -- name is specified by df
  129. -> SDoc -- Header
  130. -> SDoc -- Extra info to appear after header
  131. -> CoreProgram -> [CoreRule]
  132. -> IO ()
  133. dumpPassResult dflags mb_flag hdr extra_info binds rules
  134. | Just dflag <- mb_flag
  135. = Err.dumpSDoc dflags dflag (showSDoc dflags hdr) dump_doc
  136. | otherwise
  137. = Err.debugTraceMsg dflags 2 size_doc
  138. -- Report result size
  139. -- This has the side effect of forcing the intermediate to be evaluated
  140. where
  141. size_doc = sep [text "Result size of" <+> hdr, nest 2 (equals <+> ppr (coreBindsStats binds))]
  142. dump_doc = vcat [ nest 2 extra_info
  143. , size_doc
  144. , blankLine
  145. , pprCoreBindings binds
  146. , ppUnless (null rules) pp_rules ]
  147. pp_rules = vcat [ blankLine
  148. , ptext (sLit "------ Local rules for imported ids --------")
  149. , pprRules rules ]
  150. lintPassResult :: DynFlags -> CoreToDo -> CoreProgram -> IO ()
  151. lintPassResult dflags pass binds
  152. = when (dopt Opt_DoCoreLinting dflags) $
  153. do { let (warns, errs) = lintCoreBindings binds
  154. ; Err.showPass dflags ("Core Linted result of " ++ showPpr dflags pass)
  155. ; displayLintResults dflags pass warns errs binds }
  156. displayLintResults :: DynFlags -> CoreToDo
  157. -> Bag Err.MsgDoc -> Bag Err.MsgDoc -> CoreProgram
  158. -> IO ()
  159. displayLintResults dflags pass warns errs binds
  160. | not (isEmptyBag errs)
  161. = do { log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
  162. (vcat [ banner "errors", Err.pprMessageBag errs
  163. , ptext (sLit "*** Offending Program ***")
  164. , pprCoreBindings binds
  165. , ptext (sLit "*** End of Offense ***") ])
  166. ; Err.ghcExit dflags 1 }
  167. | not (isEmptyBag warns)
  168. , not (case pass of { CoreDesugar -> True; _ -> False })
  169. -- Suppress warnings after desugaring pass because some
  170. -- are legitimate. Notably, the desugarer generates instance
  171. -- methods with INLINE pragmas that form a mutually recursive
  172. -- group. Only afer a round of simplification are they unravelled.
  173. , not opt_NoDebugOutput
  174. , showLintWarnings pass
  175. = log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
  176. (banner "warnings" $$ Err.pprMessageBag warns)
  177. | otherwise = return ()
  178. where
  179. banner string = ptext (sLit "*** Core Lint") <+> text string
  180. <+> ptext (sLit ": in result of") <+> ppr pass
  181. <+> ptext (sLit "***")
  182. showLintWarnings :: CoreToDo -> Bool
  183. -- Disable Lint warnings on the first simplifier pass, because
  184. -- there may be some INLINE knots still tied, which is tiresomely noisy
  185. showLintWarnings (CoreDoSimplify _ (SimplMode { sm_phase = InitialPhase })) = False
  186. showLintWarnings _ = True
  187. \end{code}
  188. %************************************************************************
  189. %* *
  190. The CoreToDo type and related types
  191. Abstraction of core-to-core passes to run.
  192. %* *
  193. %************************************************************************
  194. \begin{code}
  195. data CoreToDo -- These are diff core-to-core passes,
  196. -- which may be invoked in any order,
  197. -- as many times as you like.
  198. = CoreDoSimplify -- The core-to-core simplifier.
  199. Int -- Max iterations
  200. SimplifierMode
  201. | CoreDoPluginPass String PluginPass
  202. | CoreDoFloatInwards
  203. | CoreDoFloatOutwards FloatOutSwitches
  204. | CoreLiberateCase
  205. | CoreDoPrintCore
  206. | CoreDoStaticArgs
  207. | CoreDoStrictness
  208. | CoreDoWorkerWrapper
  209. | CoreDoSpecialising
  210. | CoreDoSpecConstr
  211. | CoreCSE
  212. | CoreDoRuleCheck CompilerPhase String -- Check for non-application of rules
  213. -- matching this string
  214. | CoreDoVectorisation
  215. | CoreDoNothing -- Useful when building up
  216. | CoreDoPasses [CoreToDo] -- lists of these things
  217. | CoreDesugar -- Right after desugaring, no simple optimisation yet!
  218. | CoreDesugarOpt -- CoreDesugarXXX: Not strictly a core-to-core pass, but produces
  219. -- Core output, and hence useful to pass to endPass
  220. | CoreTidy
  221. | CorePrep
  222. \end{code}
  223. \begin{code}
  224. coreDumpFlag :: CoreToDo -> Maybe DynFlag
  225. coreDumpFlag (CoreDoSimplify {}) = Just Opt_D_dump_simpl_phases
  226. coreDumpFlag (CoreDoPluginPass {}) = Just Opt_D_dump_core_pipeline
  227. coreDumpFlag CoreDoFloatInwards = Just Opt_D_verbose_core2core
  228. coreDumpFlag (CoreDoFloatOutwards {}) = Just Opt_D_verbose_core2core
  229. coreDumpFlag CoreLiberateCase = Just Opt_D_verbose_core2core
  230. coreDumpFlag CoreDoStaticArgs = Just Opt_D_verbose_core2core
  231. coreDumpFlag CoreDoStrictness = Just Opt_D_dump_stranal
  232. coreDumpFlag CoreDoWorkerWrapper = Just Opt_D_dump_worker_wrapper
  233. coreDumpFlag CoreDoSpecialising = Just Opt_D_dump_spec
  234. coreDumpFlag CoreDoSpecConstr = Just Opt_D_dump_spec
  235. coreDumpFlag CoreCSE = Just Opt_D_dump_cse
  236. coreDumpFlag CoreDoVectorisation = Just Opt_D_dump_vect
  237. coreDumpFlag CoreDesugar = Just Opt_D_dump_ds
  238. coreDumpFlag CoreDesugarOpt = Just Opt_D_dump_ds
  239. coreDumpFlag CoreTidy = Just Opt_D_dump_simpl
  240. coreDumpFlag CorePrep = Just Opt_D_dump_prep
  241. coreDumpFlag CoreDoPrintCore = Nothing
  242. coreDumpFlag (CoreDoRuleCheck {}) = Nothing
  243. coreDumpFlag CoreDoNothing = Nothing
  244. coreDumpFlag (CoreDoPasses {}) = Nothing
  245. instance Outputable CoreToDo where
  246. ppr (CoreDoSimplify _ _) = ptext (sLit "Simplifier")
  247. ppr (CoreDoPluginPass s _) = ptext (sLit "Core plugin: ") <+> text s
  248. ppr CoreDoFloatInwards = ptext (sLit "Float inwards")
  249. ppr (CoreDoFloatOutwards f) = ptext (sLit "Float out") <> parens (ppr f)
  250. ppr CoreLiberateCase = ptext (sLit "Liberate case")
  251. ppr CoreDoStaticArgs = ptext (sLit "Static argument")
  252. ppr CoreDoStrictness = ptext (sLit "Demand analysis")
  253. ppr CoreDoWorkerWrapper = ptext (sLit "Worker Wrapper binds")
  254. ppr CoreDoSpecialising = ptext (sLit "Specialise")
  255. ppr CoreDoSpecConstr = ptext (sLit "SpecConstr")
  256. ppr CoreCSE = ptext (sLit "Common sub-expression")
  257. ppr CoreDoVectorisation = ptext (sLit "Vectorisation")
  258. ppr CoreDesugar = ptext (sLit "Desugar (before optimization)")
  259. ppr CoreDesugarOpt = ptext (sLit "Desugar (after optimization)")
  260. ppr CoreTidy = ptext (sLit "Tidy Core")
  261. ppr CorePrep = ptext (sLit "CorePrep")
  262. ppr CoreDoPrintCore = ptext (sLit "Print core")
  263. ppr (CoreDoRuleCheck {}) = ptext (sLit "Rule check")
  264. ppr CoreDoNothing = ptext (sLit "CoreDoNothing")
  265. ppr (CoreDoPasses {}) = ptext (sLit "CoreDoPasses")
  266. pprPassDetails :: CoreToDo -> SDoc
  267. pprPassDetails (CoreDoSimplify n md) = vcat [ ptext (sLit "Max iterations =") <+> int n
  268. , ppr md ]
  269. pprPassDetails _ = empty
  270. \end{code}
  271. \begin{code}
  272. data SimplifierMode -- See comments in SimplMonad
  273. = SimplMode
  274. { sm_names :: [String] -- Name(s) of the phase
  275. , sm_phase :: CompilerPhase
  276. , sm_rules :: Bool -- Whether RULES are enabled
  277. , sm_inline :: Bool -- Whether inlining is enabled
  278. , sm_case_case :: Bool -- Whether case-of-case is enabled
  279. , sm_eta_expand :: Bool -- Whether eta-expansion is enabled
  280. }
  281. instance Outputable SimplifierMode where
  282. ppr (SimplMode { sm_phase = p, sm_names = ss
  283. , sm_rules = r, sm_inline = i
  284. , sm_eta_expand = eta, sm_case_case = cc })
  285. = ptext (sLit "SimplMode") <+> braces (
  286. sep [ ptext (sLit "Phase =") <+> ppr p <+>
  287. brackets (text (concat $ intersperse "," ss)) <> comma
  288. , pp_flag i (sLit "inline") <> comma
  289. , pp_flag r (sLit "rules") <> comma
  290. , pp_flag eta (sLit "eta-expand") <> comma
  291. , pp_flag cc (sLit "case-of-case") ])
  292. where
  293. pp_flag f s = ppUnless f (ptext (sLit "no")) <+> ptext s
  294. \end{code}
  295. \begin{code}
  296. data FloatOutSwitches = FloatOutSwitches {
  297. floatOutLambdas :: Maybe Int, -- ^ Just n <=> float lambdas to top level, if
  298. -- doing so will abstract over n or fewer
  299. -- value variables
  300. -- Nothing <=> float all lambdas to top level,
  301. -- regardless of how many free variables
  302. -- Just 0 is the vanilla case: float a lambda
  303. -- iff it has no free vars
  304. floatOutConstants :: Bool, -- ^ True <=> float constants to top level,
  305. -- even if they do not escape a lambda
  306. floatOutPartialApplications :: Bool -- ^ True <=> float out partial applications
  307. -- based on arity information.
  308. }
  309. instance Outputable FloatOutSwitches where
  310. ppr = pprFloatOutSwitches
  311. pprFloatOutSwitches :: FloatOutSwitches -> SDoc
  312. pprFloatOutSwitches sw
  313. = ptext (sLit "FOS") <+> (braces $
  314. sep $ punctuate comma $
  315. [ ptext (sLit "Lam =") <+> ppr (floatOutLambdas sw)
  316. , ptext (sLit "Consts =") <+> ppr (floatOutConstants sw)
  317. , ptext (sLit "PAPs =") <+> ppr (floatOutPartialApplications sw) ])
  318. -- The core-to-core pass ordering is derived from the DynFlags:
  319. runWhen :: Bool -> CoreToDo -> CoreToDo
  320. runWhen True do_this = do_this
  321. runWhen False _ = CoreDoNothing
  322. runMaybe :: Maybe a -> (a -> CoreToDo) -> CoreToDo
  323. runMaybe (Just x) f = f x
  324. runMaybe Nothing _ = CoreDoNothing
  325. dumpSimplPhase :: DynFlags -> SimplifierMode -> Bool
  326. dumpSimplPhase dflags mode
  327. | Just spec_string <- shouldDumpSimplPhase dflags
  328. = match_spec spec_string
  329. | otherwise
  330. = dopt Opt_D_verbose_core2core dflags
  331. where
  332. match_spec :: String -> Bool
  333. match_spec spec_string
  334. = or $ map (and . map match . split ':')
  335. $ split ',' spec_string
  336. match :: String -> Bool
  337. match "" = True
  338. match s = case reads s of
  339. [(n,"")] -> phase_num n
  340. _ -> phase_name s
  341. phase_num :: Int -> Bool
  342. phase_num n = case sm_phase mode of
  343. Phase k -> n == k
  344. _ -> False
  345. phase_name :: String -> Bool
  346. phase_name s = s `elem` sm_names mode
  347. \end{code}
  348. Note [RULEs enabled in SimplGently]
  349. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  350. RULES are enabled when doing "gentle" simplification. Two reasons:
  351. * We really want the class-op cancellation to happen:
  352. op (df d1 d2) --> $cop3 d1 d2
  353. because this breaks the mutual recursion between 'op' and 'df'
  354. * I wanted the RULE
  355. lift String ===> ...
  356. to work in Template Haskell when simplifying
  357. splices, so we get simpler code for literal strings
  358. But watch out: list fusion can prevent floating. So use phase control
  359. to switch off those rules until after floating.
  360. %************************************************************************
  361. %* *
  362. Types for Plugins
  363. %* *
  364. %************************************************************************
  365. \begin{code}
  366. -- | Command line options gathered from the -PModule.Name:stuff syntax are given to you as this type
  367. type CommandLineOption = String
  368. -- | 'Plugin' is the core compiler plugin data type. Try to avoid
  369. -- constructing one of these directly, and just modify some fields of
  370. -- 'defaultPlugin' instead: this is to try and preserve source-code
  371. -- compatability when we add fields to this.
  372. --
  373. -- Nonetheless, this API is preliminary and highly likely to change in the future.
  374. data Plugin = Plugin {
  375. installCoreToDos :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
  376. -- ^ Modify the Core pipeline that will be used for compilation.
  377. -- This is called as the Core pipeline is built for every module
  378. -- being compiled, and plugins get the opportunity to modify
  379. -- the pipeline in a nondeterministic order.
  380. }
  381. -- | Default plugin: does nothing at all! For compatability reasons you should base all your
  382. -- plugin definitions on this default value.
  383. defaultPlugin :: Plugin
  384. defaultPlugin = Plugin {
  385. installCoreToDos = const return
  386. }
  387. -- | A description of the plugin pass itself
  388. type PluginPass = ModGuts -> CoreM ModGuts
  389. bindsOnlyPass :: (CoreProgram -> CoreM CoreProgram) -> ModGuts -> CoreM ModGuts
  390. bindsOnlyPass pass guts
  391. = do { binds' <- pass (mg_binds guts)
  392. ; return (guts { mg_binds = binds' }) }
  393. \end{code}
  394. %************************************************************************
  395. %* *
  396. Counting and logging
  397. %* *
  398. %************************************************************************
  399. \begin{code}
  400. verboseSimplStats :: Bool
  401. verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
  402. zeroSimplCount :: DynFlags -> SimplCount
  403. isZeroSimplCount :: SimplCount -> Bool
  404. hasDetailedCounts :: SimplCount -> Bool
  405. pprSimplCount :: SimplCount -> SDoc
  406. doSimplTick :: DynFlags -> Tick -> SimplCount -> SimplCount
  407. doFreeSimplTick :: Tick -> SimplCount -> SimplCount
  408. plusSimplCount :: SimplCount -> SimplCount -> SimplCount
  409. \end{code}
  410. \begin{code}
  411. data SimplCount
  412. = VerySimplCount !Int -- Used when don't want detailed stats
  413. | SimplCount {
  414. ticks :: !Int, -- Total ticks
  415. details :: !TickCounts, -- How many of each type
  416. n_log :: !Int, -- N
  417. log1 :: [Tick], -- Last N events; <= opt_HistorySize,
  418. -- most recent first
  419. log2 :: [Tick] -- Last opt_HistorySize events before that
  420. -- Having log1, log2 lets us accumulate the
  421. -- recent history reasonably efficiently
  422. }
  423. type TickCounts = Map Tick Int
  424. simplCountN :: SimplCount -> Int
  425. simplCountN (VerySimplCount n) = n
  426. simplCountN (SimplCount { ticks = n }) = n
  427. zeroSimplCount dflags
  428. -- This is where we decide whether to do
  429. -- the VerySimpl version or the full-stats version
  430. | dopt Opt_D_dump_simpl_stats dflags
  431. = SimplCount {ticks = 0, details = Map.empty,
  432. n_log = 0, log1 = [], log2 = []}
  433. | otherwise
  434. = VerySimplCount 0
  435. isZeroSimplCount (VerySimplCount n) = n==0
  436. isZeroSimplCount (SimplCount { ticks = n }) = n==0
  437. hasDetailedCounts (VerySimplCount {}) = False
  438. hasDetailedCounts (SimplCount {}) = True
  439. doFreeSimplTick tick sc@SimplCount { details = dts }
  440. = sc { details = dts `addTick` tick }
  441. doFreeSimplTick _ sc = sc
  442. doSimplTick dflags tick
  443. sc@(SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1 })
  444. | nl >= historySize dflags = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
  445. | otherwise = sc1 { n_log = nl+1, log1 = tick : l1 }
  446. where
  447. sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
  448. doSimplTick _ _ (VerySimplCount n) = VerySimplCount (n+1)
  449. -- Don't use Map.unionWith because that's lazy, and we want to
  450. -- be pretty strict here!
  451. addTick :: TickCounts -> Tick -> TickCounts
  452. addTick fm tick = case Map.lookup tick fm of
  453. Nothing -> Map.insert tick 1 fm
  454. Just n -> n1 `seq` Map.insert tick n1 fm
  455. where
  456. n1 = n+1
  457. plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
  458. sc2@(SimplCount { ticks = tks2, details = dts2 })
  459. = log_base { ticks = tks1 + tks2, details = Map.unionWith (+) dts1 dts2 }
  460. where
  461. -- A hackish way of getting recent log info
  462. log_base | null (log1 sc2) = sc1 -- Nothing at all in sc2
  463. | null (log2 sc2) = sc2 { log2 = log1 sc1 }
  464. | otherwise = sc2
  465. plusSimplCount (VerySimplCount n) (VerySimplCount m) = VerySimplCount (n+m)
  466. plusSimplCount _ _ = panic "plusSimplCount"
  467. -- We use one or the other consistently
  468. pprSimplCount (VerySimplCount n) = ptext (sLit "Total ticks:") <+> int n
  469. pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
  470. = vcat [ptext (sLit "Total ticks: ") <+> int tks,
  471. blankLine,
  472. pprTickCounts dts,
  473. if verboseSimplStats then
  474. vcat [blankLine,
  475. ptext (sLit "Log (most recent first)"),
  476. nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
  477. else empty
  478. ]
  479. pprTickCounts :: Map Tick Int -> SDoc
  480. pprTickCounts counts
  481. = vcat (map pprTickGroup groups)
  482. where
  483. groups :: [[(Tick,Int)]] -- Each group shares a comon tag
  484. -- toList returns common tags adjacent
  485. groups = runs same_tag (Map.toList counts)
  486. same_tag (tick1,_) (tick2,_) = tickToTag tick1 == tickToTag tick2
  487. pprTickGroup :: [(Tick, Int)] -> SDoc
  488. pprTickGroup group@((tick1,_):_)
  489. = hang (int (sum [n | (_,n) <- group]) <+> text (tickString tick1))
  490. 2 (vcat [ int n <+> pprTickCts tick
  491. -- flip as we want largest first
  492. | (tick,n) <- sortBy (flip (comparing snd)) group])
  493. pprTickGroup [] = panic "pprTickGroup"
  494. \end{code}
  495. \begin{code}
  496. data Tick
  497. = PreInlineUnconditionally Id
  498. | PostInlineUnconditionally Id
  499. | UnfoldingDone Id
  500. | RuleFired FastString -- Rule name
  501. | LetFloatFromLet
  502. | EtaExpansion Id -- LHS binder
  503. | EtaReduction Id -- Binder on outer lambda
  504. | BetaReduction Id -- Lambda binder
  505. | CaseOfCase Id -- Bndr on *inner* case
  506. | KnownBranch Id -- Case binder
  507. | CaseMerge Id -- Binder on outer case
  508. | AltMerge Id -- Case binder
  509. | CaseElim Id -- Case binder
  510. | CaseIdentity Id -- Case binder
  511. | FillInCaseDefault Id -- Case binder
  512. | BottomFound
  513. | SimplifierDone -- Ticked at each iteration of the simplifier
  514. instance Outputable Tick where
  515. ppr tick = text (tickString tick) <+> pprTickCts tick
  516. instance Eq Tick where
  517. a == b = case a `cmpTick` b of
  518. EQ -> True
  519. _ -> False
  520. instance Ord Tick where
  521. compare = cmpTick
  522. tickToTag :: Tick -> Int
  523. tickToTag (PreInlineUnconditionally _) = 0
  524. tickToTag (PostInlineUnconditionally _) = 1
  525. tickToTag (UnfoldingDone _) = 2
  526. tickToTag (RuleFired _) = 3
  527. tickToTag LetFloatFromLet = 4
  528. tickToTag (EtaExpansion _) = 5
  529. tickToTag (EtaReduction _) = 6
  530. tickToTag (BetaReduction _) = 7
  531. tickToTag (CaseOfCase _) = 8
  532. tickToTag (KnownBranch _) = 9
  533. tickToTag (CaseMerge _) = 10
  534. tickToTag (CaseElim _) = 11
  535. tickToTag (CaseIdentity _) = 12
  536. tickToTag (FillInCaseDefault _) = 13
  537. tickToTag BottomFound = 14
  538. tickToTag SimplifierDone = 16
  539. tickToTag (AltMerge _) = 17
  540. tickString :: Tick -> String
  541. tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
  542. tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
  543. tickString (UnfoldingDone _) = "UnfoldingDone"
  544. tickString (RuleFired _) = "RuleFired"
  545. tickString LetFloatFromLet = "LetFloatFromLet"
  546. tickString (EtaExpansion _) = "EtaExpansion"
  547. tickString (EtaReduction _) = "EtaReduction"
  548. tickString (BetaReduction _) = "BetaReduction"
  549. tickString (CaseOfCase _) = "CaseOfCase"
  550. tickString (KnownBranch _) = "KnownBranch"
  551. tickString (CaseMerge _) = "CaseMerge"
  552. tickString (AltMerge _) = "AltMerge"
  553. tickString (CaseElim _) = "CaseElim"
  554. tickString (CaseIdentity _) = "CaseIdentity"
  555. tickString (FillInCaseDefault _) = "FillInCaseDefault"
  556. tickString BottomFound = "BottomFound"
  557. tickString SimplifierDone = "SimplifierDone"
  558. pprTickCts :: Tick -> SDoc
  559. pprTickCts (PreInlineUnconditionally v) = ppr v
  560. pprTickCts (PostInlineUnconditionally v)= ppr v
  561. pprTickCts (UnfoldingDone v) = ppr v
  562. pprTickCts (RuleFired v) = ppr v
  563. pprTickCts LetFloatFromLet = empty
  564. pprTickCts (EtaExpansion v) = ppr v
  565. pprTickCts (EtaReduction v) = ppr v
  566. pprTickCts (BetaReduction v) = ppr v
  567. pprTickCts (CaseOfCase v) = ppr v
  568. pprTickCts (KnownBranch v) = ppr v
  569. pprTickCts (CaseMerge v) = ppr v
  570. pprTickCts (AltMerge v) = ppr v
  571. pprTickCts (CaseElim v) = ppr v
  572. pprTickCts (CaseIdentity v) = ppr v
  573. pprTickCts (FillInCaseDefault v) = ppr v
  574. pprTickCts _ = empty
  575. cmpTick :: Tick -> Tick -> Ordering
  576. cmpTick a b = case (tickToTag a `compare` tickToTag b) of
  577. GT -> GT
  578. EQ -> cmpEqTick a b
  579. LT -> LT
  580. cmpEqTick :: Tick -> Tick -> Ordering
  581. cmpEqTick (PreInlineUnconditionally a) (PreInlineUnconditionally b) = a `compare` b
  582. cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b) = a `compare` b
  583. cmpEqTick (UnfoldingDone a) (UnfoldingDone b) = a `compare` b
  584. cmpEqTick (RuleFired a) (RuleFired b) = a `compare` b
  585. cmpEqTick (EtaExpansion a) (EtaExpansion b) = a `compare` b
  586. cmpEqTick (EtaReduction a) (EtaReduction b) = a `compare` b
  587. cmpEqTick (BetaReduction a) (BetaReduction b) = a `compare` b
  588. cmpEqTick (CaseOfCase a) (CaseOfCase b) = a `compare` b
  589. cmpEqTick (KnownBranch a) (KnownBranch b) = a `compare` b
  590. cmpEqTick (CaseMerge a) (CaseMerge b) = a `compare` b
  591. cmpEqTick (AltMerge a) (AltMerge b) = a `compare` b
  592. cmpEqTick (CaseElim a) (CaseElim b) = a `compare` b
  593. cmpEqTick (CaseIdentity a) (CaseIdentity b) = a `compare` b
  594. cmpEqTick (FillInCaseDefault a) (FillInCaseDefault b) = a `compare` b
  595. cmpEqTick _ _ = EQ
  596. \end{code}
  597. %************************************************************************
  598. %* *
  599. Monad and carried data structure definitions
  600. %* *
  601. %************************************************************************
  602. \begin{code}
  603. newtype CoreState = CoreState {
  604. cs_uniq_supply :: UniqSupply
  605. }
  606. data CoreReader = CoreReader {
  607. cr_hsc_env :: HscEnv,
  608. cr_rule_base :: RuleBase,
  609. cr_module :: Module,
  610. cr_globals :: ((Bool, [String]),
  611. #ifdef GHCI
  612. (MVar PersistentLinkerState, Bool))
  613. #else
  614. ())
  615. #endif
  616. }
  617. data CoreWriter = CoreWriter {
  618. cw_simpl_count :: SimplCount
  619. }
  620. emptyWriter :: DynFlags -> CoreWriter
  621. emptyWriter dflags = CoreWriter {
  622. cw_simpl_count = zeroSimplCount dflags
  623. }
  624. plusWriter :: CoreWriter -> CoreWriter -> CoreWriter
  625. plusWriter w1 w2 = CoreWriter {
  626. cw_simpl_count = (cw_simpl_count w1) `plusSimplCount` (cw_simpl_count w2)
  627. }
  628. type CoreIOEnv = IOEnv CoreReader
  629. -- | The monad used by Core-to-Core passes to access common state, register simplification
  630. -- statistics and so on
  631. newtype CoreM a = CoreM { unCoreM :: CoreState -> CoreIOEnv (a, CoreState, CoreWriter) }
  632. instance Functor CoreM where
  633. fmap f ma = do
  634. a <- ma
  635. return (f a)
  636. instance Monad CoreM where
  637. return x = CoreM (\s -> nop s x)
  638. mx >>= f = CoreM $ \s -> do
  639. (x, s', w1) <- unCoreM mx s
  640. (y, s'', w2) <- unCoreM (f x) s'
  641. return (y, s'', w1 `plusWriter` w2)
  642. instance Applicative CoreM where
  643. pure = return
  644. (<*>) = ap
  645. -- For use if the user has imported Control.Monad.Error from MTL
  646. -- Requires UndecidableInstances
  647. instance MonadPlus IO => MonadPlus CoreM where
  648. mzero = CoreM (const mzero)
  649. m `mplus` n = CoreM (\rs -> unCoreM m rs `mplus` unCoreM n rs)
  650. instance MonadUnique CoreM where
  651. getUniqueSupplyM = do
  652. us <- getS cs_uniq_supply
  653. let (us1, us2) = splitUniqSupply us
  654. modifyS (\s -> s { cs_uniq_supply = us2 })
  655. return us1
  656. runCoreM :: HscEnv
  657. -> RuleBase
  658. -> UniqSupply
  659. -> Module
  660. -> CoreM a
  661. -> IO (a, SimplCount)
  662. runCoreM hsc_env rule_base us mod m = do
  663. glbls <- liftM2 (,) saveStaticFlagGlobals saveLinkerGlobals
  664. liftM extract $ runIOEnv (reader glbls) $ unCoreM m state
  665. where
  666. reader glbls = CoreReader {
  667. cr_hsc_env = hsc_env,
  668. cr_rule_base = rule_base,
  669. cr_module = mod,
  670. cr_globals = glbls
  671. }
  672. state = CoreState {
  673. cs_uniq_supply = us
  674. }
  675. extract :: (a, CoreState, CoreWriter) -> (a, SimplCount)
  676. extract (value, _, writer) = (value, cw_simpl_count writer)
  677. \end{code}
  678. %************************************************************************
  679. %* *
  680. Core combinators, not exported
  681. %* *
  682. %************************************************************************
  683. \begin{code}
  684. nop :: CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
  685. nop s x = do
  686. r <- getEnv
  687. return (x, s, emptyWriter $ (hsc_dflags . cr_hsc_env) r)
  688. read :: (CoreReader -> a) -> CoreM a
  689. read f = CoreM (\s -> getEnv >>= (\r -> nop s (f r)))
  690. getS :: (CoreState -> a) -> CoreM a
  691. getS f = CoreM (\s -> nop s (f s))
  692. modifyS :: (CoreState -> CoreState) -> CoreM ()
  693. modifyS f = CoreM (\s -> nop (f s) ())
  694. write :: CoreWriter -> CoreM ()
  695. write w = CoreM (\s -> return ((), s, w))
  696. \end{code}
  697. \subsection{Lifting IO into the monad}
  698. \begin{code}
  699. -- | Lift an 'IOEnv' operation into 'CoreM'
  700. liftIOEnv :: CoreIOEnv a -> CoreM a
  701. liftIOEnv mx = CoreM (\s -> mx >>= (\x -> nop s x))
  702. instance MonadIO CoreM where
  703. liftIO = liftIOEnv . IOEnv.liftIO
  704. -- | Lift an 'IO' operation into 'CoreM' while consuming its 'SimplCount'
  705. liftIOWithCount :: IO (SimplCount, a) -> CoreM a
  706. liftIOWithCount what = liftIO what >>= (\(count, x) -> addSimplCount count >> return x)
  707. \end{code}
  708. %************************************************************************
  709. %* *
  710. Reader, writer and state accessors
  711. %* *
  712. %************************************************************************
  713. \begin{code}
  714. getHscEnv :: CoreM HscEnv
  715. getHscEnv = read cr_hsc_env
  716. getRuleBase :: CoreM RuleBase
  717. getRuleBase = read cr_rule_base
  718. getModule :: CoreM Module
  719. getModule = read cr_module
  720. addSimplCount :: SimplCount -> CoreM ()
  721. addSimplCount count = write (CoreWriter { cw_simpl_count = count })
  722. -- Convenience accessors for useful fields of HscEnv
  723. instance HasDynFlags CoreM where
  724. getDynFlags = fmap hsc_dflags getHscEnv
  725. -- | The original name cache is the current mapping from 'Module' and
  726. -- 'OccName' to a compiler-wide unique 'Name'
  727. getOrigNameCache :: CoreM OrigNameCache
  728. getOrigNameCache = do
  729. nameCacheRef <- fmap hsc_NC getHscEnv
  730. liftIO $ fmap nsNames $ readIORef nameCacheRef
  731. \end{code}
  732. %************************************************************************
  733. %* *
  734. Initializing globals
  735. %* *
  736. %************************************************************************
  737. This is a rather annoying function. When a plugin is loaded, it currently
  738. gets linked against a *newly loaded* copy of the GHC package. This would
  739. not be a problem, except that the new copy has its own mutable state
  740. that is not shared with that state that has already been initialized by
  741. the original GHC package.
  742. This leads to loaded plugins calling GHC code which pokes the static flags,
  743. and then dying with a panic because the static flags *it* sees are uninitialized.
  744. There are two possible solutions:
  745. 1. Export the symbols from the GHC executable from the GHC library and link
  746. against this existing copy rather than a new copy of the GHC library
  747. 2. Carefully ensure that the global state in the two copies of the GHC
  748. library matches
  749. I tried 1. and it *almost* works (and speeds up plugin load times!) except
  750. on Windows. On Windows the GHC library tends to export more than 65536 symbols
  751. (see #5292) which overflows the limit of what we can export from the EXE and
  752. causes breakage.
  753. (Note that if the GHC exeecutable was dynamically linked this wouldn't be a problem,
  754. because we could share the GHC library it links to.)
  755. We are going to try 2. instead. Unfortunately, this means that every plugin
  756. will have to say `reinitializeGlobals` before it does anything, but never mind.
  757. I've threaded the cr_globals through CoreM rather than giving them as an
  758. argument to the plugin function so that we can turn this function into
  759. (return ()) without breaking any plugins when we eventually get 1. working.
  760. \begin{code}
  761. reinitializeGlobals :: CoreM ()
  762. reinitializeGlobals = do
  763. (sf_globals, linker_globals) <- read cr_globals
  764. liftIO $ restoreStaticFlagGlobals sf_globals
  765. liftIO $ restoreLinkerGlobals linker_globals
  766. \end{code}
  767. %************************************************************************
  768. %* *
  769. Dealing with annotations
  770. %* *
  771. %************************************************************************
  772. \begin{code}
  773. -- | Get all annotations of a given type. This happens lazily, that is
  774. -- no deserialization will take place until the [a] is actually demanded and
  775. -- the [a] can also be empty (the UniqFM is not filtered).
  776. --
  777. -- This should be done once at the start of a Core-to-Core pass that uses
  778. -- annotations.
  779. --
  780. -- See Note [Annotations]
  781. getAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM [a])
  782. getAnnotations deserialize guts = do
  783. hsc_env <- getHscEnv
  784. ann_env <- liftIO $ prepareAnnotations hsc_env (Just guts)
  785. return (deserializeAnns deserialize ann_env)
  786. -- | Get at most one annotation of a given type per Unique.
  787. getFirstAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM a)
  788. getFirstAnnotations deserialize guts
  789. = liftM (mapUFM head . filterUFM (not . null))
  790. $ getAnnotations deserialize guts
  791. \end{code}
  792. Note [Annotations]
  793. ~~~~~~~~~~~~~~~~~~
  794. A Core-to-Core pass that wants to make use of annotations calls
  795. getAnnotations or getFirstAnnotations at the beginning to obtain a UniqFM with
  796. annotations of a specific type. This produces all annotations from interface
  797. files read so far. However, annotations from interface files read during the
  798. pass will not be visible until getAnnotations is called again. This is similar
  799. to how rules work and probably isn't too bad.
  800. The current implementation could be optimised a bit: when looking up
  801. annotations for a thing from the HomePackageTable, we could search directly in
  802. the module where the thing is defined rather than building one UniqFM which
  803. contains all annotations we know of. This would work because annotations can
  804. only be given to things defined in the same module. However, since we would
  805. only want to deserialise every annotation once, we would have to build a cache
  806. for every module in the HTP. In the end, it's probably not worth it as long as
  807. we aren't using annotations heavily.
  808. %************************************************************************
  809. %* *
  810. Direct screen output
  811. %* *
  812. %************************************************************************
  813. \begin{code}
  814. msg :: (DynFlags -> SDoc -> IO ()) -> SDoc -> CoreM ()
  815. msg how doc = do
  816. dflags <- getDynFlags
  817. liftIO $ how dflags doc
  818. -- | Output a String message to the screen
  819. putMsgS :: String -> CoreM ()
  820. putMsgS = putMsg . text
  821. -- | Output a message to the screen
  822. putMsg :: SDoc -> CoreM ()
  823. putMsg = msg Err.putMsg
  824. -- | Output a string error to the screen
  825. errorMsgS :: String -> CoreM ()
  826. errorMsgS = errorMsg . text
  827. -- | Output an error to the screen
  828. errorMsg :: SDoc -> CoreM ()
  829. errorMsg = msg Err.errorMsg
  830. -- | Output a fatal string error to the screen. Note this does not by itself cause the compiler to die
  831. fatalErrorMsgS :: String -> CoreM ()
  832. fatalErrorMsgS = fatalErrorMsg . text
  833. -- | Output a fatal error to the screen. Note this does not by itself cause the compiler to die
  834. fatalErrorMsg :: SDoc -> CoreM ()
  835. fatalErrorMsg = msg Err.fatalErrorMsg
  836. -- | Output a string debugging message at verbosity level of @-v@ or higher
  837. debugTraceMsgS :: String -> CoreM ()
  838. debugTraceMsgS = debugTraceMsg . text
  839. -- | Outputs a debugging message at verbosity level of @-v@ or higher
  840. debugTraceMsg :: SDoc -> CoreM ()
  841. debugTraceMsg = msg (flip Err.debugTraceMsg 3)
  842. -- | Show some labelled 'SDoc' if a particular flag is set or at a verbosity level of @-v -ddump-most@ or higher
  843. dumpIfSet_dyn :: DynFlag -> String -> SDoc -> CoreM ()
  844. dumpIfSet_dyn flag str = msg (\dflags -> Err.dumpIfSet_dyn dflags flag str)
  845. \end{code}
  846. %************************************************************************
  847. %* *
  848. Finding TyThings
  849. %* *
  850. %************************************************************************
  851. \begin{code}
  852. instance MonadThings CoreM where
  853. lookupThing name = do
  854. hsc_env <- getHscEnv
  855. liftIO $ initTcForLookup hsc_env (tcLookupGlobal name)
  856. \end{code}
  857. %************************************************************************
  858. %* *
  859. Template Haskell interoperability
  860. %* *
  861. %************************************************************************
  862. \begin{code}
  863. #ifdef GHCI
  864. -- | Attempt to convert a Template Haskell name to one that GHC can
  865. -- understand. Original TH names such as those you get when you use
  866. -- the @'foo@ syntax will be translated to their equivalent GHC name
  867. -- exactly. Qualified or unqualifed TH names will be dynamically bound
  868. -- to names in the module being compiled, if possible. Exact TH names
  869. -- will be bound to the name they represent, exactly.
  870. thNameToGhcName :: TH.Name -> CoreM (Maybe Name)
  871. thNameToGhcName th_name = do
  872. hsc_env <- getHscEnv
  873. liftIO $ initTcForLookup hsc_env (lookupThName_maybe th_name)
  874. #endif
  875. \end{code}