PageRenderTime 53ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/simplCore/CoreMonad.lhs

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