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

/ghc-7.0.4/compiler/stranal/DmdAnal.lhs

http://picorec.googlecode.com/
Haskell | 1287 lines | 809 code | 187 blank | 291 comment | 45 complexity | b708ae01a2a3c57deebbd816cb7aa03b MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause
  1. %
  2. % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
  3. %
  4. -----------------
  5. A demand analysis
  6. -----------------
  7. \begin{code}
  8. module DmdAnal ( dmdAnalPgm, dmdAnalTopRhs,
  9. both {- needed by WwLib -}
  10. ) where
  11. #include "HsVersions.h"
  12. import DynFlags ( DynFlags )
  13. import StaticFlags ( opt_MaxWorkerArgs )
  14. import Demand -- All of it
  15. import CoreSyn
  16. import PprCore
  17. import CoreUtils ( exprIsHNF, exprIsTrivial )
  18. import CoreArity ( exprArity )
  19. import DataCon ( dataConTyCon, dataConRepStrictness )
  20. import TyCon ( isProductTyCon, isRecursiveTyCon )
  21. import Id ( Id, idType, idInlineActivation,
  22. isDataConWorkId, isGlobalId, idArity,
  23. idStrictness,
  24. setIdStrictness, idDemandInfo, idUnfolding,
  25. idDemandInfo_maybe, setIdDemandInfo
  26. )
  27. import Var ( Var )
  28. import VarEnv
  29. import TysWiredIn ( unboxedPairDataCon )
  30. import TysPrim ( realWorldStatePrimTy )
  31. import UniqFM ( addToUFM_Directly, lookupUFM_Directly,
  32. minusUFM, filterUFM )
  33. import Type ( isUnLiftedType, coreEqType, splitTyConApp_maybe )
  34. import Coercion ( coercionKind )
  35. import Util ( mapAndUnzip, lengthIs, zipEqual )
  36. import BasicTypes ( Arity, TopLevelFlag(..), isTopLevel, isNeverActive,
  37. RecFlag(..), isRec, isMarkedStrict )
  38. import Maybes ( orElse, expectJust )
  39. import Outputable
  40. import Data.List
  41. import FastString
  42. \end{code}
  43. To think about
  44. * set a noinline pragma on bottoming Ids
  45. * Consider f x = x+1 `fatbar` error (show x)
  46. We'd like to unbox x, even if that means reboxing it in the error case.
  47. %************************************************************************
  48. %* *
  49. \subsection{Top level stuff}
  50. %* *
  51. %************************************************************************
  52. \begin{code}
  53. dmdAnalPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
  54. dmdAnalPgm _ binds
  55. = do {
  56. let { binds_plus_dmds = do_prog binds } ;
  57. return binds_plus_dmds
  58. }
  59. where
  60. do_prog :: [CoreBind] -> [CoreBind]
  61. do_prog binds = snd $ mapAccumL dmdAnalTopBind emptySigEnv binds
  62. dmdAnalTopBind :: SigEnv
  63. -> CoreBind
  64. -> (SigEnv, CoreBind)
  65. dmdAnalTopBind sigs (NonRec id rhs)
  66. = (sigs2, NonRec id2 rhs2)
  67. where
  68. ( _, _, (_, rhs1)) = dmdAnalRhs TopLevel NonRecursive (virgin sigs) (id, rhs)
  69. (sigs2, _, (id2, rhs2)) = dmdAnalRhs TopLevel NonRecursive (nonVirgin sigs) (id, rhs1)
  70. -- Do two passes to improve CPR information
  71. -- See comments with ignore_cpr_info in mk_sig_ty
  72. -- and with extendSigsWithLam
  73. dmdAnalTopBind sigs (Rec pairs)
  74. = (sigs', Rec pairs')
  75. where
  76. (sigs', _, pairs') = dmdFix TopLevel (virgin sigs) pairs
  77. -- We get two iterations automatically
  78. -- c.f. the NonRec case above
  79. \end{code}
  80. \begin{code}
  81. dmdAnalTopRhs :: CoreExpr -> (StrictSig, CoreExpr)
  82. -- Analyse the RHS and return
  83. -- a) appropriate strictness info
  84. -- b) the unfolding (decorated with strictness info)
  85. dmdAnalTopRhs rhs
  86. = (sig, rhs2)
  87. where
  88. call_dmd = vanillaCall (exprArity rhs)
  89. (_, rhs1) = dmdAnal (virgin emptySigEnv) call_dmd rhs
  90. (rhs_ty, rhs2) = dmdAnal (nonVirgin emptySigEnv) call_dmd rhs1
  91. sig = mkTopSigTy rhs rhs_ty
  92. -- Do two passes; see notes with extendSigsWithLam
  93. -- Otherwise we get bogus CPR info for constructors like
  94. -- newtype T a = MkT a
  95. -- The constructor looks like (\x::T a -> x), modulo the coerce
  96. -- extendSigsWithLam will optimistically give x a CPR tag the
  97. -- first time, which is wrong in the end.
  98. \end{code}
  99. %************************************************************************
  100. %* *
  101. \subsection{The analyser itself}
  102. %* *
  103. %************************************************************************
  104. \begin{code}
  105. dmdAnal :: AnalEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
  106. dmdAnal _ Abs e = (topDmdType, e)
  107. dmdAnal env dmd e
  108. | not (isStrictDmd dmd)
  109. = let
  110. (res_ty, e') = dmdAnal env evalDmd e
  111. in
  112. (deferType res_ty, e')
  113. -- It's important not to analyse e with a lazy demand because
  114. -- a) When we encounter case s of (a,b) ->
  115. -- we demand s with U(d1d2)... but if the overall demand is lazy
  116. -- that is wrong, and we'd need to reduce the demand on s,
  117. -- which is inconvenient
  118. -- b) More important, consider
  119. -- f (let x = R in x+x), where f is lazy
  120. -- We still want to mark x as demanded, because it will be when we
  121. -- enter the let. If we analyse f's arg with a Lazy demand, we'll
  122. -- just mark x as Lazy
  123. -- c) The application rule wouldn't be right either
  124. -- Evaluating (f x) in a L demand does *not* cause
  125. -- evaluation of f in a C(L) demand!
  126. dmdAnal _ _ (Lit lit) = (topDmdType, Lit lit)
  127. dmdAnal _ _ (Type ty) = (topDmdType, Type ty) -- Doesn't happen, in fact
  128. dmdAnal env dmd (Var var)
  129. = (dmdTransform env var dmd, Var var)
  130. dmdAnal env dmd (Cast e co)
  131. = (dmd_ty, Cast e' co)
  132. where
  133. (dmd_ty, e') = dmdAnal env dmd' e
  134. to_co = snd (coercionKind co)
  135. dmd'
  136. | Just (tc, _) <- splitTyConApp_maybe to_co
  137. , isRecursiveTyCon tc = evalDmd
  138. | otherwise = dmd
  139. -- This coerce usually arises from a recursive
  140. -- newtype, and we don't want to look inside them
  141. -- for exactly the same reason that we don't look
  142. -- inside recursive products -- we might not reach
  143. -- a fixpoint. So revert to a vanilla Eval demand
  144. dmdAnal env dmd (Note n e)
  145. = (dmd_ty, Note n e')
  146. where
  147. (dmd_ty, e') = dmdAnal env dmd e
  148. dmdAnal env dmd (App fun (Type ty))
  149. = (fun_ty, App fun' (Type ty))
  150. where
  151. (fun_ty, fun') = dmdAnal env dmd fun
  152. -- Lots of the other code is there to make this
  153. -- beautiful, compositional, application rule :-)
  154. dmdAnal env dmd (App fun arg) -- Non-type arguments
  155. = let -- [Type arg handled above]
  156. (fun_ty, fun') = dmdAnal env (Call dmd) fun
  157. (arg_ty, arg') = dmdAnal env arg_dmd arg
  158. (arg_dmd, res_ty) = splitDmdTy fun_ty
  159. in
  160. (res_ty `bothType` arg_ty, App fun' arg')
  161. dmdAnal env dmd (Lam var body)
  162. | isTyCoVar var
  163. = let
  164. (body_ty, body') = dmdAnal env dmd body
  165. in
  166. (body_ty, Lam var body')
  167. | Call body_dmd <- dmd -- A call demand: good!
  168. = let
  169. env' = extendSigsWithLam env var
  170. (body_ty, body') = dmdAnal env' body_dmd body
  171. (lam_ty, var') = annotateLamIdBndr env body_ty var
  172. in
  173. (lam_ty, Lam var' body')
  174. | otherwise -- Not enough demand on the lambda; but do the body
  175. = let -- anyway to annotate it and gather free var info
  176. (body_ty, body') = dmdAnal env evalDmd body
  177. (lam_ty, var') = annotateLamIdBndr env body_ty var
  178. in
  179. (deferType lam_ty, Lam var' body')
  180. dmdAnal env dmd (Case scrut case_bndr ty [alt@(DataAlt dc, _, _)])
  181. | let tycon = dataConTyCon dc
  182. , isProductTyCon tycon
  183. , not (isRecursiveTyCon tycon)
  184. = let
  185. env_alt = extendAnalEnv NotTopLevel env case_bndr case_bndr_sig
  186. (alt_ty, alt') = dmdAnalAlt env_alt dmd alt
  187. (alt_ty1, case_bndr') = annotateBndr alt_ty case_bndr
  188. (_, bndrs', _) = alt'
  189. case_bndr_sig = cprSig
  190. -- Inside the alternative, the case binder has the CPR property.
  191. -- Meaning that a case on it will successfully cancel.
  192. -- Example:
  193. -- f True x = case x of y { I# x' -> if x' ==# 3 then y else I# 8 }
  194. -- f False x = I# 3
  195. --
  196. -- We want f to have the CPR property:
  197. -- f b x = case fw b x of { r -> I# r }
  198. -- fw True x = case x of y { I# x' -> if x' ==# 3 then x' else 8 }
  199. -- fw False x = 3
  200. -- Figure out whether the demand on the case binder is used, and use
  201. -- that to set the scrut_dmd. This is utterly essential.
  202. -- Consider f x = case x of y { (a,b) -> k y a }
  203. -- If we just take scrut_demand = U(L,A), then we won't pass x to the
  204. -- worker, so the worker will rebuild
  205. -- x = (a, absent-error)
  206. -- and that'll crash.
  207. -- So at one stage I had:
  208. -- dead_case_bndr = isAbsentDmd (idDemandInfo case_bndr')
  209. -- keepity | dead_case_bndr = Drop
  210. -- | otherwise = Keep
  211. --
  212. -- But then consider
  213. -- case x of y { (a,b) -> h y + a }
  214. -- where h : U(LL) -> T
  215. -- The above code would compute a Keep for x, since y is not Abs, which is silly
  216. -- The insight is, of course, that a demand on y is a demand on the
  217. -- scrutinee, so we need to `both` it with the scrut demand
  218. alt_dmd = Eval (Prod [idDemandInfo b | b <- bndrs', isId b])
  219. scrut_dmd = alt_dmd `both`
  220. idDemandInfo case_bndr'
  221. (scrut_ty, scrut') = dmdAnal env scrut_dmd scrut
  222. in
  223. (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' ty [alt'])
  224. dmdAnal env dmd (Case scrut case_bndr ty alts)
  225. = let
  226. (alt_tys, alts') = mapAndUnzip (dmdAnalAlt env dmd) alts
  227. (scrut_ty, scrut') = dmdAnal env evalDmd scrut
  228. (alt_ty, case_bndr') = annotateBndr (foldr1 lubType alt_tys) case_bndr
  229. in
  230. -- pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
  231. (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' ty alts')
  232. dmdAnal env dmd (Let (NonRec id rhs) body)
  233. = let
  234. (sigs', lazy_fv, (id1, rhs')) = dmdAnalRhs NotTopLevel NonRecursive env (id, rhs)
  235. (body_ty, body') = dmdAnal (updSigEnv env sigs') dmd body
  236. (body_ty1, id2) = annotateBndr body_ty id1
  237. body_ty2 = addLazyFVs body_ty1 lazy_fv
  238. in
  239. -- If the actual demand is better than the vanilla call
  240. -- demand, you might think that we might do better to re-analyse
  241. -- the RHS with the stronger demand.
  242. -- But (a) That seldom happens, because it means that *every* path in
  243. -- the body of the let has to use that stronger demand
  244. -- (b) It often happens temporarily in when fixpointing, because
  245. -- the recursive function at first seems to place a massive demand.
  246. -- But we don't want to go to extra work when the function will
  247. -- probably iterate to something less demanding.
  248. -- In practice, all the times the actual demand on id2 is more than
  249. -- the vanilla call demand seem to be due to (b). So we don't
  250. -- bother to re-analyse the RHS.
  251. (body_ty2, Let (NonRec id2 rhs') body')
  252. dmdAnal env dmd (Let (Rec pairs) body)
  253. = let
  254. bndrs = map fst pairs
  255. (sigs', lazy_fv, pairs') = dmdFix NotTopLevel env pairs
  256. (body_ty, body') = dmdAnal (updSigEnv env sigs') dmd body
  257. body_ty1 = addLazyFVs body_ty lazy_fv
  258. in
  259. sigs' `seq` body_ty `seq`
  260. let
  261. (body_ty2, _) = annotateBndrs body_ty1 bndrs
  262. -- Don't bother to add demand info to recursive
  263. -- binders as annotateBndr does;
  264. -- being recursive, we can't treat them strictly.
  265. -- But we do need to remove the binders from the result demand env
  266. in
  267. (body_ty2, Let (Rec pairs') body')
  268. dmdAnalAlt :: AnalEnv -> Demand -> Alt Var -> (DmdType, Alt Var)
  269. dmdAnalAlt env dmd (con,bndrs,rhs)
  270. = let
  271. (rhs_ty, rhs') = dmdAnal env dmd rhs
  272. rhs_ty' = addDataConPatDmds con bndrs rhs_ty
  273. (alt_ty, bndrs') = annotateBndrs rhs_ty' bndrs
  274. final_alt_ty | io_hack_reqd = alt_ty `lubType` topDmdType
  275. | otherwise = alt_ty
  276. -- There's a hack here for I/O operations. Consider
  277. -- case foo x s of { (# s, r #) -> y }
  278. -- Is this strict in 'y'. Normally yes, but what if 'foo' is an I/O
  279. -- operation that simply terminates the program (not in an erroneous way)?
  280. -- In that case we should not evaluate y before the call to 'foo'.
  281. -- Hackish solution: spot the IO-like situation and add a virtual branch,
  282. -- as if we had
  283. -- case foo x s of
  284. -- (# s, r #) -> y
  285. -- other -> return ()
  286. -- So the 'y' isn't necessarily going to be evaluated
  287. --
  288. -- A more complete example where this shows up is:
  289. -- do { let len = <expensive> ;
  290. -- ; when (...) (exitWith ExitSuccess)
  291. -- ; print len }
  292. io_hack_reqd = con == DataAlt unboxedPairDataCon &&
  293. idType (head bndrs) `coreEqType` realWorldStatePrimTy
  294. in
  295. (final_alt_ty, (con, bndrs', rhs'))
  296. addDataConPatDmds :: AltCon -> [Var] -> DmdType -> DmdType
  297. -- See Note [Add demands for strict constructors]
  298. addDataConPatDmds DEFAULT _ dmd_ty = dmd_ty
  299. addDataConPatDmds (LitAlt _) _ dmd_ty = dmd_ty
  300. addDataConPatDmds (DataAlt con) bndrs dmd_ty
  301. = foldr add dmd_ty str_bndrs
  302. where
  303. add bndr dmd_ty = addVarDmd dmd_ty bndr seqDmd
  304. str_bndrs = [ b | (b,s) <- zipEqual "addDataConPatBndrs"
  305. (filter isId bndrs)
  306. (dataConRepStrictness con)
  307. , isMarkedStrict s ]
  308. \end{code}
  309. Note [Add demands for strict constructors]
  310. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  311. Consider this program (due to Roman):
  312. data X a = X !a
  313. foo :: X Int -> Int -> Int
  314. foo (X a) n = go 0
  315. where
  316. go i | i < n = a + go (i+1)
  317. | otherwise = 0
  318. We want the worker for 'foo' too look like this:
  319. $wfoo :: Int# -> Int# -> Int#
  320. with the first argument unboxed, so that it is not eval'd each time
  321. around the loop (which would otherwise happen, since 'foo' is not
  322. strict in 'a'. It is sound for the wrapper to pass an unboxed arg
  323. because X is strict, so its argument must be evaluated. And if we
  324. *don't* pass an unboxed argument, we can't even repair it by adding a
  325. `seq` thus:
  326. foo (X a) n = a `seq` go 0
  327. because the seq is discarded (very early) since X is strict!
  328. There is the usual danger of reboxing, which as usual we ignore. But
  329. if X is monomorphic, and has an UNPACK pragma, then this optimisation
  330. is even more important. We don't want the wrapper to rebox an unboxed
  331. argument, and pass an Int to $wfoo!
  332. %************************************************************************
  333. %* *
  334. Demand transformer
  335. %* *
  336. %************************************************************************
  337. \begin{code}
  338. dmdTransform :: AnalEnv -- The strictness environment
  339. -> Id -- The function
  340. -> Demand -- The demand on the function
  341. -> DmdType -- The demand type of the function in this context
  342. -- Returned DmdEnv includes the demand on
  343. -- this function plus demand on its free variables
  344. dmdTransform env var dmd
  345. ------ DATA CONSTRUCTOR
  346. | isDataConWorkId var -- Data constructor
  347. = let
  348. StrictSig dmd_ty = idStrictness var -- It must have a strictness sig
  349. DmdType _ _ con_res = dmd_ty
  350. arity = idArity var
  351. in
  352. if arity == call_depth then -- Saturated, so unleash the demand
  353. let
  354. -- Important! If we Keep the constructor application, then
  355. -- we need the demands the constructor places (always lazy)
  356. -- If not, we don't need to. For example:
  357. -- f p@(x,y) = (p,y) -- S(AL)
  358. -- g a b = f (a,b)
  359. -- It's vital that we don't calculate Absent for a!
  360. dmd_ds = case res_dmd of
  361. Box (Eval ds) -> mapDmds box ds
  362. Eval ds -> ds
  363. _ -> Poly Top
  364. -- ds can be empty, when we are just seq'ing the thing
  365. -- If so we must make up a suitable bunch of demands
  366. arg_ds = case dmd_ds of
  367. Poly d -> replicate arity d
  368. Prod ds -> ASSERT( ds `lengthIs` arity ) ds
  369. in
  370. mkDmdType emptyDmdEnv arg_ds con_res
  371. -- Must remember whether it's a product, hence con_res, not TopRes
  372. else
  373. topDmdType
  374. ------ IMPORTED FUNCTION
  375. | isGlobalId var, -- Imported function
  376. let StrictSig dmd_ty = idStrictness var
  377. = -- pprTrace "strict-sig" (ppr var $$ ppr dmd_ty) $
  378. if dmdTypeDepth dmd_ty <= call_depth then -- Saturated, so unleash the demand
  379. dmd_ty
  380. else
  381. topDmdType
  382. ------ LOCAL LET/REC BOUND THING
  383. | Just (StrictSig dmd_ty, top_lvl) <- lookupSigEnv env var
  384. = let
  385. fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty
  386. | otherwise = deferType dmd_ty
  387. -- NB: it's important to use deferType, and not just return topDmdType
  388. -- Consider let { f x y = p + x } in f 1
  389. -- The application isn't saturated, but we must nevertheless propagate
  390. -- a lazy demand for p!
  391. in
  392. if isTopLevel top_lvl then fn_ty -- Don't record top level things
  393. else addVarDmd fn_ty var dmd
  394. ------ LOCAL NON-LET/REC BOUND THING
  395. | otherwise -- Default case
  396. = unitVarDmd var dmd
  397. where
  398. (call_depth, res_dmd) = splitCallDmd dmd
  399. \end{code}
  400. %************************************************************************
  401. %* *
  402. \subsection{Bindings}
  403. %* *
  404. %************************************************************************
  405. \begin{code}
  406. dmdFix :: TopLevelFlag
  407. -> AnalEnv -- Does not include bindings for this binding
  408. -> [(Id,CoreExpr)]
  409. -> (SigEnv, DmdEnv,
  410. [(Id,CoreExpr)]) -- Binders annotated with stricness info
  411. dmdFix top_lvl env orig_pairs
  412. = loop 1 initial_env orig_pairs
  413. where
  414. bndrs = map fst orig_pairs
  415. initial_env = addInitialSigs top_lvl env bndrs
  416. loop :: Int
  417. -> AnalEnv -- Already contains the current sigs
  418. -> [(Id,CoreExpr)]
  419. -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
  420. loop n env pairs
  421. = -- pprTrace "dmd loop" (ppr n <+> ppr bndrs $$ ppr env) $
  422. loop' n env pairs
  423. loop' n env pairs
  424. | found_fixpoint
  425. = (sigs', lazy_fv, pairs')
  426. -- Note: return pairs', not pairs. pairs' is the result of
  427. -- processing the RHSs with sigs (= sigs'), whereas pairs
  428. -- is the result of processing the RHSs with the *previous*
  429. -- iteration of sigs.
  430. | n >= 10
  431. = pprTrace "dmdFix loop" (ppr n <+> (vcat
  432. [ text "Sigs:" <+> ppr [ (id,lookupVarEnv sigs id, lookupVarEnv sigs' id)
  433. | (id,_) <- pairs],
  434. text "env:" <+> ppr env,
  435. text "binds:" <+> pprCoreBinding (Rec pairs)]))
  436. (sigEnv env, lazy_fv, orig_pairs) -- Safe output
  437. -- The lazy_fv part is really important! orig_pairs has no strictness
  438. -- info, including nothing about free vars. But if we have
  439. -- letrec f = ....y..... in ...f...
  440. -- where 'y' is free in f, we must record that y is mentioned,
  441. -- otherwise y will get recorded as absent altogether
  442. | otherwise
  443. = loop (n+1) (nonVirgin sigs') pairs'
  444. where
  445. sigs = sigEnv env
  446. found_fixpoint = all (same_sig sigs sigs') bndrs
  447. ((sigs',lazy_fv), pairs') = mapAccumL my_downRhs (sigs, emptyDmdEnv) pairs
  448. -- mapAccumL: Use the new signature to do the next pair
  449. -- The occurrence analyser has arranged them in a good order
  450. -- so this can significantly reduce the number of iterations needed
  451. my_downRhs (sigs,lazy_fv) (id,rhs)
  452. = ((sigs', lazy_fv'), pair')
  453. where
  454. (sigs', lazy_fv1, pair') = dmdAnalRhs top_lvl Recursive (updSigEnv env sigs) (id,rhs)
  455. lazy_fv' = plusVarEnv_C both lazy_fv lazy_fv1
  456. same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
  457. lookup sigs var = case lookupVarEnv sigs var of
  458. Just (sig,_) -> sig
  459. Nothing -> pprPanic "dmdFix" (ppr var)
  460. dmdAnalRhs :: TopLevelFlag -> RecFlag
  461. -> AnalEnv -> (Id, CoreExpr)
  462. -> (SigEnv, DmdEnv, (Id, CoreExpr))
  463. -- Process the RHS of the binding, add the strictness signature
  464. -- to the Id, and augment the environment with the signature as well.
  465. dmdAnalRhs top_lvl rec_flag env (id, rhs)
  466. = (sigs', lazy_fv, (id', rhs'))
  467. where
  468. arity = idArity id -- The idArity should be up to date
  469. -- The simplifier was run just beforehand
  470. (rhs_dmd_ty, rhs') = dmdAnal env (vanillaCall arity) rhs
  471. (lazy_fv, sig_ty) = WARN( arity /= dmdTypeDepth rhs_dmd_ty && not (exprIsTrivial rhs), ppr id )
  472. -- The RHS can be eta-reduced to just a variable,
  473. -- in which case we should not complain.
  474. mkSigTy top_lvl rec_flag id rhs rhs_dmd_ty
  475. id' = id `setIdStrictness` sig_ty
  476. sigs' = extendSigEnv top_lvl (sigEnv env) id sig_ty
  477. \end{code}
  478. %************************************************************************
  479. %* *
  480. \subsection{Strictness signatures and types}
  481. %* *
  482. %************************************************************************
  483. \begin{code}
  484. mkTopSigTy :: CoreExpr -> DmdType -> StrictSig
  485. -- Take a DmdType and turn it into a StrictSig
  486. -- NB: not used for never-inline things; hence False
  487. mkTopSigTy rhs dmd_ty = snd (mk_sig_ty False False rhs dmd_ty)
  488. mkSigTy :: TopLevelFlag -> RecFlag -> Id -> CoreExpr -> DmdType -> (DmdEnv, StrictSig)
  489. mkSigTy top_lvl rec_flag id rhs dmd_ty
  490. = mk_sig_ty never_inline thunk_cpr_ok rhs dmd_ty
  491. where
  492. never_inline = isNeverActive (idInlineActivation id)
  493. maybe_id_dmd = idDemandInfo_maybe id
  494. -- Is Nothing the first time round
  495. thunk_cpr_ok
  496. | isTopLevel top_lvl = False -- Top level things don't get
  497. -- their demandInfo set at all
  498. | isRec rec_flag = False -- Ditto recursive things
  499. | Just dmd <- maybe_id_dmd = isStrictDmd dmd
  500. | otherwise = True -- Optimistic, first time round
  501. -- See notes below
  502. \end{code}
  503. The thunk_cpr_ok stuff [CPR-AND-STRICTNESS]
  504. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  505. If the rhs is a thunk, we usually forget the CPR info, because
  506. it is presumably shared (else it would have been inlined, and
  507. so we'd lose sharing if w/w'd it into a function). E.g.
  508. let r = case expensive of
  509. (a,b) -> (b,a)
  510. in ...
  511. If we marked r as having the CPR property, then we'd w/w into
  512. let $wr = \() -> case expensive of
  513. (a,b) -> (# b, a #)
  514. r = case $wr () of
  515. (# b,a #) -> (b,a)
  516. in ...
  517. But now r is a thunk, which won't be inlined, so we are no further ahead.
  518. But consider
  519. f x = let r = case expensive of (a,b) -> (b,a)
  520. in if foo r then r else (x,x)
  521. Does f have the CPR property? Well, no.
  522. However, if the strictness analyser has figured out (in a previous
  523. iteration) that it's strict, then we DON'T need to forget the CPR info.
  524. Instead we can retain the CPR info and do the thunk-splitting transform
  525. (see WorkWrap.splitThunk).
  526. This made a big difference to PrelBase.modInt, which had something like
  527. modInt = \ x -> let r = ... -> I# v in
  528. ...body strict in r...
  529. r's RHS isn't a value yet; but modInt returns r in various branches, so
  530. if r doesn't have the CPR property then neither does modInt
  531. Another case I found in practice (in Complex.magnitude), looks like this:
  532. let k = if ... then I# a else I# b
  533. in ... body strict in k ....
  534. (For this example, it doesn't matter whether k is returned as part of
  535. the overall result; but it does matter that k's RHS has the CPR property.)
  536. Left to itself, the simplifier will make a join point thus:
  537. let $j k = ...body strict in k...
  538. if ... then $j (I# a) else $j (I# b)
  539. With thunk-splitting, we get instead
  540. let $j x = let k = I#x in ...body strict in k...
  541. in if ... then $j a else $j b
  542. This is much better; there's a good chance the I# won't get allocated.
  543. The difficulty with this is that we need the strictness type to
  544. look at the body... but we now need the body to calculate the demand
  545. on the variable, so we can decide whether its strictness type should
  546. have a CPR in it or not. Simple solution:
  547. a) use strictness info from the previous iteration
  548. b) make sure we do at least 2 iterations, by doing a second
  549. round for top-level non-recs. Top level recs will get at
  550. least 2 iterations except for totally-bottom functions
  551. which aren't very interesting anyway.
  552. NB: strictly_demanded is never true of a top-level Id, or of a recursive Id.
  553. The Nothing case in thunk_cpr_ok [CPR-AND-STRICTNESS]
  554. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  555. Demand info now has a 'Nothing' state, just like strictness info.
  556. The analysis works from 'dangerous' towards a 'safe' state; so we
  557. start with botSig for 'Nothing' strictness infos, and we start with
  558. "yes, it's demanded" for 'Nothing' in the demand info. The
  559. fixpoint iteration will sort it all out.
  560. We can't start with 'not-demanded' because then consider
  561. f x = let
  562. t = ... I# x
  563. in
  564. if ... then t else I# y else f x'
  565. In the first iteration we'd have no demand info for x, so assume
  566. not-demanded; then we'd get TopRes for f's CPR info. Next iteration
  567. we'd see that t was demanded, and so give it the CPR property, but by
  568. now f has TopRes, so it will stay TopRes. Instead, with the Nothing
  569. setting the first time round, we say 'yes t is demanded' the first
  570. time.
  571. However, this does mean that for non-recursive bindings we must
  572. iterate twice to be sure of not getting over-optimistic CPR info,
  573. in the case where t turns out to be not-demanded. This is handled
  574. by dmdAnalTopBind.
  575. Note [NOINLINE and strictness]
  576. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  577. The strictness analyser used to have a HACK which ensured that NOINLNE
  578. things were not strictness-analysed. The reason was unsafePerformIO.
  579. Left to itself, the strictness analyser would discover this strictness
  580. for unsafePerformIO:
  581. unsafePerformIO: C(U(AV))
  582. But then consider this sub-expression
  583. unsafePerformIO (\s -> let r = f x in
  584. case writeIORef v r s of (# s1, _ #) ->
  585. (# s1, r #)
  586. The strictness analyser will now find that r is sure to be eval'd,
  587. and may then hoist it out. This makes tests/lib/should_run/memo002
  588. deadlock.
  589. Solving this by making all NOINLINE things have no strictness info is overkill.
  590. In particular, it's overkill for runST, which is perfectly respectable.
  591. Consider
  592. f x = runST (return x)
  593. This should be strict in x.
  594. So the new plan is to define unsafePerformIO using the 'lazy' combinator:
  595. unsafePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
  596. Remember, 'lazy' is a wired-in identity-function Id, of type a->a, which is
  597. magically NON-STRICT, and is inlined after strictness analysis. So
  598. unsafePerformIO will look non-strict, and that's what we want.
  599. Now we don't need the hack in the strictness analyser. HOWEVER, this
  600. decision does mean that even a NOINLINE function is not entirely
  601. opaque: some aspect of its implementation leaks out, notably its
  602. strictness. For example, if you have a function implemented by an
  603. error stub, but which has RULES, you may want it not to be eliminated
  604. in favour of error!
  605. \begin{code}
  606. mk_sig_ty :: Bool -> Bool -> CoreExpr
  607. -> DmdType -> (DmdEnv, StrictSig)
  608. mk_sig_ty _never_inline thunk_cpr_ok rhs (DmdType fv dmds res)
  609. = (lazy_fv, mkStrictSig dmd_ty)
  610. -- Re unused never_inline, see Note [NOINLINE and strictness]
  611. where
  612. dmd_ty = DmdType strict_fv final_dmds res'
  613. lazy_fv = filterUFM (not . isStrictDmd) fv
  614. strict_fv = filterUFM isStrictDmd fv
  615. -- We put the strict FVs in the DmdType of the Id, so
  616. -- that at its call sites we unleash demands on its strict fvs.
  617. -- An example is 'roll' in imaginary/wheel-sieve2
  618. -- Something like this:
  619. -- roll x = letrec
  620. -- go y = if ... then roll (x-1) else x+1
  621. -- in
  622. -- go ms
  623. -- We want to see that roll is strict in x, which is because
  624. -- go is called. So we put the DmdEnv for x in go's DmdType.
  625. --
  626. -- Another example:
  627. -- f :: Int -> Int -> Int
  628. -- f x y = let t = x+1
  629. -- h z = if z==0 then t else
  630. -- if z==1 then x+1 else
  631. -- x + h (z-1)
  632. -- in
  633. -- h y
  634. -- Calling h does indeed evaluate x, but we can only see
  635. -- that if we unleash a demand on x at the call site for t.
  636. --
  637. -- Incidentally, here's a place where lambda-lifting h would
  638. -- lose the cigar --- we couldn't see the joint strictness in t/x
  639. --
  640. -- ON THE OTHER HAND
  641. -- We don't want to put *all* the fv's from the RHS into the
  642. -- DmdType, because that makes fixpointing very slow --- the
  643. -- DmdType gets full of lazy demands that are slow to converge.
  644. final_dmds = setUnpackStrategy dmds
  645. -- Set the unpacking strategy
  646. res' = case res of
  647. RetCPR | ignore_cpr_info -> TopRes
  648. _ -> res
  649. ignore_cpr_info = not (exprIsHNF rhs || thunk_cpr_ok)
  650. \end{code}
  651. The unpack strategy determines whether we'll *really* unpack the argument,
  652. or whether we'll just remember its strictness. If unpacking would give
  653. rise to a *lot* of worker args, we may decide not to unpack after all.
  654. \begin{code}
  655. setUnpackStrategy :: [Demand] -> [Demand]
  656. setUnpackStrategy ds
  657. = snd (go (opt_MaxWorkerArgs - nonAbsentArgs ds) ds)
  658. where
  659. go :: Int -- Max number of args available for sub-components of [Demand]
  660. -> [Demand]
  661. -> (Int, [Demand]) -- Args remaining after subcomponents of [Demand] are unpacked
  662. go n (Eval (Prod cs) : ds)
  663. | n' >= 0 = Eval (Prod cs') `cons` go n'' ds
  664. | otherwise = Box (Eval (Prod cs)) `cons` go n ds
  665. where
  666. (n'',cs') = go n' cs
  667. n' = n + 1 - non_abs_args
  668. -- Add one to the budget 'cos we drop the top-level arg
  669. non_abs_args = nonAbsentArgs cs
  670. -- Delete # of non-absent args to which we'll now be committed
  671. go n (d:ds) = d `cons` go n ds
  672. go n [] = (n,[])
  673. cons d (n,ds) = (n, d:ds)
  674. nonAbsentArgs :: [Demand] -> Int
  675. nonAbsentArgs [] = 0
  676. nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
  677. nonAbsentArgs (_ : ds) = 1 + nonAbsentArgs ds
  678. \end{code}
  679. %************************************************************************
  680. %* *
  681. \subsection{Strictness signatures and types}
  682. %* *
  683. %************************************************************************
  684. \begin{code}
  685. unitVarDmd :: Var -> Demand -> DmdType
  686. unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
  687. addVarDmd :: DmdType -> Var -> Demand -> DmdType
  688. addVarDmd (DmdType fv ds res) var dmd
  689. = DmdType (extendVarEnv_C both fv var dmd) ds res
  690. addLazyFVs :: DmdType -> DmdEnv -> DmdType
  691. addLazyFVs (DmdType fv ds res) lazy_fvs
  692. = DmdType both_fv1 ds res
  693. where
  694. both_fv = plusVarEnv_C both fv lazy_fvs
  695. both_fv1 = modifyEnv (isBotRes res) (`both` Bot) lazy_fvs fv both_fv
  696. -- This modifyEnv is vital. Consider
  697. -- let f = \x -> (x,y)
  698. -- in error (f 3)
  699. -- Here, y is treated as a lazy-fv of f, but we must `both` that L
  700. -- demand with the bottom coming up from 'error'
  701. --
  702. -- I got a loop in the fixpointer without this, due to an interaction
  703. -- with the lazy_fv filtering in mkSigTy. Roughly, it was
  704. -- letrec f n x
  705. -- = letrec g y = x `fatbar`
  706. -- letrec h z = z + ...g...
  707. -- in h (f (n-1) x)
  708. -- in ...
  709. -- In the initial iteration for f, f=Bot
  710. -- Suppose h is found to be strict in z, but the occurrence of g in its RHS
  711. -- is lazy. Now consider the fixpoint iteration for g, esp the demands it
  712. -- places on its free variables. Suppose it places none. Then the
  713. -- x `fatbar` ...call to h...
  714. -- will give a x->V demand for x. That turns into a L demand for x,
  715. -- which floats out of the defn for h. Without the modifyEnv, that
  716. -- L demand doesn't get both'd with the Bot coming up from the inner
  717. -- call to f. So we just get an L demand for x for g.
  718. --
  719. -- A better way to say this is that the lazy-fv filtering should give the
  720. -- same answer as putting the lazy fv demands in the function's type.
  721. annotateBndr :: DmdType -> Var -> (DmdType, Var)
  722. -- The returned env has the var deleted
  723. -- The returned var is annotated with demand info
  724. -- No effect on the argument demands
  725. annotateBndr dmd_ty@(DmdType fv ds res) var
  726. | isTyCoVar var = (dmd_ty, var)
  727. | otherwise = (DmdType fv' ds res, setIdDemandInfo var dmd)
  728. where
  729. (fv', dmd) = removeFV fv var res
  730. annotateBndrs :: DmdType -> [Var] -> (DmdType, [Var])
  731. annotateBndrs = mapAccumR annotateBndr
  732. annotateLamIdBndr :: AnalEnv
  733. -> DmdType -- Demand type of body
  734. -> Id -- Lambda binder
  735. -> (DmdType, -- Demand type of lambda
  736. Id) -- and binder annotated with demand
  737. annotateLamIdBndr env (DmdType fv ds res) id
  738. -- For lambdas we add the demand to the argument demands
  739. -- Only called for Ids
  740. = ASSERT( isId id )
  741. (final_ty, setIdDemandInfo id hacked_dmd)
  742. where
  743. -- Watch out! See note [Lambda-bound unfoldings]
  744. final_ty = case maybeUnfoldingTemplate (idUnfolding id) of
  745. Nothing -> main_ty
  746. Just unf -> main_ty `bothType` unf_ty
  747. where
  748. (unf_ty, _) = dmdAnal env dmd unf
  749. main_ty = DmdType fv' (hacked_dmd:ds) res
  750. (fv', dmd) = removeFV fv id res
  751. hacked_dmd = argDemand dmd
  752. -- This call to argDemand is vital, because otherwise we label
  753. -- a lambda binder with demand 'B'. But in terms of calling
  754. -- conventions that's Abs, because we don't pass it. But
  755. -- when we do a w/w split we get
  756. -- fw x = (\x y:B -> ...) x (error "oops")
  757. -- And then the simplifier things the 'B' is a strict demand
  758. -- and evaluates the (error "oops"). Sigh
  759. removeFV :: DmdEnv -> Var -> DmdResult -> (DmdEnv, Demand)
  760. removeFV fv id res = (fv', zapUnlifted id dmd)
  761. where
  762. fv' = fv `delVarEnv` id
  763. dmd = lookupVarEnv fv id `orElse` deflt
  764. deflt | isBotRes res = Bot
  765. | otherwise = Abs
  766. zapUnlifted :: Id -> Demand -> Demand
  767. -- For unlifted-type variables, we are only
  768. -- interested in Bot/Abs/Box Abs
  769. zapUnlifted _ Bot = Bot
  770. zapUnlifted _ Abs = Abs
  771. zapUnlifted id dmd | isUnLiftedType (idType id) = lazyDmd
  772. | otherwise = dmd
  773. \end{code}
  774. Note [Lamba-bound unfoldings]
  775. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  776. We allow a lambda-bound variable to carry an unfolding, a facility that is used
  777. exclusively for join points; see Note [Case binders and join points]. If so,
  778. we must be careful to demand-analyse the RHS of the unfolding! Example
  779. \x. \y{=Just x}. <body>
  780. Then if <body> uses 'y', then transitively it uses 'x', and we must not
  781. forget that fact, otherwise we might make 'x' absent when it isn't.
  782. %************************************************************************
  783. %* *
  784. \subsection{Strictness signatures}
  785. %* *
  786. %************************************************************************
  787. \begin{code}
  788. data AnalEnv
  789. = AE { ae_sigs :: SigEnv
  790. , ae_virgin :: Bool } -- True on first iteration only
  791. -- See Note [Initialising strictness]
  792. -- We use the se_env to tell us whether to
  793. -- record info about a variable in the DmdEnv
  794. -- We do so if it's a LocalId, but not top-level
  795. --
  796. -- The DmdEnv gives the demand on the free vars of the function
  797. -- when it is given enough args to satisfy the strictness signature
  798. type SigEnv = VarEnv (StrictSig, TopLevelFlag)
  799. instance Outputable AnalEnv where
  800. ppr (AE { ae_sigs = env, ae_virgin = virgin })
  801. = ptext (sLit "AE") <+> braces (vcat
  802. [ ptext (sLit "ae_virgin =") <+> ppr virgin
  803. , ptext (sLit "ae_sigs =") <+> ppr env ])
  804. emptySigEnv :: SigEnv
  805. emptySigEnv = emptyVarEnv
  806. sigEnv :: AnalEnv -> SigEnv
  807. sigEnv = ae_sigs
  808. updSigEnv :: AnalEnv -> SigEnv -> AnalEnv
  809. updSigEnv env sigs = env { ae_sigs = sigs }
  810. extendAnalEnv :: TopLevelFlag -> AnalEnv -> Id -> StrictSig -> AnalEnv
  811. extendAnalEnv top_lvl env var sig
  812. = env { ae_sigs = extendSigEnv top_lvl (ae_sigs env) var sig }
  813. extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
  814. extendSigEnv top_lvl sigs var sig = extendVarEnv sigs var (sig, top_lvl)
  815. lookupSigEnv :: AnalEnv -> Id -> Maybe (StrictSig, TopLevelFlag)
  816. lookupSigEnv env id = lookupVarEnv (ae_sigs env) id
  817. addInitialSigs :: TopLevelFlag -> AnalEnv -> [Id] -> AnalEnv
  818. -- See Note [Initialising strictness]
  819. addInitialSigs top_lvl env@(AE { ae_sigs = sigs, ae_virgin = virgin }) ids
  820. = env { ae_sigs = extendVarEnvList sigs [ (id, (init_sig id, top_lvl))
  821. | id <- ids ] }
  822. where
  823. init_sig | virgin = \_ -> botSig
  824. | otherwise = idStrictness
  825. virgin, nonVirgin :: SigEnv -> AnalEnv
  826. virgin sigs = AE { ae_sigs = sigs, ae_virgin = True }
  827. nonVirgin sigs = AE { ae_sigs = sigs, ae_virgin = False }
  828. extendSigsWithLam :: AnalEnv -> Id -> AnalEnv
  829. -- Extend the AnalEnv when we meet a lambda binder
  830. -- If the binder is marked demanded with a product demand, then give it a CPR
  831. -- signature, because in the likely event that this is a lambda on a fn defn
  832. -- [we only use this when the lambda is being consumed with a call demand],
  833. -- it'll be w/w'd and so it will be CPR-ish. E.g.
  834. -- f = \x::(Int,Int). if ...strict in x... then
  835. -- x
  836. -- else
  837. -- (a,b)
  838. -- We want f to have the CPR property because x does, by the time f has been w/w'd
  839. --
  840. -- Also note that we only want to do this for something that
  841. -- definitely has product type, else we may get over-optimistic
  842. -- CPR results (e.g. from \x -> x!).
  843. extendSigsWithLam env id
  844. = case idDemandInfo_maybe id of
  845. Nothing -> extendAnalEnv NotTopLevel env id cprSig
  846. -- Optimistic in the Nothing case;
  847. -- See notes [CPR-AND-STRICTNESS]
  848. Just (Eval (Prod _)) -> extendAnalEnv NotTopLevel env id cprSig
  849. _ -> env
  850. \end{code}
  851. Note [Initialising strictness]
  852. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  853. Our basic plan is to initialise the strictness of each Id in
  854. a recursive group to "bottom", and find a fixpoint from there.
  855. However, this group A might be inside an *enclosing* recursive
  856. group B, in which case we'll do the entire fixpoint shebang on A
  857. for each iteration of B.
  858. To speed things up, we initialise each iteration of B from the result
  859. of the last one, which is neatly recorded in each binder. That way we
  860. make use of earlier iterations of the fixpoint algorithm. (Cunning
  861. plan.)
  862. But on the *first* iteration we want to *ignore* the current strictness
  863. of the Id, and start from "bottom". Nowadays the Id can have a current
  864. strictness, because interface files record strictness for nested bindings.
  865. To know when we are in the first iteration, we look at the ae_virgin
  866. field of the AnalEnv.
  867. %************************************************************************
  868. %* *
  869. Demands
  870. %* *
  871. %************************************************************************
  872. \begin{code}
  873. splitDmdTy :: DmdType -> (Demand, DmdType)
  874. -- Split off one function argument
  875. -- We already have a suitable demand on all
  876. -- free vars, so no need to add more!
  877. splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
  878. splitDmdTy ty@(DmdType _ [] res_ty) = (resTypeArgDmd res_ty, ty)
  879. splitCallDmd :: Demand -> (Int, Demand)
  880. splitCallDmd (Call d) = case splitCallDmd d of
  881. (n, r) -> (n+1, r)
  882. splitCallDmd d = (0, d)
  883. vanillaCall :: Arity -> Demand
  884. vanillaCall 0 = evalDmd
  885. vanillaCall n = Call (vanillaCall (n-1))
  886. deferType :: DmdType -> DmdType
  887. deferType (DmdType fv _ _) = DmdType (deferEnv fv) [] TopRes
  888. -- Notice that we throw away info about both arguments and results
  889. -- For example, f = let ... in \x -> x
  890. -- We don't want to get a stricness type V->T for f.
  891. deferEnv :: DmdEnv -> DmdEnv
  892. deferEnv fv = mapVarEnv defer fv
  893. ----------------
  894. argDemand :: Demand -> Demand
  895. -- The 'Defer' demands are just Lazy at function boundaries
  896. -- Ugly! Ask John how to improve it.
  897. argDemand Top = lazyDmd
  898. argDemand (Defer _) = lazyDmd
  899. argDemand (Eval ds) = Eval (mapDmds argDemand ds)
  900. argDemand (Box Bot) = evalDmd
  901. argDemand (Box d) = box (argDemand d)
  902. argDemand Bot = Abs -- Don't pass args that are consumed (only) by bottom
  903. argDemand d = d
  904. \end{code}
  905. \begin{code}
  906. -------------------------
  907. lubType :: DmdType -> DmdType -> DmdType
  908. -- Consider (if x then y else []) with demand V
  909. -- Then the first branch gives {y->V} and the second
  910. -- *implicitly* has {y->A}. So we must put {y->(V `lub` A)}
  911. -- in the result env.
  912. lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
  913. = DmdType lub_fv2 (lub_ds ds1 ds2) (r1 `lubRes` r2)
  914. where
  915. lub_fv = plusVarEnv_C lub fv1 fv2
  916. lub_fv1 = modifyEnv (not (isBotRes r1)) absLub fv2 fv1 lub_fv
  917. lub_fv2 = modifyEnv (not (isBotRes r2)) absLub fv1 fv2 lub_fv1
  918. -- lub is the identity for Bot
  919. -- Extend the shorter argument list to match the longer
  920. lub_ds (d1:ds1) (d2:ds2) = lub d1 d2 : lub_ds ds1 ds2
  921. lub_ds [] [] = []
  922. lub_ds ds1 [] = map (`lub` resTypeArgDmd r2) ds1
  923. lub_ds [] ds2 = map (resTypeArgDmd r1 `lub`) ds2
  924. -----------------------------------
  925. bothType :: DmdType -> DmdType -> DmdType
  926. -- (t1 `bothType` t2) takes the argument/result info from t1,
  927. -- using t2 just for its free-var info
  928. -- NB: Don't forget about r2! It might be BotRes, which is
  929. -- a bottom demand on all the in-scope variables.
  930. -- Peter: can this be done more neatly?
  931. bothType (DmdType fv1 ds1 r1) (DmdType fv2 _ r2)
  932. = DmdType both_fv2 ds1 (r1 `bothRes` r2)
  933. where
  934. both_fv = plusVarEnv_C both fv1 fv2
  935. both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
  936. both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
  937. -- both is the identity for Abs
  938. \end{code}
  939. \begin{code}
  940. lubRes :: DmdResult -> DmdResult -> DmdResult
  941. lubRes BotRes r = r
  942. lubRes r BotRes = r
  943. lubRes RetCPR RetCPR = RetCPR
  944. lubRes _ _ = TopRes
  945. bothRes :: DmdResult -> DmdResult -> DmdResult
  946. -- If either diverges, the whole thing does
  947. -- Otherwise take CPR info from the first
  948. bothRes _ BotRes = BotRes
  949. bothRes r1 _ = r1
  950. \end{code}
  951. \begin{code}
  952. modifyEnv :: Bool -- No-op if False
  953. -> (Demand -> Demand) -- The zapper
  954. -> DmdEnv -> DmdEnv -- Env1 and Env2
  955. -> DmdEnv -> DmdEnv -- Transform this env
  956. -- Zap anything in Env1 but not in Env2
  957. -- Assume: dom(env) includes dom(Env1) and dom(Env2)
  958. modifyEnv need_to_modify zapper env1 env2 env
  959. | need_to_modify = foldr zap env (varEnvKeys (env1 `minusUFM` env2))
  960. | otherwise = env
  961. where
  962. zap uniq env = addToUFM_Directly env uniq (zapper current_val)
  963. where
  964. current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
  965. \end{code}
  966. %************************************************************************
  967. %* *
  968. \subsection{LUB and BOTH}
  969. %* *
  970. %************************************************************************
  971. \begin{code}
  972. lub :: Demand -> Demand -> Demand
  973. lub Bot d2 = d2
  974. lub Abs d2 = absLub d2
  975. lub Top _ = Top
  976. lub (Defer ds1) d2 = defer (Eval ds1 `lub` d2)
  977. lub (Call d1) (Call d2) = Call (d1 `lub` d2)
  978. lub d1@(Call _) (Box d2) = d1 `lub` d2 -- Just strip the box
  979. lub (Call _) d2@(Eval _) = d2 -- Presumably seq or vanilla eval
  980. lub d1@(Call _) d2 = d2 `lub` d1 -- Bot, Abs, Top
  981. -- For the Eval case, we use these approximation rules
  982. -- Box Bot <= Eval (Box Bot ...)
  983. -- Box Top <= Defer (Box Bot ...)
  984. -- Box (Eval ds) <= Eval (map Box ds)
  985. lub (Eval ds1) (Eval ds2) = Eval (ds1 `lubs` ds2)
  986. lub (Eval ds1) (Box Bot) = Eval (mapDmds (`lub` Box Bot) ds1)
  987. lub (Eval ds1) (Box (Eval ds2)) = Eval (ds1 `lubs` mapDmds box ds2)
  988. lub (Eval ds1) (Box Abs) = deferEval (mapDmds (`lub` Box Bot) ds1)
  989. lub d1@(Eval _) d2 = d2 `lub` d1 -- Bot,Abs,Top,Call,Defer
  990. lub (Box d1) (Box d2) = box (d1 `lub` d2)
  991. lub d1@(Box _) d2 = d2 `lub` d1
  992. lubs :: Demands -> Demands -> Demands
  993. lubs ds1 ds2 = zipWithDmds lub ds1 ds2
  994. ---------------------
  995. box :: Demand -> Demand
  996. -- box is the smart constructor for Box
  997. -- It computes <B,bot> & d
  998. -- INVARIANT: (Box d) => d = Bot, Abs, Eval
  999. -- Seems to be no point in allowing (Box (Call d))
  1000. box (Call d) = Call d -- The odd man out. Why?
  1001. box (Box d) = Box d
  1002. box (Defer _) = lazyDmd
  1003. box Top = lazyDmd -- Box Abs and Box Top
  1004. box Abs = lazyDmd -- are the same <B,L>
  1005. box d = Box d -- Bot, Eval
  1006. ---------------
  1007. defer :: Demand -> Demand
  1008. -- defer is the smart constructor for Defer
  1009. -- The idea is that (Defer ds) = <U(ds), L>
  1010. --
  1011. -- It specifies what happens at a lazy function argument
  1012. -- or a lambda; the L* operator
  1013. -- Set the strictness part to L, but leave
  1014. -- the boxity side unaffected
  1015. -- It also ensures that Defer (Eval [LLLL]) = L
  1016. defer Bot = Abs
  1017. defer Abs = Abs
  1018. defer Top = Top
  1019. defer (Call _) = lazyDmd -- Approximation here?
  1020. defer (Box _) = lazyDmd
  1021. defer (Defer ds) = Defer ds
  1022. defer (Eval ds) = deferEval ds
  1023. deferEval :: Demands -> Demand
  1024. -- deferEval ds = defer (Eval ds)
  1025. deferEval ds | allTop ds = Top
  1026. | otherwise = Defer ds
  1027. ---------------------
  1028. absLub :: Demand -> Demand
  1029. -- Computes (Abs `lub` d)
  1030. -- For the Bot case consider
  1031. -- f x y = if ... then x else error x
  1032. -- Then for y we get Abs `lub` Bot, and we really
  1033. -- want Abs overall
  1034. absLub Bot = Abs
  1035. absLub Abs = Abs
  1036. absLub Top = Top
  1037. absLub (Call _) = Top
  1038. absLub (Box _) = Top
  1039. absLub (Eval ds) = Defer (absLubs ds) -- Or (Defer ds)?
  1040. absLub (Defer ds) = Defer (absLubs ds) -- Or (Defer ds)?
  1041. absLubs :: Demands -> Demands
  1042. absLubs = mapDmds absLub
  1043. ---------------
  1044. both :: Demand -> Demand -> Demand
  1045. both Abs d2 = d2
  1046. -- Note [Bottom demands]
  1047. both Bot Bot = Bot
  1048. both Bot Abs = Bot
  1049. both Bot (Eval ds) = Eval (mapDmds (`both` Bot) ds)
  1050. both Bot (Defer ds) = Eval (mapDmds (`both` Bot) ds)
  1051. both Bot _ = errDmd
  1052. both Top Bot = errDmd
  1053. both Top Abs = Top
  1054. both Top Top = Top
  1055. both Top (Box d) = Box d
  1056. both Top (Call d) = Call d
  1057. both Top (Eval ds) = Eval (mapDmds (`both` Top) ds)
  1058. both Top (Defer ds) -- = defer (Top `both` Eval ds)
  1059. -- = defer (Eval (mapDmds (`both` Top) ds))
  1060. = deferEval (mapDmds (`both` Top) ds)
  1061. both (Box d1) (Box d2) = box (d1 `both` d2)
  1062. both (Box d1) d2@(Call _) = box (d1 `both` d2)
  1063. both (Box d1) d2@(Eval _) = box (d1 `both` d2)
  1064. both (Box d1) (Defer _) = Box d1
  1065. both d1@(Box _) d2 = d2 `both` d1
  1066. both (Call d1) (Call d2) = Call (d1 `both` d2)
  1067. both (Call d1) (Eval _) = Call d1 -- Could do better for (Poly Bot)?
  1068. both (Call d1) (Defer _) = Call d1 -- Ditto
  1069. both d1@(Call _) d2 = d2 `both` d1
  1070. both (Eval ds1) (Eval ds2) = Eval (ds1 `boths` ds2)
  1071. both (Eval ds1) (Defer ds2) = Eval (ds1 `boths` mapDmds defer ds2)
  1072. both d1@(Eval _) d2 = d2 `both` d1
  1073. both (Defer ds1) (Defer ds2) = deferEval (ds1 `boths` ds2)
  1074. both d1@(Defer _) d2 = d2 `both` d1
  1075. boths :: Demands -> Demands -> Demands
  1076. boths ds1 ds2 = zipWithDmds both ds1 ds2
  1077. \end{code}
  1078. Note [Bottom demands]
  1079. ~~~~~~~~~~~~~~~~~~~~~
  1080. Consider
  1081. f x = error x
  1082. From 'error' itself we get demand Bot on x
  1083. From the arg demand on x we get
  1084. x :-> evalDmd = Box (Eval (Poly Abs))
  1085. So we get Bot `both` Box (Eval (Poly Abs))
  1086. = Seq Keep (Poly Bot)
  1087. Consider also
  1088. f x = if ... then error (fst x) else fst x
  1089. Then we get (Eval (Box Bot, Bot) `lub` Eval (SA))
  1090. = Eval (SA)
  1091. which is what we want.
  1092. Consider also
  1093. f x = error [fst x]
  1094. Then we get
  1095. x :-> Bot `both` Defer [SA]
  1096. and we want the Bot demand to cancel out the Defer
  1097. so that we get Eval [SA]. Otherwise we'd have the odd
  1098. situation that
  1099. f x = error (fst x) -- Strictness U(SA)b
  1100. g x = error ('y':fst x) -- Strictness Tb