2 -- | Handy functions for creating much Core syntax
4 -- * Constructing normal syntax
6 mkCoreApp, mkCoreApps, mkCoreConApps,
7 mkCoreLams, mkWildCase, mkIfThenElse,
9 -- * Constructing boxed literals
10 mkWordExpr, mkWordExprWord,
11 mkIntExpr, mkIntExprInt,
13 mkFloatExpr, mkDoubleExpr,
14 mkCharExpr, mkStringExpr, mkStringExprFS,
16 -- * Constructing general big tuples
20 -- * Constructing small tuples
21 mkCoreVarTup, mkCoreVarTupTy,
22 mkCoreTup, mkCoreTupTy,
24 -- * Constructing big tuples
25 mkBigCoreVarTup, mkBigCoreVarTupTy,
26 mkBigCoreTup, mkBigCoreTupTy,
28 -- * Deconstructing small tuples
29 mkSmallTupleSelector, mkSmallTupleCase,
31 -- * Deconstructing big tuples
32 mkTupleSelector, mkTupleCase,
34 -- * Constructing list expressions
35 mkNilExpr, mkConsExpr, mkListExpr,
36 mkFoldrExpr, mkBuildExpr
39 #include "HsVersions.h"
42 import Var ( setTyVarUnique )
45 import CoreUtils ( exprType, needsCaseBinding, bindNonRec )
54 import TysPrim ( alphaTyVar )
55 import DataCon ( DataCon, dataConWorkId )
59 import Unique ( mkBuiltinUnique )
61 import Util ( notNull, zipEqual )
65 import Data.Char ( ord )
68 infixl 4 `mkCoreApp`, `mkCoreApps`
71 %************************************************************************
73 \subsection{Basic CoreSyn construction}
75 %************************************************************************
78 -- | Bind a binding group over an expression, using a @let@ or @case@ as
79 -- appropriate (see "CoreSyn#let_app_invariant")
80 mkCoreLet :: CoreBind -> CoreExpr -> CoreExpr
81 mkCoreLet (NonRec bndr rhs) body -- See Note [CoreSyn let/app invariant]
82 | needsCaseBinding (idType bndr) rhs
83 = Case rhs bndr (exprType body) [(DEFAULT,[],body)]
87 -- | Bind a list of binding groups over an expression. The leftmost binding
88 -- group becomes the outermost group in the resulting expression
89 mkCoreLets :: [CoreBind] -> CoreExpr -> CoreExpr
90 mkCoreLets binds body = foldr mkCoreLet body binds
92 -- | Construct an expression which represents the application of one expression
94 mkCoreApp :: CoreExpr -> CoreExpr -> CoreExpr
95 -- Check the invariant that the arg of an App is ok-for-speculation if unlifted
96 -- See CoreSyn Note [CoreSyn let/app invariant]
97 mkCoreApp fun (Type ty) = App fun (Type ty)
98 mkCoreApp fun arg = mk_val_app fun arg arg_ty res_ty
100 (arg_ty, res_ty) = splitFunTy (exprType fun)
102 -- | Construct an expression which represents the application of a number of
103 -- expressions to another. The leftmost expression in the list is applied first
104 mkCoreApps :: CoreExpr -> [CoreExpr] -> CoreExpr
105 -- Slightly more efficient version of (foldl mkCoreApp)
107 = go fun (exprType fun) args
110 go fun fun_ty (Type ty : args) = go (App fun (Type ty)) (applyTy fun_ty ty) args
111 go fun fun_ty (arg : args) = go (mk_val_app fun arg arg_ty res_ty) res_ty args
113 (arg_ty, res_ty) = splitFunTy fun_ty
115 -- | Construct an expression which represents the application of a number of
116 -- expressions to that of a data constructor expression. The leftmost expression
117 -- in the list is applied first
118 mkCoreConApps :: DataCon -> [CoreExpr] -> CoreExpr
119 mkCoreConApps con args = mkCoreApps (Var (dataConWorkId con)) args
122 mk_val_app :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
123 mk_val_app (Var f `App` Type ty1 `App` Type _ `App` arg1) arg2 _ res_ty
124 | f `hasKey` seqIdKey -- Note [Desugaring seq (1), (2)]
125 = Case arg1 case_bndr res_ty [(DEFAULT,[],arg2)]
127 case_bndr = case arg1 of
128 Var v1 | isLocalId v1 -> v1 -- Note [Desugaring seq (2) and (3)]
129 _ -> mkWildBinder ty1
131 mk_val_app fun arg arg_ty _ -- See Note [CoreSyn let/app invariant]
132 | not (needsCaseBinding arg_ty arg)
133 = App fun arg -- The vastly common case
135 mk_val_app fun arg arg_ty res_ty
136 = Case arg arg_id res_ty [(DEFAULT,[],App fun (Var arg_id))]
138 arg_id = mkWildBinder arg_ty
139 -- Lots of shadowing, but it doesn't matter,
140 -- because 'fun ' should not have a free wild-id
142 -- This is Dangerous. But this is the only place we play this
143 -- game, mk_val_app returns an expression that does not have
144 -- have a free wild-id. So the only thing that can go wrong
145 -- is if you take apart this case expression, and pass a
146 -- fragmet of it as the fun part of a 'mk_val_app'.
149 -- | Make a /wildcard binder/. This is typically used when you need a binder
150 -- that you expect to use only at a *binding* site. Do not use it at
151 -- occurrence sites because it has a single, fixed unique, and it's very
152 -- easy to get into difficulties with shadowing. That's why it is used so little.
153 mkWildBinder :: Type -> Id
154 mkWildBinder ty = mkSysLocal (fsLit "wild") (mkBuiltinUnique 1) ty
156 mkWildCase :: CoreExpr -> Type -> Type -> [CoreAlt] -> CoreExpr
157 -- Make a case expression whose case binder is unused
158 -- The alts should not have any occurrences of WildId
159 mkWildCase scrut scrut_ty res_ty alts
160 = Case scrut (mkWildBinder scrut_ty) res_ty alts
162 mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
163 mkIfThenElse guard then_expr else_expr
164 -- Not going to be refining, so okay to take the type of the "then" clause
165 = mkWildCase guard boolTy (exprType then_expr)
166 [ (DataAlt falseDataCon, [], else_expr), -- Increasing order of tag!
167 (DataAlt trueDataCon, [], then_expr) ]
170 Note [Desugaring seq (1)] cf Trac #1031
171 ~~~~~~~~~~~~~~~~~~~~~~~~~
172 f x y = x `seq` (y `seq` (# x,y #))
174 The [CoreSyn let/app invariant] means that, other things being equal, because
175 the argument to the outer 'seq' has an unlifted type, we'll use call-by-value thus:
177 f x y = case (y `seq` (# x,y #)) of v -> x `seq` v
179 But that is bad for two reasons:
180 (a) we now evaluate y before x, and
181 (b) we can't bind v to an unboxed pair
183 Seq is very, very special! So we recognise it right here, and desugar to
184 case x of _ -> case y of _ -> (# x,y #)
186 Note [Desugaring seq (2)] cf Trac #2231
187 ~~~~~~~~~~~~~~~~~~~~~~~~~
189 let chp = case b of { True -> fst x; False -> 0 }
190 in chp `seq` ...chp...
191 Here the seq is designed to plug the space leak of retaining (snd x)
194 If we rely on the ordinary inlining of seq, we'll get
195 let chp = case b of { True -> fst x; False -> 0 }
196 case chp of _ { I# -> ...chp... }
198 But since chp is cheap, and the case is an alluring contet, we'll
199 inline chp into the case scrutinee. Now there is only one use of chp,
200 so we'll inline a second copy. Alas, we've now ruined the purpose of
201 the seq, by re-introducing the space leak:
202 case (case b of {True -> fst x; False -> 0}) of
203 I# _ -> ...case b of {True -> fst x; False -> 0}...
205 We can try to avoid doing this by ensuring that the binder-swap in the
206 case happens, so we get his at an early stage:
207 case chp of chp2 { I# -> ...chp2... }
208 But this is fragile. The real culprit is the source program. Perhaps we
209 should have said explicitly
210 let !chp2 = chp in ...chp2...
212 But that's painful. So the code here does a little hack to make seq
213 more robust: a saturated application of 'seq' is turned *directly* into
214 the case expression. So we desugar to:
215 let chp = case b of { True -> fst x; False -> 0 }
216 case chp of chp { I# -> ...chp... }
217 Notice the shadowing of the case binder! And now all is well.
219 The reason it's a hack is because if you define mySeq=seq, the hack
222 Note [Desugaring seq (3)] cf Trac #2409
223 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
224 The isLocalId ensures that we don't turn
227 case True of True { ... }
228 which stupidly tries to bind the datacon 'True'.
230 -- The functions from this point don't really do anything cleverer than
231 -- their counterparts in CoreSyn, but they are here for consistency
233 -- | Create a lambda where the given expression has a number of variables
234 -- bound over it. The leftmost binder is that bound by the outermost
235 -- lambda in the result
236 mkCoreLams :: [CoreBndr] -> CoreExpr -> CoreExpr
240 %************************************************************************
242 \subsection{Making literals}
244 %************************************************************************
247 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
248 mkIntExpr :: Integer -> CoreExpr -- Result = I# i :: Int
249 mkIntExpr i = mkConApp intDataCon [mkIntLit i]
251 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
252 mkIntExprInt :: Int -> CoreExpr -- Result = I# i :: Int
253 mkIntExprInt i = mkConApp intDataCon [mkIntLitInt i]
255 -- | Create a 'CoreExpr' which will evaluate to the a @Word@ with the given value
256 mkWordExpr :: Integer -> CoreExpr
257 mkWordExpr w = mkConApp wordDataCon [mkWordLit w]
259 -- | Create a 'CoreExpr' which will evaluate to the given @Word@
260 mkWordExprWord :: Word -> CoreExpr
261 mkWordExprWord w = mkConApp wordDataCon [mkWordLitWord w]
263 -- | Create a 'CoreExpr' which will evaluate to the given @Integer@
264 mkIntegerExpr :: MonadThings m => Integer -> m CoreExpr -- Result :: Integer
266 | inIntRange i -- Small enough, so start from an Int
267 = do integer_id <- lookupId smallIntegerName
268 return (mkSmallIntegerLit integer_id i)
270 -- Special case for integral literals with a large magnitude:
271 -- They are transformed into an expression involving only smaller
272 -- integral literals. This improves constant folding.
274 | otherwise = do -- Big, so start from a string
275 plus_id <- lookupId plusIntegerName
276 times_id <- lookupId timesIntegerName
277 integer_id <- lookupId smallIntegerName
279 lit i = mkSmallIntegerLit integer_id i
280 plus a b = Var plus_id `App` a `App` b
281 times a b = Var times_id `App` a `App` b
283 -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
284 horner :: Integer -> Integer -> CoreExpr
285 horner b i | abs q <= 1 = if r == 0 || r == i
287 else lit r `plus` lit (i-r)
288 | r == 0 = horner b q `times` lit b
289 | otherwise = lit r `plus` (horner b q `times` lit b)
291 (q,r) = i `quotRem` b
293 return (horner tARGET_MAX_INT i)
295 mkSmallIntegerLit :: Id -> Integer -> CoreExpr
296 mkSmallIntegerLit small_integer i = mkApps (Var small_integer) [mkIntLit i]
299 -- | Create a 'CoreExpr' which will evaluate to the given @Float@
300 mkFloatExpr :: Float -> CoreExpr
301 mkFloatExpr f = mkConApp floatDataCon [mkFloatLitFloat f]
303 -- | Create a 'CoreExpr' which will evaluate to the given @Double@
304 mkDoubleExpr :: Double -> CoreExpr
305 mkDoubleExpr d = mkConApp doubleDataCon [mkDoubleLitDouble d]
308 -- | Create a 'CoreExpr' which will evaluate to the given @Char@
309 mkCharExpr :: Char -> CoreExpr -- Result = C# c :: Int
310 mkCharExpr c = mkConApp charDataCon [mkCharLit c]
312 -- | Create a 'CoreExpr' which will evaluate to the given @String@
313 mkStringExpr :: MonadThings m => String -> m CoreExpr -- Result :: String
314 -- | Create a 'CoreExpr' which will evaluate to a string morally equivalent to the given @FastString@
315 mkStringExprFS :: MonadThings m => FastString -> m CoreExpr -- Result :: String
317 mkStringExpr str = mkStringExprFS (mkFastString str)
321 = return (mkNilExpr charTy)
324 = do let the_char = mkCharExpr (headFS str)
325 return (mkConsExpr charTy the_char (mkNilExpr charTy))
328 = do unpack_id <- lookupId unpackCStringName
329 return (App (Var unpack_id) (Lit (MachStr str)))
332 = do unpack_id <- lookupId unpackCStringUtf8Name
333 return (App (Var unpack_id) (Lit (MachStr str)))
337 safeChar c = ord c >= 1 && ord c <= 0x7F
340 %************************************************************************
342 \subsection{Tuple constructors}
344 %************************************************************************
351 -- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
352 -- we might concievably want to build such a massive tuple as part of the
353 -- output of a desugaring stage (notably that for list comprehensions).
355 -- We call tuples above this size \"big tuples\", and emulate them by
356 -- creating and pattern matching on >nested< tuples that are expressible
359 -- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
360 -- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
361 -- construction to be big.
363 -- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
364 -- and 'mkTupleCase' functions to do all your work with tuples you should be
365 -- fine, and not have to worry about the arity limitation at all.
367 -- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon
368 mkChunkified :: ([a] -> a) -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
369 -> [a] -- ^ Possible \"big\" list of things to construct from
370 -> a -- ^ Constructed thing made possible by recursive decomposition
371 mkChunkified small_tuple as = mk_big_tuple (chunkify as)
373 -- Each sub-list is short enough to fit in a tuple
374 mk_big_tuple [as] = small_tuple as
375 mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
377 chunkify :: [a] -> [[a]]
378 -- ^ Split a list into lists that are small enough to have a corresponding
379 -- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
380 -- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
382 | n_xs <= mAX_TUPLE_SIZE = [xs]
383 | otherwise = split xs
387 split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
391 Creating tuples and their types for Core expressions
393 @mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.
395 * If it has only one element, it is the identity function.
397 * If there are more elements than a big tuple can have, it nests
402 -- | Build a small tuple holding the specified variables
403 mkCoreVarTup :: [Id] -> CoreExpr
404 mkCoreVarTup ids = mkCoreTup (map Var ids)
406 -- | Bulid the type of a small tuple that holds the specified variables
407 mkCoreVarTupTy :: [Id] -> Type
408 mkCoreVarTupTy ids = mkCoreTupTy (map idType ids)
410 -- | Build a small tuple holding the specified expressions
411 mkCoreTup :: [CoreExpr] -> CoreExpr
412 mkCoreTup [] = Var unitDataConId
414 mkCoreTup cs = mkConApp (tupleCon Boxed (length cs))
415 (map (Type . exprType) cs ++ cs)
417 -- | Build the type of a small tuple that holds the specified type of thing
418 mkCoreTupTy :: [Type] -> Type
419 mkCoreTupTy [ty] = ty
420 mkCoreTupTy tys = mkTupleTy Boxed (length tys) tys
423 -- | Build a big tuple holding the specified variables
424 mkBigCoreVarTup :: [Id] -> CoreExpr
425 mkBigCoreVarTup ids = mkBigCoreTup (map Var ids)
427 -- | Build the type of a big tuple that holds the specified variables
428 mkBigCoreVarTupTy :: [Id] -> Type
429 mkBigCoreVarTupTy ids = mkBigCoreTupTy (map idType ids)
431 -- | Build a big tuple holding the specified expressions
432 mkBigCoreTup :: [CoreExpr] -> CoreExpr
433 mkBigCoreTup = mkChunkified mkCoreTup
435 -- | Build the type of a big tuple that holds the specified type of thing
436 mkBigCoreTupTy :: [Type] -> Type
437 mkBigCoreTupTy = mkChunkified mkCoreTupTy
440 %************************************************************************
442 \subsection{Tuple destructors}
444 %************************************************************************
447 -- | Builds a selector which scrutises the given
448 -- expression and extracts the one name from the list given.
449 -- If you want the no-shadowing rule to apply, the caller
450 -- is responsible for making sure that none of these names
453 -- If there is just one 'Id' in the tuple, then the selector is
454 -- just the identity.
456 -- If necessary, we pattern match on a \"big\" tuple.
457 mkTupleSelector :: [Id] -- ^ The 'Id's to pattern match the tuple against
458 -> Id -- ^ The 'Id' to select
459 -> Id -- ^ A variable of the same type as the scrutinee
460 -> CoreExpr -- ^ Scrutinee
461 -> CoreExpr -- ^ Selector expression
463 -- mkTupleSelector [a,b,c,d] b v e
465 -- (p,q) -> case p of p {
467 -- We use 'tpl' vars for the p,q, since shadowing does not matter.
469 -- In fact, it's more convenient to generate it innermost first, getting
474 mkTupleSelector vars the_var scrut_var scrut
475 = mk_tup_sel (chunkify vars) the_var
477 mk_tup_sel [vars] the_var = mkSmallTupleSelector vars the_var scrut_var scrut
478 mk_tup_sel vars_s the_var = mkSmallTupleSelector group the_var tpl_v $
479 mk_tup_sel (chunkify tpl_vs) tpl_v
481 tpl_tys = [mkCoreTupTy (map idType gp) | gp <- vars_s]
482 tpl_vs = mkTemplateLocals tpl_tys
483 [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
488 -- | Like 'mkTupleSelector' but for tuples that are guaranteed
489 -- never to be \"big\".
491 -- > mkSmallTupleSelector [x] x v e = [| e |]
492 -- > mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]
493 mkSmallTupleSelector :: [Id] -- The tuple args
494 -> Id -- The selected one
495 -> Id -- A variable of the same type as the scrutinee
496 -> CoreExpr -- Scrutinee
498 mkSmallTupleSelector [var] should_be_the_same_var _ scrut
499 = ASSERT(var == should_be_the_same_var)
501 mkSmallTupleSelector vars the_var scrut_var scrut
502 = ASSERT( notNull vars )
503 Case scrut scrut_var (idType the_var)
504 [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
508 -- | A generalization of 'mkTupleSelector', allowing the body
509 -- of the case to be an arbitrary expression.
511 -- To avoid shadowing, we use uniques to invent new variables.
513 -- If necessary we pattern match on a \"big\" tuple.
514 mkTupleCase :: UniqSupply -- ^ For inventing names of intermediate variables
515 -> [Id] -- ^ The tuple identifiers to pattern match on
516 -> CoreExpr -- ^ Body of the case
517 -> Id -- ^ A variable of the same type as the scrutinee
518 -> CoreExpr -- ^ Scrutinee
520 -- ToDo: eliminate cases where none of the variables are needed.
522 -- mkTupleCase uniqs [a,b,c,d] body v e
523 -- = case e of v { (p,q) ->
524 -- case p of p { (a,b) ->
525 -- case q of q { (c,d) ->
527 mkTupleCase uniqs vars body scrut_var scrut
528 = mk_tuple_case uniqs (chunkify vars) body
530 -- This is the case where don't need any nesting
531 mk_tuple_case _ [vars] body
532 = mkSmallTupleCase vars body scrut_var scrut
534 -- This is the case where we must make nest tuples at least once
535 mk_tuple_case us vars_s body
536 = let (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
537 in mk_tuple_case us' (chunkify vars') body'
539 one_tuple_case chunk_vars (us, vs, body)
540 = let (us1, us2) = splitUniqSupply us
541 scrut_var = mkSysLocal (fsLit "ds") (uniqFromSupply us1)
542 (mkCoreTupTy (map idType chunk_vars))
543 body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
544 in (us2, scrut_var:vs, body')
548 -- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
549 -- not to need nesting.
551 :: [Id] -- ^ The tuple args
552 -> CoreExpr -- ^ Body of the case
553 -> Id -- ^ A variable of the same type as the scrutinee
554 -> CoreExpr -- ^ Scrutinee
557 mkSmallTupleCase [var] body _scrut_var scrut
558 = bindNonRec var scrut body
559 mkSmallTupleCase vars body scrut_var scrut
560 -- One branch no refinement?
561 = Case scrut scrut_var (exprType body) [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
564 %************************************************************************
566 \subsection{Common list manipulation expressions}
568 %************************************************************************
570 Call the constructor Ids when building explicit lists, so that they
571 interact well with rules.
574 -- | Makes a list @[]@ for lists of the specified type
575 mkNilExpr :: Type -> CoreExpr
576 mkNilExpr ty = mkConApp nilDataCon [Type ty]
578 -- | Makes a list @(:)@ for lists of the specified type
579 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
580 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
582 -- | Make a list containing the given expressions, where the list has the given type
583 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
584 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
586 -- | Make a fully applied 'foldr' expression
587 mkFoldrExpr :: MonadThings m
588 => Type -- ^ Element type of the list
589 -> Type -- ^ Fold result type
590 -> CoreExpr -- ^ "Cons" function expression for the fold
591 -> CoreExpr -- ^ "Nil" expression for the fold
592 -> CoreExpr -- ^ List expression being folded acress
594 mkFoldrExpr elt_ty result_ty c n list = do
595 foldr_id <- lookupId foldrName
596 return (Var foldr_id `App` Type elt_ty
602 -- | Make a 'build' expression applied to a locally-bound worker function
603 mkBuildExpr :: (MonadThings m, MonadUnique m)
604 => Type -- ^ Type of list elements to be built
605 -> ((Id, Type) -> (Id, Type) -> m CoreExpr) -- ^ Function that, given information about the 'Id's
606 -- of the binders for the build worker function, returns
607 -- the body of that worker
609 mkBuildExpr elt_ty mk_build_inside = do
610 [n_tyvar] <- newTyVars [alphaTyVar]
611 let n_ty = mkTyVarTy n_tyvar
612 c_ty = mkFunTys [elt_ty, n_ty] n_ty
613 [c, n] <- sequence [mkSysLocalM (fsLit "c") c_ty, mkSysLocalM (fsLit "n") n_ty]
615 build_inside <- mk_build_inside (c, c_ty) (n, n_ty)
617 build_id <- lookupId buildName
618 return $ Var build_id `App` Type elt_ty `App` mkLams [n_tyvar, c, n] build_inside
620 newTyVars tyvar_tmpls = do
622 return (zipWith setTyVarUnique tyvar_tmpls uniqs)