From: simonpj Date: Thu, 19 Jul 2001 09:26:33 +0000 (+0000) Subject: [project @ 2001-07-19 09:26:33 by simonpj] X-Git-Tag: Approximately_9120_patches~1507 X-Git-Url: http://git.megacz.com/?a=commitdiff_plain;h=feb2cd1702186da03c68e4adf2694f338660d4e5;p=ghc-hetmet.git [project @ 2001-07-19 09:26:33 by simonpj] Next cut at the demand analyser --- diff --git a/ghc/compiler/basicTypes/IdInfo.lhs b/ghc/compiler/basicTypes/IdInfo.lhs index 426d084..7e030fd 100644 --- a/ghc/compiler/basicTypes/IdInfo.lhs +++ b/ghc/compiler/basicTypes/IdInfo.lhs @@ -129,18 +129,20 @@ infixl 1 `setDemandInfo`, To be removed later \begin{code} -mkNewStrictnessInfo :: Arity -> StrictnessInfo -> CprInfo -> NewDemand.StrictSig -mkNewStrictnessInfo arity NoStrictnessInfo cpr - = NewDemand.mkStrictSig +mkNewStrictnessInfo :: Id -> Arity -> StrictnessInfo -> CprInfo -> NewDemand.StrictSig +mkNewStrictnessInfo id arity NoStrictnessInfo cpr + = NewDemand.mkStrictSig id arity - (NewDemand.mkDmdFun (replicate arity NewDemand.Lazy) (newRes False cpr)) + (NewDemand.mkTopDmdType (replicate arity NewDemand.Lazy) (newRes False cpr)) -mkNewStrictnessInfo arity (StrictnessInfo ds res) cpr - = NewDemand.mkStrictSig +mkNewStrictnessInfo id arity (StrictnessInfo ds res) cpr + = NewDemand.mkStrictSig id arity - (NewDemand.mkDmdFun (map newDemand ds) (newRes res cpr)) + (NewDemand.mkTopDmdType (take arity (map newDemand ds)) (newRes res cpr)) + -- Sometimes the old strictness analyser has more + -- demands than the arity justifies -newRes True _ = NewDemand.BotRes +newRes True _ = NewDemand.BotRes newRes False ReturnsCPR = NewDemand.RetCPR newRes False NoCPRInfo = NewDemand.TopRes @@ -148,7 +150,7 @@ newDemand :: Demand -> NewDemand.Demand newDemand (WwLazy True) = NewDemand.Abs newDemand (WwLazy False) = NewDemand.Lazy newDemand WwStrict = NewDemand.Eval -newDemand (WwUnpack unpk ds) = NewDemand.Seq NewDemand.Drop (map newDemand ds) +newDemand (WwUnpack unpk ds) = NewDemand.Seq NewDemand.Drop NewDemand.Now (map newDemand ds) newDemand WwPrim = NewDemand.Lazy newDemand WwEnum = NewDemand.Eval \end{code} diff --git a/ghc/compiler/basicTypes/MkId.lhs b/ghc/compiler/basicTypes/MkId.lhs index 21eded9..27e7e6e 100644 --- a/ghc/compiler/basicTypes/MkId.lhs +++ b/ghc/compiler/basicTypes/MkId.lhs @@ -139,14 +139,15 @@ mkDataConId :: Name -> DataCon -> Id -- Makes the *worker* for the data constructor; that is, the function -- that takes the reprsentation arguments and builds the constructor. mkDataConId work_name data_con - = mkGlobalId (DataConId data_con) work_name (dataConRepType data_con) info + = id where + id = mkGlobalId (DataConId data_con) work_name (dataConRepType data_con) info info = noCafNoTyGenIdInfo `setCgArity` arity `setArityInfo` exactArity arity `setCprInfo` cpr_info `setStrictnessInfo` strict_info - `setNewStrictnessInfo` mkNewStrictnessInfo arity strict_info cpr_info + `setNewStrictnessInfo` mkNewStrictnessInfo id arity strict_info cpr_info arity = dataConRepArity data_con strict_info = mkStrictnessInfo (dataConRepStrictness data_con, False) @@ -226,7 +227,7 @@ mkDataConWrapId data_con `setArityInfo` exactArity arity -- It's important to specify the arity, so that partial -- applications are treated as values - `setNewStrictnessInfo` mkNewStrictnessInfo arity noStrictnessInfo cpr_info + `setNewStrictnessInfo` mkNewStrictnessInfo wrap_id arity noStrictnessInfo cpr_info wrap_ty = mkForAllTys all_tyvars $ mkFunTys all_arg_tys @@ -606,7 +607,7 @@ mkPrimOpId prim_op `setCgArity` arity `setArityInfo` exactArity arity `setStrictnessInfo` strict_info - `setNewStrictnessInfo` mkNewStrictnessInfo arity strict_info NoCPRInfo + `setNewStrictnessInfo` mkNewStrictnessInfo id arity strict_info NoCPRInfo rules = maybe emptyCoreRules (addRule emptyCoreRules id) (primOpRule prim_op) @@ -626,8 +627,9 @@ mkFCallId uniq fcall ty = ASSERT( isEmptyVarSet (tyVarsOfType ty) ) -- A CCallOpId should have no free type variables; -- when doing substitutions won't substitute over it - mkGlobalId (FCallId fcall) name ty info + id where + id = mkGlobalId (FCallId fcall) name ty info occ_str = showSDocIface (braces (ppr fcall <+> ppr ty)) -- The "occurrence name" of a ccall is the full info about the -- ccall; it is encoded, but may have embedded spaces etc! @@ -638,7 +640,7 @@ mkFCallId uniq fcall ty `setCgArity` arity `setArityInfo` exactArity arity `setStrictnessInfo` strict_info - `setNewStrictnessInfo` mkNewStrictnessInfo arity strict_info NoCPRInfo + `setNewStrictnessInfo` mkNewStrictnessInfo id arity strict_info NoCPRInfo (_, tau) = tcSplitForAllTys ty (arg_tys, _) = tcSplitFunTys tau @@ -833,12 +835,13 @@ pcMiscPrelId key mod str ty info -- will be in "the right place" to be in scope. pc_bottoming_Id key mod name ty - = pcMiscPrelId key mod name ty bottoming_info + = id where + id = pcMiscPrelId key mod name ty bottoming_info strict_info = mkStrictnessInfo ([wwStrict], True) bottoming_info = noCafNoTyGenIdInfo `setStrictnessInfo` strict_info - `setNewStrictnessInfo` mkNewStrictnessInfo 1 strict_info NoCPRInfo + `setNewStrictnessInfo` mkNewStrictnessInfo id 1 strict_info NoCPRInfo -- these "bottom" out, no matter what their arguments diff --git a/ghc/compiler/basicTypes/NewDemand.lhs b/ghc/compiler/basicTypes/NewDemand.lhs index b7eb765..1cd59ef 100644 --- a/ghc/compiler/basicTypes/NewDemand.lhs +++ b/ghc/compiler/basicTypes/NewDemand.lhs @@ -5,15 +5,19 @@ \begin{code} module NewDemand( - Demand(..), Keepity(..), topDmd, + Demand(..), Keepity(..), Deferredness(..), topDmd, StrictSig(..), topSig, botSig, mkStrictSig, - DmdType(..), topDmdType, mkDmdFun, - Result(..) + DmdType(..), topDmdType, mkDmdType, mkTopDmdType, + DmdEnv, emptyDmdEnv, + DmdResult(..), isBotRes ) where #include "HsVersions.h" import BasicTypes ( Arity ) +import Var ( Id ) +import VarEnv ( VarEnv, emptyVarEnv ) +import UniqFM ( ufmToList ) import qualified Demand import Outputable \end{code} @@ -34,9 +38,9 @@ data StrictSig = StrictSig Arity DmdType topSig = StrictSig 0 topDmdType botSig = StrictSig 0 botDmdType -mkStrictSig :: Arity -> DmdType -> StrictSig -mkStrictSig arity ty - = WARN( arity /= dmdTypeDepth ty, ppr arity $$ ppr ty ) +mkStrictSig :: Id -> Arity -> DmdType -> StrictSig +mkStrictSig id arity ty + = WARN( arity /= dmdTypeDepth ty, ppr id <+> (ppr arity $$ ppr ty) ) StrictSig arity ty instance Outputable StrictSig where @@ -51,31 +55,59 @@ instance Outputable StrictSig where %************************************************************************ \begin{code} -data DmdType = DmdRes Result | DmdFun Demand DmdType - deriving( Eq ) - -- Equality needed for fixpoints in DmdAnal +data DmdType = DmdType + DmdEnv -- Demand on explicitly-mentioned + -- free variables + [Demand] -- Demand on arguments + DmdResult -- Nature of result + + -- IMPORTANT INVARIANT + -- The default demand on free variables not in the DmdEnv is: + -- DmdResult = BotRes <=> Bot + -- DmdResult = TopRes/ResCPR <=> Abs + +type DmdEnv = VarEnv Demand + +data DmdResult = TopRes -- Nothing known + | RetCPR -- Returns a constructed product + | BotRes -- Diverges or errors + deriving( Eq ) -data Result = TopRes -- Nothing known - | RetCPR -- Returns a constructed product - | BotRes -- Diverges or errors - deriving( Eq ) - -- Equality needed for fixpoints in DmdAnal +-- Equality needed for fixpoints in DmdAnal +instance Eq DmdType where + (==) (DmdType fv1 ds1 res1) + (DmdType fv2 ds2 res2) = ufmToList fv1 == ufmToList fv2 + && ds1 == ds2 && res1 == res2 instance Outputable DmdType where - ppr (DmdRes TopRes) = char 'T' - ppr (DmdRes RetCPR) = char 'M' - ppr (DmdRes BotRes) = char 'X' - ppr (DmdFun d r) = ppr d <> ppr r + ppr (DmdType fv ds res) + = hsep [text "DmdType", + hcat (map ppr ds) <> ppr res, + braces (fsep (map pp_elt (ufmToList fv)))] + where + pp_elt (uniq, dmd) = ppr uniq <> text "->" <> ppr dmd -topDmdType = DmdRes TopRes -botDmdType = DmdRes BotRes +instance Outputable DmdResult where + ppr TopRes = char 'T' + ppr RetCPR = char 'M' + ppr BotRes = char 'X' -mkDmdFun :: [Demand] -> Result -> DmdType -mkDmdFun ds res = foldr DmdFun (DmdRes res) ds +emptyDmdEnv = emptyVarEnv +topDmdType = DmdType emptyDmdEnv [] TopRes +botDmdType = DmdType emptyDmdEnv [] BotRes + +isBotRes :: DmdResult -> Bool +isBotRes BotRes = True +isBotRes other = False + +mkDmdType :: DmdEnv -> [Demand] -> DmdResult -> DmdType +mkDmdType fv ds res = DmdType fv ds res + +mkTopDmdType :: [Demand] -> DmdResult -> DmdType +mkTopDmdType ds res = DmdType emptyDmdEnv ds res dmdTypeDepth :: DmdType -> Arity -dmdTypeDepth (DmdFun _ ty) = 1 + dmdTypeDepth ty -dmdTypeDepth (DmdRes _) = 0 +dmdTypeDepth (DmdType _ ds _) = length ds \end{code} @@ -93,12 +125,16 @@ data Demand | Call Demand -- C(d) | Eval -- V | Seq Keepity -- S/U(ds) + Deferredness [Demand] | Err -- X | Bot -- B deriving( Eq ) -- Equality needed for fixpoints in DmdAnal +data Deferredness = Now | Defer + deriving( Eq ) + data Keepity = Keep | Drop deriving( Eq ) @@ -106,13 +142,17 @@ topDmd :: Demand -- The most uninformative demand topDmd = Lazy instance Outputable Demand where - ppr Lazy = char 'L' - ppr Abs = char 'A' - ppr Eval = char 'V' - ppr Err = char 'X' - ppr Bot = char 'B' - ppr (Call d) = char 'C' <> parens (ppr d) - ppr (Seq k ds) = ppr k <> parens (hcat (map ppr ds)) + ppr Lazy = char 'L' + ppr Abs = char 'A' + ppr Eval = char 'V' + ppr Err = char 'X' + ppr Bot = char 'B' + ppr (Call d) = char 'C' <> parens (ppr d) + ppr (Seq k l ds) = ppr k <> ppr l <> parens (hcat (map ppr ds)) + +instance Outputable Deferredness where + ppr Now = empty + ppr Defer = char '*' instance Outputable Keepity where ppr Keep = char 'S' diff --git a/ghc/compiler/stranal/DmdAnal.lhs b/ghc/compiler/stranal/DmdAnal.lhs index 31ebc7b..f13b363 100644 --- a/ghc/compiler/stranal/DmdAnal.lhs +++ b/ghc/compiler/stranal/DmdAnal.lhs @@ -14,26 +14,33 @@ module DmdAnal ( dmdAnalPgm ) where import CmdLineOpts ( DynFlags, DynFlag(..) ) import NewDemand -- All of it import CoreSyn +import CoreUtils ( exprIsValue, exprArity ) import DataCon ( dataConTyCon ) import TyCon ( isProductTyCon, isRecursiveTyCon ) -import Id ( Id, idInfo, idArity, idStrictness, idCprInfo, idDemandInfo, - modifyIdInfo, isDataConId, isImplicitId ) +import Id ( Id, idType, idInfo, idArity, idStrictness, idCprInfo, idDemandInfo, + modifyIdInfo, isDataConId, isImplicitId, isGlobalId ) import IdInfo ( newStrictnessInfo, setNewStrictnessInfo, mkNewStrictnessInfo, newDemandInfo, setNewDemandInfo, newDemand ) import Var ( Var ) import VarEnv -import UniqFM ( plusUFM_C, addToUFM_Directly, keysUFM, minusUFM ) +import UniqFM ( plusUFM_C, addToUFM_Directly, lookupUFM_Directly, + keysUFM, minusUFM, ufmToList ) +import Type ( isUnLiftedType ) import CoreLint ( showPass, endPass ) import ErrUtils ( dumpIfSet_dyn ) -import Util ( mapAccumL, mapAccumR, zipWithEqual ) -import BasicTypes ( Arity ) -import Maybes ( orElse ) +import Util ( mapAndUnzip, mapAccumL, mapAccumR, zipWithEqual ) +import BasicTypes ( Arity, TopLevelFlag(..), isTopLevel ) +import Maybes ( orElse, expectJust ) import Outputable import FastTypes \end{code} ToDo: set a noinline pragma on bottoming Ids +\begin{code} +instance Outputable TopLevelFlag where + ppr flag = empty +\end{code} %************************************************************************ %* * @@ -71,14 +78,13 @@ dmdAnalTopBind sigs (NonRec id rhs) = (sigs, NonRec id rhs) -- It's pre-computed in MkId.lhs | otherwise = let - (sig, rhs_env, (id', rhs')) = downRhs sigs (id, rhs) - sigs' = extendSigEnv sigs id sig + (sigs', (id', rhs')) = downRhs TopLevel sigs (id, rhs) in (sigs', NonRec id' rhs') dmdAnalTopBind sigs (Rec pairs) = let - (sigs', _, pairs') = dmdFix sigs pairs + (sigs', pairs') = dmdFix TopLevel sigs pairs in (sigs', Rec pairs') \end{code} @@ -91,18 +97,19 @@ dmdAnalTopBind sigs (Rec pairs) %************************************************************************ \begin{code} -dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, DmdEnv, CoreExpr) +dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr) -dmdAnal sigs Abs e = (DmdRes TopRes, emptyDmdEnv, e) +dmdAnal sigs Abs e = (topDmdType, e) dmdAnal sigs Lazy e = let - (res_ty, dmd_env, e') = dmdAnal sigs Eval e + (res_ty, e') = dmdAnal sigs Eval e in - (res_ty, lazify dmd_env, e') + (deferType res_ty, e') -- It's important not to analyse e with a lazy demand because -- a) When we encounter case s of (a,b) -> -- we demand s with U(d1d2)... but if the overall demand is lazy - -- that is wrong, and we'd need to reduce the demand on s (inconvenient) + -- that is wrong, and we'd need to reduce the demand on s, + -- which is inconvenient -- b) More important, consider -- f (let x = R in x+x), where f is lazy -- We still want to mark x as demanded, because it will be when we @@ -110,42 +117,36 @@ dmdAnal sigs Lazy e = let -- just mark x as Lazy -dmdAnal sigs dmd (Var var) - = (res_ty, - blackHoleEnv res_ty (unitDmdEnv var dmd), - Var var) - where - res_ty = dmdTransform sigs var dmd - dmdAnal sigs dmd (Lit lit) - = (topDmdType, emptyDmdEnv, Lit lit) + = (topDmdType, Lit lit) + +dmdAnal sigs dmd (Var var) + = (dmdTransform sigs var dmd, Var var) dmdAnal sigs dmd (Note n e) - = (dmd_ty, dmd_env, Note n e') + = (dmd_ty, Note n e') where - (dmd_ty, dmd_env, e') = dmdAnal sigs dmd e + (dmd_ty, e') = dmdAnal sigs dmd e dmdAnal sigs dmd (App fun (Type ty)) - = (fun_ty, fun_env, App fun' (Type ty)) + = (fun_ty, App fun' (Type ty)) where - (fun_ty, fun_env, fun') = dmdAnal sigs dmd fun + (fun_ty, fun') = dmdAnal sigs dmd fun dmdAnal sigs dmd (App fun arg) -- Non-type arguments = let -- [Type arg handled above] - (fun_ty, fun_env, fun') = dmdAnal sigs (Call dmd) fun - (arg_ty, arg_env, arg') = dmdAnal sigs arg_dmd arg - (arg_dmd, res_ty) = splitDmdTy fun_ty + (fun_ty, fun') = dmdAnal sigs (Call dmd) fun + (arg_ty, arg') = dmdAnal sigs arg_dmd arg + (arg_dmd, res_ty) = splitDmdTy fun_ty in - (res_ty, - blackHoleEnv res_ty (fun_env `bothEnv` arg_env), - App fun' arg') + (res_ty `bothType` arg_ty, App fun' arg') dmdAnal sigs dmd (Lam var body) | isTyVar var = let - (body_ty, body_env, body') = dmdAnal sigs dmd body + (body_ty, body') = dmdAnal sigs dmd body in - (body_ty, body_env, Lam var body') + (body_ty, Lam var body') | otherwise = let @@ -153,12 +154,10 @@ dmdAnal sigs dmd (Lam var body) Call dmd -> dmd other -> Lazy -- Conservative - (body_ty, body_env, body') = dmdAnal sigs body_dmd body - (lam_env, var') = annotateBndr body_env var + (body_ty, body') = dmdAnal sigs body_dmd body + (lam_ty, var') = annotateLamIdBndr body_ty var in - (DmdFun (idNewDemandInfo var') body_ty, - body_env `delDmdEnv` var, - Lam var' body') + (lam_ty, Lam var' body') dmdAnal sigs dmd (Case scrut case_bndr [alt@(DataAlt dc,bndrs,rhs)]) | let tycon = dataConTyCon dc, @@ -166,52 +165,38 @@ dmdAnal sigs dmd (Case scrut case_bndr [alt@(DataAlt dc,bndrs,rhs)]) not (isRecursiveTyCon tycon) = let bndr_ids = filter isId bndrs - (alt_ty, alt_env, alt') = dmdAnalAlt sigs dmd alt - (_, scrut_env, scrut') = dmdAnal sigs scrut_dmd scrut - (alt_env2, case_bndr') = annotateBndr alt_env case_bndr + (alt_ty, alt') = dmdAnalAlt sigs dmd alt + (alt_ty1, case_bndr') = annotateBndr alt_ty case_bndr (_, bndrs', _) = alt' - scrut_dmd = Seq Drop [idNewDemandInfo b | b <- bndrs', isId b] + scrut_dmd = Seq Drop Now [idNewDemandInfo b | b <- bndrs', isId b] + (scrut_ty, scrut') = dmdAnal sigs scrut_dmd scrut in - (alt_ty, - alt_env2 `bothEnv` scrut_env, - Case scrut' case_bndr' [alt']) + (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' [alt']) dmdAnal sigs dmd (Case scrut case_bndr alts) = let - (alt_tys, alt_envs, alts') = unzip3 (map (dmdAnalAlt sigs dmd) alts) - (scrut_ty, scrut_env, scrut') = dmdAnal sigs Eval scrut - (alt_env2, case_bndr') = annotateBndr (foldr1 lubEnv alt_envs) case_bndr + (alt_tys, alts') = mapAndUnzip (dmdAnalAlt sigs dmd) alts + (scrut_ty, scrut') = dmdAnal sigs Eval scrut + (alt_ty, case_bndr') = annotateBndr (foldr1 lubType alt_tys) case_bndr in - (foldr1 lubDmdTy alt_tys, - alt_env2 `bothEnv` scrut_env, - Case scrut' case_bndr' alts') +-- pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys) + (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' alts') dmdAnal sigs dmd (Let (NonRec id rhs) body) - | idArity id == 0 -- A thunk; analyse the body first, then the thunk = let - (body_ty, body_env, body') = dmdAnal sigs dmd body - (rhs_ty, rhs_env, rhs') = dmdAnal sigs (lookupDmd body_env id) rhs - (body_env1, id1) = annotateBndr body_env id + (sigs', (id1, rhs')) = downRhs NotTopLevel sigs (id, rhs) + (body_ty, body') = dmdAnal sigs' dmd body + (body_ty1, id2) = annotateBndr body_ty id1 in - (body_ty, body_env1 `bothEnv` rhs_env, Let (NonRec id1 rhs') body') - - | otherwise -- A function; analyse the function first, then the body - = let - (sig, rhs_env, (id1, rhs')) = downRhs sigs (id, rhs) - sigs' = extendSigEnv sigs id sig - (body_ty, body_env, body') = dmdAnal sigs' dmd body - rhs_env1 = weaken body_env id rhs_env - (body_env1, id2) = annotateBndr body_env id1 - in - (body_ty, body_env1 `bothEnv` rhs_env1, Let (NonRec id2 rhs') body') +-- pprTrace "dmdLet" (ppr id <+> ppr (sig,rhs_env)) + (body_ty1, Let (NonRec id2 rhs') body') dmdAnal sigs dmd (Let (Rec pairs) body) = let - bndrs = map fst pairs - (sigs', rhs_envs, pairs') = dmdFix sigs pairs - (body_ty, body_env, body') = dmdAnal sigs' dmd body + bndrs = map fst pairs + (sigs', pairs') = dmdFix NotTopLevel sigs pairs + (body_ty, body') = dmdAnal sigs' dmd body - weakened_rhs_envs = zipWithEqual "dmdAnal:Let" (weaken body_env) bndrs rhs_envs -- I saw occasions where it was really worth using the -- call demands on the Ids to propagate demand info -- on the free variables. An example is 'roll' in imaginary/wheel-sieve2 @@ -219,25 +204,25 @@ dmdAnal sigs dmd (Let (Rec pairs) body) -- roll x = letrec go y = if ... then roll (x-1) else x+1 -- in go ms -- We want to see that this is strict in x. + -- + -- This will happen because sigs' has a binding for 'go' that + -- has a demand on x. - rhs_env1 = foldr1 bothEnv weakened_rhs_envs - - result_env = delDmdEnvList (body_env `bothEnv` rhs_env1) bndrs + (result_ty, _) = annotateBndrs body_ty bndrs -- Don't bother to add demand info to recursive -- binders as annotateBndr does; -- being recursive, we can't treat them strictly. -- But we do need to remove the binders from the result demand env in - (body_ty, result_env, Let (Rec pairs') body') -\end{code} + (result_ty, Let (Rec pairs') body') + -\begin{code} dmdAnalAlt sigs dmd (con,bndrs,rhs) = let - (rhs_ty, rhs_env, rhs') = dmdAnal sigs dmd rhs - (alt_env, bndrs') = annotateBndrs rhs_env bndrs + (rhs_ty, rhs') = dmdAnal sigs dmd rhs + (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs in - (rhs_ty, alt_env, (con, bndrs', rhs')) + (alt_ty, (con, bndrs', rhs')) \end{code} %************************************************************************ @@ -247,43 +232,87 @@ dmdAnalAlt sigs dmd (con,bndrs,rhs) %************************************************************************ \begin{code} -dmdFix :: SigEnv -- Does not include bindings for this binding +dmdFix :: TopLevelFlag + -> SigEnv -- Does not include bindings for this binding -> [(Id,CoreExpr)] -> (SigEnv, - [DmdEnv], -- Demands from RHSs [(Id,CoreExpr)]) -- Binders annotated with stricness info -dmdFix sigs pairs - = loop (map initial_sig pairs) pairs +dmdFix top_lvl sigs pairs + = loop 1 initial_sigs pairs where - loop id_sigs pairs - | id_sigs == id_sigs' = (sigs', rhs_envs, pairs') - | otherwise = loop id_sigs' pairs' + bndrs = map fst pairs + initial_sigs = extendSigEnvList sigs [(id, (initial_sig id, top_lvl)) | id <- bndrs] + + loop :: Int + -> SigEnv -- Already contains the current sigs + -> [(Id,CoreExpr)] + -> (SigEnv, [(Id,CoreExpr)]) + loop n sigs pairs + | all (same_sig sigs sigs') bndrs = (sigs, pairs) + -- Note: use pairs, not pairs'. Since the sigs are the same + -- there'll be no change, unless this is the very first visit, + -- and the first iteraion of that visit. But in that case, the + -- function is bottom anyway, there's no point in looking. + | n >= 5 = pprTrace "dmdFix" (ppr n <+> ppr pairs) (loop (n+1) sigs' pairs') + | otherwise = {- pprTrace "dmdFixLoop" (ppr id_sigs) -} (loop (n+1) sigs' pairs') where - extra_sigs = [(id,sig) | ((id,_),sig) <- pairs `zip` id_sigs] - sigs' = extendSigEnvList sigs extra_sigs - (id_sigs', rhs_envs, pairs') = unzip3 (map (downRhs sigs') pairs) + -- Use the new signature to do the next pair + -- The occurrence analyser has arranged them in a good order + -- so this can significantly reduce the number of iterations needed + (sigs', pairs') = mapAccumL (downRhs top_lvl) sigs pairs + -- Get an initial strictness signature from the Id -- itself. That way we make use of earlier iterations -- of the fixpoint algorithm. (Cunning plan.) - initial_sig (id,_) = idNewStrictness_maybe id `orElse` botSig + -- Note that the cunning plan extends to the DmdEnv too, + -- since it is part of the strictness signature + initial_sig id = idNewStrictness_maybe id `orElse` botSig + same_sig sigs sigs' var = lookup sigs var == lookup sigs' var + lookup sigs var = case lookupVarEnv sigs var of + Just (sig,_) -> sig -downRhs :: SigEnv -> (Id, CoreExpr) - -> (StrictSig, DmdEnv, (Id, CoreExpr)) +downRhs :: TopLevelFlag + -> SigEnv -> (Id, CoreExpr) + -> (SigEnv, (Id, CoreExpr)) -- On the way down, compute a strictness signature -- for the function. Keep its annotated RHS and dmd env -- for use on the way up -- The demand-env is that computed for a vanilla call. -downRhs sigs (id, rhs) - = (sig, rhs_env, (id', rhs')) +downRhs top_lvl sigs (id, rhs) + = (sigs', (id', rhs')) where - arity = idArity id - (rhs_ty, rhs_env, rhs') = dmdAnal sigs (vanillaCall arity) rhs - sig = mkStrictSig arity rhs_ty - id' = id `setIdNewStrictness` sig + arity = exprArity rhs -- The idArity may not be up to date + (rhs_ty, rhs') = dmdAnal sigs (vanillaCall arity) rhs + sig = mkStrictSig id arity (mkSigTy rhs rhs_ty) + id' = id `setIdNewStrictness` sig + sigs' = extendSigEnv top_lvl sigs id sig + +mkSigTy rhs (DmdType fv [] RetCPR) + | not (exprIsValue rhs) = DmdType fv [] TopRes + -- If the rhs is a thunk, we forget the CPR info, because + -- it is presumably shared (else it would have been inlined, and + -- so we'd lose sharing if w/w'd it into a function. + -- + -- ** But keep the demand unleashed on the free + -- vars when the thing is evaluated! ** + -- + -- DONE IN OLD CPR ANALYSER, BUT NOT YET HERE + -- Also, if the strictness analyser has figured out that it's strict, + -- the let-to-case transformation will happen, so again it's good. + -- (CPR analysis runs before the simplifier has had a chance to do + -- the let-to-case transform.) + -- This made a big difference to PrelBase.modInt, which had something like + -- modInt = \ x -> let r = ... -> I# v in + -- ...body strict in r... + -- r's RHS isn't a value yet; but modInt returns r in various branches, so + -- if r doesn't have the CPR property then neither does modInt + +mkSigTy rhs (DmdType fv dmds res) = DmdType fv (map lazify dmds) res +-- Get rid of defers \end{code} @@ -294,86 +323,38 @@ downRhs sigs (id, rhs) %************************************************************************ \begin{code} -data DmdEnv - = DmdEnv (VarEnv Demand) -- All the explicitly mentioned variables - Bool -- True <=> all the others are Bot - -- False <=> all the others are Abs - -emptyDmdEnv = DmdEnv emptyVarEnv False -unitDmdEnv var dmd = DmdEnv (unitVarEnv var dmd) False - -lookupDmd :: DmdEnv -> Var -> Demand -lookupDmd (DmdEnv env bh) var = lookupVarEnv env var `orElse` deflt - where - deflt | bh = Bot - | otherwise = Abs - -delDmdEnv :: DmdEnv -> Var -> DmdEnv -delDmdEnv (DmdEnv env b) var = DmdEnv (env `delVarEnv` var) b - -delDmdEnvList :: DmdEnv -> [Var] -> DmdEnv -delDmdEnvList (DmdEnv env b) vars = DmdEnv (env `delVarEnvList` vars) b +unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes +addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd + | isTopLevel top_lvl = dmd_ty -- Don't record top level things + | otherwise = DmdType (extendVarEnv fv var dmd) ds res -blackHoleEnv :: DmdType -> DmdEnv -> DmdEnv -blackHoleEnv (DmdRes BotRes) (DmdEnv env _) = DmdEnv env True -blackHoleEnv other env = env - -bothEnv (DmdEnv env1 b1) (DmdEnv env2 b2) - = DmdEnv both_env2 (b1 || b2) - where - both_env = plusUFM_C both env1 env2 - both_env1 = modifyEnv b1 Bot env2 env1 both_env - both_env2 = modifyEnv b2 Bot env1 env2 both_env1 - -lubEnv (DmdEnv env1 b1) (DmdEnv env2 b2) - = DmdEnv lub_env2 (b1 && b2) - where - lub_env = plusUFM_C lub env1 env2 - lub_env1 = modifyEnv (not b1) Lazy env2 env1 lub_env - lub_env2 = modifyEnv (not b2) Lazy env1 env2 lub_env1 - -modifyEnv :: Bool -- No-op if False - -> Demand -- The zap value - -> VarEnv Demand -> VarEnv Demand -- Env1 and Env2 - -> VarEnv Demand -> VarEnv Demand -- Transform this env - -- Zap anything in Env1 but not in Env2 - -- Assume: dom(env) includes dom(Env1) and dom(Env2) - -modifyEnv need_to_modify zap_value env1 env2 env - | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2)) - | otherwise = env - where - zap uniq env = addToUFM_Directly env uniq zap_value - -annotateBndr :: DmdEnv -> Var -> (DmdEnv, Var) +annotateBndr :: DmdType -> Var -> (DmdType, Var) -- The returned env has the var deleted -- The returned var is annotated with demand info -annotateBndr dmd_env var - | isTyVar var = (dmd_env, var) - | otherwise = (dmd_env `delDmdEnv` var, setIdNewDemandInfo var (lookupDmd dmd_env var)) +-- No effect on the argument demands +annotateBndr dmd_ty@(DmdType fv ds res) var + | isTyVar var = (dmd_ty, var) + | otherwise = (DmdType fv' ds res, setIdNewDemandInfo var dmd) + where + (fv', dmd) = removeFV fv var res annotateBndrs = mapAccumR annotateBndr -weaken :: DmdEnv -- How the Id is used in its scope - -> Id - -> DmdEnv -- The RHS env for the Id, assuming a vanilla call demand - -> DmdEnv -- The RHS env given the actual demand --- Consider let f = \x -> R in B --- The vanilla call demand is C(V), and that's what we use to --- compute f's strictness signature. If the *actual* demand on --- f from B is less than this, we must weaken, or lazify, the --- demands in R to match this - -weaken body_env id rhs_env - | depth >= idArity id -- Enough demand - = rhs_env - | otherwise -- Not enough demand - = lazify rhs_env +annotateLamIdBndr dmd_ty@(DmdType fv ds res) id +-- For lambdas we add the demand to the argument demands +-- Only called for Ids + = ASSERT( isId id ) + (DmdType fv' (dmd:ds) res, setIdNewDemandInfo id dmd) where - (depth,_) = splitCallDmd (lookupDmd body_env id) - -lazify (DmdEnv env _) = DmdEnv (mapVarEnv (\_ -> Lazy) env) False + (fv', dmd) = removeFV fv id res + +removeFV fv var res = (fv', dmd) + where + fv' = fv `delVarEnv` var + dmd = lookupVarEnv fv var `orElse` deflt + deflt | isBotRes res = Bot + | otherwise = Abs \end{code} %************************************************************************ @@ -385,29 +366,16 @@ lazify (DmdEnv env _) = DmdEnv (mapVarEnv (\_ -> Lazy) env) False \begin{code} splitDmdTy :: DmdType -> (Demand, DmdType) -- Split off one function argument -splitDmdTy (DmdFun dmd res_ty) = (dmd, res_ty) -splitDmdTy (DmdRes TopRes) = (topDmd, topDmdType) -splitDmdTy (DmdRes BotRes) = (Abs, DmdRes BotRes) +splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty) +splitDmdTy ty@(DmdType fv [] TopRes) = (topDmd, ty) +splitDmdTy ty@(DmdType fv [] BotRes) = (Abs, ty) -- We already have a suitable demand on all -- free vars, so no need to add more! -splitDmdTy (DmdRes RetCPR) = panic "splitDmdTy" - -------------------------- -dmdTypeRes :: DmdType -> Result -dmdTypeRes (DmdFun dmd res_ty) = dmdTypeRes res_ty -dmdTypeRes (DmdRes res) = res +splitDmdTy (DmdType fv [] RetCPR) = panic "splitDmdTy" ------------------------- -lubDmdTy :: DmdType -> DmdType -> DmdType -lubDmdTy (DmdFun d1 t1) (DmdFun d2 t2) = DmdFun (d1 `lub` d2) (t1 `lubDmdTy` t2) -lubDmdTy (DmdRes r1) (DmdRes r2) = DmdRes (r1 `lubRes` r2) -lubDmdTy t1 t2 = topDmdType - -------------------------- -lubRes BotRes r = r -lubRes r BotRes = r -lubRes RetCPR RetCPR = RetCPR -lubRes r1 r2 = TopRes +dmdTypeRes :: DmdType -> DmdResult +dmdTypeRes (DmdType _ _ res_ty) = res_ty \end{code} @@ -418,43 +386,72 @@ lubRes r1 r2 = TopRes %************************************************************************ \begin{code} -type SigEnv = VarEnv StrictSig +type SigEnv = VarEnv (StrictSig, TopLevelFlag) + -- We use the SigEnv to tell us whether to + -- record info about a variable in the DmdEnv + -- We do so if it's a LocalId, but not top-level + -- + -- The DmdEnv gives the demand on the free vars of the function + -- when it is given enough args to satisfy the strictness signature + emptySigEnv = emptyVarEnv -extendSigEnv = extendVarEnv + +extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv +extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl) + extendSigEnvList = extendVarEnvList -lookupSig sigs v = case lookupVarEnv sigs v of - Just sig -> Just sig - Nothing -> idNewStrictness_maybe v dmdTransform :: SigEnv -- The strictness environment -> Id -- The function -> Demand -- The demand on the function -> DmdType -- The demand type of the function in this context + -- Returned DmdEnv includes the demand on + -- this function plus demand on its free variables dmdTransform sigs var dmd - | isDataConId var, -- Data constructor - Seq k ds <- res_dmd, -- and the demand looks inside its fields - StrictSig arity dmd_ty <- idNewStrictness var, -- It must have a strictness sig - length ds == arity -- It's saturated - = mkDmdFun ds (dmdTypeRes dmd_ty) - -- Need to extract whether it's a product - - | Just (StrictSig arity dmd_ty) <- lookupSig sigs var, - arity <= depth -- Saturated function; - = dmd_ty -- Unleash the demand! +------ DATA CONSTRUCTOR + | isDataConId var, -- Data constructor + Seq k Now ds <- res_dmd, -- and the demand looks inside its fields + let StrictSig arity dmd_ty = idNewStrictness var -- It must have a strictness sig + = if arity == length ds then -- Saturated, so unleash the demand + -- ds can be empty, when we are just seq'ing the thing + mkDmdType emptyDmdEnv ds (dmdTypeRes dmd_ty) + -- Need to extract whether it's a product + else + topDmdType + +------ IMPORTED FUNCTION + | isGlobalId var, -- Imported function + let StrictSig arity dmd_ty = getNewStrictness var + = if arity <= depth then -- Saturated, so unleash the demand + dmd_ty + else + topDmdType + +------ LOCAL LET/REC BOUND THING + | Just (StrictSig arity dmd_ty, top_lvl) <- lookupVarEnv sigs var + = let + fn_ty = if arity <= depth then dmd_ty else topDmdType + in + addVarDmd top_lvl fn_ty var dmd +------ LOCAL NON-LET/REC BOUND THING | otherwise -- Default case - = topDmdType + = unitVarDmd var dmd where (depth, res_dmd) = splitCallDmd dmd +\end{code} + +\begin{code} +squashDmdEnv (StrictSig a (DmdType fv ds res)) = StrictSig a (DmdType emptyDmdEnv ds res) betterStrict :: StrictSig -> StrictSig -> Bool betterStrict (StrictSig ar1 t1) (StrictSig ar2 t2) = (ar1 >= ar2) && (t1 `betterDmdType` t2) -betterDmdType t1 t2 = (t1 `lubDmdTy` t2) == t2 +betterDmdType t1 t2 = (t1 `lubType` t2) == t2 \end{code} @@ -474,7 +471,35 @@ vanillaCall :: Arity -> Demand vanillaCall 0 = Eval vanillaCall n = Call (vanillaCall (n-1)) ------------------------------------ +deferType :: DmdType -> DmdType +deferType (DmdType fv ds _) = DmdType (mapVarEnv defer fv) ds TopRes + -- Check this + +defer :: Demand -> Demand +-- c.f. `lub` Abs +defer Abs = Abs +defer (Seq k _ ds) = Seq k Defer ds +defer other = Lazy + +lazify :: Demand -> Demand +-- The 'Defer' demands are just Lazy at function boundaries +lazify (Seq k Defer ds) = Lazy +lazify (Seq k Now ds) = Seq k Now (map lazify ds) +lazify d = d + +betterDemand :: Demand -> Demand -> Bool +-- If d1 `better` d2, and d2 `better` d2, then d1==d2 +betterDemand d1 d2 = (d1 `lub` d2) == d2 +\end{code} + + +%************************************************************************ +%* * +\subsection{LUB and BOTH} +%* * +%************************************************************************ + +\begin{code} lub :: Demand -> Demand -> Demand lub Bot d = d @@ -484,24 +509,47 @@ lub Lazy d = Lazy lub Err Bot = Err lub Err d = d -lub Abs Bot = Abs -lub Abs Err = Abs -lub Abs Abs = Abs -lub Abs d = d +lub Abs Bot = Abs +lub Abs Err = Abs +lub Abs Abs = Abs +lub Abs (Seq k _ ds) = Seq k Defer ds -- Very important ('radicals' example) +lub Abs d = Lazy -lub Eval Abs = Lazy -lub Eval Lazy = Lazy -lub Eval (Seq k ds) = Seq Keep ds -lub Eval d = Eval +lub Eval Abs = Lazy +lub Eval Lazy = Lazy +lub Eval (Seq k Now ds) = Seq Keep Now ds +lub Eval d = Eval lub (Call d1) (Call d2) = Call (lub d1 d2) -lub (Seq k1 ds1) (Seq k2 ds2) = Seq (k1 `vee` k2) - (zipWithEqual "lub" lub ds1 ds2) +lub (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) (l1 `or_defer` l2) + (zipWithEqual "lub" lub ds1 ds2) -- The last clauses deal with the remaining cases for Call and Seq -lub d1@(Call _) d2@(Seq _ _) = pprPanic "lub" (ppr d1 $$ ppr d2) -lub d1 d2 = lub d2 d1 +lub d1@(Call _) d2@(Seq _ _ _) = pprPanic "lub" (ppr d1 $$ ppr d2) +lub d1 d2 = lub d2 d1 + +or_defer Now Now = Now +or_defer _ _ = Defer + +------------------------- +-- Consider (if x then y else []) with demand V +-- Then the first branch gives {y->V} and the second +-- *implicitly* has {y->A}. So we must put {y->(V `lub` A)} +-- in the result env. +lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2) + = DmdType lub_fv2 (zipWith lub ds1 ds2) (r1 `lubRes` r2) + where + lub_fv = plusUFM_C lub fv1 fv2 + lub_fv1 = modifyEnv (not (isBotRes r1)) (Abs `lub`) fv2 fv1 lub_fv + lub_fv2 = modifyEnv (not (isBotRes r2)) (Abs `lub`) fv1 fv2 lub_fv1 + -- lub is the identity for Bot + +------------------------- +lubRes BotRes r = r +lubRes r BotRes = r +lubRes RetCPR RetCPR = RetCPR +lubRes r1 r2 = TopRes ----------------------------------- vee :: Keepity -> Keepity -> Keepity @@ -520,29 +568,65 @@ both Err Bot = Bot both Err Abs = Err both Err d = d -both Lazy Bot = Bot -both Lazy Abs = Lazy -both Lazy Err = Lazy -both Lazy (Seq k ds) = Seq Keep ds -both Lazy d = d - -both Eval Bot = Bot -both Eval (Seq k ds) = Seq Keep ds -both Eval (Call d) = Call d -both Eval d = Eval - -both (Seq k1 ds1) (Seq k2 ds2) = Seq (k1 `vee` k2) - (zipWithEqual "both" both ds1 ds2) +both Lazy Bot = Bot +both Lazy Abs = Lazy +both Lazy Err = Lazy +both Lazy (Seq k Now ds) = Seq Keep Now ds +both Lazy d = d + +both Eval Bot = Bot +both Eval (Seq k l ds) = Seq Keep Now ds +both Eval (Call d) = Call d +both Eval d = Eval + +both (Seq k1 Defer ds1) (Seq k2 Defer ds2) = Seq (k1 `vee` k2) Defer + (zipWithEqual "both" both ds1 ds2) +both (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) Now + (zipWithEqual "both" both ds1' ds2') + where + ds1' = case l1 of { Now -> ds1; Defer -> map defer ds1 } + ds2' = case l2 of { Now -> ds2; Defer -> map defer ds2 } both (Call d1) (Call d2) = Call (d1 `both` d2) -- The last clauses deal with the remaining cases for Call and Seq -both d1@(Call _) d2@(Seq _ _) = pprPanic "both" (ppr d1 $$ ppr d2) -both d1 d2 = both d2 d1 +both d1@(Call _) d2@(Seq _ _ _) = pprPanic "both" (ppr d1 $$ ppr d2) +both d1 d2 = both d2 d1 -betterDemand :: Demand -> Demand -> Bool --- If d1 `better` d2, and d2 `better` d2, then d1==d2 -betterDemand d1 d2 = (d1 `lub` d2) == d2 +----------------------------------- +bothRes :: DmdResult -> DmdResult -> DmdResult +-- Left-biased for CPR info +bothRes BotRes _ = BotRes +bothRes _ BotRes = BotRes +bothRes r1 _ = r1 + +----------------------------------- +-- (t1 `bothType` t2) takes the argument/result info from t1, +-- using t2 just for its free-var info +bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2) + = DmdType both_fv2 ds1 r1 + where + both_fv = plusUFM_C both fv1 fv2 + both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv + both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1 + -- both is the identity for Abs +\end{code} + +\begin{code} +modifyEnv :: Bool -- No-op if False + -> (Demand -> Demand) -- The zapper + -> DmdEnv -> DmdEnv -- Env1 and Env2 + -> DmdEnv -> DmdEnv -- Transform this env + -- Zap anything in Env1 but not in Env2 + -- Assume: dom(env) includes dom(Env1) and dom(Env2) + +modifyEnv need_to_modify zapper env1 env2 env + | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2)) + | otherwise = env + where + zap uniq env = addToUFM_Directly env uniq (zapper current_val) + where + current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq) \end{code} @@ -561,6 +645,15 @@ idNewStrictness :: Id -> StrictSig idNewStrictness_maybe id = newStrictnessInfo (idInfo id) idNewStrictness id = idNewStrictness_maybe id `orElse` topSig +getNewStrictness :: Id -> StrictSig +-- First tries the "new-strictness" field, and then +-- reverts to the old one. This is just until we have +-- cross-module info for new strictness +getNewStrictness id = idNewStrictness_maybe id `orElse` newStrictnessFromOld id + +newStrictnessFromOld :: Id -> StrictSig +newStrictnessFromOld id = mkNewStrictnessInfo id (idArity id) (idStrictness id) (idCprInfo id) + setIdNewStrictness :: Id -> StrictSig -> Id setIdNewStrictness id sig = modifyIdInfo (`setNewStrictnessInfo` sig) id @@ -588,11 +681,11 @@ get_changes_expr (Var v) = empty get_changes_expr (Lit l) = empty get_changes_expr (Note n e) = get_changes_expr e get_changes_expr (App e1 e2) = get_changes_expr e1 $$ get_changes_expr e2 -get_changes_expr (Lam b e) = get_changes_var b $$ get_changes_expr e +get_changes_expr (Lam b e) = {- get_changes_var b $$ -} get_changes_expr e get_changes_expr (Let b e) = get_changes_bind b $$ get_changes_expr e get_changes_expr (Case e b a) = get_changes_expr e $$ get_changes_var b $$ vcat (map get_changes_alt a) -get_changes_alt (con,bs,rhs) = vcat (map get_changes_var bs) $$ get_changes_expr rhs +get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs get_changes_str id | new_better && old_better = empty @@ -602,12 +695,13 @@ get_changes_str id where message word = text word <+> text "strictness for" <+> ppr id <+> info info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new) - new = idNewStrictness id - old = mkNewStrictnessInfo (idArity id) (idStrictness id) (idCprInfo id) + new = squashDmdEnv (idNewStrictness id) -- Don't report diffs in the env + old = newStrictnessFromOld id old_better = old `betterStrict` new new_better = new `betterStrict` old get_changes_dmd id + | isUnLiftedType (idType id) = empty -- Not useful | new_better && old_better = empty | new_better = message "BETTER" | old_better = message "WORSE" @@ -615,10 +709,9 @@ get_changes_dmd id where message word = text word <+> text "demand for" <+> ppr id <+> info info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new) - new = idNewDemandInfo id + new = lazify (idNewDemandInfo id) -- Lazify to avoid spurious improvements old = newDemand (idDemandInfo id) new_better = new `betterDemand` old old_better = old `betterDemand` new #endif /* DEBUG */ \end{code} -