PageRenderTime 37ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/simplCore/OccurAnal.lhs

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