2 % (c) The University of Glasgow, 1994-2000
4 \section{Core pass to saturate constructors and PrimOps}
8 coreSatPgm, coreSatExpr
11 #include "HsVersions.h"
19 import Var ( TyVar, setTyVarUnique )
31 -- ---------------------------------------------------------------------------
33 -- ---------------------------------------------------------------------------
35 Most of the contents of this pass used to be in CoreToStg. The
36 primary goals here are:
38 1. Get the program into "A-normal form". In particular:
40 f E ==> let x = E in f x
41 OR ==> case E of x -> f x
44 if E is a non-trivial expression.
45 Which transformation is used depends on whether f is strict or not.
46 [Previously the transformation to case used to be done by the
47 simplifier, but it's better done here. It does mean that f needs
48 to have its strictness info correct!.]
50 2. Similarly, convert any unboxed let's into cases.
51 [I'm experimenting with leaving 'ok-for-speculation' rhss in let-form
52 right up to this point.]
54 This is all done modulo type applications and abstractions, so that
55 when type erasure is done for conversion to STG, we don't end up with
56 any trivial or useless bindings.
58 3. Ensure that lambdas only occur as the RHS of a binding
59 (The code generator can't deal with anything else.)
61 4. Saturate constructor and primop applications.
65 -- -----------------------------------------------------------------------------
67 -- -----------------------------------------------------------------------------
70 coreSatPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
71 coreSatPgm dflags binds
72 = do showPass dflags "CoreSat"
73 us <- mkSplitUniqSupply 's'
74 let new_binds = initUs_ us (coreSatBinds binds)
75 endPass dflags "CoreSat" Opt_D_dump_sat new_binds
77 coreSatExpr :: DynFlags -> CoreExpr -> IO CoreExpr
78 coreSatExpr dflags expr
79 = do showPass dflags "CoreSat"
80 us <- mkSplitUniqSupply 's'
81 let new_expr = initUs_ us (coreSatAnExpr expr)
82 dumpIfSet_dyn dflags Opt_D_dump_sat "Saturated/Normal form syntax:"
86 -- ---------------------------------------------------------------------------
87 -- Dealing with bindings
88 -- ---------------------------------------------------------------------------
91 = RecF [(Id, CoreExpr)]
93 CoreExpr -- *Can* be a Lam
97 coreSatBinds :: [CoreBind] -> UniqSM [CoreBind]
98 coreSatBinds [] = returnUs []
100 = coreSatBind b `thenUs` \ float ->
101 coreSatBinds bs `thenUs` \ new_bs ->
103 NonRecF bndr rhs dem floats
104 -> ASSERT2( not (isStrictDem dem) &&
105 not (isUnLiftedType (idType bndr)),
106 ppr b ) -- No top-level cases!
108 mkBinds floats rhs `thenUs` \ new_rhs ->
109 returnUs (NonRec bndr new_rhs : new_bs)
110 -- Keep all the floats inside...
111 -- Some might be cases etc
112 -- We might want to revisit this decision
114 RecF prs -> returnUs (Rec prs : new_bs)
116 coreSatBind :: CoreBind -> UniqSM FloatingBind
117 coreSatBind (NonRec binder rhs)
118 = coreSatExprFloat rhs `thenUs` \ (floats, new_rhs) ->
119 returnUs (NonRecF binder new_rhs (bdrDem binder) floats)
120 coreSatBind (Rec pairs)
121 = mapUs do_rhs pairs `thenUs` \ new_rhss ->
122 returnUs (RecF (binders `zip` new_rhss))
124 binders = map fst pairs
126 coreSatExprFloat rhs `thenUs` \ (floats, new_rhs) ->
127 mkBinds floats new_rhs `thenUs` \ new_rhs' ->
128 -- NB: new_rhs' might still be a Lam (and we want that)
131 -- ---------------------------------------------------------------------------
132 -- Making arguments atomic (function args & constructor args)
133 -- ---------------------------------------------------------------------------
135 -- This is where we arrange that a non-trivial argument is let-bound
136 coreSatArg :: CoreArg -> RhsDemand -> UniqSM ([FloatingBind], CoreArg)
138 = coreSatExprFloat arg `thenUs` \ (floats, arg') ->
139 if exprIsTrivial arg'
140 then returnUs (floats, arg')
141 else newVar (exprType arg') `thenUs` \ v ->
142 returnUs ([NonRecF v arg' dem floats], Var v)
144 -- ---------------------------------------------------------------------------
145 -- Dealing with expressions
146 -- ---------------------------------------------------------------------------
148 coreSatAnExpr :: CoreExpr -> UniqSM CoreExpr
150 = coreSatExprFloat expr `thenUs` \ (floats, expr) ->
154 coreSatExprFloat :: CoreExpr -> UniqSM ([FloatingBind], CoreExpr)
158 -- e = let bs in e' (semantically, that is!)
161 -- f (g x) ===> ([v = g x], f v)
163 coreSatExprFloat (Var v)
164 = maybeSaturate v (Var v) 0 (idType v) `thenUs` \ app ->
167 coreSatExprFloat (Lit lit)
168 = returnUs ([], Lit lit)
170 coreSatExprFloat (Let bind body)
171 = coreSatBind bind `thenUs` \ new_bind ->
172 coreSatExprFloat body `thenUs` \ (floats, new_body) ->
173 returnUs (new_bind:floats, new_body)
175 coreSatExprFloat (Note other_note expr)
176 = coreSatExprFloat expr `thenUs` \ (floats, expr) ->
177 returnUs (floats, Note other_note expr)
179 coreSatExprFloat expr@(Type _)
180 = returnUs ([], expr)
182 coreSatExprFloat (Lam v e)
183 = coreSatAnExpr e `thenUs` \ e' ->
184 returnUs ([], Lam v e')
186 coreSatExprFloat (Case scrut bndr alts)
187 = coreSatExprFloat scrut `thenUs` \ (floats, scrut) ->
188 mapUs sat_alt alts `thenUs` \ alts ->
189 returnUs (floats, Case scrut bndr alts)
191 sat_alt (con, bs, rhs)
192 = coreSatAnExpr rhs `thenUs` \ rhs ->
193 deLam rhs `thenUs` \ rhs ->
194 returnUs (con, bs, rhs)
196 coreSatExprFloat expr@(App _ _)
197 = collect_args expr 0 `thenUs` \ (app,(head,depth),ty,floats,ss) ->
198 ASSERT(null ss) -- make sure we used all the strictness info
200 -- Now deal with the function
203 -> maybeSaturate fn_id app depth ty `thenUs` \ app' ->
204 returnUs (floats, app')
206 -> returnUs (floats, app)
212 -> Int -- current app depth
213 -> UniqSM (CoreExpr, -- the rebuilt expression
214 (CoreExpr,Int), -- the head of the application,
215 -- and no. of args it was applied to
216 Type, -- type of the whole expr
217 [FloatingBind], -- any floats we pulled out
218 [Demand]) -- remaining argument demands
220 collect_args (App fun arg@(Type arg_ty)) depth
221 = collect_args fun depth `thenUs` \ (fun',hd,fun_ty,floats,ss) ->
222 returnUs (App fun' arg, hd, applyTy fun_ty arg_ty, floats, ss)
224 collect_args (App fun arg) depth
225 = collect_args fun (depth+1) `thenUs` \ (fun',hd,fun_ty,floats,ss) ->
227 (ss1, ss_rest) = case ss of
228 (ss1:ss_rest) -> (ss1, ss_rest)
230 (arg_ty, res_ty) = expectJust "coreSatExprFloat:collect_args" $
231 splitFunTy_maybe fun_ty
233 coreSatArg arg (mkDemTy ss1 arg_ty) `thenUs` \ (fs, arg') ->
234 returnUs (App fun' arg', hd, res_ty, fs ++ floats, ss_rest)
236 collect_args (Var v) depth
237 = returnUs (Var v, (Var v, depth), idType v, [], stricts)
239 stricts = case idStrictness v of
240 StrictnessInfo demands _
241 | depth >= length demands -> demands
244 -- If depth < length demands, then we have too few args to
245 -- satisfy strictness info so we have to ignore all the
246 -- strictness info, e.g. + (error "urk")
247 -- Here, we can't evaluate the arg strictly, because this
248 -- partial application might be seq'd
250 collect_args (Note (Coerce ty1 ty2) fun) depth
251 = collect_args fun depth `thenUs` \ (fun', hd, fun_ty, floats, ss) ->
252 returnUs (Note (Coerce ty1 ty2) fun', hd, ty1, floats, ss)
254 collect_args (Note note fun) depth
256 = collect_args fun depth `thenUs` \ (fun', hd, fun_ty, floats, ss) ->
257 returnUs (Note note fun', hd, fun_ty, floats, ss)
259 -- non-variable fun, better let-bind it
260 collect_args fun depth
261 = newVar ty `thenUs` \ fn_id ->
262 coreSatExprFloat fun `thenUs` \ (fun_floats, fun) ->
263 returnUs (Var fn_id, (Var fn_id, depth), ty,
264 [NonRecF fn_id fun onceDem fun_floats], [])
265 where ty = exprType fun
267 ignore_note InlineCall = True
268 ignore_note InlineMe = True
269 ignore_note _other = False
270 -- we don't ignore SCCs, since they require some code generation
272 ------------------------------------------------------------------------------
273 -- Generating new binders
274 -- ---------------------------------------------------------------------------
276 newVar :: Type -> UniqSM Id
278 = getUniqueUs `thenUs` \ uniq ->
280 returnUs (mkSysLocal SLIT("sat") uniq ty)
282 cloneTyVar :: TyVar -> UniqSM TyVar
284 = getUniqueUs `thenUs` \ uniq ->
285 returnUs (setTyVarUnique tv uniq)
287 ------------------------------------------------------------------------------
288 -- Building the saturated syntax
289 -- ---------------------------------------------------------------------------
291 maybeSaturate :: Id -> CoreExpr -> Int -> Type -> UniqSM CoreExpr
292 -- mkApp deals with saturating primops and constructors
293 -- The type is the type of the entire application
294 maybeSaturate fn expr n_args ty
295 = case idFlavour fn of
296 PrimOpId (CCallOp ccall)
297 -- Sigh...make a guaranteed unique name for a dynamic ccall
298 -- Done here, not earlier, because it's a code-gen thing
299 -> getUniqueUs `thenUs` \ uniq ->
301 flavour = PrimOpId (CCallOp (setCCallUnique ccall uniq))
302 fn' = modifyIdInfo (`setFlavourInfo` flavour) fn
304 saturate fn' expr n_args ty
306 PrimOpId op -> saturate fn expr n_args ty
307 DataConId dc -> saturate fn expr n_args ty
308 other -> returnUs expr
310 saturate :: Id -> CoreExpr -> Int -> Type -> UniqSM CoreExpr
311 -- The type should be the type of (id args)
312 -- The returned expression should also have this type
313 saturate fn expr n_args ty
314 = go excess_arity expr ty
316 fn_arity = idArity fn
317 excess_arity = fn_arity - n_args
320 | n == 0 -- Saturated, so nothing to do
323 | otherwise -- An unsaturated constructor or primop; eta expand it
324 = case splitForAllTy_maybe ty of {
325 Just (tv,ty') -> go n (App expr (Type (mkTyVarTy tv))) ty' `thenUs` \ expr' ->
326 returnUs (Lam tv expr') ;
329 case splitFunTy_maybe ty of {
330 Just (arg_ty, res_ty)
331 -> newVar arg_ty `thenUs` \ arg' ->
332 go (n-1) (App expr (Var arg')) res_ty `thenUs` \ expr' ->
333 returnUs (Lam arg' expr') ;
336 case splitNewType_maybe ty of {
337 Just ty' -> go n (mkCoerce ty' ty expr) ty' `thenUs` \ expr' ->
338 returnUs (mkCoerce ty ty' expr') ;
340 Nothing -> pprTrace "Bad saturate" ((ppr fn <+> ppr expr) $$ ppr ty)
346 -----------------------------------------------------------------------------
347 -- Eliminate Lam as a non-rhs (STG doesn't have such a thing)
348 -----------------------------------------------------------------------------
351 = deLam e `thenUs` \ e ->
354 -- types will all disappear, so that's ok
355 deLam (Lam x e) | isTyVar x
356 = deLam e `thenUs` \ e ->
360 -- Try for eta reduction
364 -- Eta failed, so let-bind the lambda
366 = newVar (exprType expr) `thenUs` \ fn ->
367 returnUs (Let (NonRec fn expr) (Var fn))
370 (bndrs, body) = collectBinders expr
373 | n_remaining >= 0 &&
374 and (zipWith ok bndrs last_args) &&
375 not (any (`elemVarSet` fvs_remaining) bndrs)
376 = Just remaining_expr
378 (f, args) = collectArgs expr
379 remaining_expr = mkApps f remaining_args
380 fvs_remaining = exprFreeVars remaining_expr
381 (remaining_args, last_args) = splitAt n_remaining args
382 n_remaining = length args - length bndrs
384 ok bndr (Var arg) = bndr == arg
385 ok bndr other = False
387 eta (Let bind@(NonRec b r) body)
388 | not (any (`elemVarSet` fvs) bndrs)
390 Just e -> Just (Let bind e)
392 where fvs = exprFreeVars r
396 deLam expr = returnUs expr
398 -- ---------------------------------------------------------------------------
399 -- Precipitating the floating bindings
400 -- ---------------------------------------------------------------------------
402 mkBinds :: [FloatingBind] -> CoreExpr -> UniqSM CoreExpr
403 mkBinds [] body = returnUs body
405 = deLam body `thenUs` \ body' ->
408 go [] body = returnUs body
409 go (b:bs) body = go bs body `thenUs` \ body' ->
413 mkBind (RecF prs) body = returnUs (Let (Rec prs) body)
415 mkBind (NonRecF bndr rhs dem floats) body
417 -- We shouldn't get let or case of the form v=w
418 = if exprIsTrivial rhs
419 then pprTrace "mkBind" (ppr bndr <+> ppr rhs)
420 (mk_let bndr rhs dem floats body)
421 else mk_let bndr rhs dem floats body
423 mk_let bndr rhs dem floats body
425 | isUnLiftedType bndr_rep_ty
426 = ASSERT( not (isUnboxedTupleType bndr_rep_ty) )
427 mkBinds floats (Case rhs bndr [(DEFAULT, [], body)])
431 -- Strict let with WHNF rhs
433 Let (NonRec bndr rhs) body
435 -- Lazy let with WHNF rhs; float until we find a strict binding
437 (floats_out, floats_in) = splitFloats floats
439 mkBinds floats_in rhs `thenUs` \ new_rhs ->
441 Let (NonRec bndr new_rhs) body
443 | otherwise -- Not WHNF
445 -- Strict let with non-WHNF rhs
446 mkBinds floats (Case rhs bndr [(DEFAULT, [], body)])
448 -- Lazy let with non-WHNF rhs, so keep the floats in the RHS
449 mkBinds floats rhs `thenUs` \ new_rhs ->
450 returnUs (Let (NonRec bndr new_rhs) body)
453 bndr_rep_ty = repType (idType bndr)
454 is_strict = isStrictDem dem
455 is_whnf = exprIsValue rhs
457 splitFloats fs@(NonRecF _ _ dem _ : _)
458 | isStrictDem dem = ([], fs)
460 splitFloats (f : fs) = case splitFloats fs of
461 (fs_out, fs_in) -> (f : fs_out, fs_in)
463 splitFloats [] = ([], [])
465 -- -----------------------------------------------------------------------------
467 -- -----------------------------------------------------------------------------
470 = RhsDemand { isStrictDem :: Bool, -- True => used at least once
471 isOnceDem :: Bool -- True => used at most once
474 mkDem :: Demand -> Bool -> RhsDemand
475 mkDem strict once = RhsDemand (isStrict strict) once
477 mkDemTy :: Demand -> Type -> RhsDemand
478 mkDemTy strict ty = RhsDemand (isStrict strict) (isOnceTy ty)
480 isOnceTy :: Type -> Bool
484 opt_UsageSPOn && -- can't expect annotations if -fusagesp is off
489 once | u == usOnce = True
490 | u == usMany = False
491 | isTyVarTy u = False -- if unknown at compile-time, is Top ie usMany
493 bdrDem :: Id -> RhsDemand
494 bdrDem id = mkDem (idDemandInfo id) (isOnceTy (idType id))
496 safeDem, onceDem :: RhsDemand
497 safeDem = RhsDemand False False -- always safe to use this
498 onceDem = RhsDemand False True -- used at most once