PageRenderTime 60ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/simplCore/OccurAnal.lhs

https://github.com/luite/ghc
Haskell | 1865 lines | 1290 code | 332 blank | 243 comment | 104 complexity | bb6d36efb13c7958f13039e3d80215b1 MD5 | raw file
  1. %
  2. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  3. %
  4. %************************************************************************
  5. %* *
  6. \section[OccurAnal]{Occurrence analysis pass}
  7. %* *
  8. %************************************************************************
  9. The occurrence analyser re-typechecks a core expression, returning a new
  10. core expression with (hopefully) improved usage information.
  11. \begin{code}
  12. {-# LANGUAGE BangPatterns #-}
  13. module OccurAnal (
  14. occurAnalysePgm, occurAnalyseExpr, occurAnalyseExpr_NoBinderSwap
  15. ) where
  16. #include "HsVersions.h"
  17. import CoreSyn
  18. import CoreFVs
  19. import CoreUtils ( exprIsTrivial, isDefaultAlt, isExpandableApp )
  20. import Id
  21. import Name( localiseName )
  22. import BasicTypes
  23. import Module( Module )
  24. import Coercion
  25. import VarSet
  26. import VarEnv
  27. import Var
  28. import Maybes ( orElse )
  29. import Digraph ( SCC(..), stronglyConnCompFromEdgedVerticesR )
  30. import PrelNames ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
  31. import Unique
  32. import UniqFM
  33. import Util
  34. import Outputable
  35. import FastString
  36. import Data.List
  37. \end{code}
  38. %************************************************************************
  39. %* *
  40. \subsection[OccurAnal-main]{Counting occurrences: main function}
  41. %* *
  42. %************************************************************************
  43. Here's the externally-callable interface:
  44. \begin{code}
  45. occurAnalysePgm :: Module -- Used only in debug output
  46. -> (Activation -> Bool)
  47. -> [CoreRule] -> [CoreVect] -> VarSet
  48. -> CoreProgram -> CoreProgram
  49. occurAnalysePgm this_mod active_rule imp_rules vects vectVars binds
  50. | isEmptyVarEnv final_usage
  51. = binds'
  52. | otherwise -- See Note [Glomming]
  53. = WARN( True, hang (text "Glomming in" <+> ppr this_mod <> colon)
  54. 2 (ppr final_usage ) )
  55. [Rec (flattenBinds binds')]
  56. where
  57. (final_usage, binds') = go (initOccEnv active_rule) binds
  58. initial_uds = addIdOccs emptyDetails
  59. (rulesFreeVars imp_rules `unionVarSet`
  60. vectsFreeVars vects `unionVarSet`
  61. vectVars)
  62. -- The RULES and VECTORISE declarations keep things alive! (For VECTORISE declarations,
  63. -- we only get them *until* the vectoriser runs. Afterwards, these dependencies are
  64. -- reflected in 'vectors' — see Note [Vectorisation declarations and occurences].)
  65. -- Note [Preventing loops due to imported functions rules]
  66. imp_rules_edges = foldr (plusVarEnv_C unionVarSet) emptyVarEnv
  67. [ mapVarEnv (const maps_to) (exprFreeIds arg `delVarSetList` ru_bndrs imp_rule)
  68. | imp_rule <- imp_rules
  69. , let maps_to = exprFreeIds (ru_rhs imp_rule)
  70. `delVarSetList` ru_bndrs imp_rule
  71. , arg <- ru_args imp_rule ]
  72. go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
  73. go _ []
  74. = (initial_uds, [])
  75. go env (bind:binds)
  76. = (final_usage, bind' ++ binds')
  77. where
  78. (bs_usage, binds') = go env binds
  79. (final_usage, bind') = occAnalBind env env imp_rules_edges bind bs_usage
  80. occurAnalyseExpr :: CoreExpr -> CoreExpr
  81. -- Do occurrence analysis, and discard occurence info returned
  82. occurAnalyseExpr = occurAnalyseExpr' True -- do binder swap
  83. occurAnalyseExpr_NoBinderSwap :: CoreExpr -> CoreExpr
  84. occurAnalyseExpr_NoBinderSwap = occurAnalyseExpr' False -- do not do binder swap
  85. occurAnalyseExpr' :: Bool -> CoreExpr -> CoreExpr
  86. occurAnalyseExpr' enable_binder_swap expr
  87. = snd (occAnal env expr)
  88. where
  89. env = (initOccEnv all_active_rules) {occ_binder_swap = enable_binder_swap}
  90. -- To be conservative, we say that all inlines and rules are active
  91. all_active_rules = \_ -> True
  92. \end{code}
  93. %************************************************************************
  94. %* *
  95. \subsection[OccurAnal-main]{Counting occurrences: main function}
  96. %* *
  97. %************************************************************************
  98. Bindings
  99. ~~~~~~~~
  100. \begin{code}
  101. occAnalBind :: OccEnv -- The incoming OccEnv
  102. -> OccEnv -- Same, but trimmed by (binderOf bind)
  103. -> IdEnv IdSet -- Mapping from FVs of imported RULE LHSs to RHS FVs
  104. -> CoreBind
  105. -> UsageDetails -- Usage details of scope
  106. -> (UsageDetails, -- Of the whole let(rec)
  107. [CoreBind])
  108. occAnalBind env _ imp_rules_edges (NonRec binder rhs) body_usage
  109. | isTyVar binder -- A type let; we don't gather usage info
  110. = (body_usage, [NonRec binder rhs])
  111. | not (binder `usedIn` body_usage) -- It's not mentioned
  112. = (body_usage, [])
  113. | otherwise -- It's mentioned in the body
  114. = (body_usage' +++ rhs_usage4, [NonRec tagged_binder rhs'])
  115. where
  116. (body_usage', tagged_binder) = tagBinder body_usage binder
  117. (rhs_usage1, rhs') = occAnalRhs env (Just tagged_binder) rhs
  118. rhs_usage2 = addIdOccs rhs_usage1 (idUnfoldingVars binder)
  119. rhs_usage3 = addIdOccs rhs_usage2 (idRuleVars binder)
  120. -- See Note [Rules are extra RHSs] and Note [Rule dependency info]
  121. rhs_usage4 = maybe rhs_usage3 (addIdOccs rhs_usage3) $ lookupVarEnv imp_rules_edges binder
  122. -- See Note [Preventing loops due to imported functions rules]
  123. occAnalBind _ env imp_rules_edges (Rec pairs) body_usage
  124. = foldr occAnalRec (body_usage, []) sccs
  125. -- For a recursive group, we
  126. -- * occ-analyse all the RHSs
  127. -- * compute strongly-connected components
  128. -- * feed those components to occAnalRec
  129. where
  130. bndr_set = mkVarSet (map fst pairs)
  131. sccs :: [SCC (Node Details)]
  132. sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompFromEdgedVerticesR nodes
  133. nodes :: [Node Details]
  134. nodes = {-# SCC "occAnalBind.assoc" #-} map (makeNode env imp_rules_edges bndr_set) pairs
  135. \end{code}
  136. Note [Dead code]
  137. ~~~~~~~~~~~~~~~~
  138. Dropping dead code for a cyclic Strongly Connected Component is done
  139. in a very simple way:
  140. the entire SCC is dropped if none of its binders are mentioned
  141. in the body; otherwise the whole thing is kept.
  142. The key observation is that dead code elimination happens after
  143. dependency analysis: so 'occAnalBind' processes SCCs instead of the
  144. original term's binding groups.
  145. Thus 'occAnalBind' does indeed drop 'f' in an example like
  146. letrec f = ...g...
  147. g = ...(...g...)...
  148. in
  149. ...g...
  150. when 'g' no longer uses 'f' at all (eg 'f' does not occur in a RULE in
  151. 'g'). 'occAnalBind' first consumes 'CyclicSCC g' and then it consumes
  152. 'AcyclicSCC f', where 'body_usage' won't contain 'f'.
  153. ------------------------------------------------------------
  154. Note [Forming Rec groups]
  155. ~~~~~~~~~~~~~~~~~~~~~~~~~
  156. We put bindings {f = ef; g = eg } in a Rec group if "f uses g"
  157. and "g uses f", no matter how indirectly. We do a SCC analysis
  158. with an edge f -> g if "f uses g".
  159. More precisely, "f uses g" iff g should be in scope whereever f is.
  160. That is, g is free in:
  161. a) the rhs 'ef'
  162. b) or the RHS of a rule for f (Note [Rules are extra RHSs])
  163. c) or the LHS or a rule for f (Note [Rule dependency info])
  164. These conditions apply regardless of the activation of the RULE (eg it might be
  165. inactive in this phase but become active later). Once a Rec is broken up
  166. it can never be put back together, so we must be conservative.
  167. The principle is that, regardless of rule firings, every variale is
  168. always in scope.
  169. * Note [Rules are extra RHSs]
  170. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  171. A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
  172. keeps the specialised "children" alive. If the parent dies
  173. (because it isn't referenced any more), then the children will die
  174. too (unless they are already referenced directly).
  175. To that end, we build a Rec group for each cyclic strongly
  176. connected component,
  177. *treating f's rules as extra RHSs for 'f'*.
  178. More concretely, the SCC analysis runs on a graph with an edge
  179. from f -> g iff g is mentioned in
  180. (a) f's rhs
  181. (b) f's RULES
  182. These are rec_edges.
  183. Under (b) we include variables free in *either* LHS *or* RHS of
  184. the rule. The former might seems silly, but see Note [Rule
  185. dependency info]. So in Example [eftInt], eftInt and eftIntFB
  186. will be put in the same Rec, even though their 'main' RHSs are
  187. both non-recursive.
  188. * Note [Rule dependency info]
  189. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  190. The VarSet in a SpecInfo is used for dependency analysis in the
  191. occurrence analyser. We must track free vars in *both* lhs and rhs.
  192. Hence use of idRuleVars, rather than idRuleRhsVars in occAnalBind.
  193. Why both? Consider
  194. x = y
  195. RULE f x = v+4
  196. Then if we substitute y for x, we'd better do so in the
  197. rule's LHS too, so we'd better ensure the RULE appears to mention 'x'
  198. as well as 'v'
  199. * Note [Rules are visible in their own rec group]
  200. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  201. We want the rules for 'f' to be visible in f's right-hand side.
  202. And we'd like them to be visible in other functions in f's Rec
  203. group. E.g. in Note [Specialisation rules] we want f' rule
  204. to be visible in both f's RHS, and fs's RHS.
  205. This means that we must simplify the RULEs first, before looking
  206. at any of the definitions. This is done by Simplify.simplRecBind,
  207. when it calls addLetIdInfo.
  208. ------------------------------------------------------------
  209. Note [Choosing loop breakers]
  210. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  211. Loop breaking is surprisingly subtle. First read the section 4 of
  212. "Secrets of the GHC inliner". This describes our basic plan.
  213. We avoid infinite inlinings by choosing loop breakers, and
  214. ensuring that a loop breaker cuts each loop.
  215. Fundamentally, we do SCC analysis on a graph. For each recursive
  216. group we choose a loop breaker, delete all edges to that node,
  217. re-analyse the SCC, and iterate.
  218. But what is the graph? NOT the same graph as was used for Note
  219. [Forming Rec groups]! In particular, a RULE is like an equation for
  220. 'f' that is *always* inlined if it is applicable. We do *not* disable
  221. rules for loop-breakers. It's up to whoever makes the rules to make
  222. sure that the rules themselves always terminate. See Note [Rules for
  223. recursive functions] in Simplify.lhs
  224. Hence, if
  225. f's RHS (or its INLINE template if it has one) mentions g, and
  226. g has a RULE that mentions h, and
  227. h has a RULE that mentions f
  228. then we *must* choose f to be a loop breaker. Example: see Note
  229. [Specialisation rules].
  230. In general, take the free variables of f's RHS, and augment it with
  231. all the variables reachable by RULES from those starting points. That
  232. is the whole reason for computing rule_fv_env in occAnalBind. (Of
  233. course we only consider free vars that are also binders in this Rec
  234. group.) See also Note [Finding rule RHS free vars]
  235. Note that when we compute this rule_fv_env, we only consider variables
  236. free in the *RHS* of the rule, in contrast to the way we build the
  237. Rec group in the first place (Note [Rule dependency info])
  238. Note that if 'g' has RHS that mentions 'w', we should add w to
  239. g's loop-breaker edges. More concretely there is an edge from f -> g
  240. iff
  241. (a) g is mentioned in f's RHS `xor` f's INLINE rhs
  242. (see Note [Inline rules])
  243. (b) or h is mentioned in f's RHS, and
  244. g appears in the RHS of an active RULE of h
  245. or a transitive sequence of active rules starting with h
  246. Why "active rules"? See Note [Finding rule RHS free vars]
  247. Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
  248. chosen as a loop breaker, because their RHSs don't mention each other.
  249. And indeed both can be inlined safely.
  250. Note again that the edges of the graph we use for computing loop breakers
  251. are not the same as the edges we use for computing the Rec blocks.
  252. That's why we compute
  253. - rec_edges for the Rec block analysis
  254. - loop_breaker_edges for the loop breaker analysis
  255. * Note [Finding rule RHS free vars]
  256. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  257. Consider this real example from Data Parallel Haskell
  258. tagZero :: Array Int -> Array Tag
  259. {-# INLINE [1] tagZeroes #-}
  260. tagZero xs = pmap (\x -> fromBool (x==0)) xs
  261. {-# RULES "tagZero" [~1] forall xs n.
  262. pmap fromBool <blah blah> = tagZero xs #-}
  263. So tagZero's RHS mentions pmap, and pmap's RULE mentions tagZero.
  264. However, tagZero can only be inlined in phase 1 and later, while
  265. the RULE is only active *before* phase 1. So there's no problem.
  266. To make this work, we look for the RHS free vars only for
  267. *active* rules. That's the reason for the occ_rule_act field
  268. of the OccEnv.
  269. * Note [Weak loop breakers]
  270. ~~~~~~~~~~~~~~~~~~~~~~~~~
  271. There is a last nasty wrinkle. Suppose we have
  272. Rec { f = f_rhs
  273. RULE f [] = g
  274. h = h_rhs
  275. g = h
  276. ...more...
  277. }
  278. Remember that we simplify the RULES before any RHS (see Note
  279. [Rules are visible in their own rec group] above).
  280. So we must *not* postInlineUnconditionally 'g', even though
  281. its RHS turns out to be trivial. (I'm assuming that 'g' is
  282. not choosen as a loop breaker.) Why not? Because then we
  283. drop the binding for 'g', which leaves it out of scope in the
  284. RULE!
  285. Here's a somewhat different example of the same thing
  286. Rec { g = h
  287. ; h = ...f...
  288. ; f = f_rhs
  289. RULE f [] = g }
  290. Here the RULE is "below" g, but we *still* can't postInlineUnconditionally
  291. g, because the RULE for f is active throughout. So the RHS of h
  292. might rewrite to h = ...g...
  293. So g must remain in scope in the output program!
  294. We "solve" this by:
  295. Make g a "weak" loop breaker (OccInfo = IAmLoopBreaker True)
  296. iff g is a "missing free variable" of the Rec group
  297. A "missing free variable" x is one that is mentioned in an RHS or
  298. INLINE or RULE of a binding in the Rec group, but where the
  299. dependency on x may not show up in the loop_breaker_edges (see
  300. note [Choosing loop breakers} above).
  301. A normal "strong" loop breaker has IAmLoopBreaker False. So
  302. Inline postInlineUnconditionally
  303. IAmLoopBreaker False no no
  304. IAmLoopBreaker True yes no
  305. other yes yes
  306. The **sole** reason for this kind of loop breaker is so that
  307. postInlineUnconditionally does not fire. Ugh. (Typically it'll
  308. inline via the usual callSiteInline stuff, so it'll be dead in the
  309. next pass, so the main Ugh is the tiresome complication.)
  310. Note [Rules for imported functions]
  311. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  312. Consider this
  313. f = /\a. B.g a
  314. RULE B.g Int = 1 + f Int
  315. Note that
  316. * The RULE is for an imported function.
  317. * f is non-recursive
  318. Now we
  319. can get
  320. f Int --> B.g Int Inlining f
  321. --> 1 + f Int Firing RULE
  322. and so the simplifier goes into an infinite loop. This
  323. would not happen if the RULE was for a local function,
  324. because we keep track of dependencies through rules. But
  325. that is pretty much impossible to do for imported Ids. Suppose
  326. f's definition had been
  327. f = /\a. C.h a
  328. where (by some long and devious process), C.h eventually inlines to
  329. B.g. We could only spot such loops by exhaustively following
  330. unfoldings of C.h etc, in case we reach B.g, and hence (via the RULE)
  331. f.
  332. Note that RULES for imported functions are important in practice; they
  333. occur a lot in the libraries.
  334. We regard this potential infinite loop as a *programmer* error.
  335. It's up the programmer not to write silly rules like
  336. RULE f x = f x
  337. and the example above is just a more complicated version.
  338. Note [Preventing loops due to imported functions rules]
  339. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  340. Consider:
  341. import GHC.Base (foldr)
  342. {-# RULES "filterList" forall p. foldr (filterFB (:) p) [] = filter p #-}
  343. filter p xs = build (\c n -> foldr (filterFB c p) n xs)
  344. filterFB c p = ...
  345. f = filter p xs
  346. Note that filter is not a loop-breaker, so what happens is:
  347. f = filter p xs
  348. = {inline} build (\c n -> foldr (filterFB c p) n xs)
  349. = {inline} foldr (filterFB (:) p) [] xs
  350. = {RULE} filter p xs
  351. We are in an infinite loop.
  352. A more elaborate example (that I actually saw in practice when I went to
  353. mark GHC.List.filter as INLINABLE) is as follows. Say I have this module:
  354. {-# LANGUAGE RankNTypes #-}
  355. module GHCList where
  356. import Prelude hiding (filter)
  357. import GHC.Base (build)
  358. {-# INLINABLE filter #-}
  359. filter :: (a -> Bool) -> [a] -> [a]
  360. filter p [] = []
  361. filter p (x:xs) = if p x then x : filter p xs else filter p xs
  362. {-# NOINLINE [0] filterFB #-}
  363. filterFB :: (a -> b -> b) -> (a -> Bool) -> a -> b -> b
  364. filterFB c p x r | p x = x `c` r
  365. | otherwise = r
  366. {-# RULES
  367. "filter" [~1] forall p xs. filter p xs = build (\c n -> foldr
  368. (filterFB c p) n xs)
  369. "filterList" [1] forall p. foldr (filterFB (:) p) [] = filter p
  370. #-}
  371. Then (because RULES are applied inside INLINABLE unfoldings, but inlinings
  372. are not), the unfolding given to "filter" in the interface file will be:
  373. filter p [] = []
  374. filter p (x:xs) = if p x then x : build (\c n -> foldr (filterFB c p) n xs)
  375. else build (\c n -> foldr (filterFB c p) n xs
  376. Note that because this unfolding does not mention "filter", filter is not
  377. marked as a strong loop breaker. Therefore at a use site in another module:
  378. filter p xs
  379. = {inline}
  380. case xs of [] -> []
  381. (x:xs) -> if p x then x : build (\c n -> foldr (filterFB c p) n xs)
  382. else build (\c n -> foldr (filterFB c p) n xs)
  383. build (\c n -> foldr (filterFB c p) n xs)
  384. = {inline} foldr (filterFB (:) p) [] xs
  385. = {RULE} filter p xs
  386. And we are in an infinite loop again, except that this time the loop is producing an
  387. infinitely large *term* (an unrolling of filter) and so the simplifier finally
  388. dies with "ticks exhausted"
  389. Because of this problem, we make a small change in the occurrence analyser
  390. designed to mark functions like "filter" as strong loop breakers on the basis that:
  391. 1. The RHS of filter mentions the local function "filterFB"
  392. 2. We have a rule which mentions "filterFB" on the LHS and "filter" on the RHS
  393. So for each RULE for an *imported* function we are going to add
  394. dependency edges between the *local* FVS of the rule LHS and the
  395. *local* FVS of the rule RHS. We don't do anything special for RULES on
  396. local functions because the standard occurrence analysis stuff is
  397. pretty good at getting loop-breakerness correct there.
  398. It is important to note that even with this extra hack we aren't always going to get
  399. things right. For example, it might be that the rule LHS mentions an imported Id,
  400. and another module has a RULE that can rewrite that imported Id to one of our local
  401. Ids.
  402. Note [Specialising imported functions]
  403. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  404. BUT for *automatically-generated* rules, the programmer can't be
  405. responsible for the "programmer error" in Note [Rules for imported
  406. functions]. In paricular, consider specialising a recursive function
  407. defined in another module. If we specialise a recursive function B.g,
  408. we get
  409. g_spec = .....(B.g Int).....
  410. RULE B.g Int = g_spec
  411. Here, g_spec doesn't look recursive, but when the rule fires, it
  412. becomes so. And if B.g was mutually recursive, the loop might
  413. not be as obvious as it is here.
  414. To avoid this,
  415. * When specialising a function that is a loop breaker,
  416. give a NOINLINE pragma to the specialised function
  417. Note [Glomming]
  418. ~~~~~~~~~~~~~~~
  419. RULES for imported Ids can make something at the top refer to something at the bottom:
  420. f = \x -> B.g (q x)
  421. h = \y -> 3
  422. RULE: B.g (q x) = h x
  423. Applying this rule makes f refer to h, although f doesn't appear to
  424. depend on h. (And, as in Note [Rules for imported functions], the
  425. dependency might be more indirect. For example, f might mention C.t
  426. rather than B.g, where C.t eventually inlines to B.g.)
  427. NOTICE that this cannot happen for rules whose head is a
  428. locally-defined function, because we accurately track dependencies
  429. through RULES. It only happens for rules whose head is an imported
  430. function (B.g in the example above).
  431. Solution:
  432. - When simplifying, bring all top level identifiers into
  433. scope at the start, ignoring the Rec/NonRec structure, so
  434. that when 'h' pops up in f's rhs, we find it in the in-scope set
  435. (as the simplifier generally expects). This happens in simplTopBinds.
  436. - In the occurrence analyser, if there are any out-of-scope
  437. occurrences that pop out of the top, which will happen after
  438. firing the rule: f = \x -> h x
  439. h = \y -> 3
  440. then just glom all the bindings into a single Rec, so that
  441. the *next* iteration of the occurrence analyser will sort
  442. them all out. This part happens in occurAnalysePgm.
  443. ------------------------------------------------------------
  444. Note [Inline rules]
  445. ~~~~~~~~~~~~~~~~~~~
  446. None of the above stuff about RULES applies to Inline Rules,
  447. stored in a CoreUnfolding. The unfolding, if any, is simplified
  448. at the same time as the regular RHS of the function (ie *not* like
  449. Note [Rules are visible in their own rec group]), so it should be
  450. treated *exactly* like an extra RHS.
  451. Or, rather, when computing loop-breaker edges,
  452. * If f has an INLINE pragma, and it is active, we treat the
  453. INLINE rhs as f's rhs
  454. * If it's inactive, we treat f as having no rhs
  455. * If it has no INLINE pragma, we look at f's actual rhs
  456. There is a danger that we'll be sub-optimal if we see this
  457. f = ...f...
  458. [INLINE f = ..no f...]
  459. where f is recursive, but the INLINE is not. This can just about
  460. happen with a sufficiently odd set of rules; eg
  461. foo :: Int -> Int
  462. {-# INLINE [1] foo #-}
  463. foo x = x+1
  464. bar :: Int -> Int
  465. {-# INLINE [1] bar #-}
  466. bar x = foo x + 1
  467. {-# RULES "foo" [~1] forall x. foo x = bar x #-}
  468. Here the RULE makes bar recursive; but it's INLINE pragma remains
  469. non-recursive. It's tempting to then say that 'bar' should not be
  470. a loop breaker, but an attempt to do so goes wrong in two ways:
  471. a) We may get
  472. $df = ...$cfoo...
  473. $cfoo = ...$df....
  474. [INLINE $cfoo = ...no-$df...]
  475. But we want $cfoo to depend on $df explicitly so that we
  476. put the bindings in the right order to inline $df in $cfoo
  477. and perhaps break the loop altogether. (Maybe this
  478. b)
  479. Example [eftInt]
  480. ~~~~~~~~~~~~~~~
  481. Example (from GHC.Enum):
  482. eftInt :: Int# -> Int# -> [Int]
  483. eftInt x y = ...(non-recursive)...
  484. {-# INLINE [0] eftIntFB #-}
  485. eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
  486. eftIntFB c n x y = ...(non-recursive)...
  487. {-# RULES
  488. "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
  489. "eftIntList" [1] eftIntFB (:) [] = eftInt
  490. #-}
  491. Note [Specialisation rules]
  492. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  493. Consider this group, which is typical of what SpecConstr builds:
  494. fs a = ....f (C a)....
  495. f x = ....f (C a)....
  496. {-# RULE f (C a) = fs a #-}
  497. So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
  498. But watch out! If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
  499. - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
  500. - fs is inlined (say it's small)
  501. - now there's another opportunity to apply the RULE
  502. This showed up when compiling Control.Concurrent.Chan.getChanContents.
  503. \begin{code}
  504. type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
  505. -- which is gotten from the Id.
  506. data Details
  507. = ND { nd_bndr :: Id -- Binder
  508. , nd_rhs :: CoreExpr -- RHS, already occ-analysed
  509. , nd_uds :: UsageDetails -- Usage from RHS, and RULES, and InlineRule unfolding
  510. -- ignoring phase (ie assuming all are active)
  511. -- See Note [Forming Rec groups]
  512. , nd_inl :: IdSet -- Free variables of
  513. -- the InlineRule (if present and active)
  514. -- or the RHS (ir no InlineRule)
  515. -- but excluding any RULES
  516. -- This is the IdSet that may be used if the Id is inlined
  517. , nd_weak :: IdSet -- Binders of this Rec that are mentioned in nd_uds
  518. -- but are *not* in nd_inl. These are the ones whose
  519. -- dependencies might not be respected by loop_breaker_edges
  520. -- See Note [Weak loop breakers]
  521. , nd_active_rule_fvs :: IdSet -- Free variables of the RHS of active RULES
  522. }
  523. instance Outputable Details where
  524. ppr nd = ptext (sLit "ND") <> braces
  525. (sep [ ptext (sLit "bndr =") <+> ppr (nd_bndr nd)
  526. , ptext (sLit "uds =") <+> ppr (nd_uds nd)
  527. , ptext (sLit "inl =") <+> ppr (nd_inl nd)
  528. , ptext (sLit "weak =") <+> ppr (nd_weak nd)
  529. , ptext (sLit "rule =") <+> ppr (nd_active_rule_fvs nd)
  530. ])
  531. makeNode :: OccEnv -> IdEnv IdSet -> VarSet -> (Var, CoreExpr) -> Node Details
  532. makeNode env imp_rules_edges bndr_set (bndr, rhs)
  533. = (details, varUnique bndr, keysUFM node_fvs)
  534. where
  535. details = ND { nd_bndr = bndr
  536. , nd_rhs = rhs'
  537. , nd_uds = rhs_usage3
  538. , nd_weak = node_fvs `minusVarSet` inl_fvs
  539. , nd_inl = inl_fvs
  540. , nd_active_rule_fvs = active_rule_fvs }
  541. -- Constructing the edges for the main Rec computation
  542. -- See Note [Forming Rec groups]
  543. (rhs_usage1, rhs') = occAnalRhs env Nothing rhs
  544. rhs_usage2 = addIdOccs rhs_usage1 all_rule_fvs -- Note [Rules are extra RHSs]
  545. -- Note [Rule dependency info]
  546. rhs_usage3 = case mb_unf_fvs of
  547. Just unf_fvs -> addIdOccs rhs_usage2 unf_fvs
  548. Nothing -> rhs_usage2
  549. node_fvs = udFreeVars bndr_set rhs_usage3
  550. -- Finding the free variables of the rules
  551. is_active = occ_rule_act env :: Activation -> Bool
  552. rules = filterOut isBuiltinRule (idCoreRules bndr)
  553. rules_w_fvs :: [(Activation, VarSet)] -- Find the RHS fvs
  554. rules_w_fvs = maybe id (\ids -> ((AlwaysActive, ids):)) (lookupVarEnv imp_rules_edges bndr)
  555. -- See Note [Preventing loops due to imported functions rules]
  556. [ (ru_act rule, fvs)
  557. | rule <- rules
  558. , let fvs = exprFreeVars (ru_rhs rule)
  559. `delVarSetList` ru_bndrs rule
  560. , not (isEmptyVarSet fvs) ]
  561. all_rule_fvs = foldr (unionVarSet . snd) rule_lhs_fvs rules_w_fvs
  562. rule_lhs_fvs = foldr (unionVarSet . (\ru -> exprsFreeVars (ru_args ru)
  563. `delVarSetList` ru_bndrs ru))
  564. emptyVarSet rules
  565. active_rule_fvs = unionVarSets [fvs | (a,fvs) <- rules_w_fvs, is_active a]
  566. -- Finding the free variables of the INLINE pragma (if any)
  567. unf = realIdUnfolding bndr -- Ignore any current loop-breaker flag
  568. mb_unf_fvs = stableUnfoldingVars isLocalId unf
  569. -- Find the "nd_inl" free vars; for the loop-breaker phase
  570. inl_fvs = case mb_unf_fvs of
  571. Nothing -> udFreeVars bndr_set rhs_usage1 -- No INLINE, use RHS
  572. Just unf_fvs -> unf_fvs
  573. -- We could check for an *active* INLINE (returning
  574. -- emptyVarSet for an inactive one), but is_active
  575. -- isn't the right thing (it tells about
  576. -- RULE activation), so we'd need more plumbing
  577. -----------------------------
  578. occAnalRec :: SCC (Node Details)
  579. -> (UsageDetails, [CoreBind])
  580. -> (UsageDetails, [CoreBind])
  581. -- The NonRec case is just like a Let (NonRec ...) above
  582. occAnalRec (AcyclicSCC (ND { nd_bndr = bndr, nd_rhs = rhs, nd_uds = rhs_uds}, _, _))
  583. (body_uds, binds)
  584. | not (bndr `usedIn` body_uds)
  585. = (body_uds, binds) -- See Note [Dead code]
  586. | otherwise -- It's mentioned in the body
  587. = (body_uds' +++ rhs_uds,
  588. NonRec tagged_bndr rhs : binds)
  589. where
  590. (body_uds', tagged_bndr) = tagBinder body_uds bndr
  591. -- The Rec case is the interesting one
  592. -- See Note [Loop breaking]
  593. occAnalRec (CyclicSCC nodes) (body_uds, binds)
  594. | not (any (`usedIn` body_uds) bndrs) -- NB: look at body_uds, not total_uds
  595. = (body_uds, binds) -- See Note [Dead code]
  596. | otherwise -- At this point we always build a single Rec
  597. = -- pprTrace "occAnalRec" (vcat
  598. -- [ text "tagged nodes" <+> ppr tagged_nodes
  599. -- , text "lb edges" <+> ppr loop_breaker_edges])
  600. (final_uds, Rec pairs : binds)
  601. where
  602. bndrs = [b | (ND { nd_bndr = b }, _, _) <- nodes]
  603. bndr_set = mkVarSet bndrs
  604. ----------------------------
  605. -- Tag the binders with their occurrence info
  606. tagged_nodes = map tag_node nodes
  607. total_uds = foldl add_uds body_uds nodes
  608. final_uds = total_uds `minusVarEnv` bndr_set
  609. add_uds usage_so_far (nd, _, _) = usage_so_far +++ nd_uds nd
  610. tag_node :: Node Details -> Node Details
  611. tag_node (details@ND { nd_bndr = bndr }, k, ks)
  612. = (details { nd_bndr = setBinderOcc total_uds bndr }, k, ks)
  613. ---------------------------
  614. -- Now reconstruct the cycle
  615. pairs :: [(Id,CoreExpr)]
  616. pairs | isEmptyVarSet weak_fvs = reOrderNodes 0 bndr_set weak_fvs tagged_nodes []
  617. | otherwise = loopBreakNodes 0 bndr_set weak_fvs loop_breaker_edges []
  618. -- If weak_fvs is empty, the loop_breaker_edges will include all
  619. -- the edges in tagged_nodes, so there isn't any point in doing
  620. -- a fresh SCC computation that will yield a single CyclicSCC result.
  621. weak_fvs :: VarSet
  622. weak_fvs = foldr (unionVarSet . nd_weak . fstOf3) emptyVarSet nodes
  623. -- See Note [Choosing loop breakers] for loop_breaker_edges
  624. loop_breaker_edges = map mk_node tagged_nodes
  625. mk_node (details@(ND { nd_inl = inl_fvs }), k, _)
  626. = (details, k, keysUFM (extendFvs_ rule_fv_env inl_fvs))
  627. ------------------------------------
  628. rule_fv_env :: IdEnv IdSet
  629. -- Maps a variable f to the variables from this group
  630. -- mentioned in RHS of active rules for f
  631. -- Domain is *subset* of bound vars (others have no rule fvs)
  632. rule_fv_env = transClosureFV (mkVarEnv init_rule_fvs)
  633. init_rule_fvs -- See Note [Finding rule RHS free vars]
  634. = [ (b, trimmed_rule_fvs)
  635. | (ND { nd_bndr = b, nd_active_rule_fvs = rule_fvs },_,_) <- nodes
  636. , let trimmed_rule_fvs = rule_fvs `intersectVarSet` bndr_set
  637. , not (isEmptyVarSet trimmed_rule_fvs)]
  638. \end{code}
  639. @loopBreakSCC@ is applied to the list of (binder,rhs) pairs for a cyclic
  640. strongly connected component (there's guaranteed to be a cycle). It returns the
  641. same pairs, but
  642. a) in a better order,
  643. b) with some of the Ids having a IAmALoopBreaker pragma
  644. The "loop-breaker" Ids are sufficient to break all cycles in the SCC. This means
  645. that the simplifier can guarantee not to loop provided it never records an inlining
  646. for these no-inline guys.
  647. Furthermore, the order of the binds is such that if we neglect dependencies
  648. on the no-inline Ids then the binds are topologically sorted. This means
  649. that the simplifier will generally do a good job if it works from top bottom,
  650. recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
  651. \begin{code}
  652. type Binding = (Id,CoreExpr)
  653. mk_loop_breaker :: Node Details -> Binding
  654. mk_loop_breaker (ND { nd_bndr = bndr, nd_rhs = rhs}, _, _)
  655. = (setIdOccInfo bndr strongLoopBreaker, rhs)
  656. mk_non_loop_breaker :: VarSet -> Node Details -> Binding
  657. -- See Note [Weak loop breakers]
  658. mk_non_loop_breaker used_in_rules (ND { nd_bndr = bndr, nd_rhs = rhs}, _, _)
  659. | bndr `elemVarSet` used_in_rules = (setIdOccInfo bndr weakLoopBreaker, rhs)
  660. | otherwise = (bndr, rhs)
  661. udFreeVars :: VarSet -> UsageDetails -> VarSet
  662. -- Find the subset of bndrs that are mentioned in uds
  663. udFreeVars bndrs uds = intersectUFM_C (\b _ -> b) bndrs uds
  664. loopBreakNodes :: Int
  665. -> VarSet -- All binders
  666. -> VarSet -- Binders whose dependencies may be "missing"
  667. -- See Note [Weak loop breakers]
  668. -> [Node Details]
  669. -> [Binding] -- Append these to the end
  670. -> [Binding]
  671. -- Return the bindings sorted into a plausible order, and marked with loop breakers.
  672. loopBreakNodes depth bndr_set weak_fvs nodes binds
  673. = go (stronglyConnCompFromEdgedVerticesR nodes) binds
  674. where
  675. go [] binds = binds
  676. go (scc:sccs) binds = loop_break_scc scc (go sccs binds)
  677. loop_break_scc scc binds
  678. = case scc of
  679. AcyclicSCC node -> mk_non_loop_breaker weak_fvs node : binds
  680. CyclicSCC [node] -> mk_loop_breaker node : binds
  681. CyclicSCC nodes -> reOrderNodes depth bndr_set weak_fvs nodes binds
  682. reOrderNodes :: Int -> VarSet -> VarSet -> [Node Details] -> [Binding] -> [Binding]
  683. -- Choose a loop breaker, mark it no-inline,
  684. -- do SCC analysis on the rest, and recursively sort them out
  685. reOrderNodes _ _ _ [] _ = panic "reOrderNodes"
  686. reOrderNodes depth bndr_set weak_fvs (node : nodes) binds
  687. = -- pprTrace "reOrderNodes" (text "unchosen" <+> ppr unchosen $$
  688. -- text "chosen" <+> ppr chosen_nodes) $
  689. loopBreakNodes new_depth bndr_set weak_fvs unchosen $
  690. (map mk_loop_breaker chosen_nodes ++ binds)
  691. where
  692. (chosen_nodes, unchosen) = choose_loop_breaker (score node) [node] [] nodes
  693. approximate_loop_breaker = depth >= 2
  694. new_depth | approximate_loop_breaker = 0
  695. | otherwise = depth+1
  696. -- After two iterations (d=0, d=1) give up
  697. -- and approximate, returning to d=0
  698. choose_loop_breaker :: Int -- Best score so far
  699. -> [Node Details] -- Nodes with this score
  700. -> [Node Details] -- Nodes with higher scores
  701. -> [Node Details] -- Unprocessed nodes
  702. -> ([Node Details], [Node Details])
  703. -- This loop looks for the bind with the lowest score
  704. -- to pick as the loop breaker. The rest accumulate in
  705. choose_loop_breaker _ loop_nodes acc []
  706. = (loop_nodes, acc) -- Done
  707. -- If approximate_loop_breaker is True, we pick *all*
  708. -- nodes with lowest score, else just one
  709. -- See Note [Complexity of loop breaking]
  710. choose_loop_breaker loop_sc loop_nodes acc (node : nodes)
  711. | sc < loop_sc -- Lower score so pick this new one
  712. = choose_loop_breaker sc [node] (loop_nodes ++ acc) nodes
  713. | approximate_loop_breaker && sc == loop_sc
  714. = choose_loop_breaker loop_sc (node : loop_nodes) acc nodes
  715. | otherwise -- Higher score so don't pick it
  716. = choose_loop_breaker loop_sc loop_nodes (node : acc) nodes
  717. where
  718. sc = score node
  719. score :: Node Details -> Int -- Higher score => less likely to be picked as loop breaker
  720. score (ND { nd_bndr = bndr, nd_rhs = rhs }, _, _)
  721. | not (isId bndr) = 100 -- A type or cercion variable is never a loop breaker
  722. | isDFunId bndr = 9 -- Never choose a DFun as a loop breaker
  723. -- Note [DFuns should not be loop breakers]
  724. | Just inl_source <- isStableCoreUnfolding_maybe (idUnfolding bndr)
  725. = case inl_source of
  726. InlineWrapper {} -> 10 -- Note [INLINE pragmas]
  727. _other -> 3 -- Data structures are more important than this
  728. -- so that dictionary/method recursion unravels
  729. -- Note that this case hits all InlineRule things, so we
  730. -- never look at 'rhs' for InlineRule stuff. That's right, because
  731. -- 'rhs' is irrelevant for inlining things with an InlineRule
  732. | is_con_app rhs = 5 -- Data types help with cases: Note [Constructor applications]
  733. | exprIsTrivial rhs = 10 -- Practically certain to be inlined
  734. -- Used to have also: && not (isExportedId bndr)
  735. -- But I found this sometimes cost an extra iteration when we have
  736. -- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
  737. -- where df is the exported dictionary. Then df makes a really
  738. -- bad choice for loop breaker
  739. -- If an Id is marked "never inline" then it makes a great loop breaker
  740. -- The only reason for not checking that here is that it is rare
  741. -- and I've never seen a situation where it makes a difference,
  742. -- so it probably isn't worth the time to test on every binder
  743. -- | isNeverActive (idInlinePragma bndr) = -10
  744. | isOneOcc (idOccInfo bndr) = 2 -- Likely to be inlined
  745. | canUnfold (realIdUnfolding bndr) = 1
  746. -- The Id has some kind of unfolding
  747. -- Ignore loop-breaker-ness here because that is what we are setting!
  748. | otherwise = 0
  749. -- Checking for a constructor application
  750. -- Cheap and cheerful; the simplifer moves casts out of the way
  751. -- The lambda case is important to spot x = /\a. C (f a)
  752. -- which comes up when C is a dictionary constructor and
  753. -- f is a default method.
  754. -- Example: the instance for Show (ST s a) in GHC.ST
  755. --
  756. -- However we *also* treat (\x. C p q) as a con-app-like thing,
  757. -- Note [Closure conversion]
  758. is_con_app (Var v) = isConLikeId v
  759. is_con_app (App f _) = is_con_app f
  760. is_con_app (Lam _ e) = is_con_app e
  761. is_con_app (Tick _ e) = is_con_app e
  762. is_con_app _ = False
  763. \end{code}
  764. Note [Complexity of loop breaking]
  765. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  766. The loop-breaking algorithm knocks out one binder at a time, and
  767. performs a new SCC analysis on the remaining binders. That can
  768. behave very badly in tightly-coupled groups of bindings; in the
  769. worst case it can be (N**2)*log N, because it does a full SCC
  770. on N, then N-1, then N-2 and so on.
  771. To avoid this, we switch plans after 2 (or whatever) attempts:
  772. Plan A: pick one binder with the lowest score, make it
  773. a loop breaker, and try again
  774. Plan B: pick *all* binders with the lowest score, make them
  775. all loop breakers, and try again
  776. Since there are only a small finite number of scores, this will
  777. terminate in a constant number of iterations, rather than O(N)
  778. iterations.
  779. You might thing that it's very unlikely, but RULES make it much
  780. more likely. Here's a real example from Trac #1969:
  781. Rec { $dm = \d.\x. op d
  782. {-# RULES forall d. $dm Int d = $s$dm1
  783. forall d. $dm Bool d = $s$dm2 #-}
  784. dInt = MkD .... opInt ...
  785. dInt = MkD .... opBool ...
  786. opInt = $dm dInt
  787. opBool = $dm dBool
  788. $s$dm1 = \x. op dInt
  789. $s$dm2 = \x. op dBool }
  790. The RULES stuff means that we can't choose $dm as a loop breaker
  791. (Note [Choosing loop breakers]), so we must choose at least (say)
  792. opInt *and* opBool, and so on. The number of loop breakders is
  793. linear in the number of instance declarations.
  794. Note [INLINE pragmas]
  795. ~~~~~~~~~~~~~~~~~~~~~
  796. Avoid choosing a function with an INLINE pramga as the loop breaker!
  797. If such a function is mutually-recursive with a non-INLINE thing,
  798. then the latter should be the loop-breaker.
  799. Usually this is just a question of optimisation. But a particularly
  800. bad case is wrappers generated by the demand analyser: if you make
  801. then into a loop breaker you may get an infinite inlining loop. For
  802. example:
  803. rec {
  804. $wfoo x = ....foo x....
  805. {-loop brk-} foo x = ...$wfoo x...
  806. }
  807. The interface file sees the unfolding for $wfoo, and sees that foo is
  808. strict (and hence it gets an auto-generated wrapper). Result: an
  809. infinite inlining in the importing scope. So be a bit careful if you
  810. change this. A good example is Tree.repTree in
  811. nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
  812. breaker then compiling Game.hs goes into an infinite loop. This
  813. happened when we gave is_con_app a lower score than inline candidates:
  814. Tree.repTree
  815. = __inline_me (/\a. \w w1 w2 ->
  816. case Tree.$wrepTree @ a w w1 w2 of
  817. { (# ww1, ww2 #) -> Branch @ a ww1 ww2 })
  818. Tree.$wrepTree
  819. = /\a w w1 w2 ->
  820. (# w2_smP, map a (Tree a) (Tree.repTree a w1 w) (w w2) #)
  821. Here we do *not* want to choose 'repTree' as the loop breaker.
  822. Note [DFuns should not be loop breakers]
  823. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  824. It's particularly bad to make a DFun into a loop breaker. See
  825. Note [How instance declarations are translated] in TcInstDcls
  826. We give DFuns a higher score than ordinary CONLIKE things because
  827. if there's a choice we want the DFun to be the non-looop breker. Eg
  828. rec { sc = /\ a \$dC. $fBWrap (T a) ($fCT @ a $dC)
  829. $fCT :: forall a_afE. (Roman.C a_afE) => Roman.C (Roman.T a_afE)
  830. {-# DFUN #-}
  831. $fCT = /\a \$dC. MkD (T a) ((sc @ a $dC) |> blah) ($ctoF @ a $dC)
  832. }
  833. Here 'sc' (the superclass) looks CONLIKE, but we'll never get to it
  834. if we can't unravel the DFun first.
  835. Note [Constructor applications]
  836. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  837. It's really really important to inline dictionaries. Real
  838. example (the Enum Ordering instance from GHC.Base):
  839. rec f = \ x -> case d of (p,q,r) -> p x
  840. g = \ x -> case d of (p,q,r) -> q x
  841. d = (v, f, g)
  842. Here, f and g occur just once; but we can't inline them into d.
  843. On the other hand we *could* simplify those case expressions if
  844. we didn't stupidly choose d as the loop breaker.
  845. But we won't because constructor args are marked "Many".
  846. Inlining dictionaries is really essential to unravelling
  847. the loops in static numeric dictionaries, see GHC.Float.
  848. Note [Closure conversion]
  849. ~~~~~~~~~~~~~~~~~~~~~~~~~
  850. We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
  851. The immediate motivation came from the result of a closure-conversion transformation
  852. which generated code like this:
  853. data Clo a b = forall c. Clo (c -> a -> b) c
  854. ($:) :: Clo a b -> a -> b
  855. Clo f env $: x = f env x
  856. rec { plus = Clo plus1 ()
  857. ; plus1 _ n = Clo plus2 n
  858. ; plus2 Zero n = n
  859. ; plus2 (Succ m) n = Succ (plus $: m $: n) }
  860. If we inline 'plus' and 'plus1', everything unravels nicely. But if
  861. we choose 'plus1' as the loop breaker (which is entirely possible
  862. otherwise), the loop does not unravel nicely.
  863. @occAnalRhs@ deals with the question of bindings where the Id is marked
  864. by an INLINE pragma. For these we record that anything which occurs
  865. in its RHS occurs many times. This pessimistically assumes that ths
  866. inlined binder also occurs many times in its scope, but if it doesn't
  867. we'll catch it next time round. At worst this costs an extra simplifier pass.
  868. ToDo: try using the occurrence info for the inline'd binder.
  869. [March 97] We do the same for atomic RHSs. Reason: see notes with loopBreakSCC.
  870. [June 98, SLPJ] I've undone this change; I don't understand it. See notes with loopBreakSCC.
  871. \begin{code}
  872. occAnalRhs :: OccEnv
  873. -> Maybe Id -> CoreExpr -- Binder and rhs
  874. -- Just b => non-rec, and alrady tagged with occurrence info
  875. -- Nothing => Rec, no occ info
  876. -> (UsageDetails, CoreExpr)
  877. -- Returned usage details covers only the RHS,
  878. -- and *not* the RULE or INLINE template for the Id
  879. occAnalRhs env mb_bndr rhs
  880. = occAnal ctxt rhs
  881. where
  882. -- See Note [Cascading inlines]
  883. ctxt = case mb_bndr of
  884. Just b | certainly_inline b -> env
  885. _other -> rhsCtxt env
  886. certainly_inline bndr -- See Note [Cascading inlines]
  887. = case idOccInfo bndr of
  888. OneOcc in_lam one_br _ -> not in_lam && one_br && active && not_stable
  889. _ -> False
  890. where
  891. active = isAlwaysActive (idInlineActivation bndr)
  892. not_stable = not (isStableUnfolding (idUnfolding bndr))
  893. addIdOccs :: UsageDetails -> VarSet -> UsageDetails
  894. addIdOccs usage id_set = foldVarSet add usage id_set
  895. where
  896. add v u | isId v = addOneOcc u v NoOccInfo
  897. | otherwise = u
  898. -- Give a non-committal binder info (i.e NoOccInfo) because
  899. -- a) Many copies of the specialised thing can appear
  900. -- b) We don't want to substitute a BIG expression inside a RULE
  901. -- even if that's the only occurrence of the thing
  902. -- (Same goes for INLINE.)
  903. \end{code}
  904. Note [Cascading inlines]
  905. ~~~~~~~~~~~~~~~~~~~~~~~~
  906. By default we use an rhsCtxt for the RHS of a binding. This tells the
  907. occ anal n that it's looking at an RHS, which has an effect in
  908. occAnalApp. In particular, for constructor applications, it makes
  909. the arguments appear to have NoOccInfo, so that we don't inline into
  910. them. Thus x = f y
  911. k = Just x
  912. we do not want to inline x.
  913. But there's a problem. Consider
  914. x1 = a0 : []
  915. x2 = a1 : x1
  916. x3 = a2 : x2
  917. g = f x3
  918. First time round, it looks as if x1 and x2 occur as an arg of a
  919. let-bound constructor ==> give them a many-occurrence.
  920. But then x3 is inlined (unconditionally as it happens) and
  921. next time round, x2 will be, and the next time round x1 will be
  922. Result: multiple simplifier iterations. Sigh.
  923. So, when analysing the RHS of x3 we notice that x3 will itself
  924. definitely inline the next time round, and so we analyse x3's rhs in
  925. an ordinary context, not rhsCtxt. Hence the "certainly_inline" stuff.
  926. Annoyingly, we have to approximate SimplUtils.preInlineUnconditionally.
  927. If we say "yes" when preInlineUnconditionally says "no" the simplifier iterates
  928. indefinitely:
  929. x = f y
  930. k = Just x
  931. inline ==>
  932. k = Just (f y)
  933. float ==>
  934. x1 = f y
  935. k = Just x1
  936. This is worse than the slow cascade, so we only want to say "certainly_inline"
  937. if it really is certain. Look at the note with preInlineUnconditionally
  938. for the various clauses.
  939. Expressions
  940. ~~~~~~~~~~~
  941. \begin{code}
  942. occAnal :: OccEnv
  943. -> CoreExpr
  944. -> (UsageDetails, -- Gives info only about the "interesting" Ids
  945. CoreExpr)
  946. occAnal _ expr@(Type _) = (emptyDetails, expr)
  947. occAnal _ expr@(Lit _) = (emptyDetails, expr)
  948. occAnal env expr@(Var v) = (mkOneOcc env v False, expr)
  949. -- At one stage, I gathered the idRuleVars for v here too,
  950. -- which in a way is the right thing to do.
  951. -- But that went wrong right after specialisation, when
  952. -- the *occurrences* of the overloaded function didn't have any
  953. -- rules in them, so the *specialised* versions looked as if they
  954. -- weren't used at all.
  955. occAnal _ (Coercion co)
  956. = (addIdOccs emptyDetails (coVarsOfCo co), Coercion co)
  957. -- See Note [Gather occurrences of coercion veriables]
  958. \end{code}
  959. Note [Gather occurrences of coercion veriables]
  960. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  961. We need to gather info about what coercion variables appear, so that
  962. we can sort them into the right place when doing dependency analysis.
  963. \begin{code}
  964. occAnal env (Tick tickish body)
  965. | Breakpoint _ ids <- tickish
  966. = (mapVarEnv markInsideSCC usage
  967. +++ mkVarEnv (zip ids (repeat NoOccInfo)), Tick tickish body')
  968. -- never substitute for any of the Ids in a Breakpoint
  969. | tickishScoped tickish
  970. = (mapVarEnv markInsideSCC usage, Tick tickish body')
  971. | otherwise
  972. = (usage, Tick tickish body')
  973. where
  974. !(usage,body') = occAnal env body
  975. occAnal env (Cast expr co)
  976. = case occAnal env expr of { (usage, expr') ->
  977. let usage1 = markManyIf (isRhsEnv env) usage
  978. usage2 = addIdOccs usage1 (coVarsOfCo co)
  979. -- See Note [Gather occurrences of coercion veriables]
  980. in (usage2, Cast expr' co)
  981. -- If we see let x = y `cast` co
  982. -- then mark y as 'Many' so that we don't
  983. -- immediately inline y again.
  984. }
  985. \end{code}
  986. \begin{code}
  987. occAnal env app@(App _ _)
  988. = occAnalApp env (collectArgs app)
  989. -- Ignore type variables altogether
  990. -- (a) occurrences inside type lambdas only not marked as InsideLam
  991. -- (b) type variables not in environment
  992. occAnal env (Lam x body) | isTyVar x
  993. = case occAnal env body of { (body_usage, body') ->
  994. (body_usage, Lam x body')
  995. }
  996. -- For value lambdas we do a special hack. Consider
  997. -- (\x. \y. ...x...)
  998. -- If we did nothing, x is used inside the \y, so would be marked
  999. -- as dangerous to dup. But in the common case where the abstraction
  1000. -- is applied to two arguments this is over-pessimistic.
  1001. -- So instead, we just mark each binder with its occurrence
  1002. -- info in the *body* of the multiple lambda.
  1003. -- Then, the simplifier is careful when partially applying lambdas.
  1004. occAnal env expr@(Lam _ _)
  1005. = case occAnal env_body body of { (body_usage, body') ->
  1006. let
  1007. (final_usage, tagged_binders) = tagLamBinders body_usage binders'
  1008. -- Use binders' to put one-shot info on the lambdas
  1009. -- URGH! Sept 99: we don't seem to be able to use binders' here, because
  1010. -- we get linear-typed things in the resulting program that we can't handle yet.
  1011. -- (e.g. PrelShow) TODO
  1012. really_final_usage = if linear then
  1013. final_usage
  1014. else
  1015. mapVarEnv markInsideLam final_usage
  1016. in
  1017. (really_final_usage,
  1018. mkLams tagged_binders body') }
  1019. where
  1020. env_body = vanillaCtxt env
  1021. -- Body is (no longer) an RhsContext
  1022. (binders, body) = collectBinders expr
  1023. binders' = oneShotGroup env binders
  1024. linear = all is_one_shot binders'
  1025. is_one_shot b = isId b && isOneShotBndr b
  1026. occAnal env (Case scrut bndr ty alts)
  1027. = case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
  1028. case mapAndUnzip occ_anal_alt alts of { (alts_usage_s, alts') ->
  1029. let
  1030. alts_usage = foldr combineAltsUsageDetails emptyDetails alts_usage_s
  1031. (alts_usage1, tagged_bndr) = tag_case_bndr alts_usage bndr
  1032. total_usage = scrut_usage +++ alts_usage1
  1033. in
  1034. total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
  1035. where
  1036. -- Note [Case binder usage]
  1037. -- ~~~~~~~~~~~~~~~~~~~~~~~~
  1038. -- The case binder gets a usage of either "many" or "dead", never "one".
  1039. -- Reason: we like to inline single occurrences, to eliminate a binding,
  1040. -- but inlining a case binder *doesn't* eliminate a binding.
  1041. -- We *don't* want to transform
  1042. -- case x of w { (p,q) -> f w }
  1043. -- into
  1044. -- case x of w { (p,q) -> f (p,q) }
  1045. tag_case_bndr usage bndr
  1046. = case lookupVarEnv usage bndr of
  1047. Nothing -> (usage, setIdOccInfo bndr IAmDead)
  1048. Just _ -> (usage `delVarEnv` bndr, setIdOccInfo bndr NoOccInfo)
  1049. alt_env = mkAltEnv env scrut bndr
  1050. occ_anal_alt = occAnalAlt alt_env bndr
  1051. occ_anal_scrut (Var v) (alt1 : other_alts)
  1052. | not (null other_alts) || not (isDefaultAlt alt1)
  1053. = (mkOneOcc env v True, Var v) -- The 'True' says that the variable occurs
  1054. -- in an interesting context; the case has
  1055. -- at least one non-default alternative
  1056. occ_anal_scrut scrut _alts
  1057. = occAnal (vanillaCtxt env) scrut -- No need for rhsCtxt
  1058. occAnal env (Let bind body)
  1059. = case occAnal env body of { (body_usage, body') ->
  1060. case occAnalBind env env emptyVarEnv bind body_usage of { (final_usage, new_binds) ->
  1061. (final_usage, mkLets new_binds body') }}
  1062. occAnalArgs :: OccEnv -> [CoreExpr] -> (UsageDetails, [CoreExpr])
  1063. occAnalArgs env args
  1064. = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
  1065. (foldr (+++) emptyDetails arg_uds_s, args')}
  1066. where
  1067. arg_env = vanillaCtxt env
  1068. \end{code}
  1069. Applications are dealt with specially because we want
  1070. the "build hack" to work.
  1071. Note [Arguments of let-bound constructors]
  1072. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1073. Consider
  1074. f x = let y = expensive x in
  1075. let z = (True,y) in
  1076. (case z of {(p,q)->q}, case z of {(p,q)->q})
  1077. We feel free to duplicate the WHNF (True,y), but that means
  1078. that y may be duplicated thereby.
  1079. If we aren't careful we duplicate the (expensive x) call!
  1080. Constructors are rather like lambdas in this way.
  1081. \begin{code}
  1082. occAnalApp :: OccEnv
  1083. -> (Expr CoreBndr, [Arg CoreBndr])
  1084. -> (UsageDetails, Expr CoreBndr)
  1085. occAnalApp env (Var fun, args)
  1086. = case args_stuff of { (args_uds, args') ->
  1087. let
  1088. final_args_uds = markManyIf (isRhsEnv env && is_exp) args_uds
  1089. -- We mark the free vars of the argument of a constructor or PAP
  1090. -- as "many", if it is the RHS of a let(rec).
  1091. -- This means that nothing gets inlined into a constructor argument
  1092. -- position, which is what we want. Typically those constructor
  1093. -- arguments are just variables, or trivial expressions.
  1094. --
  1095. -- This is the *whole point* of the isRhsEnv predicate
  1096. -- See Note [Arguments of let-bound constructors]
  1097. in
  1098. (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
  1099. where
  1100. fun_uniq = idUnique fun
  1101. fun_uds = mkOneOcc env fun (valArgCount args > 0)
  1102. is_exp = isExpandableApp fun (valArgCount args)
  1103. -- See Note [CONLIKE pragma] in BasicTypes
  1104. -- The definition of is_exp should match that in
  1105. -- Simplify.prepareRhs
  1106. -- Hack for build, fold, runST
  1107. args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
  1108. | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
  1109. | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
  1110. | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
  1111. -- (foldr k z xs) may call k many times, but it never
  1112. -- shares a partial application of k; hence [False,True]
  1113. -- This means we can optimise
  1114. -- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
  1115. -- by floating in the v
  1116. | otherwise = occAnalArgs env args
  1117. occAnalApp env (fun, args)
  1118. = case occAnal (addAppCtxt env args) fun of { (fun_uds, fun') ->
  1119. -- The addAppCtxt is a bit cunning. One iteration of the simplifier
  1120. -- often leaves behind beta redexs like
  1121. -- (\x y -> e) a1 a2
  1122. -- Here we would like to mark x,y as one-shot, and treat the whole
  1123. -- thing much like a let. We do this by pushing some True items
  1124. -- onto the context stack.
  1125. case occAnalArgs env args of { (args_uds, args') ->
  1126. let
  1127. final_uds = fun_uds +++ args_uds
  1128. in
  1129. (final_uds, mkApps fun' args') }}
  1130. markManyIf :: Bool -- If this is true
  1131. -> UsageDetails -- Then do markMany on this
  1132. -> UsageDetails
  1133. markManyIf True uds = mapVarEnv markMany uds
  1134. markManyIf False uds = uds
  1135. appSpecial :: OccEnv
  1136. -> Int -> CtxtTy -- Argument number, and context to use for it
  1137. -> [CoreExpr]
  1138. -> (UsageDetails, [CoreExpr])
  1139. appSpecial env n ctxt args
  1140. = go n args
  1141. where
  1142. arg_env = vanillaCtxt env
  1143. go _ [] = (emptyDetails, []) -- Too few args
  1144. go 1 (arg:args) -- The magic arg
  1145. = case occAnal (setCtxtTy arg_env ctxt) arg of { (arg_uds, arg') ->
  1146. case occAnalArgs env args of { (args_uds, args') ->
  1147. (arg_uds +++ args_uds, arg':args') }}
  1148. go n (arg:args)
  1149. = case occAnal arg_env arg of { (arg_uds, arg') ->
  1150. case go (n-1) args of { (args_uds, args') ->
  1151. (arg_uds +++ args_uds, arg':args') }}
  1152. \end{code}
  1153. Note [Binders in case alternatives]
  1154. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1155. Consider
  1156. case x of y { (a,b) -> f y }
  1157. We treat 'a', 'b' as dead, because they don't physically occur in the
  1158. case alternative. (Indeed, a variable is dead iff it doesn't occur in
  1159. its scope in the output of OccAnal.) It really helps to know when
  1160. binders are unused. See esp the call to isDeadBinder in
  1161. Simplify.mkDupableAlt
  1162. In this example, though, the Simplifier will bring 'a' and 'b' back to
  1163. life, beause it binds 'y' to (a,b) (imagine got inlined and
  1164. scrutinised y).
  1165. \begin{code}
  1166. occAnalAlt :: (OccEnv, Maybe (Id, CoreExpr))
  1167. -> CoreBndr
  1168. -> CoreAlt
  1169. -> (UsageDetails, Alt IdWithOccInfo)
  1170. occAnalAlt (env, scrut_bind) case_bndr (con, bndrs, rhs)
  1171. = case occAnal env rhs of { (rhs_usage1, rhs1) ->
  1172. let
  1173. (rhs_usage2, rhs2) =
  1174. wrapProxy (occ_binder_swap env) scrut_bind case_bndr rhs_usage1 rhs1
  1175. (alt_usg, tagged_bndrs) = tagLamBinders rhs_usage2 bndrs
  1176. bndrs' = tagged_bndrs -- See Note [Binders in case alternatives]
  1177. in
  1178. (alt_usg, (con, bndrs', rhs2)) }
  1179. wrapProxy :: Bool -> Maybe (Id, CoreExpr) -> Id -> UsageDetails -> CoreExpr -> (UsageDetails, CoreExpr)
  1180. wrapProxy enable_binder_swap (Just (scrut_var, rhs)) case_bndr body_usg body
  1181. | enable_binder_swap,
  1182. scrut_var `usedIn` body_usg
  1183. = ( body_usg' +++ unitVarEnv case_bndr NoOccInfo
  1184. , Let (NonRec tagged_scrut_var rhs) body )
  1185. where
  1186. (body_usg', tagged_scrut_var) = tagBinder body_usg scrut_var
  1187. wrapProxy _ _ _ body_usg body
  1188. = (body_usg, body)
  1189. \end{code}
  1190. %************************************************************************
  1191. %* *
  1192. OccEnv
  1193. %* *
  1194. %************************************************************************
  1195. \begin{code}
  1196. data OccEnv
  1197. = OccEnv { occ_encl :: !OccEncl -- Enclosing context information
  1198. , occ_ctxt :: !CtxtTy -- Tells about linearity
  1199. , occ_gbl_scrut :: GlobalScruts
  1200. , occ_rule_act :: Activation -> Bool -- Which rules are active
  1201. -- See Note [Finding rule RHS free vars]
  1202. , occ_binder_swap :: !Bool -- enable the binder_swap
  1203. -- See CorePrep Note [Dead code in CorePrep]
  1204. }
  1205. type GlobalScruts = IdSet -- See Note [Binder swap on GlobalId scrutinees]
  1206. -----------------------------
  1207. -- OccEncl is used to control whether to inline into constructor arguments
  1208. -- For example:
  1209. -- x = (p,q) -- Don't inline p or q
  1210. -- y = /\a -> (p a, q a) -- Still don't inline p or q
  1211. -- z = f (p,q) -- Do inline p,q; it may make a rule fire
  1212. -- So OccEncl tells enought about the context to know what to do when
  1213. -- we encounter a contructor application or PAP.
  1214. data OccEncl
  1215. = OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
  1216. -- Don't inline into constructor args here
  1217. | OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
  1218. -- Do inline into constructor args here
  1219. instance Outputable OccEncl where
  1220. ppr OccRhs = ptext (sLit "occRhs")
  1221. ppr OccVanilla = ptext (sLit "occVanilla")
  1222. type CtxtTy = [Bool]
  1223. -- [] No info
  1224. --
  1225. -- True:ctxt Analysing a function-valued expression that will be
  1226. -- applied just once
  1227. --
  1228. -- False:ctxt Analysing a function-valued expression that may
  1229. -- be applied many times; but when it is,
  1230. -- the CtxtTy inside applies
  1231. initOccEnv :: (Activation -> Bool) -> OccEnv
  1232. initOccEnv active_rule
  1233. = OccEnv { occ_encl = OccVanilla
  1234. , occ_ctxt = []
  1235. , occ_gbl_scrut = emptyVarSet -- PE emptyVarEnv emptyVarSet
  1236. , occ_rule_act = active_rule
  1237. , occ_binder_swap = True }
  1238. vanillaCtxt :: OccEnv -> OccEnv
  1239. vanillaCtxt env = env { occ_encl = OccVanilla, occ_ctxt = [] }
  1240. rhsCtxt :: OccEnv -> OccEnv
  1241. rhsCtxt env = env { occ_encl = OccRhs, occ_ctxt = [] }
  1242. setCtxtTy :: OccEnv -> CtxtTy -> OccEnv
  1243. setCtxtTy env ctxt = env { occ_ctxt = ctxt }
  1244. isRhsEnv :: OccEnv -> Bool
  1245. isRhsEnv (OccEnv { occ_encl = OccRhs }) = True
  1246. isRhsEnv (OccEnv { occ_encl = OccVanilla }) = False
  1247. oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
  1248. -- The result binders have one-shot-ness set that they might not have had originally.
  1249. -- This happens in (build (\cn -> e)). Here the occurrence analyser
  1250. -- linearity context knows that c,n are one-shot, and it records that fact in
  1251. -- the binder. This is useful to guide subsequent float-in/float-out tranformations
  1252. oneShotGroup (OccEnv { occ_ctxt = ctxt }) bndrs
  1253. = go ctxt bndrs []
  1254. where
  1255. go _ [] rev_bndrs = reverse rev_bndrs
  1256. go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
  1257. | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
  1258. where
  1259. bndr' | lin_ctxt = setOneShotLambda bndr
  1260. | otherwise = bndr
  1261. go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
  1262. addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
  1263. addAppCtxt env@(OccEnv { occ_ctxt = ctxt }) args
  1264. = env { occ_ctxt = replicate (valArgCount args) True ++ ctxt }
  1265. \end{code}
  1266. \begin{code}
  1267. transClosureFV :: UniqFM VarSet -> UniqFM VarSet
  1268. -- If (f,g), (g,h) are in the input, then (f,h) is in the output
  1269. -- as well as (f,g), (g,h)
  1270. transClosureFV env
  1271. | no_change = env
  1272. | otherwise = transClosureFV (listToUFM new_fv_list)
  1273. where
  1274. (no_change, new_fv_list) = mapAccumL bump True (ufmToList env)
  1275. bump no_change (b,fvs)
  1276. | no_change_here = (no_change, (b,fvs))
  1277. | otherwise = (False, (b,new_fvs))
  1278. where
  1279. (new_fvs, no_change_here) = extendFvs env fvs
  1280. -------------
  1281. extendFvs_ :: UniqFM VarSet -> VarSet -> VarSet
  1282. extendFvs_ env s = fst (extendFvs env s) -- Discard the Bool flag
  1283. extendFvs :: UniqFM VarSet -> VarSet -> (VarSet, Bool)
  1284. -- (extendFVs env s) returns
  1285. -- (s `union` env(s), env(s) `subset` s)
  1286. extendFvs env s
  1287. | isNullUFM env
  1288. = (s, True)
  1289. | otherwise
  1290. = (s `unionVarSet` extras, extras `subVarSet` s)
  1291. where
  1292. extras :: VarSet -- env(s)
  1293. extras = foldUFM unionVarSet emptyVarSet $
  1294. intersectUFM_C (\x _ -> x) env s
  1295. \end{code}
  1296. %************************************************************************
  1297. %* *
  1298. Binder swap
  1299. %* *
  1300. %************************************************************************
  1301. Note [Binder swap]
  1302. ~~~~~~~~~~~~~~~~~~
  1303. We do these two transformations right here:
  1304. (1) case x of b { pi -> ri }
  1305. ==>
  1306. case x of b { pi -> let x=b in ri }
  1307. (2) case (x |> co) of b { pi -> ri }
  1308. ==>
  1309. case (x |> co) of b { pi -> let x = b |> sym co in ri }
  1310. Why (2)? See Note [Case of cast]
  1311. In both cases, in a particular alternative (pi -> ri), we only
  1312. add the binding if
  1313. (a) x occurs free in (pi -> ri)
  1314. (ie it occurs in ri, but is not bound in pi)
  1315. (b) the pi does not bind b (or the free vars of co)
  1316. We need (a) and (b) for the inserted binding to be correct.
  1317. For the alternatives where we inject the binding, we can transfer
  1318. all x's OccInfo to b. And that is the point.
  1319. Notice that
  1320. * The deliberate shadowing of 'x'.
  1321. * That (a) rapidly becomes false, so no bindings are injected.
  1322. The reason for doing these transformations here is because it allows
  1323. us to adjust the OccInfo for 'x' and 'b' as we go.
  1324. * Suppose the only occurrences of 'x' are the scrutinee and in the
  1325. ri; then this transformation makes it occur just once, and hence
  1326. get inlined right away.
  1327. * If we do this in the Simplifier, we don't know whether 'x' is used
  1328. in ri, so we are forced to pessimistically zap b's OccInfo even
  1329. though it is typically dead (ie neither it nor x appear in the
  1330. ri). There's nothing actually wrong with zapping it, except that
  1331. it's kind of nice to know which variables are dead. My nose
  1332. tells me to keep this information as robustly as possible.
  1333. The Maybe (Id,CoreExpr) passed to occAnalAlt is the extra let-binding
  1334. {x=b}; it's Nothing if the binder-swap doesn't happen.
  1335. There is a danger though. Consider
  1336. let v = x +# y
  1337. in case (f v) of w -> ...v...v...
  1338. And suppose that (f v) expands to just v. Then we'd like to
  1339. use 'w' instead of 'v' in the alternative. But it may be too
  1340. late; we may have substituted the (cheap) x+#y for v in the
  1341. same simplifier pass that reduced (f v) to v.
  1342. I think this is just too bad. CSE will recover some of it.
  1343. Note [Case of cast]
  1344. ~~~~~~~~~~~~~~~~~~~
  1345. Consider case (x `cast` co) of b { I# ->
  1346. ... (case (x `cast` co) of {...}) ...
  1347. We'd like to eliminate the inner case. That is the motivation for
  1348. equation (2) in Note [Binder swap]. When we get to the inner case, we
  1349. inline x, cancel the casts, and away we go.
  1350. Note [Binder swap on GlobalId scrutinees]
  1351. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1352. When the scrutinee is a GlobalId we must take care in two ways
  1353. i) In order to *know* whether 'x' occurs free in the RHS, we need its
  1354. occurrence info. BUT, we don't gather occurrence info for
  1355. GlobalIds. That's the reason for the (small) occ_gbl_scrut env in
  1356. OccEnv is for: it says "gather occurrence info for these.
  1357. ii) We must call localiseId on 'x' first, in case it's a GlobalId, or
  1358. has an External Name. See, for example, SimplEnv Note [Global Ids in
  1359. the substitution].
  1360. Note [Zap case binders in proxy bindings]
  1361. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1362. From the original
  1363. case x of cb(dead) { p -> ...x... }
  1364. we will get
  1365. case x of cb(live) { p -> let x = cb in ...x... }
  1366. Core Lint never expects to find an *occurence* of an Id marked
  1367. as Dead, so we must zap the OccInfo on cb before making the
  1368. binding x = cb. See Trac #5028.
  1369. Historical note [no-case-of-case]
  1370. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1371. We *used* to suppress the binder-swap in case expressions when
  1372. -fno-case-of-case is on. Old remarks:
  1373. "This happens in the first simplifier pass,
  1374. and enhances full laziness. Here's the bad case:
  1375. f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
  1376. If we eliminate the inner case, we trap it inside the I# v -> arm,
  1377. which might prevent some full laziness happening. I've seen this
  1378. in action in spectral/cichelli/Prog.hs:
  1379. [(m,n) | m <- [1..max], n <- [1..max]]
  1380. Hence the check for NoCaseOfCase."
  1381. However, now the full-laziness pass itself reverses the binder-swap, so this
  1382. check is no longer necessary.
  1383. Historical note [Suppressing the case binder-swap]
  1384. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1385. This old note describes a problem that is also fixed by doing the
  1386. binder-swap in OccAnal:
  1387. There is another situation when it might make sense to suppress the
  1388. case-expression binde-swap. If we have
  1389. case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
  1390. ...other cases .... }
  1391. We'll perform the binder-swap for the outer case, giving
  1392. case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
  1393. ...other cases .... }
  1394. But there is no point in doing it for the inner case, because w1 can't
  1395. be inlined anyway. Furthermore, doing the case-swapping involves
  1396. zapping w2's occurrence info (see paragraphs that follow), and that
  1397. forces us to bind w2 when doing case merging. So we get
  1398. case x of w1 { A -> let w2 = w1 in e1
  1399. B -> let w2 = w1 in e2
  1400. ...other cases .... }
  1401. This is plain silly in the common case where w2 is dead.
  1402. Even so, I can't see a good way to implement this idea. I tried
  1403. not doing the binder-swap if the scrutinee was already evaluated
  1404. but that failed big-time:
  1405. data T = MkT !Int
  1406. case v of w { MkT x ->
  1407. case x of x1 { I# y1 ->
  1408. case x of x2 { I# y2 -> ...
  1409. Notice that because MkT is strict, x is marked "evaluated". But to
  1410. eliminate the last case, we must either make sure that x (as well as
  1411. x1) has unfolding MkT y1. THe straightforward thing to do is to do
  1412. the binder-swap. So this whole note is a no-op.
  1413. It's fixed by doing the binder-swap in OccAnal because we can do the
  1414. binder-swap unconditionally and still get occurrence analysis
  1415. information right.
  1416. \begin{code}
  1417. mkAltEnv :: OccEnv -> CoreExpr -> Id -> (OccEnv, Maybe (Id, CoreExpr))
  1418. -- Does two things: a) makes the occ_ctxt = OccVanilla
  1419. -- b) extends the GlobalScruts if possible
  1420. -- c) returns a proxy mapping, binding the scrutinee
  1421. -- to the case binder, if possible
  1422. mkAltEnv env@(OccEnv { occ_gbl_scrut = pe }) scrut case_bndr
  1423. = case scrut of
  1424. Var v -> add_scrut v case_bndr'
  1425. Cast (Var v) co -> add_scrut v (Cast case_bndr' (mkSymCo co))
  1426. -- See Note [Case of cast]
  1427. _ -> (env { occ_encl = OccVanilla }, Nothing)
  1428. where
  1429. add_scrut v rhs = ( env { occ_encl = OccVanilla, occ_gbl_scrut = pe `extendVarSet` v }
  1430. , Just (localise v, rhs) )
  1431. case_bndr' = Var (zapIdOccInfo case_bndr) -- See Note [Zap case binders in proxy bindings]
  1432. localise scrut_var = mkLocalId (localiseName (idName scrut_var)) (idType scrut_var)
  1433. -- Localise the scrut_var before shadowing it; we're making a
  1434. -- new binding for it, and it might have an External Name, or
  1435. -- even be a GlobalId; Note [Binder swap on GlobalId scrutinees]
  1436. -- Also we don't want any INLINE or NOINLINE pragmas!
  1437. \end{code}
  1438. %************************************************************************
  1439. %* *
  1440. \subsection[OccurAnal-types]{OccEnv}
  1441. %* *
  1442. %************************************************************************
  1443. \begin{code}
  1444. type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
  1445. -- INVARIANT: never IAmDead
  1446. -- (Deadness is signalled by not being in the map at all)
  1447. (+++), combineAltsUsageDetails
  1448. :: UsageDetails -> UsageDetails -> UsageDetails
  1449. (+++) usage1 usage2
  1450. = plusVarEnv_C addOccInfo usage1 usage2
  1451. combineAltsUsageDetails usage1 usage2
  1452. = plusVarEnv_C orOccInfo usage1 usage2
  1453. addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
  1454. addOneOcc usage id info
  1455. = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
  1456. -- ToDo: make this more efficient
  1457. emptyDetails :: UsageDetails
  1458. emptyDetails = (emptyVarEnv :: UsageDetails)
  1459. usedIn :: Id -> UsageDetails -> Bool
  1460. v `usedIn` details = isExportedId v || v `elemVarEnv` details
  1461. type IdWithOccInfo = Id
  1462. tagLamBinders :: UsageDetails -- Of scope
  1463. -> [Id] -- Binders
  1464. -> (UsageDetails, -- Details with binders removed
  1465. [IdWithOccInfo]) -- Tagged binders
  1466. -- Used for lambda and case binders
  1467. -- It copes with the fact that lambda bindings can have InlineRule
  1468. -- unfoldings, used for join points
  1469. tagLamBinders usage binders = usage' `seq` (usage', bndrs')
  1470. where
  1471. (usage', bndrs') = mapAccumR tag_lam usage binders
  1472. tag_lam usage bndr = (usage2, setBinderOcc usage bndr)
  1473. where
  1474. usage1 = usage `delVarEnv` bndr
  1475. usage2 | isId bndr = addIdOccs usage1 (idUnfoldingVars bndr)
  1476. | otherwise = usage1
  1477. tagBinder :: UsageDetails -- Of scope
  1478. -> Id -- Binders
  1479. -> (UsageDetails, -- Details with binders removed
  1480. IdWithOccInfo) -- Tagged binders
  1481. tagBinder usage binder
  1482. = let
  1483. usage' = usage `delVarEnv` binder
  1484. binder' = setBinderOcc usage binder
  1485. in
  1486. usage' `seq` (usage', binder')
  1487. setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
  1488. setBinderOcc usage bndr
  1489. | isTyVar bndr = bndr
  1490. | isExportedId bndr = case idOccInfo bndr of
  1491. NoOccInfo -> bndr
  1492. _ -> setIdOccInfo bndr NoOccInfo
  1493. -- Don't use local usage info for visible-elsewhere things
  1494. -- BUT *do* erase any IAmALoopBreaker annotation, because we're
  1495. -- about to re-generate it and it shouldn't be "sticky"
  1496. | otherwise = setIdOccInfo bndr occ_info
  1497. where
  1498. occ_info = lookupVarEnv usage bndr `orElse` IAmDead
  1499. \end{code}
  1500. %************************************************************************
  1501. %* *
  1502. \subsection{Operations over OccInfo}
  1503. %* *
  1504. %************************************************************************
  1505. \begin{code}
  1506. mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
  1507. mkOneOcc env id int_cxt
  1508. | isLocalId id
  1509. = unitVarEnv id (OneOcc False True int_cxt)
  1510. | id `elemVarEnv` occ_gbl_scrut env
  1511. = unitVarEnv id NoOccInfo
  1512. | otherwise
  1513. = emptyDetails
  1514. markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
  1515. markMany _ = NoOccInfo
  1516. markInsideSCC occ = markInsideLam occ
  1517. -- inside an SCC, we can inline lambdas only.
  1518. markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
  1519. markInsideLam occ = occ
  1520. addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
  1521. addOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
  1522. NoOccInfo -- Both branches are at least One
  1523. -- (Argument is never IAmDead)
  1524. -- (orOccInfo orig new) is used
  1525. -- when combining occurrence info from branches of a case
  1526. orOccInfo (OneOcc in_lam1 _ int_cxt1)
  1527. (OneOcc in_lam2 _ int_cxt2)
  1528. = OneOcc (in_lam1 || in_lam2)
  1529. False -- False, because it occurs in both branches
  1530. (int_cxt1 && int_cxt2)
  1531. orOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
  1532. NoOccInfo
  1533. \end{code}