PageRenderTime 61ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/simplCore/OccurAnal.lhs

https://bitbucket.org/khibino/ghc-hack
Haskell | 1931 lines | 1347 code | 336 blank | 248 comment | 104 complexity | 5998137417091eeedb7e1a233fac88c4 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause, LGPL-3.0

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 ( mapAndUnzip, filterOut, fstOf3 )
  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. go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
  69. go _ []
  70. = (initial_uds, [])
  71. go env (bind:binds)
  72. = (final_usage, bind' ++ binds')
  73. where
  74. (bs_usage, binds') = go env binds
  75. (final_usage, bind') = occAnalBind env env bind bs_usage
  76. occurAnalyseExpr :: CoreExpr -> CoreExpr
  77. -- Do occurrence analysis, and discard occurence info returned
  78. occurAnalyseExpr expr
  79. = snd (occAnal (initOccEnv all_active_rules) expr)
  80. where
  81. -- To be conservative, we say that all inlines and rules are active
  82. all_active_rules = \_ -> True
  83. \end{code}
  84. %************************************************************************
  85. %* *
  86. \subsection[OccurAnal-main]{Counting occurrences: main function}
  87. %* *
  88. %************************************************************************
  89. Bindings
  90. ~~~~~~~~
  91. \begin{code}
  92. occAnalBind :: OccEnv -- The incoming OccEnv
  93. -> OccEnv -- Same, but trimmed by (binderOf bind)
  94. -> CoreBind
  95. -> UsageDetails -- Usage details of scope
  96. -> (UsageDetails, -- Of the whole let(rec)
  97. [CoreBind])
  98. occAnalBind env _ (NonRec binder rhs) body_usage
  99. | isTyVar binder -- A type let; we don't gather usage info
  100. = (body_usage, [NonRec binder rhs])
  101. | not (binder `usedIn` body_usage) -- It's not mentioned
  102. = (body_usage, [])
  103. | otherwise -- It's mentioned in the body
  104. = (body_usage' +++ rhs_usage3, [NonRec tagged_binder rhs'])
  105. where
  106. (body_usage', tagged_binder) = tagBinder body_usage binder
  107. (rhs_usage1, rhs') = occAnalRhs env (Just tagged_binder) rhs
  108. rhs_usage2 = addIdOccs rhs_usage1 (idUnfoldingVars binder)
  109. rhs_usage3 = addIdOccs rhs_usage2 (idRuleVars binder)
  110. -- See Note [Rules are extra RHSs] and Note [Rule dependency info]
  111. occAnalBind _ env (Rec pairs) body_usage
  112. = foldr occAnalRec (body_usage, []) sccs
  113. -- For a recursive group, we
  114. -- * occ-analyse all the RHSs
  115. -- * compute strongly-connected components
  116. -- * feed those components to occAnalRec
  117. where
  118. bndr_set = mkVarSet (map fst pairs)
  119. sccs :: [SCC (Node Details)]
  120. sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompFromEdgedVerticesR nodes
  121. nodes :: [Node Details]
  122. nodes = {-# SCC "occAnalBind.assoc" #-} map (makeNode env bndr_set) pairs
  123. \end{code}
  124. Note [Dead code]
  125. ~~~~~~~~~~~~~~~~
  126. Dropping dead code for recursive bindings is done in a very simple way:
  127. the entire set of bindings is dropped if none of its binders are
  128. mentioned in its body; otherwise none are.
  129. This seems to miss an obvious improvement.
  130. letrec f = ...g...
  131. g = ...f...
  132. in
  133. ...g...
  134. ===>
  135. letrec f = ...g...
  136. g = ...(...g...)...
  137. in
  138. ...g...
  139. Now 'f' is unused! But it's OK! Dependency analysis will sort this
  140. out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
  141. dropped. It isn't easy to do a perfect job in one blow. Consider
  142. letrec f = ...g...
  143. g = ...h...
  144. h = ...k...
  145. k = ...m...
  146. m = ...m...
  147. in
  148. ...m...
  149. ------------------------------------------------------------
  150. Note [Forming Rec groups]
  151. ~~~~~~~~~~~~~~~~~~~~~~~~~
  152. We put bindings {f = ef; g = eg } in a Rec group if "f uses g"
  153. and "g uses f", no matter how indirectly. We do a SCC analysis
  154. with an edge f -> g if "f uses g".
  155. More precisely, "f uses g" iff g should be in scope whereever f is.
  156. That is, g is free in:
  157. a) the rhs 'ef'
  158. b) or the RHS of a rule for f (Note [Rules are extra RHSs])
  159. c) or the LHS or a rule for f (Note [Rule dependency info])
  160. These conditions apply regardless of the activation of the RULE (eg it might be
  161. inactive in this phase but become active later). Once a Rec is broken up
  162. it can never be put back together, so we must be conservative.
  163. The principle is that, regardless of rule firings, every variale is
  164. always in scope.
  165. * Note [Rules are extra RHSs]
  166. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  167. A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
  168. keeps the specialised "children" alive. If the parent dies
  169. (because it isn't referenced any more), then the children will die
  170. too (unless they are already referenced directly).
  171. To that end, we build a Rec group for each cyclic strongly
  172. connected component,
  173. *treating f's rules as extra RHSs for 'f'*.
  174. More concretely, the SCC analysis runs on a graph with an edge
  175. from f -> g iff g is mentioned in
  176. (a) f's rhs
  177. (b) f's RULES
  178. These are rec_edges.
  179. Under (b) we include variables free in *either* LHS *or* RHS of
  180. the rule. The former might seems silly, but see Note [Rule
  181. dependency info]. So in Example [eftInt], eftInt and eftIntFB
  182. will be put in the same Rec, even though their 'main' RHSs are
  183. both non-recursive.
  184. * Note [Rule dependency info]
  185. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  186. The VarSet in a SpecInfo is used for dependency analysis in the
  187. occurrence analyser. We must track free vars in *both* lhs and rhs.
  188. Hence use of idRuleVars, rather than idRuleRhsVars in occAnalBind.
  189. Why both? Consider
  190. x = y
  191. RULE f x = v+4
  192. Then if we substitute y for x, we'd better do so in the
  193. rule's LHS too, so we'd better ensure the RULE appears to mention 'x'
  194. as well as 'v'
  195. * Note [Rules are visible in their own rec group]
  196. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  197. We want the rules for 'f' to be visible in f's right-hand side.
  198. And we'd like them to be visible in other functions in f's Rec
  199. group. E.g. in Note [Specialisation rules] we want f' rule
  200. to be visible in both f's RHS, and fs's RHS.
  201. This means that we must simplify the RULEs first, before looking
  202. at any of the definitions. This is done by Simplify.simplRecBind,
  203. when it calls addLetIdInfo.
  204. ------------------------------------------------------------
  205. Note [Choosing loop breakers]
  206. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  207. Loop breaking is surprisingly subtle. First read the section 4 of
  208. "Secrets of the GHC inliner". This describes our basic plan.
  209. We avoid infinite inlinings by choosing loop breakers, and
  210. ensuring that a loop breaker cuts each loop.
  211. Fundamentally, we do SCC analysis on a graph. For each recursive
  212. group we choose a loop breaker, delete all edges to that node,
  213. re-analyse the SCC, and iterate.
  214. But what is the graph? NOT the same graph as was used for Note
  215. [Forming Rec groups]! In particular, a RULE is like an equation for
  216. 'f' that is *always* inlined if it is applicable. We do *not* disable
  217. rules for loop-breakers. It's up to whoever makes the rules to make
  218. sure that the rules themselves always terminate. See Note [Rules for
  219. recursive functions] in Simplify.lhs
  220. Hence, if
  221. f's RHS (or its INLINE template if it has one) mentions g, and
  222. g has a RULE that mentions h, and
  223. h has a RULE that mentions f
  224. then we *must* choose f to be a loop breaker. Example: see Note
  225. [Specialisation rules].
  226. In general, take the free variables of f's RHS, and augment it with
  227. all the variables reachable by RULES from those starting points. That
  228. is the whole reason for computing rule_fv_env in occAnalBind. (Of
  229. course we only consider free vars that are also binders in this Rec
  230. group.) See also Note [Finding rule RHS free vars]
  231. Note that when we compute this rule_fv_env, we only consider variables
  232. free in the *RHS* of the rule, in contrast to the way we build the
  233. Rec group in the first place (Note [Rule dependency info])
  234. Note that if 'g' has RHS that mentions 'w', we should add w to
  235. g's loop-breaker edges. More concretely there is an edge from f -> g
  236. iff
  237. (a) g is mentioned in f's RHS `xor` f's INLINE rhs
  238. (see Note [Inline rules])
  239. (b) or h is mentioned in f's RHS, and
  240. g appears in the RHS of an active RULE of h
  241. or a transitive sequence of active rules starting with h
  242. Why "active rules"? See Note [Finding rule RHS free vars]
  243. Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
  244. chosen as a loop breaker, because their RHSs don't mention each other.
  245. And indeed both can be inlined safely.
  246. Note again that the edges of the graph we use for computing loop breakers
  247. are not the same as the edges we use for computing the Rec blocks.
  248. That's why we compute
  249. - rec_edges for the Rec block analysis
  250. - loop_breaker_edges for the loop breaker analysis
  251. * Note [Finding rule RHS free vars]
  252. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  253. Consider this real example from Data Parallel Haskell
  254. tagZero :: Array Int -> Array Tag
  255. {-# INLINE [1] tagZeroes #-}
  256. tagZero xs = pmap (\x -> fromBool (x==0)) xs
  257. {-# RULES "tagZero" [~1] forall xs n.
  258. pmap fromBool <blah blah> = tagZero xs #-}
  259. So tagZero's RHS mentions pmap, and pmap's RULE mentions tagZero.
  260. However, tagZero can only be inlined in phase 1 and later, while
  261. the RULE is only active *before* phase 1. So there's no problem.
  262. To make this work, we look for the RHS free vars only for
  263. *active* rules. That's the reason for the occ_rule_act field
  264. of the OccEnv.
  265. * Note [Weak loop breakers]
  266. ~~~~~~~~~~~~~~~~~~~~~~~~~
  267. There is a last nasty wrinkle. Suppose we have
  268. Rec { f = f_rhs
  269. RULE f [] = g
  270. h = h_rhs
  271. g = h
  272. ...more...
  273. }
  274. Remember that we simplify the RULES before any RHS (see Note
  275. [Rules are visible in their own rec group] above).
  276. So we must *not* postInlineUnconditionally 'g', even though
  277. its RHS turns out to be trivial. (I'm assuming that 'g' is
  278. not choosen as a loop breaker.) Why not? Because then we
  279. drop the binding for 'g', which leaves it out of scope in the
  280. RULE!
  281. Here's a somewhat different example of the same thing
  282. Rec { g = h
  283. ; h = ...f...
  284. ; f = f_rhs
  285. RULE f [] = g }
  286. Here the RULE is "below" g, but we *still* can't postInlineUnconditionally
  287. g, because the RULE for f is active throughout. So the RHS of h
  288. might rewrite to h = ...g...
  289. So g must remain in scope in the output program!
  290. We "solve" this by:
  291. Make g a "weak" loop breaker (OccInfo = IAmLoopBreaker True)
  292. iff g is a "missing free variable" of the Rec group
  293. A "missing free variable" x is one that is mentioned in an RHS or
  294. INLINE or RULE of a binding in the Rec group, but where the
  295. dependency on x may not show up in the loop_breaker_edges (see
  296. note [Choosing loop breakers} above).
  297. A normal "strong" loop breaker has IAmLoopBreaker False. So
  298. Inline postInlineUnconditionally
  299. IAmLoopBreaker False no no
  300. IAmLoopBreaker True yes no
  301. other yes yes
  302. The **sole** reason for this kind of loop breaker is so that
  303. postInlineUnconditionally does not fire. Ugh. (Typically it'll
  304. inline via the usual callSiteInline stuff, so it'll be dead in the
  305. next pass, so the main Ugh is the tiresome complication.)
  306. Note [Rules for imported functions]
  307. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  308. Consider this
  309. f = /\a. B.g a
  310. RULE B.g Int = 1 + f Int
  311. Note that
  312. * The RULE is for an imported function.
  313. * f is non-recursive
  314. Now we
  315. can get
  316. f Int --> B.g Int Inlining f
  317. --> 1 + f Int Firing RULE
  318. and so the simplifier goes into an infinite loop. This
  319. would not happen if the RULE was for a local function,
  320. because we keep track of dependencies through rules. But
  321. that is pretty much impossible to do for imported Ids. Suppose
  322. f's definition had been
  323. f = /\a. C.h a
  324. where (by some long and devious process), C.h eventually inlines to
  325. B.g. We could only spot such loops by exhaustively following
  326. unfoldings of C.h etc, in case we reach B.g, and hence (via the RULE)
  327. f.
  328. Note that RULES for imported functions are important in practice; they
  329. occur a lot in the libraries.
  330. We regard this potential infinite loop as a *programmer* error.
  331. It's up the programmer not to write silly rules like
  332. RULE f x = f x
  333. and the example above is just a more complicated version.
  334. Note [Specialising imported functions]
  335. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  336. BUT for *automatically-generated* rules, the programmer can't be
  337. responsible for the "programmer error" in Note [Rules for imported
  338. functions]. In paricular, consider specialising a recursive function
  339. defined in another module. If we specialise a recursive function B.g,
  340. we get
  341. g_spec = .....(B.g Int).....
  342. RULE B.g Int = g_spec
  343. Here, g_spec doesn't look recursive, but when the rule fires, it
  344. becomes so. And if B.g was mutually recursive, the loop might
  345. not be as obvious as it is here.
  346. To avoid this,
  347. * When specialising a function that is a loop breaker,
  348. give a NOINLINE pragma to the specialised function
  349. Note [Glomming]
  350. ~~~~~~~~~~~~~~~
  351. RULES for imported Ids can make something at the top refer to something at the bottom:
  352. f = \x -> B.g (q x)
  353. h = \y -> 3
  354. RULE: B.g (q x) = h x
  355. Applying this rule makes f refer to h, although f doesn't appear to
  356. depend on h. (And, as in Note [Rules for imported functions], the
  357. dependency might be more indirect. For example, f might mention C.t
  358. rather than B.g, where C.t eventually inlines to B.g.)
  359. NOTICE that this cannot happen for rules whose head is a
  360. locally-defined function, because we accurately track dependencies
  361. through RULES. It only happens for rules whose head is an imported
  362. function (B.g in the example above).
  363. Solution:
  364. - When simplifying, bring all top level identifiers into
  365. scope at the start, ignoring the Rec/NonRec structure, so
  366. that when 'h' pops up in f's rhs, we find it in the in-scope set
  367. (as the simplifier generally expects). This happens in simplTopBinds.
  368. - In the occurrence analyser, if there are any out-of-scope
  369. occurrences that pop out of the top, which will happen after
  370. firing the rule: f = \x -> h x
  371. h = \y -> 3
  372. then just glom all the bindings into a single Rec, so that
  373. the *next* iteration of the occurrence analyser will sort
  374. them all out. This part happens in occurAnalysePgm.
  375. ------------------------------------------------------------
  376. Note [Inline rules]
  377. ~~~~~~~~~~~~~~~~~~~
  378. None of the above stuff about RULES applies to Inline Rules,
  379. stored in a CoreUnfolding. The unfolding, if any, is simplified
  380. at the same time as the regular RHS of the function (ie *not* like
  381. Note [Rules are visible in their own rec group]), so it should be
  382. treated *exactly* like an extra RHS.
  383. Or, rather, when computing loop-breaker edges,
  384. * If f has an INLINE pragma, and it is active, we treat the
  385. INLINE rhs as f's rhs
  386. * If it's inactive, we treat f as having no rhs
  387. * If it has no INLINE pragma, we look at f's actual rhs
  388. There is a danger that we'll be sub-optimal if we see this
  389. f = ...f...
  390. [INLINE f = ..no f...]
  391. where f is recursive, but the INLINE is not. This can just about
  392. happen with a sufficiently odd set of rules; eg
  393. foo :: Int -> Int
  394. {-# INLINE [1] foo #-}
  395. foo x = x+1
  396. bar :: Int -> Int
  397. {-# INLINE [1] bar #-}
  398. bar x = foo x + 1
  399. {-# RULES "foo" [~1] forall x. foo x = bar x #-}
  400. Here the RULE makes bar recursive; but it's INLINE pragma remains
  401. non-recursive. It's tempting to then say that 'bar' should not be
  402. a loop breaker, but an attempt to do so goes wrong in two ways:
  403. a) We may get
  404. $df = ...$cfoo...
  405. $cfoo = ...$df....
  406. [INLINE $cfoo = ...no-$df...]
  407. But we want $cfoo to depend on $df explicitly so that we
  408. put the bindings in the right order to inline $df in $cfoo
  409. and perhaps break the loop altogether. (Maybe this
  410. b)
  411. Example [eftInt]
  412. ~~~~~~~~~~~~~~~
  413. Example (from GHC.Enum):
  414. eftInt :: Int# -> Int# -> [Int]
  415. eftInt x y = ...(non-recursive)...
  416. {-# INLINE [0] eftIntFB #-}
  417. eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
  418. eftIntFB c n x y = ...(non-recursive)...
  419. {-# RULES
  420. "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
  421. "eftIntList" [1] eftIntFB (:) [] = eftInt
  422. #-}
  423. Note [Specialisation rules]
  424. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  425. Consider this group, which is typical of what SpecConstr builds:
  426. fs a = ....f (C a)....
  427. f x = ....f (C a)....
  428. {-# RULE f (C a) = fs a #-}
  429. So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
  430. But watch out! If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
  431. - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
  432. - fs is inlined (say it's small)
  433. - now there's another opportunity to apply the RULE
  434. This showed up when compiling Control.Concurrent.Chan.getChanContents.
  435. \begin{code}
  436. type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
  437. -- which is gotten from the Id.
  438. data Details
  439. = ND { nd_bndr :: Id -- Binder
  440. , nd_rhs :: CoreExpr -- RHS, already occ-analysed
  441. , nd_uds :: UsageDetails -- Usage from RHS, and RULES, and InlineRule unfolding
  442. -- ignoring phase (ie assuming all are active)
  443. -- See Note [Forming Rec groups]
  444. , nd_inl :: IdSet -- Free variables of
  445. -- the InlineRule (if present and active)
  446. -- or the RHS (ir no InlineRule)
  447. -- but excluding any RULES
  448. -- This is the IdSet that may be used if the Id is inlined
  449. , nd_weak :: IdSet -- Binders of this Rec that are mentioned in nd_uds
  450. -- but are *not* in nd_inl. These are the ones whose
  451. -- dependencies might not be respected by loop_breaker_edges
  452. -- See Note [Weak loop breakers]
  453. , nd_active_rule_fvs :: IdSet -- Free variables of the RHS of active RULES
  454. }
  455. instance Outputable Details where
  456. ppr nd = ptext (sLit "ND") <> braces
  457. (sep [ ptext (sLit "bndr =") <+> ppr (nd_bndr nd)
  458. , ptext (sLit "uds =") <+> ppr (nd_uds nd)
  459. , ptext (sLit "inl =") <+> ppr (nd_inl nd)
  460. , ptext (sLit "weak =") <+> ppr (nd_weak nd)
  461. , ptext (sLit "rule =") <+> ppr (nd_active_rule_fvs nd)
  462. ])
  463. makeNode :: OccEnv -> VarSet -> (Var, CoreExpr) -> Node Details
  464. makeNode env bndr_set (bndr, rhs)
  465. = (details, varUnique bndr, keysUFM node_fvs)
  466. where
  467. details = ND { nd_bndr = bndr
  468. , nd_rhs = rhs'
  469. , nd_uds = rhs_usage3
  470. , nd_weak = node_fvs `minusVarSet` inl_fvs
  471. , nd_inl = inl_fvs
  472. , nd_active_rule_fvs = active_rule_fvs }
  473. -- Constructing the edges for the main Rec computation
  474. -- See Note [Forming Rec groups]
  475. (rhs_usage1, rhs') = occAnalRhs env Nothing rhs
  476. rhs_usage2 = addIdOccs rhs_usage1 all_rule_fvs -- Note [Rules are extra RHSs]
  477. -- Note [Rule dependency info]
  478. rhs_usage3 = case mb_unf_fvs of
  479. Just unf_fvs -> addIdOccs rhs_usage2 unf_fvs
  480. Nothing -> rhs_usage2
  481. node_fvs = udFreeVars bndr_set rhs_usage3
  482. -- Finding the free variables of the rules
  483. is_active = occ_rule_act env :: Activation -> Bool
  484. rules = filterOut isBuiltinRule (idCoreRules bndr)
  485. rules_w_fvs :: [(Activation, VarSet)] -- Find the RHS fvs
  486. rules_w_fvs = [ (ru_act rule, fvs)
  487. | rule <- rules
  488. , let fvs = exprFreeVars (ru_rhs rule)
  489. `delVarSetList` ru_bndrs rule
  490. , not (isEmptyVarSet fvs) ]
  491. all_rule_fvs = foldr (unionVarSet . snd) rule_lhs_fvs rules_w_fvs
  492. rule_lhs_fvs = foldr (unionVarSet . (\ru -> exprsFreeVars (ru_args ru)
  493. `delVarSetList` ru_bndrs ru))
  494. emptyVarSet rules
  495. active_rule_fvs = unionVarSets [fvs | (a,fvs) <- rules_w_fvs, is_active a]
  496. -- Finding the free variables of the INLINE pragma (if any)
  497. unf = realIdUnfolding bndr -- Ignore any current loop-breaker flag
  498. mb_unf_fvs = stableUnfoldingVars isLocalId unf
  499. -- Find the "nd_inl" free vars; for the loop-breaker phase
  500. inl_fvs = case mb_unf_fvs of
  501. Nothing -> udFreeVars bndr_set rhs_usage1 -- No INLINE, use RHS
  502. Just unf_fvs -> unf_fvs
  503. -- We could check for an *active* INLINE (returning
  504. -- emptyVarSet for an inactive one), but is_active
  505. -- isn't the right thing (it tells about
  506. -- RULE activation), so we'd need more plumbing
  507. -----------------------------
  508. occAnalRec :: SCC (Node Details)
  509. -> (UsageDetails, [CoreBind])
  510. -> (UsageDetails, [CoreBind])
  511. -- The NonRec case is just like a Let (NonRec ...) above
  512. occAnalRec (AcyclicSCC (ND { nd_bndr = bndr, nd_rhs = rhs, nd_uds = rhs_uds}, _, _))
  513. (body_uds, binds)
  514. | not (bndr `usedIn` body_uds)
  515. = (body_uds, binds)
  516. | otherwise -- It's mentioned in the body
  517. = (body_uds' +++ rhs_uds,
  518. NonRec tagged_bndr rhs : binds)
  519. where
  520. (body_uds', tagged_bndr) = tagBinder body_uds bndr
  521. -- The Rec case is the interesting one
  522. -- See Note [Loop breaking]
  523. occAnalRec (CyclicSCC nodes) (body_uds, binds)
  524. | not (any (`usedIn` body_uds) bndrs) -- NB: look at body_uds, not total_uds
  525. = (body_uds, binds) -- Dead code
  526. | otherwise -- At this point we always build a single Rec
  527. = -- pprTrace "occAnalRec" (vcat
  528. -- [ text "tagged nodes" <+> ppr tagged_nodes
  529. -- , text "lb edges" <+> ppr loop_breaker_edges])
  530. (final_uds, Rec pairs : binds)
  531. where
  532. bndrs = [b | (ND { nd_bndr = b }, _, _) <- nodes]
  533. bndr_set = mkVarSet bndrs
  534. ----------------------------
  535. -- Tag the binders with their occurrence info
  536. tagged_nodes = map tag_node nodes
  537. total_uds = foldl add_uds body_uds nodes
  538. final_uds = total_uds `minusVarEnv` bndr_set
  539. add_uds usage_so_far (nd, _, _) = usage_so_far +++ nd_uds nd
  540. tag_node :: Node Details -> Node Details
  541. tag_node (details@ND { nd_bndr = bndr }, k, ks)
  542. = (details { nd_bndr = setBinderOcc total_uds bndr }, k, ks)
  543. ---------------------------
  544. -- Now reconstruct the cycle
  545. pairs :: [(Id,CoreExpr)]
  546. pairs | isEmptyVarSet weak_fvs = reOrderNodes 0 bndr_set weak_fvs tagged_nodes []
  547. | otherwise = loopBreakNodes 0 bndr_set weak_fvs loop_breaker_edges []
  548. -- If weak_fvs is empty, the loop_breaker_edges will include all
  549. -- the edges in tagged_nodes, so there isn't any point in doing
  550. -- a fresh SCC computation that will yield a single CyclicSCC result.
  551. weak_fvs :: VarSet
  552. weak_fvs = foldr (unionVarSet . nd_weak . fstOf3) emptyVarSet nodes
  553. -- See Note [Choosing loop breakers] for loop_breaker_edges
  554. loop_breaker_edges = map mk_node tagged_nodes
  555. mk_node (details@(ND { nd_inl = inl_fvs }), k, _)
  556. = (details, k, keysUFM (extendFvs_ rule_fv_env inl_fvs))
  557. ------------------------------------
  558. rule_fv_env :: IdEnv IdSet
  559. -- Maps a variable f to the variables from this group
  560. -- mentioned in RHS of active rules for f
  561. -- Domain is *subset* of bound vars (others have no rule fvs)
  562. rule_fv_env = transClosureFV (mkVarEnv init_rule_fvs)
  563. init_rule_fvs -- See Note [Finding rule RHS free vars]
  564. = [ (b, trimmed_rule_fvs)
  565. | (ND { nd_bndr = b, nd_active_rule_fvs = rule_fvs },_,_) <- nodes
  566. , let trimmed_rule_fvs = rule_fvs `intersectVarSet` bndr_set
  567. , not (isEmptyVarSet trimmed_rule_fvs)]
  568. \end{code}
  569. @loopBreakSCC@ is applied to the list of (binder,rhs) pairs for a cyclic
  570. strongly connected component (there's guaranteed to be a cycle). It returns the
  571. same pairs, but
  572. a) in a better order,
  573. b) with some of the Ids having a IAmALoopBreaker pragma
  574. The "loop-breaker" Ids are sufficient to break all cycles in the SCC. This means
  575. that the simplifier can guarantee not to loop provided it never records an inlining
  576. for these no-inline guys.
  577. Furthermore, the order of the binds is such that if we neglect dependencies
  578. on the no-inline Ids then the binds are topologically sorted. This means
  579. that the simplifier will generally do a good job if it works from top bottom,
  580. recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
  581. \begin{code}
  582. type Binding = (Id,CoreExpr)
  583. mk_loop_breaker :: Node Details -> Binding
  584. mk_loop_breaker (ND { nd_bndr = bndr, nd_rhs = rhs}, _, _)
  585. = (setIdOccInfo bndr strongLoopBreaker, rhs)
  586. mk_non_loop_breaker :: VarSet -> Node Details -> Binding
  587. -- See Note [Weak loop breakers]
  588. mk_non_loop_breaker used_in_rules (ND { nd_bndr = bndr, nd_rhs = rhs}, _, _)
  589. | bndr `elemVarSet` used_in_rules = (setIdOccInfo bndr weakLoopBreaker, rhs)
  590. | otherwise = (bndr, rhs)
  591. udFreeVars :: VarSet -> UsageDetails -> VarSet
  592. -- Find the subset of bndrs that are mentioned in uds
  593. udFreeVars bndrs uds = intersectUFM_C (\b _ -> b) bndrs uds
  594. loopBreakNodes :: Int
  595. -> VarSet -- All binders
  596. -> VarSet -- Binders whose dependencies may be "missing"
  597. -- See Note [Weak loop breakers]
  598. -> [Node Details]
  599. -> [Binding] -- Append these to the end
  600. -> [Binding]
  601. -- Return the bindings sorted into a plausible order, and marked with loop breakers.
  602. loopBreakNodes depth bndr_set weak_fvs nodes binds
  603. = go (stronglyConnCompFromEdgedVerticesR nodes) binds
  604. where
  605. go [] binds = binds
  606. go (scc:sccs) binds = loop_break_scc scc (go sccs binds)
  607. loop_break_scc scc binds
  608. = case scc of
  609. AcyclicSCC node -> mk_non_loop_breaker weak_fvs node : binds
  610. CyclicSCC [node] -> mk_loop_breaker node : binds
  611. CyclicSCC nodes -> reOrderNodes depth bndr_set weak_fvs nodes binds
  612. reOrderNodes :: Int -> VarSet -> VarSet -> [Node Details] -> [Binding] -> [Binding]
  613. -- Choose a loop breaker, mark it no-inline,
  614. -- do SCC analysis on the rest, and recursively sort them out
  615. reOrderNodes _ _ _ [] _ = panic "reOrderNodes"
  616. reOrderNodes depth bndr_set weak_fvs (node : nodes) binds
  617. = -- pprTrace "reOrderNodes" (text "unchosen" <+> ppr unchosen $$
  618. -- text "chosen" <+> ppr chosen_nodes) $
  619. loopBreakNodes new_depth bndr_set weak_fvs unchosen $
  620. (map mk_loop_breaker chosen_nodes ++ binds)
  621. where
  622. (chosen_nodes, unchosen) = choose_loop_breaker (score node) [node] [] nodes
  623. approximate_loop_breaker = depth >= 2
  624. new_depth | approximate_loop_breaker = 0
  625. | otherwise = depth+1
  626. -- After two iterations (d=0, d=1) give up
  627. -- and approximate, returning to d=0
  628. choose_loop_breaker :: Int -- Best score so far
  629. -> [Node Details] -- Nodes with this score
  630. -> [Node Details] -- Nodes with higher scores
  631. -> [Node Details] -- Unprocessed nodes
  632. -> ([Node Details], [Node Details])
  633. -- This loop looks for the bind with the lowest score
  634. -- to pick as the loop breaker. The rest accumulate in
  635. choose_loop_breaker _ loop_nodes acc []
  636. = (loop_nodes, acc) -- Done
  637. -- If approximate_loop_breaker is True, we pick *all*
  638. -- nodes with lowest score, else just one
  639. -- See Note [Complexity of loop breaking]
  640. choose_loop_breaker loop_sc loop_nodes acc (node : nodes)
  641. | sc < loop_sc -- Lower score so pick this new one
  642. = choose_loop_breaker sc [node] (loop_nodes ++ acc) nodes
  643. | approximate_loop_breaker && sc == loop_sc
  644. = choose_loop_breaker loop_sc (node : loop_nodes) acc nodes
  645. | otherwise -- Higher score so don't pick it
  646. = choose_loop_breaker loop_sc loop_nodes (node : acc) nodes
  647. where
  648. sc = score node
  649. score :: Node Details -> Int -- Higher score => less likely to be picked as loop breaker
  650. score (ND { nd_bndr = bndr, nd_rhs = rhs }, _, _)
  651. | not (isId bndr) = 100 -- A type or cercion variable is never a loop breaker
  652. | isDFunId bndr = 9 -- Never choose a DFun as a loop breaker
  653. -- Note [DFuns should not be loop breakers]
  654. | Just inl_source <- isStableCoreUnfolding_maybe (idUnfolding bndr)
  655. = case inl_source of
  656. InlineWrapper {} -> 10 -- Note [INLINE pragmas]
  657. _other -> 3 -- Data structures are more important than this
  658. -- so that dictionary/method recursion unravels
  659. -- Note that this case hits all InlineRule things, so we
  660. -- never look at 'rhs' for InlineRule stuff. That's right, because
  661. -- 'rhs' is irrelevant for inlining things with an InlineRule
  662. | is_con_app rhs = 5 -- Data types help with cases: Note [Constructor applications]
  663. | exprIsTrivial rhs = 10 -- Practically certain to be inlined
  664. -- Used to have also: && not (isExportedId bndr)
  665. -- But I found this sometimes cost an extra iteration when we have
  666. -- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
  667. -- where df is the exported dictionary. Then df makes a really
  668. -- bad choice for loop breaker
  669. -- If an Id is marked "never inline" then it makes a great loop breaker
  670. -- The only reason for not checking that here is that it is rare
  671. -- and I've never seen a situation where it makes a difference,
  672. -- so it probably isn't worth the time to test on every binder
  673. -- | isNeverActive (idInlinePragma bndr) = -10
  674. | isOneOcc (idOccInfo bndr) = 2 -- Likely to be inlined
  675. | canUnfold (realIdUnfolding bndr) = 1
  676. -- The Id has some kind of unfolding
  677. -- Ignore loop-breaker-ness here because that is what we are setting!
  678. | otherwise = 0
  679. -- Checking for a constructor application
  680. -- Cheap and cheerful; the simplifer moves casts out of the way
  681. -- The lambda case is important to spot x = /\a. C (f a)
  682. -- which comes up when C is a dictionary constructor and
  683. -- f is a default method.
  684. -- Example: the instance for Show (ST s a) in GHC.ST
  685. --
  686. -- However we *also* treat (\x. C p q) as a con-app-like thing,
  687. -- Note [Closure conversion]
  688. is_con_app (Var v) = isConLikeId v
  689. is_con_app (App f _) = is_con_app f
  690. is_con_app (Lam _ e) = is_con_app e
  691. is_con_app (Tick _ e) = is_con_app e
  692. is_con_app _ = False
  693. \end{code}
  694. Note [Complexity of loop breaking]
  695. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  696. The loop-breaking algorithm knocks out one binder at a time, and
  697. performs a new SCC analysis on the remaining binders. That can
  698. behave very badly in tightly-coupled groups of bindings; in the
  699. worst case it can be (N**2)*log N, because it does a full SCC
  700. on N, then N-1, then N-2 and so on.
  701. To avoid this, we switch plans after 2 (or whatever) attempts:
  702. Plan A: pick one binder with the lowest score, make it
  703. a loop breaker, and try again
  704. Plan B: pick *all* binders with the lowest score, make them
  705. all loop breakers, and try again
  706. Since there are only a small finite number of scores, this will
  707. terminate in a constant number of iterations, rather than O(N)
  708. iterations.
  709. You might thing that it's very unlikely, but RULES make it much
  710. more likely. Here's a real example from Trac #1969:
  711. Rec { $dm = \d.\x. op d
  712. {-# RULES forall d. $dm Int d = $s$dm1
  713. forall d. $dm Bool d = $s$dm2 #-}
  714. dInt = MkD .... opInt ...
  715. dInt = MkD .... opBool ...
  716. opInt = $dm dInt
  717. opBool = $dm dBool
  718. $s$dm1 = \x. op dInt
  719. $s$dm2 = \x. op dBool }
  720. The RULES stuff means that we can't choose $dm as a loop breaker
  721. (Note [Choosing loop breakers]), so we must choose at least (say)
  722. opInt *and* opBool, and so on. The number of loop breakders is
  723. linear in the number of instance declarations.
  724. Note [INLINE pragmas]
  725. ~~~~~~~~~~~~~~~~~~~~~
  726. Avoid choosing a function with an INLINE pramga as the loop breaker!
  727. If such a function is mutually-recursive with a non-INLINE thing,
  728. then the latter should be the loop-breaker.
  729. Usually this is just a question of optimisation. But a particularly
  730. bad case is wrappers generated by the demand analyser: if you make
  731. then into a loop breaker you may get an infinite inlining loop. For
  732. example:
  733. rec {
  734. $wfoo x = ....foo x....
  735. {-loop brk-} foo x = ...$wfoo x...
  736. }
  737. The interface file sees the unfolding for $wfoo, and sees that foo is
  738. strict (and hence it gets an auto-generated wrapper). Result: an
  739. infinite inlining in the importing scope. So be a bit careful if you
  740. change this. A good example is Tree.repTree in
  741. nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
  742. breaker then compiling Game.hs goes into an infinite loop. This
  743. happened when we gave is_con_app a lower score than inline candidates:
  744. Tree.repTree
  745. = __inline_me (/\a. \w w1 w2 ->
  746. case Tree.$wrepTree @ a w w1 w2 of
  747. { (# ww1, ww2 #) -> Branch @ a ww1 ww2 })
  748. Tree.$wrepTree
  749. = /\a w w1 w2 ->
  750. (# w2_smP, map a (Tree a) (Tree.repTree a w1 w) (w w2) #)
  751. Here we do *not* want to choose 'repTree' as the loop breaker.
  752. Note [DFuns should not be loop breakers]
  753. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  754. It's particularly bad to make a DFun into a loop breaker. See
  755. Note [How instance declarations are translated] in TcInstDcls
  756. We give DFuns a higher score than ordinary CONLIKE things because
  757. if there's a choice we want the DFun to be the non-looop breker. Eg
  758. rec { sc = /\ a \$dC. $fBWrap (T a) ($fCT @ a $dC)
  759. $fCT :: forall a_afE. (Roman.C a_afE) => Roman.C (Roman.T a_afE)
  760. {-# DFUN #-}
  761. $fCT = /\a \$dC. MkD (T a) ((sc @ a $dC) |> blah) ($ctoF @ a $dC)
  762. }
  763. Here 'sc' (the superclass) looks CONLIKE, but we'll never get to it
  764. if we can't unravel the DFun first.
  765. Note [Constructor applications]
  766. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  767. It's really really important to inline dictionaries. Real
  768. example (the Enum Ordering instance from GHC.Base):
  769. rec f = \ x -> case d of (p,q,r) -> p x
  770. g = \ x -> case d of (p,q,r) -> q x
  771. d = (v, f, g)
  772. Here, f and g occur just once; but we can't inline them into d.
  773. On the other hand we *could* simplify those case expressions if
  774. we didn't stupidly choose d as the loop breaker.
  775. But we won't because constructor args are marked "Many".
  776. Inlining dictionaries is really essential to unravelling
  777. the loops in static numeric dictionaries, see GHC.Float.
  778. Note [Closure conversion]
  779. ~~~~~~~~~~~~~~~~~~~~~~~~~
  780. We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
  781. The immediate motivation came from the result of a closure-conversion transformation
  782. which generated code like this:
  783. data Clo a b = forall c. Clo (c -> a -> b) c
  784. ($:) :: Clo a b -> a -> b
  785. Clo f env $: x = f env x
  786. rec { plus = Clo plus1 ()
  787. ; plus1 _ n = Clo plus2 n
  788. ; plus2 Zero n = n
  789. ; plus2 (Succ m) n = Succ (plus $: m $: n) }
  790. If we inline 'plus' and 'plus1', everything unravels nicely. But if
  791. we choose 'plus1' as the loop breaker (which is entirely possible
  792. otherwise), the loop does not unravel nicely.
  793. @occAnalRhs@ deals with the question of bindings where the Id is marked
  794. by an INLINE pragma. For these we record that anything which occurs
  795. in its RHS occurs many times. This pessimistically assumes that ths
  796. inlined binder also occurs many times in its scope, but if it doesn't
  797. we'll catch it next time round. At worst this costs an extra simplifier pass.
  798. ToDo: try using the occurrence info for the inline'd binder.
  799. [March 97] We do the same for atomic RHSs. Reason: see notes with loopBreakSCC.
  800. [June 98, SLPJ] I've undone this change; I don't understand it. See notes with loopBreakSCC.
  801. \begin{code}
  802. occAnalRhs :: OccEnv
  803. -> Maybe Id -> CoreExpr -- Binder and rhs
  804. -- Just b => non-rec, and alrady tagged with occurrence info
  805. -- Nothing => Rec, no occ info
  806. -> (UsageDetails, CoreExpr)
  807. -- Returned usage details covers only the RHS,
  808. -- and *not* the RULE or INLINE template for the Id
  809. occAnalRhs env mb_bndr rhs
  810. = occAnal ctxt rhs
  811. where
  812. -- See Note [Cascading inlines]
  813. ctxt = case mb_bndr of
  814. Just b | certainly_inline b -> env
  815. _other -> rhsCtxt env
  816. certainly_inline bndr -- See Note [Cascading inlines]
  817. = case idOccInfo bndr of
  818. OneOcc in_lam one_br _ -> not in_lam && one_br && active && not_stable
  819. _ -> False
  820. where
  821. active = isAlwaysActive (idInlineActivation bndr)
  822. not_stable = not (isStableUnfolding (idUnfolding bndr))
  823. addIdOccs :: UsageDetails -> VarSet -> UsageDetails
  824. addIdOccs usage id_set = foldVarSet add usage id_set
  825. where
  826. add v u | isId v = addOneOcc u v NoOccInfo
  827. | otherwise = u
  828. -- Give a non-committal binder info (i.e NoOccInfo) because
  829. -- a) Many copies of the specialised thing can appear
  830. -- b) We don't want to substitute a BIG expression inside a RULE
  831. -- even if that's the only occurrence of the thing
  832. -- (Same goes for INLINE.)
  833. \end{code}
  834. Note [Cascading inlines]
  835. ~~~~~~~~~~~~~~~~~~~~~~~~
  836. By default we use an rhsCtxt for the RHS of a binding. This tells the
  837. occ anal n that it's looking at an RHS, which has an effect in
  838. occAnalApp. In particular, for constructor applications, it makes
  839. the arguments appear to have NoOccInfo, so that we don't inline into
  840. them. Thus x = f y
  841. k = Just x
  842. we do not want to inline x.
  843. But there's a problem. Consider
  844. x1 = a0 : []
  845. x2 = a1 : x1
  846. x3 = a2 : x2
  847. g = f x3
  848. First time round, it looks as if x1 and x2 occur as an arg of a
  849. let-bound constructor ==> give them a many-occurrence.
  850. But then x3 is inlined (unconditionally as it happens) and
  851. next time round, x2 will be, and the next time round x1 will be
  852. Result: multiple simplifier iterations. Sigh.
  853. So, when analysing the RHS of x3 we notice that x3 will itself
  854. definitely inline the next time round, and so we analyse x3's rhs in
  855. an ordinary context, not rhsCtxt. Hence the "certainly_inline" stuff.
  856. Annoyingly, we have to approximiate SimplUtils.preInlineUnconditionally.
  857. If we say "yes" when preInlineUnconditionally says "no" the simplifier iterates
  858. indefinitely:
  859. x = f y
  860. k = Just x
  861. inline ==>
  862. k = Just (f y)
  863. float ==>
  864. x1 = f y
  865. k = Just x1
  866. This is worse than the slow cascade, so we only want to say "certainly_inline"
  867. if it really is certain. Look at the note with preInlineUnconditionally
  868. for the various clauses.
  869. Expressions
  870. ~~~~~~~~~~~
  871. \begin{code}
  872. occAnal :: OccEnv
  873. -> CoreExpr
  874. -> (UsageDetails, -- Gives info only about the "interesting" Ids
  875. CoreExpr)
  876. occAnal _ expr@(Type _) = (emptyDetails, expr)
  877. occAnal _ expr@(Lit _) = (emptyDetails, expr)
  878. occAnal env expr@(Var v) = (mkOneOcc env v False, expr)
  879. -- At one stage, I gathered the idRuleVars for v here too,
  880. -- which in a way is the right thing to do.
  881. -- But that went wrong right after specialisation, when
  882. -- the *occurrences* of the overloaded function didn't have any
  883. -- rules in them, so the *specialised* versions looked as if they
  884. -- weren't used at all.
  885. occAnal _ (Coercion co)
  886. = (addIdOccs emptyDetails (coVarsOfCo co), Coercion co)
  887. -- See Note [Gather occurrences of coercion veriables]
  888. \end{code}
  889. Note [Gather occurrences of coercion veriables]
  890. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  891. We need to gather info about what coercion variables appear, so that
  892. we can sort them into the right place when doing dependency analysis.
  893. \begin{code}
  894. occAnal env (Tick tickish body)
  895. | Breakpoint _ ids <- tickish
  896. = (mapVarEnv markInsideSCC usage
  897. +++ mkVarEnv (zip ids (repeat NoOccInfo)), Tick tickish body')
  898. -- never substitute for any of the Ids in a Breakpoint
  899. | tickishScoped tickish
  900. = (mapVarEnv markInsideSCC usage, Tick tickish body')
  901. | otherwise
  902. = (usage, Tick tickish body')
  903. where
  904. !(usage,body') = occAnal env body
  905. occAnal env (Cast expr co)
  906. = case occAnal env expr of { (usage, expr') ->
  907. let usage1 = markManyIf (isRhsEnv env) usage
  908. usage2 = addIdOccs usage1 (coVarsOfCo co)
  909. -- See Note [Gather occurrences of coercion veriables]
  910. in (usage2, Cast expr' co)
  911. -- If we see let x = y `cast` co
  912. -- then mark y as 'Many' so that we don't
  913. -- immediately inline y again.
  914. }
  915. \end{code}
  916. \begin{code}
  917. occAnal env app@(App _ _)
  918. = occAnalApp env (collectArgs app)
  919. -- Ignore type variables altogether
  920. -- (a) occurrences inside type lambdas only not marked as InsideLam
  921. -- (b) type variables not in environment
  922. occAnal env (Lam x body) | isTyVar x
  923. = case occAnal env body of { (body_usage, body') ->
  924. (body_usage, Lam x body')
  925. }
  926. -- For value lambdas we do a special hack. Consider
  927. -- (\x. \y. ...x...)
  928. -- If we did nothing, x is used inside the \y, so would be marked
  929. -- as dangerous to dup. But in the common case where the abstraction
  930. -- is applied to two arguments this is over-pessimistic.
  931. -- So instead, we just mark each binder with its occurrence
  932. -- info in the *body* of the multiple lambda.
  933. -- Then, the simplifier is careful when partially applying lambdas.
  934. occAnal env expr@(Lam _ _)
  935. = case occAnal env_body body of { (body_usage, body') ->
  936. let
  937. (final_usage, tagged_binders) = tagLamBinders body_usage binders'
  938. -- Use binders' to put one-shot info on the lambdas
  939. -- URGH! Sept 99: we don't seem to be able to use binders' here, because
  940. -- we get linear-typed things in the resulting program that we can't handle yet.
  941. -- (e.g. PrelShow) TODO
  942. really_final_usage = if linear then
  943. final_usage
  944. else
  945. mapVarEnv markInsideLam final_usage
  946. in
  947. (really_final_usage,
  948. mkLams tagged_binders body') }
  949. where
  950. env_body = vanillaCtxt (trimOccEnv env binders)
  951. -- Body is (no longer) an RhsContext
  952. (binders, body) = collectBinders expr
  953. binders' = oneShotGroup env binders
  954. linear = all is_one_shot binders'
  955. is_one_shot b = isId b && isOneShotBndr b
  956. occAnal env (Case scrut bndr ty alts)
  957. = case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
  958. case mapAndUnzip occ_anal_alt alts of { (alts_usage_s, alts') ->
  959. let
  960. alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
  961. (alts_usage1, tagged_bndr) = tag_case_bndr alts_usage bndr
  962. total_usage = scrut_usage +++ alts_usage1
  963. in
  964. total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
  965. where
  966. -- Note [Case binder usage]
  967. -- ~~~~~~~~~~~~~~~~~~~~~~~~
  968. -- The case binder gets a usage of either "many" or "dead", never "one".
  969. -- Reason: we like to inline single occurrences, to eliminate a binding,
  970. -- but inlining a case binder *doesn't* eliminate a binding.
  971. -- We *don't* want to transform
  972. -- case x of w { (p,q) -> f w }
  973. -- into
  974. -- case x of w { (p,q) -> f (p,q) }
  975. tag_case_bndr usage bndr
  976. = case lookupVarEnv usage bndr of
  977. Nothing -> (usage, setIdOccInfo bndr IAmDead)
  978. Just _ -> (usage `delVarEnv` bndr, setIdOccInfo bndr NoOccInfo)
  979. alt_env = mkAltEnv env scrut bndr
  980. occ_anal_alt = occAnalAlt alt_env bndr
  981. occ_anal_scrut (Var v) (alt1 : other_alts)
  982. | not (null other_alts) || not (isDefaultAlt alt1)
  983. = (mkOneOcc env v True, Var v) -- The 'True' says that the variable occurs
  984. -- in an interesting context; the case has
  985. -- at least one non-default alternative
  986. occ_anal_scrut scrut _alts
  987. = occAnal (vanillaCtxt env) scrut -- No need for rhsCtxt
  988. occAnal env (Let bind body)
  989. = case occAnal env_body body of { (body_usage, body') ->
  990. case occAnalBind env env_body bind body_usage of { (final_usage, new_binds) ->
  991. (final_usage, mkLets new_binds body') }}
  992. where
  993. env_body = trimOccEnv env (bindersOf bind)
  994. occAnalArgs :: OccEnv -> [CoreExpr] -> (UsageDetails, [CoreExpr])
  995. occAnalArgs env args
  996. = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
  997. (foldr (+++) emptyDetails arg_uds_s, args')}
  998. where
  999. arg_env = vanillaCtxt env
  1000. \end{code}
  1001. Applications are dealt with specially because we want
  1002. the "build hack" to work.
  1003. Note [Arguments of let-bound constructors]
  1004. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1005. Consider
  1006. f x = let y = expensive x in
  1007. let z = (True,y) in
  1008. (case z of {(p,q)->q}, case z of {(p,q)->q})
  1009. We feel free to duplicate the WHNF (True,y), but that means
  1010. that y may be duplicated thereby.
  1011. If we aren't careful we duplicate the (expensive x) call!
  1012. Constructors are rather like lambdas in this way.
  1013. \begin{code}
  1014. occAnalApp :: OccEnv
  1015. -> (Expr CoreBndr, [Arg CoreBndr])
  1016. -> (UsageDetails, Expr CoreBndr)
  1017. occAnalApp env (Var fun, args)
  1018. = case args_stuff of { (args_uds, args') ->
  1019. let
  1020. final_args_uds = markManyIf (isRhsEnv env && is_exp) args_uds
  1021. -- We mark the free vars of the argument of a constructor or PAP
  1022. -- as "many", if it is the RHS of a let(rec).
  1023. -- This means that nothing gets inlined into a constructor argument
  1024. -- position, which is what we want. Typically those constructor
  1025. -- arguments are just variables, or trivial expressions.
  1026. --
  1027. -- This is the *whole point* of the isRhsEnv predicate
  1028. -- See Note [Arguments of let-bound constructors]
  1029. in
  1030. (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
  1031. where
  1032. fun_uniq = idUnique fun
  1033. fun_uds = mkOneOcc env fun (valArgCount args > 0)
  1034. is_exp = isExpandableApp fun (valArgCount args)
  1035. -- See Note [CONLIKE pragma] in BasicTypes
  1036. -- The definition of is_exp should match that in
  1037. -- Simplify.prepareRhs
  1038. -- Hack for build, fold, runST
  1039. args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
  1040. | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
  1041. | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
  1042. | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
  1043. -- (foldr k z xs) may call k many times, but it never
  1044. -- shares a partial application of k; hence [False,True]
  1045. -- This means we can optimise
  1046. -- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
  1047. -- by floating in the v
  1048. | otherwise = occAnalArgs env args
  1049. occAnalApp env (fun, args)
  1050. = case occAnal (addAppCtxt env args) fun of { (fun_uds, fu

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