2 % (c) The University of Glasgow 2002-2006
5 ByteCodeGen: Generate bytecode from Core
8 module ByteCodeGen ( UnlinkedBCO, byteCodeGen, coreExprToBCOs ) where
10 #include "HsVersions.h"
50 import Data.List ( intersperse, sortBy, zip4, zip6, partition )
51 import Foreign ( Ptr, castPtr, mallocBytes, pokeByteOff, Word8,
52 withForeignPtr, castFunPtrToPtr )
53 import Foreign.C ( CInt )
54 import Control.Exception ( throwDyn )
56 import GHC.Exts ( Int(..), ByteArray# )
58 import Control.Monad ( when )
59 import Data.Char ( ord, chr )
61 -- -----------------------------------------------------------------------------
62 -- Generating byte code for a complete module
64 byteCodeGen :: DynFlags
67 -> IO CompiledByteCode
68 byteCodeGen dflags binds tycs
69 = do showPass dflags "ByteCodeGen"
71 let flatBinds = [ (bndr, freeVars rhs)
72 | (bndr, rhs) <- flattenBinds binds]
74 (BcM_State final_ctr mallocd, proto_bcos)
75 <- runBc (mapM schemeTopBind flatBinds)
77 when (notNull mallocd)
78 (panic "ByteCodeGen.byteCodeGen: missing final emitBc?")
80 dumpIfSet_dyn dflags Opt_D_dump_BCOs
81 "Proto-BCOs" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
83 assembleBCOs proto_bcos tycs
85 -- -----------------------------------------------------------------------------
86 -- Generating byte code for an expression
88 -- Returns: (the root BCO for this expression,
89 -- a list of auxilary BCOs resulting from compiling closures)
90 coreExprToBCOs :: DynFlags
93 coreExprToBCOs dflags expr
94 = do showPass dflags "ByteCodeGen"
96 -- create a totally bogus name for the top-level BCO; this
97 -- should be harmless, since it's never used for anything
98 let invented_name = mkSystemVarName (mkPseudoUniqueE 0) FSLIT("ExprTopLevel")
99 invented_id = Id.mkLocalId invented_name (panic "invented_id's type")
101 (BcM_State final_ctr mallocd, proto_bco)
102 <- runBc (schemeTopBind (invented_id, freeVars expr))
104 when (notNull mallocd)
105 (panic "ByteCodeGen.coreExprToBCOs: missing final emitBc?")
107 dumpIfSet_dyn dflags Opt_D_dump_BCOs "Proto-BCOs" (ppr proto_bco)
109 assembleBCO proto_bco
112 -- -----------------------------------------------------------------------------
113 -- Compilation schema for the bytecode generator
115 type BCInstrList = OrdList BCInstr
117 type Sequel = Int -- back off to this depth before ENTER
119 -- Maps Ids to the offset from the stack _base_ so we don't have
120 -- to mess with it after each push/pop.
121 type BCEnv = FiniteMap Id Int -- To find vars on the stack
123 ppBCEnv :: BCEnv -> SDoc
126 $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
129 pp_one (var, offset) = int offset <> colon <+> ppr var <+> ppr (idCgRep var)
130 cmp_snd x y = compare (snd x) (snd y)
132 -- Create a BCO and do a spot of peephole optimisation on the insns
137 -> Either [AnnAlt Id VarSet] (AnnExpr Id VarSet)
141 -> Bool -- True <=> is a return point, rather than a function
144 mkProtoBCO nm instrs_ordlist origin arity bitmap_size bitmap
145 is_ret mallocd_blocks
148 protoBCOInstrs = maybe_with_stack_check,
149 protoBCOBitmap = bitmap,
150 protoBCOBitmapSize = bitmap_size,
151 protoBCOArity = arity,
152 protoBCOExpr = origin,
153 protoBCOPtrs = mallocd_blocks
156 -- Overestimate the stack usage (in words) of this BCO,
157 -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
158 -- stack check. (The interpreter always does a stack check
159 -- for iNTERP_STACK_CHECK_THRESH words at the start of each
160 -- BCO anyway, so we only need to add an explicit on in the
161 -- (hopefully rare) cases when the (overestimated) stack use
162 -- exceeds iNTERP_STACK_CHECK_THRESH.
163 maybe_with_stack_check
165 -- don't do stack checks at return points;
166 -- everything is aggregated up to the top BCO
167 -- (which must be a function)
168 | stack_overest >= iNTERP_STACK_CHECK_THRESH
169 = STKCHECK stack_overest : peep_d
171 = peep_d -- the supposedly common case
173 -- We assume that this sum doesn't wrap
174 stack_overest = sum (map bciStackUse peep_d)
176 -- Merge local pushes
177 peep_d = peep (fromOL instrs_ordlist)
179 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
180 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
181 peep (PUSH_L off1 : PUSH_L off2 : rest)
182 = PUSH_LL off1 (off2-1) : peep rest
188 argBits :: [CgRep] -> [Bool]
191 | isFollowableArg rep = False : argBits args
192 | otherwise = take (cgRepSizeW rep) (repeat True) ++ argBits args
194 -- -----------------------------------------------------------------------------
197 -- Compile code for the right-hand side of a top-level binding
199 schemeTopBind :: (Id, AnnExpr Id VarSet) -> BcM (ProtoBCO Name)
202 schemeTopBind (id, rhs)
203 | Just data_con <- isDataConWorkId_maybe id,
204 isNullaryRepDataCon data_con
205 = -- Special case for the worker of a nullary data con.
206 -- It'll look like this: Nil = /\a -> Nil a
207 -- If we feed it into schemeR, we'll get
209 -- because mkConAppCode treats nullary constructor applications
210 -- by just re-using the single top-level definition. So
211 -- for the worker itself, we must allocate it directly.
212 emitBc (mkProtoBCO (getName id) (toOL [PACK data_con 0, ENTER])
213 (Right rhs) 0 0 [{-no bitmap-}] False{-not alts-})
216 = schemeR [{- No free variables -}] (id, rhs)
218 -- -----------------------------------------------------------------------------
221 -- Compile code for a right-hand side, to give a BCO that,
222 -- when executed with the free variables and arguments on top of the stack,
223 -- will return with a pointer to the result on top of the stack, after
224 -- removing the free variables and arguments.
226 -- Park the resulting BCO in the monad. Also requires the
227 -- variable to which this value was bound, so as to give the
228 -- resulting BCO a name.
230 schemeR :: [Id] -- Free vars of the RHS, ordered as they
231 -- will appear in the thunk. Empty for
232 -- top-level things, which have no free vars.
233 -> (Id, AnnExpr Id VarSet)
234 -> BcM (ProtoBCO Name)
235 schemeR fvs (nm, rhs)
239 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
240 $$ pprCoreExpr (deAnnotate rhs)
246 = schemeR_wrk fvs nm rhs (collect [] rhs)
248 collect xs (_, AnnNote note e) = collect xs e
249 collect xs (_, AnnCast e _) = collect xs e
250 collect xs (_, AnnLam x e) = collect (if isTyVar x then xs else (x:xs)) e
251 collect xs (_, not_lambda) = (reverse xs, not_lambda)
253 schemeR_wrk fvs nm original_body (args, body)
255 all_args = reverse args ++ fvs
256 arity = length all_args
257 -- all_args are the args in reverse order. We're compiling a function
258 -- \fv1..fvn x1..xn -> e
259 -- i.e. the fvs come first
261 szsw_args = map idSizeW all_args
262 szw_args = sum szsw_args
263 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
265 -- make the arg bitmap
266 bits = argBits (reverse (map idCgRep all_args))
267 bitmap_size = length bits
268 bitmap = mkBitmap bits
270 body_code <- schemeE szw_args 0 p_init body
271 emitBc (mkProtoBCO (getName nm) body_code (Right original_body)
272 arity bitmap_size bitmap False{-not alts-})
275 fvsToEnv :: BCEnv -> VarSet -> [Id]
276 -- Takes the free variables of a right-hand side, and
277 -- delivers an ordered list of the local variables that will
278 -- be captured in the thunk for the RHS
279 -- The BCEnv argument tells which variables are in the local
280 -- environment: these are the ones that should be captured
282 -- The code that constructs the thunk, and the code that executes
283 -- it, have to agree about this layout
284 fvsToEnv p fvs = [v | v <- varSetElems fvs,
285 isId v, -- Could be a type variable
288 -- -----------------------------------------------------------------------------
291 -- Compile code to apply the given expression to the remaining args
292 -- on the stack, returning a HNF.
293 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList
295 -- Delegate tail-calls to schemeT.
296 schemeE d s p e@(AnnApp f a)
299 schemeE d s p e@(AnnVar v)
300 | not (isUnLiftedType v_type)
301 = -- Lifted-type thing; push it in the normal way
305 = do -- Returning an unlifted value.
306 -- Heave it on the stack, SLIDE, and RETURN.
307 (push, szw) <- pushAtom d p (AnnVar v)
308 return (push -- value onto stack
309 `appOL` mkSLIDE szw (d-s) -- clear to sequel
310 `snocOL` RETURN_UBX v_rep) -- go
313 v_rep = typeCgRep v_type
315 schemeE d s p (AnnLit literal)
316 = do (push, szw) <- pushAtom d p (AnnLit literal)
317 let l_rep = typeCgRep (literalType literal)
318 return (push -- value onto stack
319 `appOL` mkSLIDE szw (d-s) -- clear to sequel
320 `snocOL` RETURN_UBX l_rep) -- go
322 schemeE d s p (AnnLet (AnnNonRec x (_,rhs)) (_,body))
323 | (AnnVar v, args_r_to_l) <- splitApp rhs,
324 Just data_con <- isDataConWorkId_maybe v,
325 dataConRepArity data_con == length args_r_to_l
326 = do -- Special case for a non-recursive let whose RHS is a
327 -- saturatred constructor application.
328 -- Just allocate the constructor and carry on
329 alloc_code <- mkConAppCode d s p data_con args_r_to_l
330 body_code <- schemeE (d+1) s (addToFM p x d) body
331 return (alloc_code `appOL` body_code)
333 -- General case for let. Generates correct, if inefficient, code in
335 schemeE d s p (AnnLet binds (_,body))
336 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
337 AnnRec xs_n_rhss -> unzip xs_n_rhss
340 fvss = map (fvsToEnv p' . fst) rhss
342 -- Sizes of free vars
343 sizes = map (\rhs_fvs -> sum (map idSizeW rhs_fvs)) fvss
345 -- the arity of each rhs
346 arities = map (length . fst . collect []) rhss
348 -- This p', d' defn is safe because all the items being pushed
349 -- are ptrs, so all have size 1. d' and p' reflect the stack
350 -- after the closures have been allocated in the heap (but not
351 -- filled in), and pointers to them parked on the stack.
352 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n_binds 1)))
354 zipE = zipEqual "schemeE"
356 -- ToDo: don't build thunks for things with no free variables
357 build_thunk dd [] size bco off arity
358 = return (PUSH_BCO bco `consOL` unitOL (mkap (off+size) size))
360 mkap | arity == 0 = MKAP
362 build_thunk dd (fv:fvs) size bco off arity = do
363 (push_code, pushed_szw) <- pushAtom dd p' (AnnVar fv)
364 more_push_code <- build_thunk (dd+pushed_szw) fvs size bco off arity
365 return (push_code `appOL` more_push_code)
367 alloc_code = toOL (zipWith mkAlloc sizes arities)
368 where mkAlloc sz 0 = ALLOC_AP sz
369 mkAlloc sz arity = ALLOC_PAP arity sz
371 compile_bind d' fvs x rhs size arity off = do
372 bco <- schemeR fvs (x,rhs)
373 build_thunk d' fvs size bco off arity
376 [ compile_bind d' fvs x rhs size arity n
377 | (fvs, x, rhs, size, arity, n) <-
378 zip6 fvss xs rhss sizes arities [n_binds, n_binds-1 .. 1]
381 body_code <- schemeE d' s p' body
382 thunk_codes <- sequence compile_binds
383 return (alloc_code `appOL` concatOL thunk_codes `appOL` body_code)
387 schemeE d s p (AnnCase scrut bndr _ [(DataAlt dc, [bind1, bind2], rhs)])
388 | isUnboxedTupleCon dc, VoidArg <- typeCgRep (idType bind1)
390 -- case .... of x { (# VoidArg'd-thing, a #) -> ... }
392 -- case .... of a { DEFAULT -> ... }
393 -- becuse the return convention for both are identical.
395 -- Note that it does not matter losing the void-rep thing from the
396 -- envt (it won't be bound now) because we never look such things up.
398 = --trace "automagic mashing of case alts (# VoidArg, a #)" $
399 doCase d s p scrut bind2 [(DEFAULT, [], rhs)] True{-unboxed tuple-}
401 | isUnboxedTupleCon dc, VoidArg <- typeCgRep (idType bind2)
402 = --trace "automagic mashing of case alts (# a, VoidArg #)" $
403 doCase d s p scrut bind1 [(DEFAULT, [], rhs)] True{-unboxed tuple-}
405 schemeE d s p (AnnCase scrut bndr _ [(DataAlt dc, [bind1], rhs)])
406 | isUnboxedTupleCon dc
407 -- Similarly, convert
408 -- case .... of x { (# a #) -> ... }
410 -- case .... of a { DEFAULT -> ... }
411 = --trace "automagic mashing of case alts (# a #)" $
412 doCase d s p scrut bind1 [(DEFAULT, [], rhs)] True{-unboxed tuple-}
414 schemeE d s p (AnnCase scrut bndr _ alts)
415 = doCase d s p scrut bndr alts False{-not an unboxed tuple-}
417 schemeE d s p (AnnNote note (_, body))
420 schemeE d s p (AnnCast (_, body) _)
424 = pprPanic "ByteCodeGen.schemeE: unhandled case"
425 (pprCoreExpr (deAnnotate' other))
428 -- Compile code to do a tail call. Specifically, push the fn,
429 -- slide the on-stack app back down to the sequel depth,
430 -- and enter. Four cases:
433 -- An application "GHC.Prim.tagToEnum# <type> unboxed-int".
434 -- The int will be on the stack. Generate a code sequence
435 -- to convert it to the relevant constructor, SLIDE and ENTER.
437 -- 1. The fn denotes a ccall. Defer to generateCCall.
439 -- 2. (Another nasty hack). Spot (# a::VoidArg, b #) and treat
440 -- it simply as b -- since the representations are identical
441 -- (the VoidArg takes up zero stack space). Also, spot
442 -- (# b #) and treat it as b.
444 -- 3. Application of a constructor, by defn saturated.
445 -- Split the args into ptrs and non-ptrs, and push the nonptrs,
446 -- then the ptrs, and then do PACK and RETURN.
448 -- 4. Otherwise, it must be a function call. Push the args
449 -- right to left, SLIDE and ENTER.
451 schemeT :: Int -- Stack depth
452 -> Sequel -- Sequel depth
453 -> BCEnv -- stack env
454 -> AnnExpr' Id VarSet
459 -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
460 -- = panic "schemeT ?!?!"
462 -- | trace ("\nschemeT\n" ++ showSDoc (pprCoreExpr (deAnnotate' app)) ++ "\n") False
466 | Just (arg, constr_names) <- maybe_is_tagToEnum_call
467 = do (push, arg_words) <- pushAtom d p arg
468 tagToId_sequence <- implement_tagToId constr_names
469 return (push `appOL` tagToId_sequence
470 `appOL` mkSLIDE 1 (d+arg_words-s)
474 | Just (CCall ccall_spec) <- isFCallId_maybe fn
475 = generateCCall d s p ccall_spec fn args_r_to_l
477 -- Case 2: Constructor application
478 | Just con <- maybe_saturated_dcon,
479 isUnboxedTupleCon con
480 = case args_r_to_l of
481 [arg1,arg2] | isVoidArgAtom arg1 ->
482 unboxedTupleReturn d s p arg2
483 [arg1,arg2] | isVoidArgAtom arg2 ->
484 unboxedTupleReturn d s p arg1
485 _other -> unboxedTupleException
487 -- Case 3: Ordinary data constructor
488 | Just con <- maybe_saturated_dcon
489 = do alloc_con <- mkConAppCode d s p con args_r_to_l
490 return (alloc_con `appOL`
491 mkSLIDE 1 (d - s) `snocOL`
494 -- Case 4: Tail call of function
496 = doTailCall d s p fn args_r_to_l
499 -- Detect and extract relevant info for the tagToEnum kludge.
500 maybe_is_tagToEnum_call
501 = let extract_constr_Names ty
502 | Just (tyc, []) <- splitTyConApp_maybe (repType ty),
504 = map (getName . dataConWorkId) (tyConDataCons tyc)
505 -- NOTE: use the worker name, not the source name of
506 -- the DataCon. See DataCon.lhs for details.
508 = panic "maybe_is_tagToEnum_call.extract_constr_Ids"
511 (AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg)
512 -> case isPrimOpId_maybe v of
513 Just TagToEnumOp -> Just (snd arg, extract_constr_Names t)
517 -- Extract the args (R->L) and fn
518 -- The function will necessarily be a variable,
519 -- because we are compiling a tail call
520 (AnnVar fn, args_r_to_l) = splitApp app
522 -- Only consider this to be a constructor application iff it is
523 -- saturated. Otherwise, we'll call the constructor wrapper.
524 n_args = length args_r_to_l
526 = case isDataConWorkId_maybe fn of
527 Just con | dataConRepArity con == n_args -> Just con
530 -- -----------------------------------------------------------------------------
531 -- Generate code to build a constructor application,
532 -- leaving it on top of the stack
534 mkConAppCode :: Int -> Sequel -> BCEnv
535 -> DataCon -- The data constructor
536 -> [AnnExpr' Id VarSet] -- Args, in *reverse* order
539 mkConAppCode orig_d s p con [] -- Nullary constructor
540 = ASSERT( isNullaryRepDataCon con )
541 return (unitOL (PUSH_G (getName (dataConWorkId con))))
542 -- Instead of doing a PACK, which would allocate a fresh
543 -- copy of this constructor, use the single shared version.
545 mkConAppCode orig_d s p con args_r_to_l
546 = ASSERT( dataConRepArity con == length args_r_to_l )
547 do_pushery orig_d (non_ptr_args ++ ptr_args)
549 -- The args are already in reverse order, which is the way PACK
550 -- expects them to be. We must push the non-ptrs after the ptrs.
551 (ptr_args, non_ptr_args) = partition isPtrAtom args_r_to_l
553 do_pushery d (arg:args)
554 = do (push, arg_words) <- pushAtom d p arg
555 more_push_code <- do_pushery (d+arg_words) args
556 return (push `appOL` more_push_code)
558 = return (unitOL (PACK con n_arg_words))
560 n_arg_words = d - orig_d
563 -- -----------------------------------------------------------------------------
564 -- Returning an unboxed tuple with one non-void component (the only
565 -- case we can handle).
567 -- Remember, we don't want to *evaluate* the component that is being
568 -- returned, even if it is a pointed type. We always just return.
571 :: Int -> Sequel -> BCEnv
572 -> AnnExpr' Id VarSet -> BcM BCInstrList
573 unboxedTupleReturn d s p arg = do
574 (push, sz) <- pushAtom d p arg
576 mkSLIDE sz (d-s) `snocOL`
577 RETURN_UBX (atomRep arg))
579 -- -----------------------------------------------------------------------------
580 -- Generate code for a tail-call
583 :: Int -> Sequel -> BCEnv
584 -> Id -> [AnnExpr' Id VarSet]
586 doTailCall init_d s p fn args
587 = do_pushes init_d args (map atomRep args)
589 do_pushes d [] reps = do
590 ASSERT( null reps ) return ()
591 (push_fn, sz) <- pushAtom d p (AnnVar fn)
592 ASSERT( sz == 1 ) return ()
593 return (push_fn `appOL` (
594 mkSLIDE ((d-init_d) + 1) (init_d - s) `appOL`
596 do_pushes d args reps = do
597 let (push_apply, n, rest_of_reps) = findPushSeq reps
598 (these_args, rest_of_args) = splitAt n args
599 (next_d, push_code) <- push_seq d these_args
600 instrs <- do_pushes (next_d + 1) rest_of_args rest_of_reps
601 -- ^^^ for the PUSH_APPLY_ instruction
602 return (push_code `appOL` (push_apply `consOL` instrs))
604 push_seq d [] = return (d, nilOL)
605 push_seq d (arg:args) = do
606 (push_code, sz) <- pushAtom d p arg
607 (final_d, more_push_code) <- push_seq (d+sz) args
608 return (final_d, push_code `appOL` more_push_code)
610 -- v. similar to CgStackery.findMatch, ToDo: merge
611 findPushSeq (PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: rest)
612 = (PUSH_APPLY_PPPPPP, 6, rest)
613 findPushSeq (PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: rest)
614 = (PUSH_APPLY_PPPPP, 5, rest)
615 findPushSeq (PtrArg: PtrArg: PtrArg: PtrArg: rest)
616 = (PUSH_APPLY_PPPP, 4, rest)
617 findPushSeq (PtrArg: PtrArg: PtrArg: rest)
618 = (PUSH_APPLY_PPP, 3, rest)
619 findPushSeq (PtrArg: PtrArg: rest)
620 = (PUSH_APPLY_PP, 2, rest)
621 findPushSeq (PtrArg: rest)
622 = (PUSH_APPLY_P, 1, rest)
623 findPushSeq (VoidArg: rest)
624 = (PUSH_APPLY_V, 1, rest)
625 findPushSeq (NonPtrArg: rest)
626 = (PUSH_APPLY_N, 1, rest)
627 findPushSeq (FloatArg: rest)
628 = (PUSH_APPLY_F, 1, rest)
629 findPushSeq (DoubleArg: rest)
630 = (PUSH_APPLY_D, 1, rest)
631 findPushSeq (LongArg: rest)
632 = (PUSH_APPLY_L, 1, rest)
634 = panic "ByteCodeGen.findPushSeq"
636 -- -----------------------------------------------------------------------------
639 doCase :: Int -> Sequel -> BCEnv
640 -> AnnExpr Id VarSet -> Id -> [AnnAlt Id VarSet]
641 -> Bool -- True <=> is an unboxed tuple case, don't enter the result
643 doCase d s p (_,scrut)
644 bndr alts is_unboxed_tuple
646 -- Top of stack is the return itbl, as usual.
647 -- underneath it is the pointer to the alt_code BCO.
648 -- When an alt is entered, it assumes the returned value is
649 -- on top of the itbl.
652 -- An unlifted value gets an extra info table pushed on top
653 -- when it is returned.
654 unlifted_itbl_sizeW | isAlgCase = 0
657 -- depth of stack after the return value has been pushed
658 d_bndr = d + ret_frame_sizeW + idSizeW bndr
660 -- depth of stack after the extra info table for an unboxed return
661 -- has been pushed, if any. This is the stack depth at the
663 d_alts = d_bndr + unlifted_itbl_sizeW
665 -- Env in which to compile the alts, not including
666 -- any vars bound by the alts themselves
667 p_alts = addToFM p bndr (d_bndr - 1)
669 bndr_ty = idType bndr
670 isAlgCase = not (isUnLiftedType bndr_ty) && not is_unboxed_tuple
672 -- given an alt, return a discr and code for it.
673 codeALt alt@(DEFAULT, _, (_,rhs))
674 = do rhs_code <- schemeE d_alts s p_alts rhs
675 return (NoDiscr, rhs_code)
676 codeAlt alt@(discr, bndrs, (_,rhs))
677 -- primitive or nullary constructor alt: no need to UNPACK
678 | null real_bndrs = do
679 rhs_code <- schemeE d_alts s p_alts rhs
680 return (my_discr alt, rhs_code)
681 -- algebraic alt with some binders
682 | ASSERT(isAlgCase) otherwise =
684 (ptrs,nptrs) = partition (isFollowableArg.idCgRep) real_bndrs
685 ptr_sizes = map idSizeW ptrs
686 nptrs_sizes = map idSizeW nptrs
687 bind_sizes = ptr_sizes ++ nptrs_sizes
688 size = sum ptr_sizes + sum nptrs_sizes
689 -- the UNPACK instruction unpacks in reverse order...
690 p' = addListToFM p_alts
691 (zip (reverse (ptrs ++ nptrs))
692 (mkStackOffsets d_alts (reverse bind_sizes)))
694 rhs_code <- schemeE (d_alts+size) s p' rhs
695 return (my_discr alt, unitOL (UNPACK size) `appOL` rhs_code)
697 real_bndrs = filter (not.isTyVar) bndrs
700 my_discr (DEFAULT, binds, rhs) = NoDiscr {-shouldn't really happen-}
701 my_discr (DataAlt dc, binds, rhs)
702 | isUnboxedTupleCon dc
703 = unboxedTupleException
705 = DiscrP (dataConTag dc - fIRST_TAG)
706 my_discr (LitAlt l, binds, rhs)
707 = case l of MachInt i -> DiscrI (fromInteger i)
708 MachFloat r -> DiscrF (fromRational r)
709 MachDouble r -> DiscrD (fromRational r)
710 MachChar i -> DiscrI (ord i)
711 _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
714 | not isAlgCase = Nothing
716 = case [dc | (DataAlt dc, _, _) <- alts] of
718 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
720 -- the bitmap is relative to stack depth d, i.e. before the
721 -- BCO, info table and return value are pushed on.
722 -- This bit of code is v. similar to buildLivenessMask in CgBindery,
723 -- except that here we build the bitmap from the known bindings of
724 -- things that are pointers, whereas in CgBindery the code builds the
725 -- bitmap from the free slots and unboxed bindings.
728 -- NOTE [7/12/2006] bug #1013, testcase ghci/should_run/ghci002.
729 -- The bitmap must cover the portion of the stack up to the sequel only.
730 -- Previously we were building a bitmap for the whole depth (d), but we
731 -- really want a bitmap up to depth (d-s). This affects compilation of
732 -- case-of-case expressions, which is the only time we can be compiling a
733 -- case expression with s /= 0.
735 bitmap = intsToReverseBitmap bitmap_size{-size-}
736 (sortLe (<=) (filter (< bitmap_size) rel_slots))
739 rel_slots = concat (map spread binds)
741 | isFollowableArg (idCgRep id) = [ rel_offset ]
743 where rel_offset = d - offset - 1
746 alt_stuff <- mapM codeAlt alts
747 alt_final <- mkMultiBranch maybe_ncons alt_stuff
749 alt_bco_name = getName bndr
750 alt_bco = mkProtoBCO alt_bco_name alt_final (Left alts)
751 0{-no arity-} bitmap_size bitmap True{-is alts-}
753 -- trace ("case: bndr = " ++ showSDocDebug (ppr bndr) ++ "\ndepth = " ++ show d ++ "\nenv = \n" ++ showSDocDebug (ppBCEnv p) ++
754 -- "\n bitmap = " ++ show bitmap) $ do
755 scrut_code <- schemeE (d + ret_frame_sizeW) (d + ret_frame_sizeW) p scrut
756 alt_bco' <- emitBc alt_bco
758 | isAlgCase = PUSH_ALTS alt_bco'
759 | otherwise = PUSH_ALTS_UNLIFTED alt_bco' (typeCgRep bndr_ty)
760 return (push_alts `consOL` scrut_code)
763 -- -----------------------------------------------------------------------------
764 -- Deal with a CCall.
766 -- Taggedly push the args onto the stack R->L,
767 -- deferencing ForeignObj#s and adjusting addrs to point to
768 -- payloads in Ptr/Byte arrays. Then, generate the marshalling
769 -- (machine) code for the ccall, and create bytecodes to call that and
770 -- then return in the right way.
772 generateCCall :: Int -> Sequel -- stack and sequel depths
774 -> CCallSpec -- where to call
775 -> Id -- of target, for type info
776 -> [AnnExpr' Id VarSet] -- args (atoms)
779 generateCCall d0 s p ccall_spec@(CCallSpec target cconv safety) fn args_r_to_l
782 addr_sizeW = cgRepSizeW NonPtrArg
784 -- Get the args on the stack, with tags and suitably
785 -- dereferenced for the CCall. For each arg, return the
786 -- depth to the first word of the bits for that arg, and the
787 -- CgRep of what was actually pushed.
789 pargs d [] = return []
791 = let arg_ty = repType (exprType (deAnnotate' a))
793 in case splitTyConApp_maybe arg_ty of
794 -- Don't push the FO; instead push the Addr# it
797 | t == arrayPrimTyCon || t == mutableArrayPrimTyCon
798 -> do rest <- pargs (d + addr_sizeW) az
799 code <- parg_ArrayishRep arrPtrsHdrSize d p a
800 return ((code,NonPtrArg):rest)
802 | t == byteArrayPrimTyCon || t == mutableByteArrayPrimTyCon
803 -> do rest <- pargs (d + addr_sizeW) az
804 code <- parg_ArrayishRep arrWordsHdrSize d p a
805 return ((code,NonPtrArg):rest)
807 -- Default case: push taggedly, but otherwise intact.
809 -> do (code_a, sz_a) <- pushAtom d p a
810 rest <- pargs (d+sz_a) az
811 return ((code_a, atomRep a) : rest)
813 -- Do magic for Ptr/Byte arrays. Push a ptr to the array on
814 -- the stack but then advance it over the headers, so as to
815 -- point to the payload.
816 parg_ArrayishRep hdrSize d p a
817 = do (push_fo, _) <- pushAtom d p a
818 -- The ptr points at the header. Advance it over the
819 -- header and then pretend this is an Addr#.
820 return (push_fo `snocOL` SWIZZLE 0 hdrSize)
823 code_n_reps <- pargs d0 args_r_to_l
825 (pushs_arg, a_reps_pushed_r_to_l) = unzip code_n_reps
827 push_args = concatOL pushs_arg
828 d_after_args = d0 + sum (map cgRepSizeW a_reps_pushed_r_to_l)
830 | null a_reps_pushed_r_to_l || head a_reps_pushed_r_to_l /= VoidArg
831 = panic "ByteCodeGen.generateCCall: missing or invalid World token?"
833 = reverse (tail a_reps_pushed_r_to_l)
835 -- Now: a_reps_pushed_RAW are the reps which are actually on the stack.
836 -- push_args is the code to do that.
837 -- d_after_args is the stack depth once the args are on.
839 -- Get the result rep.
840 (returns_void, r_rep)
841 = case maybe_getCCallReturnRep (idType fn) of
842 Nothing -> (True, VoidArg)
843 Just rr -> (False, rr)
845 Because the Haskell stack grows down, the a_reps refer to
846 lowest to highest addresses in that order. The args for the call
847 are on the stack. Now push an unboxed Addr# indicating
848 the C function to call. Then push a dummy placeholder for the
849 result. Finally, emit a CCALL insn with an offset pointing to the
850 Addr# just pushed, and a literal field holding the mallocville
851 address of the piece of marshalling code we generate.
852 So, just prior to the CCALL insn, the stack looks like this
853 (growing down, as usual):
858 Addr# address_of_C_fn
859 <placeholder-for-result#> (must be an unboxed type)
861 The interpreter then calls the marshall code mentioned
862 in the CCALL insn, passing it (& <placeholder-for-result#>),
863 that is, the addr of the topmost word in the stack.
864 When this returns, the placeholder will have been
865 filled in. The placeholder is slid down to the sequel
866 depth, and we RETURN.
868 This arrangement makes it simple to do f-i-dynamic since the Addr#
869 value is the first arg anyway.
871 The marshalling code is generated specifically for this
872 call site, and so knows exactly the (Haskell) stack
873 offsets of the args, fn address and placeholder. It
874 copies the args to the C stack, calls the stacked addr,
875 and parks the result back in the placeholder. The interpreter
876 calls it as a normal C call, assuming it has a signature
877 void marshall_code ( StgWord* ptr_to_top_of_stack )
879 -- resolve static address
883 -> return (False, panic "ByteCodeGen.generateCCall(dyn)")
885 -> do res <- ioToBc (lookupStaticPtr target)
888 (is_static, static_target_addr) <- get_target_info
891 -- Get the arg reps, zapping the leading Addr# in the dynamic case
892 a_reps -- | trace (showSDoc (ppr a_reps_pushed_RAW)) False = error "???"
893 | is_static = a_reps_pushed_RAW
894 | otherwise = if null a_reps_pushed_RAW
895 then panic "ByteCodeGen.generateCCall: dyn with no args"
896 else tail a_reps_pushed_RAW
899 (push_Addr, d_after_Addr)
901 = (toOL [PUSH_UBX (Right static_target_addr) addr_sizeW],
902 d_after_args + addr_sizeW)
903 | otherwise -- is already on the stack
904 = (nilOL, d_after_args)
906 -- Push the return placeholder. For a call returning nothing,
907 -- this is a VoidArg (tag).
908 r_sizeW = cgRepSizeW r_rep
909 d_after_r = d_after_Addr + r_sizeW
910 r_lit = mkDummyLiteral r_rep
911 push_r = (if returns_void
913 else unitOL (PUSH_UBX (Left r_lit) r_sizeW))
915 -- generate the marshalling code we're going to call
918 arg1_offW = r_sizeW + addr_sizeW
919 args_offW = map (arg1_offW +)
920 (init (scanl (+) 0 (map cgRepSizeW a_reps)))
922 addr_of_marshaller <- ioToBc (mkMarshalCode cconv
923 (r_offW, r_rep) addr_offW
924 (zip args_offW a_reps))
925 recordItblMallocBc (ItblPtr (castFunPtrToPtr addr_of_marshaller))
927 -- Offset of the next stack frame down the stack. The CCALL
928 -- instruction needs to describe the chunk of stack containing
929 -- the ccall args to the GC, so it needs to know how large it
930 -- is. See comment in Interpreter.c with the CCALL instruction.
931 stk_offset = d_after_r - s
934 do_call = unitOL (CCALL stk_offset (castFunPtrToPtr addr_of_marshaller))
936 wrapup = mkSLIDE r_sizeW (d_after_r - r_sizeW - s)
937 `snocOL` RETURN_UBX r_rep
939 --trace (show (arg1_offW, args_offW , (map cgRepSizeW a_reps) )) $
942 push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup
946 -- Make a dummy literal, to be used as a placeholder for FFI return
947 -- values on the stack.
948 mkDummyLiteral :: CgRep -> Literal
951 NonPtrArg -> MachWord 0
952 DoubleArg -> MachDouble 0
953 FloatArg -> MachFloat 0
954 LongArg -> MachWord64 0
955 _ -> moan64 "mkDummyLiteral" (ppr pr)
959 -- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld
960 -- -> (# GHC.Prim.State# GHC.Prim.RealWorld, GHC.Prim.Int# #)
963 -- and check that an unboxed pair is returned wherein the first arg is VoidArg'd.
965 -- Alternatively, for call-targets returning nothing, convert
967 -- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld
968 -- -> (# GHC.Prim.State# GHC.Prim.RealWorld #)
972 maybe_getCCallReturnRep :: Type -> Maybe CgRep
973 maybe_getCCallReturnRep fn_ty
974 = let (a_tys, r_ty) = splitFunTys (dropForAlls fn_ty)
976 = if isSingleton r_reps then Nothing else Just (r_reps !! 1)
978 = case splitTyConApp_maybe (repType r_ty) of
979 (Just (tyc, tys)) -> (tyc, map typeCgRep tys)
981 ok = ( ( r_reps `lengthIs` 2 && VoidArg == head r_reps)
982 || r_reps == [VoidArg] )
983 && isUnboxedTupleTyCon r_tycon
984 && case maybe_r_rep_to_go of
986 Just r_rep -> r_rep /= PtrArg
987 -- if it was, it would be impossible
988 -- to create a valid return value
989 -- placeholder on the stack
990 blargh = pprPanic "maybe_getCCallReturn: can't handle:"
993 --trace (showSDoc (ppr (a_reps, r_reps))) $
994 if ok then maybe_r_rep_to_go else blargh
996 -- Compile code which expects an unboxed Int on the top of stack,
997 -- (call it i), and pushes the i'th closure in the supplied list
999 implement_tagToId :: [Name] -> BcM BCInstrList
1000 implement_tagToId names
1001 = ASSERT( notNull names )
1002 do labels <- getLabelsBc (length names)
1003 label_fail <- getLabelBc
1004 label_exit <- getLabelBc
1005 let infos = zip4 labels (tail labels ++ [label_fail])
1007 steps = map (mkStep label_exit) infos
1008 return (concatOL steps
1010 toOL [LABEL label_fail, CASEFAIL, LABEL label_exit])
1012 mkStep l_exit (my_label, next_label, n, name_for_n)
1013 = toOL [LABEL my_label,
1014 TESTEQ_I n next_label,
1019 -- -----------------------------------------------------------------------------
1022 -- Push an atom onto the stack, returning suitable code & number of
1023 -- stack words used.
1025 -- The env p must map each variable to the highest- numbered stack
1026 -- slot for it. For example, if the stack has depth 4 and we
1027 -- tagged-ly push (v :: Int#) on it, the value will be in stack[4],
1028 -- the tag in stack[5], the stack will have depth 6, and p must map v
1029 -- to 5 and not to 4. Stack locations are numbered from zero, so a
1030 -- depth 6 stack has valid words 0 .. 5.
1032 pushAtom :: Int -> BCEnv -> AnnExpr' Id VarSet -> BcM (BCInstrList, Int)
1034 pushAtom d p (AnnApp f (_, AnnType _))
1035 = pushAtom d p (snd f)
1037 pushAtom d p (AnnNote note e)
1038 = pushAtom d p (snd e)
1040 pushAtom d p (AnnLam x e)
1042 = pushAtom d p (snd e)
1044 pushAtom d p (AnnVar v)
1046 | idCgRep v == VoidArg
1050 = pprPanic "pushAtom: shouldn't get an FCallId here" (ppr v)
1052 | Just primop <- isPrimOpId_maybe v
1053 = return (unitOL (PUSH_PRIMOP primop), 1)
1055 | Just d_v <- lookupBCEnv_maybe p v -- v is a local variable
1056 = return (toOL (nOfThem sz (PUSH_L (d-d_v+sz-2))), sz)
1057 -- d - d_v the number of words between the TOS
1058 -- and the 1st slot of the object
1060 -- d - d_v - 1 the offset from the TOS of the 1st slot
1062 -- d - d_v - 1 + sz - 1 the offset from the TOS of the last slot
1065 -- Having found the last slot, we proceed to copy the right number of
1066 -- slots on to the top of the stack.
1068 | otherwise -- v must be a global variable
1070 return (unitOL (PUSH_G (getName v)), sz)
1076 pushAtom d p (AnnLit lit)
1078 MachLabel fs _ -> code NonPtrArg
1079 MachWord w -> code NonPtrArg
1080 MachInt i -> code PtrArg
1081 MachFloat r -> code FloatArg
1082 MachDouble r -> code DoubleArg
1083 MachChar c -> code NonPtrArg
1084 MachStr s -> pushStr s
1087 = let size_host_words = cgRepSizeW rep
1088 in return (unitOL (PUSH_UBX (Left lit) size_host_words),
1092 = let getMallocvilleAddr
1094 FastString _ n _ fp _ ->
1095 -- we could grab the Ptr from the ForeignPtr,
1096 -- but then we have no way to control its lifetime.
1097 -- In reality it'll probably stay alive long enoungh
1098 -- by virtue of the global FastString table, but
1099 -- to be on the safe side we copy the string into
1100 -- a malloc'd area of memory.
1101 do ptr <- ioToBc (mallocBytes (n+1))
1104 withForeignPtr fp $ \p -> do
1105 memcpy ptr p (fromIntegral n)
1106 pokeByteOff ptr n (fromIntegral (ord '\0') :: Word8)
1110 addr <- getMallocvilleAddr
1111 -- Get the addr on the stack, untaggedly
1112 return (unitOL (PUSH_UBX (Right addr) 1), 1)
1114 pushAtom d p (AnnCast e _)
1115 = pushAtom d p (snd e)
1118 = pprPanic "ByteCodeGen.pushAtom"
1119 (pprCoreExpr (deAnnotate (undefined, other)))
1121 foreign import ccall unsafe "memcpy"
1122 memcpy :: Ptr a -> Ptr b -> CInt -> IO ()
1125 -- -----------------------------------------------------------------------------
1126 -- Given a bunch of alts code and their discrs, do the donkey work
1127 -- of making a multiway branch using a switch tree.
1128 -- What a load of hassle!
1130 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
1131 -- a hint; generates better code
1132 -- Nothing is always safe
1133 -> [(Discr, BCInstrList)]
1135 mkMultiBranch maybe_ncons raw_ways
1136 = let d_way = filter (isNoDiscr.fst) raw_ways
1138 (\w1 w2 -> leAlt (fst w1) (fst w2))
1139 (filter (not.isNoDiscr.fst) raw_ways)
1141 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
1142 mkTree [] range_lo range_hi = return the_default
1144 mkTree [val] range_lo range_hi
1145 | range_lo `eqAlt` range_hi
1148 = do label_neq <- getLabelBc
1149 return (mkTestEQ (fst val) label_neq
1151 `appOL` unitOL (LABEL label_neq)
1152 `appOL` the_default))
1154 mkTree vals range_lo range_hi
1155 = let n = length vals `div` 2
1156 vals_lo = take n vals
1157 vals_hi = drop n vals
1158 v_mid = fst (head vals_hi)
1160 label_geq <- getLabelBc
1161 code_lo <- mkTree vals_lo range_lo (dec v_mid)
1162 code_hi <- mkTree vals_hi v_mid range_hi
1163 return (mkTestLT v_mid label_geq
1165 `appOL` unitOL (LABEL label_geq)
1169 = case d_way of [] -> unitOL CASEFAIL
1172 -- None of these will be needed if there are no non-default alts
1173 (mkTestLT, mkTestEQ, init_lo, init_hi)
1175 = panic "mkMultiBranch: awesome foursome"
1177 = case fst (head notd_ways) of {
1178 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
1179 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
1182 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
1183 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
1186 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
1187 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
1190 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
1191 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
1193 DiscrP algMaxBound )
1196 (algMinBound, algMaxBound)
1197 = case maybe_ncons of
1198 Just n -> (0, n - 1)
1199 Nothing -> (minBound, maxBound)
1201 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
1202 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
1203 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
1204 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
1205 NoDiscr `eqAlt` NoDiscr = True
1208 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
1209 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
1210 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
1211 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
1212 NoDiscr `leAlt` NoDiscr = True
1215 isNoDiscr NoDiscr = True
1218 dec (DiscrI i) = DiscrI (i-1)
1219 dec (DiscrP i) = DiscrP (i-1)
1220 dec other = other -- not really right, but if you
1221 -- do cases on floating values, you'll get what you deserve
1223 -- same snotty comment applies to the following
1225 minD, maxD :: Double
1231 mkTree notd_ways init_lo init_hi
1234 -- -----------------------------------------------------------------------------
1235 -- Supporting junk for the compilation schemes
1237 -- Describes case alts
1245 instance Outputable Discr where
1246 ppr (DiscrI i) = int i
1247 ppr (DiscrF f) = text (show f)
1248 ppr (DiscrD d) = text (show d)
1249 ppr (DiscrP i) = int i
1250 ppr NoDiscr = text "DEF"
1253 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
1254 lookupBCEnv_maybe = lookupFM
1256 idSizeW :: Id -> Int
1257 idSizeW id = cgRepSizeW (typeCgRep (idType id))
1259 unboxedTupleException :: a
1260 unboxedTupleException
1263 ("Bytecode generator can't handle unboxed tuples. Possibly due\n" ++
1264 "\tto foreign import/export decls in source. Workaround:\n" ++
1265 "\tcompile this module to a .o file, then restart session."))
1268 mkSLIDE n d = if d == 0 then nilOL else unitOL (SLIDE n d)
1271 splitApp :: AnnExpr' id ann -> (AnnExpr' id ann, [AnnExpr' id ann])
1272 -- The arguments are returned in *right-to-left* order
1273 splitApp (AnnApp (_,f) (_,a))
1274 | isTypeAtom a = splitApp f
1275 | otherwise = case splitApp f of
1276 (f', as) -> (f', a:as)
1277 splitApp (AnnNote n (_,e)) = splitApp e
1278 splitApp (AnnCast (_,e) _) = splitApp e
1279 splitApp e = (e, [])
1282 isTypeAtom :: AnnExpr' id ann -> Bool
1283 isTypeAtom (AnnType _) = True
1284 isTypeAtom _ = False
1286 isVoidArgAtom :: AnnExpr' id ann -> Bool
1287 isVoidArgAtom (AnnVar v) = typeCgRep (idType v) == VoidArg
1288 isVoidArgAtom (AnnNote n (_,e)) = isVoidArgAtom e
1289 isVoidArgAtom (AnnCast (_,e) _) = isVoidArgAtom e
1290 isVoidArgAtom _ = False
1292 atomRep :: AnnExpr' Id ann -> CgRep
1293 atomRep (AnnVar v) = typeCgRep (idType v)
1294 atomRep (AnnLit l) = typeCgRep (literalType l)
1295 atomRep (AnnNote n b) = atomRep (snd b)
1296 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
1297 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
1298 atomRep (AnnCast b _) = atomRep (snd b)
1299 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
1301 isPtrAtom :: AnnExpr' Id ann -> Bool
1302 isPtrAtom e = atomRep e == PtrArg
1304 -- Let szsw be the sizes in words of some items pushed onto the stack,
1305 -- which has initial depth d'. Return the values which the stack environment
1306 -- should map these items to.
1307 mkStackOffsets :: Int -> [Int] -> [Int]
1308 mkStackOffsets original_depth szsw
1309 = map (subtract 1) (tail (scanl (+) original_depth szsw))
1311 -- -----------------------------------------------------------------------------
1312 -- The bytecode generator's monad
1314 type BcPtr = Either ItblPtr (Ptr ())
1318 nextlabel :: Int, -- for generating local labels
1319 malloced :: [BcPtr] } -- thunks malloced for current BCO
1320 -- Should be free()d when it is GCd
1322 newtype BcM r = BcM (BcM_State -> IO (BcM_State, r))
1324 ioToBc :: IO a -> BcM a
1325 ioToBc io = BcM $ \st -> do
1329 runBc :: BcM r -> IO (BcM_State, r)
1330 runBc (BcM m) = m (BcM_State 0 [])
1332 thenBc :: BcM a -> (a -> BcM b) -> BcM b
1333 thenBc (BcM expr) cont = BcM $ \st0 -> do
1334 (st1, q) <- expr st0
1339 thenBc_ :: BcM a -> BcM b -> BcM b
1340 thenBc_ (BcM expr) (BcM cont) = BcM $ \st0 -> do
1341 (st1, q) <- expr st0
1342 (st2, r) <- cont st1
1345 returnBc :: a -> BcM a
1346 returnBc result = BcM $ \st -> (return (st, result))
1348 instance Monad BcM where
1353 emitBc :: ([BcPtr] -> ProtoBCO Name) -> BcM (ProtoBCO Name)
1355 = BcM $ \st -> return (st{malloced=[]}, bco (malloced st))
1357 recordMallocBc :: Ptr a -> BcM ()
1359 = BcM $ \st -> return (st{malloced = Right (castPtr a) : malloced st}, ())
1361 recordItblMallocBc :: ItblPtr -> BcM ()
1362 recordItblMallocBc a
1363 = BcM $ \st -> return (st{malloced = Left a : malloced st}, ())
1365 getLabelBc :: BcM Int
1367 = BcM $ \st -> return (st{nextlabel = 1 + nextlabel st}, nextlabel st)
1369 getLabelsBc :: Int -> BcM [Int]
1371 = BcM $ \st -> let ctr = nextlabel st
1372 in return (st{nextlabel = ctr+n}, [ctr .. ctr+n-1])