PageRenderTime 35ms CodeModel.GetById 7ms RepoModel.GetById 1ms app.codeStats 0ms

/ghc-7.0.4/compiler/simplCore/FloatOut.lhs

http://picorec.googlecode.com/
Haskell | 487 lines | 344 code | 97 blank | 46 comment | 13 complexity | 333bbc6e0814fc540b66fbe259e200d7 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause
  1. %
  2. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  3. %
  4. \section[FloatOut]{Float bindings outwards (towards the top level)}
  5. ``Long-distance'' floating of bindings towards the top level.
  6. \begin{code}
  7. module FloatOut ( floatOutwards ) where
  8. import CoreSyn
  9. import CoreUtils
  10. import CoreArity ( etaExpand )
  11. import CoreMonad ( FloatOutSwitches(..) )
  12. import DynFlags ( DynFlags, DynFlag(..) )
  13. import ErrUtils ( dumpIfSet_dyn )
  14. import CostCentre ( dupifyCC, CostCentre )
  15. import Id ( Id, idType, idArity, isBottomingId )
  16. import Type ( isUnLiftedType )
  17. import SetLevels ( Level(..), LevelledExpr, LevelledBind,
  18. setLevels, isTopLvl )
  19. import UniqSupply ( UniqSupply )
  20. import Bag
  21. import Util
  22. import Maybes
  23. import UniqFM
  24. import Outputable
  25. import FastString
  26. \end{code}
  27. -----------------
  28. Overall game plan
  29. -----------------
  30. The Big Main Idea is:
  31. To float out sub-expressions that can thereby get outside
  32. a non-one-shot value lambda, and hence may be shared.
  33. To achieve this we may need to do two thing:
  34. a) Let-bind the sub-expression:
  35. f (g x) ==> let lvl = f (g x) in lvl
  36. Now we can float the binding for 'lvl'.
  37. b) More than that, we may need to abstract wrt a type variable
  38. \x -> ... /\a -> let v = ...a... in ....
  39. Here the binding for v mentions 'a' but not 'x'. So we
  40. abstract wrt 'a', to give this binding for 'v':
  41. vp = /\a -> ...a...
  42. v = vp a
  43. Now the binding for vp can float out unimpeded.
  44. I can't remember why this case seemed important enough to
  45. deal with, but I certainly found cases where important floats
  46. didn't happen if we did not abstract wrt tyvars.
  47. With this in mind we can also achieve another goal: lambda lifting.
  48. We can make an arbitrary (function) binding float to top level by
  49. abstracting wrt *all* local variables, not just type variables, leaving
  50. a binding that can be floated right to top level. Whether or not this
  51. happens is controlled by a flag.
  52. Random comments
  53. ~~~~~~~~~~~~~~~
  54. At the moment we never float a binding out to between two adjacent
  55. lambdas. For example:
  56. @
  57. \x y -> let t = x+x in ...
  58. ===>
  59. \x -> let t = x+x in \y -> ...
  60. @
  61. Reason: this is less efficient in the case where the original lambda
  62. is never partially applied.
  63. But there's a case I've seen where this might not be true. Consider:
  64. @
  65. elEm2 x ys
  66. = elem' x ys
  67. where
  68. elem' _ [] = False
  69. elem' x (y:ys) = x==y || elem' x ys
  70. @
  71. It turns out that this generates a subexpression of the form
  72. @
  73. \deq x ys -> let eq = eqFromEqDict deq in ...
  74. @
  75. vwhich might usefully be separated to
  76. @
  77. \deq -> let eq = eqFromEqDict deq in \xy -> ...
  78. @
  79. Well, maybe. We don't do this at the moment.
  80. %************************************************************************
  81. %* *
  82. \subsection[floatOutwards]{@floatOutwards@: let-floating interface function}
  83. %* *
  84. %************************************************************************
  85. \begin{code}
  86. floatOutwards :: FloatOutSwitches
  87. -> DynFlags
  88. -> UniqSupply
  89. -> [CoreBind] -> IO [CoreBind]
  90. floatOutwards float_sws dflags us pgm
  91. = do {
  92. let { annotated_w_levels = setLevels float_sws pgm us ;
  93. (fss, binds_s') = unzip (map floatTopBind annotated_w_levels)
  94. } ;
  95. dumpIfSet_dyn dflags Opt_D_verbose_core2core "Levels added:"
  96. (vcat (map ppr annotated_w_levels));
  97. let { (tlets, ntlets, lams) = get_stats (sum_stats fss) };
  98. dumpIfSet_dyn dflags Opt_D_dump_simpl_stats "FloatOut stats:"
  99. (hcat [ int tlets, ptext (sLit " Lets floated to top level; "),
  100. int ntlets, ptext (sLit " Lets floated elsewhere; from "),
  101. int lams, ptext (sLit " Lambda groups")]);
  102. return (concat binds_s')
  103. }
  104. floatTopBind :: LevelledBind -> (FloatStats, [CoreBind])
  105. floatTopBind bind
  106. = case (floatBind bind) of { (fs, floats) ->
  107. (fs, bagToList (flattenFloats floats)) }
  108. \end{code}
  109. %************************************************************************
  110. %* *
  111. \subsection[FloatOut-Bind]{Floating in a binding (the business end)}
  112. %* *
  113. %************************************************************************
  114. \begin{code}
  115. floatBind :: LevelledBind -> (FloatStats, FloatBinds)
  116. floatBind (NonRec (TB var level) rhs)
  117. = case (floatRhs level rhs) of { (fs, rhs_floats, rhs') ->
  118. -- A tiresome hack:
  119. -- see Note [Bottoming floats: eta expansion] in SetLevels
  120. let rhs'' | isBottomingId var = etaExpand (idArity var) rhs'
  121. | otherwise = rhs'
  122. in (fs, rhs_floats `plusFloats` unitFloat level (NonRec var rhs'')) }
  123. floatBind (Rec pairs)
  124. = case floatList do_pair pairs of { (fs, rhs_floats, new_pairs) ->
  125. -- NB: the rhs floats may contain references to the
  126. -- bound things. For example
  127. -- f = ...(let v = ...f... in b) ...
  128. if not (isTopLvl dest_lvl) then
  129. -- Find which bindings float out at least one lambda beyond this one
  130. -- These ones can't mention the binders, because they couldn't
  131. -- be escaping a major level if so.
  132. -- The ones that are not going further can join the letrec;
  133. -- they may not be mutually recursive but the occurrence analyser will
  134. -- find that out. In our example we make a Rec thus:
  135. -- v = ...f...
  136. -- f = ... b ...
  137. case (partitionByMajorLevel dest_lvl rhs_floats) of { (floats', heres) ->
  138. (fs, floats' `plusFloats` unitFloat dest_lvl
  139. (Rec (floatsToBindPairs heres new_pairs))) }
  140. else
  141. -- For top level, no need to partition; just make them all recursive
  142. -- (And the partition wouldn't work because they'd all end up in floats')
  143. (fs, unitFloat dest_lvl
  144. (Rec (floatsToBindPairs (flattenFloats rhs_floats) new_pairs))) }
  145. where
  146. (((TB _ dest_lvl), _) : _) = pairs
  147. do_pair (TB name level, rhs)
  148. = case (floatRhs level rhs) of { (fs, rhs_floats, rhs') ->
  149. (fs, rhs_floats, (name, rhs')) }
  150. ---------------
  151. floatList :: (a -> (FloatStats, FloatBinds, b)) -> [a] -> (FloatStats, FloatBinds, [b])
  152. floatList _ [] = (zeroStats, emptyFloats, [])
  153. floatList f (a:as) = case f a of { (fs_a, binds_a, b) ->
  154. case floatList f as of { (fs_as, binds_as, bs) ->
  155. (fs_a `add_stats` fs_as, binds_a `plusFloats` binds_as, b:bs) }}
  156. \end{code}
  157. %************************************************************************
  158. \subsection[FloatOut-Expr]{Floating in expressions}
  159. %* *
  160. %************************************************************************
  161. \begin{code}
  162. floatExpr, floatRhs, floatCaseAlt
  163. :: Level
  164. -> LevelledExpr
  165. -> (FloatStats, FloatBinds, CoreExpr)
  166. floatCaseAlt lvl arg -- Used rec rhss, and case-alternative rhss
  167. = case (floatExpr lvl arg) of { (fsa, floats, arg') ->
  168. case (partitionByMajorLevel lvl floats) of { (floats', heres) ->
  169. -- Dump bindings that aren't going to escape from a lambda;
  170. -- in particular, we must dump the ones that are bound by
  171. -- the rec or case alternative
  172. (fsa, floats', install heres arg') }}
  173. -----------------
  174. floatRhs lvl arg -- Used for nested non-rec rhss, and fn args
  175. -- See Note [Floating out of RHS]
  176. = floatExpr lvl arg
  177. -----------------
  178. floatExpr _ (Var v) = (zeroStats, emptyFloats, Var v)
  179. floatExpr _ (Type ty) = (zeroStats, emptyFloats, Type ty)
  180. floatExpr _ (Lit lit) = (zeroStats, emptyFloats, Lit lit)
  181. floatExpr lvl (App e a)
  182. = case (floatExpr lvl e) of { (fse, floats_e, e') ->
  183. case (floatRhs lvl a) of { (fsa, floats_a, a') ->
  184. (fse `add_stats` fsa, floats_e `plusFloats` floats_a, App e' a') }}
  185. floatExpr _ lam@(Lam _ _)
  186. = let
  187. (bndrs_w_lvls, body) = collectBinders lam
  188. bndrs = [b | TB b _ <- bndrs_w_lvls]
  189. lvls = [l | TB _ l <- bndrs_w_lvls]
  190. -- For the all-tyvar case we are prepared to pull
  191. -- the lets out, to implement the float-out-of-big-lambda
  192. -- transform; but otherwise we only float bindings that are
  193. -- going to escape a value lambda.
  194. -- In particular, for one-shot lambdas we don't float things
  195. -- out; we get no saving by so doing.
  196. partition_fn | all isTyCoVar bndrs = partitionByLevel
  197. | otherwise = partitionByMajorLevel
  198. in
  199. case (floatExpr (last lvls) body) of { (fs, floats, body') ->
  200. -- Dump any bindings which absolutely cannot go any further
  201. case (partition_fn (head lvls) floats) of { (floats', heres) ->
  202. (add_to_stats fs floats', floats', mkLams bndrs (install heres body'))
  203. }}
  204. floatExpr lvl (Note note@(SCC cc) expr)
  205. = case (floatExpr lvl expr) of { (fs, floating_defns, expr') ->
  206. let
  207. -- Annotate bindings floated outwards past an scc expression
  208. -- with the cc. We mark that cc as "duplicated", though.
  209. annotated_defns = wrapCostCentre (dupifyCC cc) floating_defns
  210. in
  211. (fs, annotated_defns, Note note expr') }
  212. floatExpr lvl (Note note expr) -- Other than SCCs
  213. = case (floatExpr lvl expr) of { (fs, floating_defns, expr') ->
  214. (fs, floating_defns, Note note expr') }
  215. floatExpr lvl (Cast expr co)
  216. = case (floatExpr lvl expr) of { (fs, floating_defns, expr') ->
  217. (fs, floating_defns, Cast expr' co) }
  218. floatExpr lvl (Let (NonRec (TB bndr bndr_lvl) rhs) body)
  219. | isUnLiftedType (idType bndr) -- Treat unlifted lets just like a case
  220. -- I.e. floatExpr for rhs, floatCaseAlt for body
  221. = case floatExpr lvl rhs of { (_, rhs_floats, rhs') ->
  222. case floatCaseAlt bndr_lvl body of { (fs, body_floats, body') ->
  223. (fs, rhs_floats `plusFloats` body_floats, Let (NonRec bndr rhs') body') }}
  224. floatExpr lvl (Let bind body)
  225. = case (floatBind bind) of { (fsb, bind_floats) ->
  226. case (floatExpr lvl body) of { (fse, body_floats, body') ->
  227. case partitionByMajorLevel lvl (bind_floats `plusFloats` body_floats)
  228. of { (floats, heres) ->
  229. -- See Note [Avoiding unnecessary floating]
  230. (add_stats fsb fse, floats, install heres body') } } }
  231. floatExpr lvl (Case scrut (TB case_bndr case_lvl) ty alts)
  232. = case floatExpr lvl scrut of { (fse, fde, scrut') ->
  233. case floatList float_alt alts of { (fsa, fda, alts') ->
  234. (add_stats fse fsa, fda `plusFloats` fde, Case scrut' case_bndr ty alts')
  235. }}
  236. where
  237. -- Use floatCaseAlt for the alternatives, so that we
  238. -- don't gratuitiously float bindings out of the RHSs
  239. float_alt (con, bs, rhs)
  240. = case (floatCaseAlt case_lvl rhs) of { (fs, rhs_floats, rhs') ->
  241. (fs, rhs_floats, (con, [b | TB b _ <- bs], rhs')) }
  242. \end{code}
  243. Note [Avoiding unnecessary floating]
  244. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  245. In general we want to avoid floating a let unnecessarily, because
  246. it might worsen strictness:
  247. let
  248. x = ...(let y = e in y+y)....
  249. Here y is demanded. If we float it outside the lazy 'x=..' then
  250. we'd have to zap its demand info, and it may never be restored.
  251. So at a 'let' we leave the binding right where the are unless
  252. the binding will escape a value lambda. That's what the
  253. partitionByMajorLevel does in the floatExpr (Let ...) case.
  254. Notice, though, that we must take care to drop any bindings
  255. from the body of the let that depend on the staying-put bindings.
  256. We used instead to do the partitionByMajorLevel on the RHS of an '=',
  257. in floatRhs. But that was quite tiresome. We needed to test for
  258. values or trival rhss, because (in particular) we don't want to insert
  259. new bindings between the "=" and the "\". E.g.
  260. f = \x -> let <bind> in <body>
  261. We do not want
  262. f = let <bind> in \x -> <body>
  263. (a) The simplifier will immediately float it further out, so we may
  264. as well do so right now; in general, keeping rhss as manifest
  265. values is good
  266. (b) If a float-in pass follows immediately, it might add yet more
  267. bindings just after the '='. And some of them might (correctly)
  268. be strict even though the 'let f' is lazy, because f, being a value,
  269. gets its demand-info zapped by the simplifier.
  270. And even all that turned out to be very fragile, and broke
  271. altogether when profiling got in the way.
  272. So now we do the partition right at the (Let..) itself.
  273. %************************************************************************
  274. %* *
  275. \subsection{Utility bits for floating stats}
  276. %* *
  277. %************************************************************************
  278. I didn't implement this with unboxed numbers. I don't want to be too
  279. strict in this stuff, as it is rarely turned on. (WDP 95/09)
  280. \begin{code}
  281. data FloatStats
  282. = FlS Int -- Number of top-floats * lambda groups they've been past
  283. Int -- Number of non-top-floats * lambda groups they've been past
  284. Int -- Number of lambda (groups) seen
  285. get_stats :: FloatStats -> (Int, Int, Int)
  286. get_stats (FlS a b c) = (a, b, c)
  287. zeroStats :: FloatStats
  288. zeroStats = FlS 0 0 0
  289. sum_stats :: [FloatStats] -> FloatStats
  290. sum_stats xs = foldr add_stats zeroStats xs
  291. add_stats :: FloatStats -> FloatStats -> FloatStats
  292. add_stats (FlS a1 b1 c1) (FlS a2 b2 c2)
  293. = FlS (a1 + a2) (b1 + b2) (c1 + c2)
  294. add_to_stats :: FloatStats -> FloatBinds -> FloatStats
  295. add_to_stats (FlS a b c) (FB tops others)
  296. = FlS (a + lengthBag tops) (b + lengthBag (flattenMajor others)) (c + 1)
  297. \end{code}
  298. %************************************************************************
  299. %* *
  300. \subsection{Utility bits for floating}
  301. %* *
  302. %************************************************************************
  303. Note [Representation of FloatBinds]
  304. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  305. The FloatBinds types is somewhat important. We can get very large numbers
  306. of floating bindings, often all destined for the top level. A typical example
  307. is x = [4,2,5,2,5, .... ]
  308. Then we get lots of small expressions like (fromInteger 4), which all get
  309. lifted to top level.
  310. The trouble is that
  311. (a) we partition these floating bindings *at every binding site*
  312. (b) SetLevels introduces a new bindings site for every float
  313. So we had better not look at each binding at each binding site!
  314. That is why MajorEnv is represented as a finite map.
  315. We keep the bindings destined for the *top* level separate, because
  316. we float them out even if they don't escape a *value* lambda; see
  317. partitionByMajorLevel.
  318. \begin{code}
  319. type FloatBind = CoreBind -- INVARIANT: a FloatBind is always lifted
  320. data FloatBinds = FB !(Bag FloatBind) -- Destined for top level
  321. !MajorEnv -- Levels other than top
  322. -- See Note [Representation of FloatBinds]
  323. type MajorEnv = UniqFM MinorEnv -- Keyed by major level
  324. type MinorEnv = UniqFM (Bag FloatBind) -- Keyed by minor level
  325. flattenFloats :: FloatBinds -> Bag FloatBind
  326. flattenFloats (FB tops others) = tops `unionBags` flattenMajor others
  327. flattenMajor :: MajorEnv -> Bag FloatBind
  328. flattenMajor = foldUFM (unionBags . flattenMinor) emptyBag
  329. flattenMinor :: MinorEnv -> Bag FloatBind
  330. flattenMinor = foldUFM unionBags emptyBag
  331. emptyFloats :: FloatBinds
  332. emptyFloats = FB emptyBag emptyUFM
  333. unitFloat :: Level -> FloatBind -> FloatBinds
  334. unitFloat lvl@(Level major minor) b
  335. | isTopLvl lvl = FB (unitBag b) emptyUFM
  336. | otherwise = FB emptyBag (unitUFM major (unitUFM minor (unitBag b)))
  337. plusFloats :: FloatBinds -> FloatBinds -> FloatBinds
  338. plusFloats (FB t1 b1) (FB t2 b2) = FB (t1 `unionBags` t2) (b1 `plusMajor` b2)
  339. plusMajor :: MajorEnv -> MajorEnv -> MajorEnv
  340. plusMajor = plusUFM_C plusMinor
  341. plusMinor :: MinorEnv -> MinorEnv -> MinorEnv
  342. plusMinor = plusUFM_C unionBags
  343. floatsToBindPairs :: Bag FloatBind -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
  344. floatsToBindPairs floats binds = foldrBag add binds floats
  345. where
  346. add (Rec pairs) binds = pairs ++ binds
  347. add (NonRec binder rhs) binds = (binder,rhs) : binds
  348. install :: Bag FloatBind -> CoreExpr -> CoreExpr
  349. install defn_groups expr
  350. = foldrBag install_group expr defn_groups
  351. where
  352. install_group defns body = Let defns body
  353. partitionByMajorLevel, partitionByLevel
  354. :: Level -- Partitioning level
  355. -> FloatBinds -- Defns to be divided into 2 piles...
  356. -> (FloatBinds, -- Defns with level strictly < partition level,
  357. Bag FloatBind) -- The rest
  358. -- ---- partitionByMajorLevel ----
  359. -- Float it if we escape a value lambda, *or* if we get to the top level
  360. -- If we can get to the top level, say "yes" anyway. This means that
  361. -- x = f e
  362. -- transforms to
  363. -- lvl = e
  364. -- x = f lvl
  365. -- which is as it should be
  366. partitionByMajorLevel (Level major _) (FB tops defns)
  367. = (FB tops outer, heres `unionBags` flattenMajor inner)
  368. where
  369. (outer, mb_heres, inner) = splitUFM defns major
  370. heres = case mb_heres of
  371. Nothing -> emptyBag
  372. Just h -> flattenMinor h
  373. partitionByLevel (Level major minor) (FB tops defns)
  374. = (FB tops (outer_maj `plusMajor` unitUFM major outer_min),
  375. here_min `unionBags` flattenMinor inner_min
  376. `unionBags` flattenMajor inner_maj)
  377. where
  378. (outer_maj, mb_here_maj, inner_maj) = splitUFM defns major
  379. (outer_min, mb_here_min, inner_min) = case mb_here_maj of
  380. Nothing -> (emptyUFM, Nothing, emptyUFM)
  381. Just min_defns -> splitUFM min_defns minor
  382. here_min = mb_here_min `orElse` emptyBag
  383. wrapCostCentre :: CostCentre -> FloatBinds -> FloatBinds
  384. wrapCostCentre cc (FB tops defns)
  385. = FB (wrap_defns tops) (mapUFM (mapUFM wrap_defns) defns)
  386. where
  387. wrap_defns = mapBag wrap_one
  388. wrap_one (NonRec binder rhs) = NonRec binder (mkSCC cc rhs)
  389. wrap_one (Rec pairs) = Rec (mapSnd (mkSCC cc) pairs)
  390. \end{code}