PageRenderTime 75ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/simplCore/OccurAnal.lhs

https://bitbucket.org/carter/ghc
Haskell | 2025 lines | 1411 code | 354 blank | 260 comment | 113 complexity | ea05f00d043100fa11ab93570388d697 MD5 | raw file

Large files files are truncated, but you can click here to view the full 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

Large files files are truncated, but you can click here to view the full file