2 -- | Handy functions for creating much Core syntax
4 -- * Constructing normal syntax
6 mkCoreApp, mkCoreApps, mkCoreConApps,
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 )
55 import TysPrim ( alphaTyVar )
56 import DataCon ( DataCon, dataConWorkId )
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 == seqId -- 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)]
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 (mkWildId arg_ty) res_ty [(DEFAULT,[],App fun (Var arg_id))]
138 arg_id = mkWildId arg_ty -- Lots of shadowing, but it doesn't matter,
139 -- because 'fun ' should not have a free wild-id
142 Note [Desugaring seq (1)] cf Trac #1031
143 ~~~~~~~~~~~~~~~~~~~~~~~~~
144 f x y = x `seq` (y `seq` (# x,y #))
146 The [CoreSyn let/app invariant] means that, other things being equal, because
147 the argument to the outer 'seq' has an unlifted type, we'll use call-by-value thus:
149 f x y = case (y `seq` (# x,y #)) of v -> x `seq` v
151 But that is bad for two reasons:
152 (a) we now evaluate y before x, and
153 (b) we can't bind v to an unboxed pair
155 Seq is very, very special! So we recognise it right here, and desugar to
156 case x of _ -> case y of _ -> (# x,y #)
158 Note [Desugaring seq (2)] cf Trac #2231
159 ~~~~~~~~~~~~~~~~~~~~~~~~~
161 let chp = case b of { True -> fst x; False -> 0 }
162 in chp `seq` ...chp...
163 Here the seq is designed to plug the space leak of retaining (snd x)
166 If we rely on the ordinary inlining of seq, we'll get
167 let chp = case b of { True -> fst x; False -> 0 }
168 case chp of _ { I# -> ...chp... }
170 But since chp is cheap, and the case is an alluring contet, we'll
171 inline chp into the case scrutinee. Now there is only one use of chp,
172 so we'll inline a second copy. Alas, we've now ruined the purpose of
173 the seq, by re-introducing the space leak:
174 case (case b of {True -> fst x; False -> 0}) of
175 I# _ -> ...case b of {True -> fst x; False -> 0}...
177 We can try to avoid doing this by ensuring that the binder-swap in the
178 case happens, so we get his at an early stage:
179 case chp of chp2 { I# -> ...chp2... }
180 But this is fragile. The real culprit is the source program. Perhaps we
181 should have said explicitly
182 let !chp2 = chp in ...chp2...
184 But that's painful. So the code here does a little hack to make seq
185 more robust: a saturated application of 'seq' is turned *directly* into
186 the case expression. So we desugar to:
187 let chp = case b of { True -> fst x; False -> 0 }
188 case chp of chp { I# -> ...chp... }
189 Notice the shadowing of the case binder! And now all is well.
191 The reason it's a hack is because if you define mySeq=seq, the hack
194 Note [Desugaring seq (3)] cf Trac #2409
195 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
196 The isLocalId ensures that we don't turn
199 case True of True { ... }
200 which stupidly tries to bind the datacon 'True'.
202 -- The functions from this point don't really do anything cleverer than
203 -- their counterparts in CoreSyn, but they are here for consistency
205 -- | Create a lambda where the given expression has a number of variables
206 -- bound over it. The leftmost binder is that bound by the outermost
207 -- lambda in the result
208 mkCoreLams :: [CoreBndr] -> CoreExpr -> CoreExpr
212 %************************************************************************
214 \subsection{Making literals}
216 %************************************************************************
219 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
220 mkIntExpr :: Integer -> CoreExpr -- Result = I# i :: Int
221 mkIntExpr i = mkConApp intDataCon [mkIntLit i]
223 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
224 mkIntExprInt :: Int -> CoreExpr -- Result = I# i :: Int
225 mkIntExprInt i = mkConApp intDataCon [mkIntLitInt i]
227 -- | Create a 'CoreExpr' which will evaluate to the a @Word@ with the given value
228 mkWordExpr :: Integer -> CoreExpr
229 mkWordExpr w = mkConApp wordDataCon [mkWordLit w]
231 -- | Create a 'CoreExpr' which will evaluate to the given @Word@
232 mkWordExprWord :: Word -> CoreExpr
233 mkWordExprWord w = mkConApp wordDataCon [mkWordLitWord w]
235 -- | Create a 'CoreExpr' which will evaluate to the given @Integer@
236 mkIntegerExpr :: MonadThings m => Integer -> m CoreExpr -- Result :: Integer
238 | inIntRange i -- Small enough, so start from an Int
239 = do integer_id <- lookupId smallIntegerName
240 return (mkSmallIntegerLit integer_id i)
242 -- Special case for integral literals with a large magnitude:
243 -- They are transformed into an expression involving only smaller
244 -- integral literals. This improves constant folding.
246 | otherwise = do -- Big, so start from a string
247 plus_id <- lookupId plusIntegerName
248 times_id <- lookupId timesIntegerName
249 integer_id <- lookupId smallIntegerName
251 lit i = mkSmallIntegerLit integer_id i
252 plus a b = Var plus_id `App` a `App` b
253 times a b = Var times_id `App` a `App` b
255 -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
256 horner :: Integer -> Integer -> CoreExpr
257 horner b i | abs q <= 1 = if r == 0 || r == i
259 else lit r `plus` lit (i-r)
260 | r == 0 = horner b q `times` lit b
261 | otherwise = lit r `plus` (horner b q `times` lit b)
263 (q,r) = i `quotRem` b
265 return (horner tARGET_MAX_INT i)
267 mkSmallIntegerLit :: Id -> Integer -> CoreExpr
268 mkSmallIntegerLit small_integer i = mkApps (Var small_integer) [mkIntLit i]
271 -- | Create a 'CoreExpr' which will evaluate to the given @Float@
272 mkFloatExpr :: Float -> CoreExpr
273 mkFloatExpr f = mkConApp floatDataCon [mkFloatLitFloat f]
275 -- | Create a 'CoreExpr' which will evaluate to the given @Double@
276 mkDoubleExpr :: Double -> CoreExpr
277 mkDoubleExpr d = mkConApp doubleDataCon [mkDoubleLitDouble d]
280 -- | Create a 'CoreExpr' which will evaluate to the given @Char@
281 mkCharExpr :: Char -> CoreExpr -- Result = C# c :: Int
282 mkCharExpr c = mkConApp charDataCon [mkCharLit c]
284 -- | Create a 'CoreExpr' which will evaluate to the given @String@
285 mkStringExpr :: MonadThings m => String -> m CoreExpr -- Result :: String
286 -- | Create a 'CoreExpr' which will evaluate to a string morally equivalent to the given @FastString@
287 mkStringExprFS :: MonadThings m => FastString -> m CoreExpr -- Result :: String
289 mkStringExpr str = mkStringExprFS (mkFastString str)
293 = return (mkNilExpr charTy)
296 = do let the_char = mkCharExpr (headFS str)
297 return (mkConsExpr charTy the_char (mkNilExpr charTy))
300 = do unpack_id <- lookupId unpackCStringName
301 return (App (Var unpack_id) (Lit (MachStr str)))
304 = do unpack_id <- lookupId unpackCStringUtf8Name
305 return (App (Var unpack_id) (Lit (MachStr str)))
309 safeChar c = ord c >= 1 && ord c <= 0x7F
312 %************************************************************************
314 \subsection{Tuple constructors}
316 %************************************************************************
323 -- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
324 -- we might concievably want to build such a massive tuple as part of the
325 -- output of a desugaring stage (notably that for list comprehensions).
327 -- We call tuples above this size \"big tuples\", and emulate them by
328 -- creating and pattern matching on >nested< tuples that are expressible
331 -- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
332 -- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
333 -- construction to be big.
335 -- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
336 -- and 'mkTupleCase' functions to do all your work with tuples you should be
337 -- fine, and not have to worry about the arity limitation at all.
339 -- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon
340 mkChunkified :: ([a] -> a) -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
341 -> [a] -- ^ Possible \"big\" list of things to construct from
342 -> a -- ^ Constructed thing made possible by recursive decomposition
343 mkChunkified small_tuple as = mk_big_tuple (chunkify as)
345 -- Each sub-list is short enough to fit in a tuple
346 mk_big_tuple [as] = small_tuple as
347 mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
349 chunkify :: [a] -> [[a]]
350 -- ^ Split a list into lists that are small enough to have a corresponding
351 -- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
352 -- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
354 | n_xs <= mAX_TUPLE_SIZE = [xs]
355 | otherwise = split xs
359 split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
363 Creating tuples and their types for Core expressions
365 @mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.
367 * If it has only one element, it is the identity function.
369 * If there are more elements than a big tuple can have, it nests
374 -- | Build a small tuple holding the specified variables
375 mkCoreVarTup :: [Id] -> CoreExpr
376 mkCoreVarTup ids = mkCoreTup (map Var ids)
378 -- | Bulid the type of a small tuple that holds the specified variables
379 mkCoreVarTupTy :: [Id] -> Type
380 mkCoreVarTupTy ids = mkCoreTupTy (map idType ids)
382 -- | Build a small tuple holding the specified expressions
383 mkCoreTup :: [CoreExpr] -> CoreExpr
384 mkCoreTup [] = Var unitDataConId
386 mkCoreTup cs = mkConApp (tupleCon Boxed (length cs))
387 (map (Type . exprType) cs ++ cs)
389 -- | Build the type of a small tuple that holds the specified type of thing
390 mkCoreTupTy :: [Type] -> Type
391 mkCoreTupTy [ty] = ty
392 mkCoreTupTy tys = mkTupleTy Boxed (length tys) tys
395 -- | Build a big tuple holding the specified variables
396 mkBigCoreVarTup :: [Id] -> CoreExpr
397 mkBigCoreVarTup ids = mkBigCoreTup (map Var ids)
399 -- | Build the type of a big tuple that holds the specified variables
400 mkBigCoreVarTupTy :: [Id] -> Type
401 mkBigCoreVarTupTy ids = mkBigCoreTupTy (map idType ids)
403 -- | Build a big tuple holding the specified expressions
404 mkBigCoreTup :: [CoreExpr] -> CoreExpr
405 mkBigCoreTup = mkChunkified mkCoreTup
407 -- | Build the type of a big tuple that holds the specified type of thing
408 mkBigCoreTupTy :: [Type] -> Type
409 mkBigCoreTupTy = mkChunkified mkCoreTupTy
412 %************************************************************************
414 \subsection{Tuple destructors}
416 %************************************************************************
419 -- | Builds a selector which scrutises the given
420 -- expression and extracts the one name from the list given.
421 -- If you want the no-shadowing rule to apply, the caller
422 -- is responsible for making sure that none of these names
425 -- If there is just one 'Id' in the tuple, then the selector is
426 -- just the identity.
428 -- If necessary, we pattern match on a \"big\" tuple.
429 mkTupleSelector :: [Id] -- ^ The 'Id's to pattern match the tuple against
430 -> Id -- ^ The 'Id' to select
431 -> Id -- ^ A variable of the same type as the scrutinee
432 -> CoreExpr -- ^ Scrutinee
433 -> CoreExpr -- ^ Selector expression
435 -- mkTupleSelector [a,b,c,d] b v e
437 -- (p,q) -> case p of p {
439 -- We use 'tpl' vars for the p,q, since shadowing does not matter.
441 -- In fact, it's more convenient to generate it innermost first, getting
446 mkTupleSelector vars the_var scrut_var scrut
447 = mk_tup_sel (chunkify vars) the_var
449 mk_tup_sel [vars] the_var = mkSmallTupleSelector vars the_var scrut_var scrut
450 mk_tup_sel vars_s the_var = mkSmallTupleSelector group the_var tpl_v $
451 mk_tup_sel (chunkify tpl_vs) tpl_v
453 tpl_tys = [mkCoreTupTy (map idType gp) | gp <- vars_s]
454 tpl_vs = mkTemplateLocals tpl_tys
455 [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
460 -- | Like 'mkTupleSelector' but for tuples that are guaranteed
461 -- never to be \"big\".
463 -- > mkSmallTupleSelector [x] x v e = [| e |]
464 -- > mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]
465 mkSmallTupleSelector :: [Id] -- The tuple args
466 -> Id -- The selected one
467 -> Id -- A variable of the same type as the scrutinee
468 -> CoreExpr -- Scrutinee
470 mkSmallTupleSelector [var] should_be_the_same_var _ scrut
471 = ASSERT(var == should_be_the_same_var)
473 mkSmallTupleSelector vars the_var scrut_var scrut
474 = ASSERT( notNull vars )
475 Case scrut scrut_var (idType the_var)
476 [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
480 -- | A generalization of 'mkTupleSelector', allowing the body
481 -- of the case to be an arbitrary expression.
483 -- To avoid shadowing, we use uniques to invent new variables.
485 -- If necessary we pattern match on a \"big\" tuple.
486 mkTupleCase :: UniqSupply -- ^ For inventing names of intermediate variables
487 -> [Id] -- ^ The tuple identifiers to pattern match on
488 -> CoreExpr -- ^ Body of the case
489 -> Id -- ^ A variable of the same type as the scrutinee
490 -> CoreExpr -- ^ Scrutinee
492 -- ToDo: eliminate cases where none of the variables are needed.
494 -- mkTupleCase uniqs [a,b,c,d] body v e
495 -- = case e of v { (p,q) ->
496 -- case p of p { (a,b) ->
497 -- case q of q { (c,d) ->
499 mkTupleCase uniqs vars body scrut_var scrut
500 = mk_tuple_case uniqs (chunkify vars) body
502 -- This is the case where don't need any nesting
503 mk_tuple_case _ [vars] body
504 = mkSmallTupleCase vars body scrut_var scrut
506 -- This is the case where we must make nest tuples at least once
507 mk_tuple_case us vars_s body
508 = let (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
509 in mk_tuple_case us' (chunkify vars') body'
511 one_tuple_case chunk_vars (us, vs, body)
512 = let (us1, us2) = splitUniqSupply us
513 scrut_var = mkSysLocal (fsLit "ds") (uniqFromSupply us1)
514 (mkCoreTupTy (map idType chunk_vars))
515 body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
516 in (us2, scrut_var:vs, body')
520 -- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
521 -- not to need nesting.
523 :: [Id] -- ^ The tuple args
524 -> CoreExpr -- ^ Body of the case
525 -> Id -- ^ A variable of the same type as the scrutinee
526 -> CoreExpr -- ^ Scrutinee
529 mkSmallTupleCase [var] body _scrut_var scrut
530 = bindNonRec var scrut body
531 mkSmallTupleCase vars body scrut_var scrut
532 -- One branch no refinement?
533 = Case scrut scrut_var (exprType body) [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
536 %************************************************************************
538 \subsection{Common list manipulation expressions}
540 %************************************************************************
542 Call the constructor Ids when building explicit lists, so that they
543 interact well with rules.
546 -- | Makes a list @[]@ for lists of the specified type
547 mkNilExpr :: Type -> CoreExpr
548 mkNilExpr ty = mkConApp nilDataCon [Type ty]
550 -- | Makes a list @(:)@ for lists of the specified type
551 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
552 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
554 -- | Make a list containing the given expressions, where the list has the given type
555 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
556 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
558 -- | Make a fully applied 'foldr' expression
559 mkFoldrExpr :: MonadThings m
560 => Type -- ^ Element type of the list
561 -> Type -- ^ Fold result type
562 -> CoreExpr -- ^ "Cons" function expression for the fold
563 -> CoreExpr -- ^ "Nil" expression for the fold
564 -> CoreExpr -- ^ List expression being folded acress
566 mkFoldrExpr elt_ty result_ty c n list = do
567 foldr_id <- lookupId foldrName
568 return (Var foldr_id `App` Type elt_ty
574 -- | Make a 'build' expression applied to a locally-bound worker function
575 mkBuildExpr :: (MonadThings m, MonadUnique m)
576 => Type -- ^ Type of list elements to be built
577 -> ((Id, Type) -> (Id, Type) -> m CoreExpr) -- ^ Function that, given information about the 'Id's
578 -- of the binders for the build worker function, returns
579 -- the body of that worker
581 mkBuildExpr elt_ty mk_build_inside = do
582 [n_tyvar] <- newTyVars [alphaTyVar]
583 let n_ty = mkTyVarTy n_tyvar
584 c_ty = mkFunTys [elt_ty, n_ty] n_ty
585 [c, n] <- sequence [mkSysLocalM (fsLit "c") c_ty, mkSysLocalM (fsLit "n") n_ty]
587 build_inside <- mk_build_inside (c, c_ty) (n, n_ty)
589 build_id <- lookupId buildName
590 return $ Var build_id `App` Type elt_ty `App` mkLams [n_tyvar, c, n] build_inside
592 newTyVars tyvar_tmpls = do
594 return (zipWith setTyVarUnique tyvar_tmpls uniqs)