2 % (c) The University of Glasgow 2002
4 \section[ByteCodeGen]{Generate bytecode from Core}
7 module ByteCodeGen ( UnlinkedBCO, byteCodeGen, coreExprToBCOs ) where
9 #include "HsVersions.h"
12 import ByteCodeFFI ( mkMarshalCode, moan64 )
13 import ByteCodeAsm ( CompiledByteCode(..), UnlinkedBCO,
14 assembleBCO, assembleBCOs, iNTERP_STACK_CHECK_THRESH )
15 import ByteCodeLink ( lookupStaticPtr )
18 import Name ( Name, getName, mkSystemName )
21 import ForeignCall ( ForeignCall(..), CCallTarget(..), CCallSpec(..) )
22 import HscTypes ( ModGuts(..), ModGuts, typeEnvTyCons, typeEnvClasses )
23 import CoreUtils ( exprType )
25 import PprCore ( pprCoreExpr )
26 import Literal ( Literal(..), literalPrimRep )
28 import PrimOp ( PrimOp(..) )
29 import CoreFVs ( freeVars )
30 import Type ( typePrimRep, isUnLiftedType, splitTyConApp_maybe,
32 import DataCon ( DataCon, dataConTag, fIRST_TAG, dataConTyCon,
33 isUnboxedTupleCon, isNullaryDataCon,
35 import TyCon ( tyConFamilySize, isDataTyCon, tyConDataCons,
36 isFunTyCon, isUnboxedTupleTyCon )
37 import Class ( Class, classTyCon )
38 import Type ( Type, repType, splitFunTys, dropForAlls )
40 import DataCon ( dataConRepArity )
41 import Var ( isTyVar )
42 import VarSet ( VarSet, varSetElems )
43 import TysPrim ( foreignObjPrimTyCon,
44 arrayPrimTyCon, mutableArrayPrimTyCon,
45 byteArrayPrimTyCon, mutableByteArrayPrimTyCon
47 import PrimRep ( isFollowableRep )
48 import CmdLineOpts ( DynFlags, DynFlag(..) )
49 import ErrUtils ( showPass, dumpIfSet_dyn )
50 import Unique ( mkPseudoUnique3 )
51 import FastString ( FastString(..), unpackFS )
52 import Panic ( GhcException(..) )
53 import PprType ( pprType )
54 import SMRep ( arrWordsHdrSize, arrPtrsHdrSize )
56 import Constants ( wORD_SIZE )
57 import BasicTypes ( TopLevelFlag(..), isTopLevel, isNotTopLevel )
59 import Data.List ( intersperse, sortBy, zip4, zip5, partition )
60 import Foreign ( Ptr, castPtr, mallocBytes, pokeByteOff, Word8 )
61 import Foreign.C ( CInt )
62 import Control.Exception ( throwDyn )
64 import GHC.Exts ( Int(..), ByteArray# )
66 import Control.Monad ( when, mapAndUnzipM )
67 import Data.Char ( ord )
70 -- -----------------------------------------------------------------------------
71 -- Generating byte code for a complete module
73 byteCodeGen :: DynFlags
75 -> IO CompiledByteCode
76 byteCodeGen dflags (ModGuts { mg_binds = binds, mg_types = type_env })
77 = do showPass dflags "ByteCodeGen"
78 let local_tycons = typeEnvTyCons type_env
79 local_classes = typeEnvClasses type_env
80 tycs = local_tycons ++ map classTyCon local_classes
82 let flatBinds = [ (bndr, freeVars rhs)
83 | (bndr, rhs) <- flattenBinds binds]
85 (BcM_State final_ctr mallocd, proto_bcos)
86 <- runBc (mapM schemeTopBind flatBinds)
88 when (notNull mallocd)
89 (panic "ByteCodeGen.byteCodeGen: missing final emitBc?")
91 dumpIfSet_dyn dflags Opt_D_dump_BCOs
92 "Proto-BCOs" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
94 assembleBCOs proto_bcos tycs
96 -- -----------------------------------------------------------------------------
97 -- Generating byte code for an expression
99 -- Returns: (the root BCO for this expression,
100 -- a list of auxilary BCOs resulting from compiling closures)
101 coreExprToBCOs :: DynFlags
104 coreExprToBCOs dflags expr
105 = do showPass dflags "ByteCodeGen"
107 -- create a totally bogus name for the top-level BCO; this
108 -- should be harmless, since it's never used for anything
109 let invented_name = mkSystemName (mkPseudoUnique3 0) FSLIT("ExprTopLevel")
110 invented_id = mkLocalId invented_name (panic "invented_id's type")
112 (BcM_State final_ctr mallocd, proto_bco)
113 <- runBc (schemeTopBind (invented_id, freeVars expr))
115 when (notNull mallocd)
116 (panic "ByteCodeGen.coreExprToBCOs: missing final emitBc?")
118 dumpIfSet_dyn dflags Opt_D_dump_BCOs "Proto-BCOs" (ppr proto_bco)
120 assembleBCO proto_bco
123 -- -----------------------------------------------------------------------------
124 -- Compilation schema for the bytecode generator
126 type BCInstrList = OrdList BCInstr
128 type Sequel = Int -- back off to this depth before ENTER
130 -- Maps Ids to the offset from the stack _base_ so we don't have
131 -- to mess with it after each push/pop.
132 type BCEnv = FiniteMap Id Int -- To find vars on the stack
134 ppBCEnv :: BCEnv -> SDoc
137 $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
140 pp_one (var, offset) = int offset <> colon <+> ppr var <+> ppr (idPrimRep var)
141 cmp_snd x y = compare (snd x) (snd y)
143 -- Create a BCO and do a spot of peephole optimisation on the insns
148 -> Either [AnnAlt Id VarSet] (AnnExpr Id VarSet)
154 mkProtoBCO nm instrs_ordlist origin arity bitmap_size bitmap mallocd_blocks
157 protoBCOInstrs = maybe_with_stack_check,
158 protoBCOBitmap = bitmap,
159 protoBCOBitmapSize = bitmap_size,
160 protoBCOArity = arity,
161 protoBCOExpr = origin,
162 protoBCOPtrs = mallocd_blocks
165 -- Overestimate the stack usage (in words) of this BCO,
166 -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
167 -- stack check. (The interpreter always does a stack check
168 -- for iNTERP_STACK_CHECK_THRESH words at the start of each
169 -- BCO anyway, so we only need to add an explicit on in the
170 -- (hopefully rare) cases when the (overestimated) stack use
171 -- exceeds iNTERP_STACK_CHECK_THRESH.
172 maybe_with_stack_check
173 | stack_overest >= 65535
174 = pprPanic "mkProtoBCO: stack use won't fit in 16 bits"
176 | stack_overest >= iNTERP_STACK_CHECK_THRESH
177 = (STKCHECK stack_overest) : peep_d
179 = peep_d -- the supposedly common case
181 stack_overest = sum (map bciStackUse peep_d)
182 + 10 {- just to be really really sure -}
184 -- Merge local pushes
185 peep_d = peep (fromOL instrs_ordlist)
187 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
188 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
189 peep (PUSH_L off1 : PUSH_L off2 : rest)
190 = PUSH_LL off1 (off2-1) : peep rest
196 argBits :: [PrimRep] -> [Bool]
199 | isFollowableRep rep = False : argBits args
200 | otherwise = take (getPrimRepSize rep) (repeat True) ++ argBits args
202 mkBitmap :: [Bool] -> [StgWord]
204 mkBitmap stuff = chunkToLiveness chunk : mkBitmap rest
205 where (chunk, rest) = splitAt wORD_SIZE_IN_BITS stuff
207 chunkToLiveness :: [Bool] -> StgWord
208 chunkToLiveness chunk =
209 foldr (.|.) 0 [ 1 `shiftL` n | (True,n) <- zip chunk [0..] ]
211 -- make a bitmap where the slots specified are the *zeros* in the bitmap.
212 -- eg. [1,2,4], size 4 ==> 0x8 (we leave any bits outside the size as zero,
213 -- just to make the bitmap easier to read).
214 intsToBitmap :: Int -> [Int] -> [StgWord]
215 intsToBitmap size slots{- must be sorted -}
218 (foldr xor init (map (1 `shiftL`) these)) :
219 intsToBitmap (size - wORD_SIZE_IN_BITS)
220 (map (\x -> x - wORD_SIZE_IN_BITS) rest)
221 where (these,rest) = span (<wORD_SIZE_IN_BITS) slots
223 | size >= wORD_SIZE_IN_BITS = complement 0
224 | otherwise = (1 `shiftL` size) - 1
226 wORD_SIZE_IN_BITS = wORD_SIZE * 8 :: Int
228 -- -----------------------------------------------------------------------------
231 -- Compile code for the right-hand side of a top-level binding
233 schemeTopBind :: (Id, AnnExpr Id VarSet) -> BcM (ProtoBCO Name)
236 schemeTopBind (id, rhs)
237 | Just data_con <- isDataConWrapId_maybe id,
238 isNullaryDataCon data_con
239 = -- Special case for the wrapper of a nullary data con.
240 -- It'll look like this: Nil = /\a -> $wNil a
241 -- If we feed it into schemeR, we'll get
243 -- because mkConAppCode treats nullary constructor applications
244 -- by just re-using the single top-level definition. So
245 -- for the wrapper itself, we must allocate it directly.
246 emitBc (mkProtoBCO (getName id) (toOL [PACK data_con 0, ENTER])
247 (Right rhs) 0 0 [{-no bitmap-}])
250 = schemeR [{- No free variables -}] (id, rhs)
252 -- -----------------------------------------------------------------------------
255 -- Compile code for a right-hand side, to give a BCO that,
256 -- when executed with the free variables and arguments on top of the stack,
257 -- will return with a pointer to the result on top of the stack, after
258 -- removing the free variables and arguments.
260 -- Park the resulting BCO in the monad. Also requires the
261 -- variable to which this value was bound, so as to give the
262 -- resulting BCO a name.
264 schemeR :: [Id] -- Free vars of the RHS, ordered as they
265 -- will appear in the thunk. Empty for
266 -- top-level things, which have no free vars.
267 -> (Id, AnnExpr Id VarSet)
268 -> BcM (ProtoBCO Name)
269 schemeR fvs (nm, rhs)
273 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
274 $$ pprCoreExpr (deAnnotate rhs)
280 = schemeR_wrk fvs nm rhs (collect [] rhs)
282 collect xs (_, AnnNote note e) = collect xs e
283 collect xs (_, AnnLam x e) = collect (if isTyVar x then xs else (x:xs)) e
284 collect xs (_, not_lambda) = (reverse xs, not_lambda)
286 schemeR_wrk fvs nm original_body (args, body)
288 all_args = reverse args ++ fvs
289 arity = length all_args
290 -- all_args are the args in reverse order. We're compiling a function
291 -- \fv1..fvn x1..xn -> e
292 -- i.e. the fvs come first
294 szsw_args = map idSizeW all_args
295 szw_args = sum szsw_args
296 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
298 -- make the arg bitmap
299 bits = argBits (reverse (map idPrimRep all_args))
300 bitmap_size = length bits
301 bitmap = mkBitmap bits
303 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
304 emitBc (mkProtoBCO (getName nm) body_code (Right original_body)
305 arity bitmap_size bitmap)
308 fvsToEnv :: BCEnv -> VarSet -> [Id]
309 -- Takes the free variables of a right-hand side, and
310 -- delivers an ordered list of the local variables that will
311 -- be captured in the thunk for the RHS
312 -- The BCEnv argument tells which variables are in the local
313 -- environment: these are the ones that should be captured
315 -- The code that constructs the thunk, and the code that executes
316 -- it, have to agree about this layout
317 fvsToEnv p fvs = [v | v <- varSetElems fvs,
318 isId v, -- Could be a type variable
321 -- -----------------------------------------------------------------------------
324 -- Compile code to apply the given expression to the remaining args
325 -- on the stack, returning a HNF.
326 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList
328 -- Delegate tail-calls to schemeT.
329 schemeE d s p e@(AnnApp f a)
332 schemeE d s p e@(AnnVar v)
333 | not (isUnLiftedType v_type)
334 = -- Lifted-type thing; push it in the normal way
338 = -- Returning an unlifted value.
339 -- Heave it on the stack, SLIDE, and RETURN.
340 pushAtom d p (AnnVar v) `thenBc` \ (push, szw) ->
341 returnBc (push -- value onto stack
342 `appOL` mkSLIDE szw (d-s) -- clear to sequel
343 `snocOL` RETURN_UBX v_rep) -- go
346 v_rep = typePrimRep v_type
348 schemeE d s p (AnnLit literal)
349 = pushAtom d p (AnnLit literal) `thenBc` \ (push, szw) ->
350 let l_rep = literalPrimRep literal
351 in returnBc (push -- value onto stack
352 `appOL` mkSLIDE szw (d-s) -- clear to sequel
353 `snocOL` RETURN_UBX l_rep) -- go
356 schemeE d s p (AnnLet (AnnNonRec x (_,rhs)) (_,body))
357 | (AnnVar v, args_r_to_l) <- splitApp rhs,
358 Just data_con <- isDataConId_maybe v,
359 dataConRepArity data_con == length args_r_to_l
360 = -- Special case for a non-recursive let whose RHS is a
361 -- saturatred constructor application.
362 -- Just allocate the constructor and carry on
363 mkConAppCode d s p data_con args_r_to_l `thenBc` \ alloc_code ->
364 schemeE (d+1) s (addToFM p x d) body `thenBc` \ body_code ->
365 returnBc (alloc_code `appOL` body_code)
367 -- General case for let. Generates correct, if inefficient, code in
369 schemeE d s p (AnnLet binds (_,body))
370 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
371 AnnRec xs_n_rhss -> unzip xs_n_rhss
374 fvss = map (fvsToEnv p' . fst) rhss
376 -- Sizes of free vars, + 1 for the fn
377 sizes = map (\rhs_fvs -> 1 + sum (map idSizeW rhs_fvs)) fvss
379 -- the arity of each rhs
380 arities = map (length . fst . collect []) rhss
382 -- This p', d' defn is safe because all the items being pushed
383 -- are ptrs, so all have size 1. d' and p' reflect the stack
384 -- after the closures have been allocated in the heap (but not
385 -- filled in), and pointers to them parked on the stack.
386 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n_binds 1)))
388 zipE = zipEqual "schemeE"
390 -- ToDo: don't build thunks for things with no free variables
391 build_thunk dd [] size bco off
392 = returnBc (PUSH_BCO bco
393 `consOL` unitOL (MKAP (off+size-1) size))
394 build_thunk dd (fv:fvs) size bco off = do
395 (push_code, pushed_szw) <- pushAtom dd p' (AnnVar fv)
396 more_push_code <- build_thunk (dd+pushed_szw) fvs size bco off
397 returnBc (push_code `appOL` more_push_code)
399 alloc_code = toOL (zipWith mkAlloc sizes arities)
400 where mkAlloc sz 0 = ALLOC_AP sz
401 mkAlloc sz arity = ALLOC_PAP arity sz
403 compile_bind d' fvs x rhs size off = do
404 bco <- schemeR fvs (x,rhs)
405 build_thunk d' fvs size bco off
408 [ compile_bind d' fvs x rhs size n
409 | (fvs, x, rhs, size, n) <-
410 zip5 fvss xs rhss sizes [n_binds, n_binds-1 .. 1]
413 body_code <- schemeE d' s p' body
414 thunk_codes <- sequence compile_binds
415 returnBc (alloc_code `appOL` concatOL thunk_codes `appOL` body_code)
419 schemeE d s p (AnnCase scrut bndr [(DataAlt dc, [bind1, bind2], rhs)])
420 | isUnboxedTupleCon dc && VoidRep == typePrimRep (idType bind1)
422 -- case .... of x { (# VoidRep'd-thing, a #) -> ... }
424 -- case .... of a { DEFAULT -> ... }
425 -- becuse the return convention for both are identical.
427 -- Note that it does not matter losing the void-rep thing from the
428 -- envt (it won't be bound now) because we never look such things up.
430 = --trace "automagic mashing of case alts (# VoidRep, a #)" $
431 doCase d s p scrut bind2 [(DEFAULT, [], rhs)] True{-unboxed tuple-}
433 | isUnboxedTupleCon dc && VoidRep == typePrimRep (idType bind2)
434 = --trace "automagic mashing of case alts (# a, VoidRep #)" $
435 doCase d s p scrut bind1 [(DEFAULT, [], rhs)] True{-unboxed tuple-}
437 schemeE d s p (AnnCase scrut bndr [(DataAlt dc, [bind1], rhs)])
438 | isUnboxedTupleCon dc
439 -- Similarly, convert
440 -- case .... of x { (# a #) -> ... }
442 -- case .... of a { DEFAULT -> ... }
443 = --trace "automagic mashing of case alts (# a #)" $
444 doCase d s p scrut bind1 [(DEFAULT, [], rhs)] True{-unboxed tuple-}
446 schemeE d s p (AnnCase scrut bndr alts)
447 = doCase d s p scrut bndr alts False{-not an unboxed tuple-}
449 schemeE d s p (AnnNote note (_, body))
453 = pprPanic "ByteCodeGen.schemeE: unhandled case"
454 (pprCoreExpr (deAnnotate' other))
457 -- Compile code to do a tail call. Specifically, push the fn,
458 -- slide the on-stack app back down to the sequel depth,
459 -- and enter. Four cases:
462 -- An application "GHC.Prim.tagToEnum# <type> unboxed-int".
463 -- The int will be on the stack. Generate a code sequence
464 -- to convert it to the relevant constructor, SLIDE and ENTER.
466 -- 1. The fn denotes a ccall. Defer to generateCCall.
468 -- 2. (Another nasty hack). Spot (# a::VoidRep, b #) and treat
469 -- it simply as b -- since the representations are identical
470 -- (the VoidRep takes up zero stack space). Also, spot
471 -- (# b #) and treat it as b.
473 -- 3. Application of a constructor, by defn saturated.
474 -- Split the args into ptrs and non-ptrs, and push the nonptrs,
475 -- then the ptrs, and then do PACK and RETURN.
477 -- 4. Otherwise, it must be a function call. Push the args
478 -- right to left, SLIDE and ENTER.
480 schemeT :: Int -- Stack depth
481 -> Sequel -- Sequel depth
482 -> BCEnv -- stack env
483 -> AnnExpr' Id VarSet
488 -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
489 -- = panic "schemeT ?!?!"
491 -- | trace ("\nschemeT\n" ++ showSDoc (pprCoreExpr (deAnnotate' app)) ++ "\n") False
495 | Just (arg, constr_names) <- maybe_is_tagToEnum_call
496 = pushAtom d p arg `thenBc` \ (push, arg_words) ->
497 implement_tagToId constr_names `thenBc` \ tagToId_sequence ->
498 returnBc (push `appOL` tagToId_sequence
499 `appOL` mkSLIDE 1 (d+arg_words-s)
503 | Just (CCall ccall_spec) <- isFCallId_maybe fn
504 = generateCCall d s p ccall_spec fn args_r_to_l
506 -- Case 2: Constructor application
507 | Just con <- maybe_saturated_dcon,
508 isUnboxedTupleCon con
509 = case args_r_to_l of
510 [arg1,arg2] | isVoidRepAtom arg1 ->
511 unboxedTupleReturn d s p arg2
512 [arg1,arg2] | isVoidRepAtom arg2 ->
513 unboxedTupleReturn d s p arg1
514 _other -> unboxedTupleException
516 -- Case 3: Ordinary data constructor
517 | Just con <- maybe_saturated_dcon
518 = mkConAppCode d s p con args_r_to_l `thenBc` \ alloc_con ->
519 returnBc (alloc_con `appOL`
520 mkSLIDE 1 (d - s) `snocOL`
523 -- Case 4: Tail call of function
525 = doTailCall d s p fn args_r_to_l
528 -- Detect and extract relevant info for the tagToEnum kludge.
529 maybe_is_tagToEnum_call
530 = let extract_constr_Names ty
531 = case splitTyConApp_maybe (repType ty) of
532 (Just (tyc, [])) | isDataTyCon tyc
533 -> map getName (tyConDataCons tyc)
534 other -> panic "maybe_is_tagToEnum_call.extract_constr_Ids"
537 (AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg)
538 -> case isPrimOpId_maybe v of
539 Just TagToEnumOp -> Just (snd arg, extract_constr_Names t)
543 -- Extract the args (R->L) and fn
544 -- The function will necessarily be a variable,
545 -- because we are compiling a tail call
546 (AnnVar fn, args_r_to_l) = splitApp app
548 -- Only consider this to be a constructor application iff it is
549 -- saturated. Otherwise, we'll call the constructor wrapper.
550 n_args = length args_r_to_l
552 = case isDataConId_maybe fn of
553 Just con | dataConRepArity con == n_args -> Just con
556 -- -----------------------------------------------------------------------------
557 -- Generate code to build a constructor application,
558 -- leaving it on top of the stack
560 mkConAppCode :: Int -> Sequel -> BCEnv
561 -> DataCon -- The data constructor
562 -> [AnnExpr' Id VarSet] -- Args, in *reverse* order
565 mkConAppCode orig_d s p con [] -- Nullary constructor
566 = ASSERT( isNullaryDataCon con )
567 returnBc (unitOL (PUSH_G (getName con)))
568 -- Instead of doing a PACK, which would allocate a fresh
569 -- copy of this constructor, use the single shared version.
570 -- The name of the constructor is the name of its wrapper function
572 mkConAppCode orig_d s p con args_r_to_l
573 = ASSERT( dataConRepArity con == length args_r_to_l )
574 do_pushery orig_d (non_ptr_args ++ ptr_args)
576 -- The args are already in reverse order, which is the way PACK
577 -- expects them to be. We must push the non-ptrs after the ptrs.
578 (ptr_args, non_ptr_args) = partition isPtrAtom args_r_to_l
580 do_pushery d (arg:args)
581 = pushAtom d p arg `thenBc` \ (push, arg_words) ->
582 do_pushery (d+arg_words) args `thenBc` \ more_push_code ->
583 returnBc (push `appOL` more_push_code)
585 = returnBc (unitOL (PACK con n_arg_words))
587 n_arg_words = d - orig_d
590 -- -----------------------------------------------------------------------------
591 -- Returning an unboxed tuple with one non-void component (the only
592 -- case we can handle).
594 -- Remember, we don't want to *evaluate* the component that is being
595 -- returned, even if it is a pointed type. We always just return.
598 :: Int -> Sequel -> BCEnv
599 -> AnnExpr' Id VarSet -> BcM BCInstrList
600 unboxedTupleReturn d s p arg = do
601 (push, sz) <- pushAtom d p arg
602 returnBc (push `appOL`
603 mkSLIDE sz (d-s) `snocOL`
604 RETURN_UBX (atomRep arg))
606 -- -----------------------------------------------------------------------------
607 -- Generate code for a tail-call
610 :: Int -> Sequel -> BCEnv
611 -> Id -> [AnnExpr' Id VarSet]
613 doTailCall init_d s p fn args
614 = do_pushes init_d args (map (primRepToArgRep.atomRep) args)
616 do_pushes d [] reps = do
618 (push_fn, sz) <- pushAtom d p (AnnVar fn)
620 returnBc (push_fn `appOL` (
621 mkSLIDE ((d-init_d) + 1) (init_d - s) `appOL`
623 do_pushes d args reps = do
624 let (push_apply, n, rest_of_reps) = findPushSeq reps
625 (these_args, rest_of_args) = splitAt n args
626 (next_d, push_code) <- push_seq d these_args
627 instrs <- do_pushes (next_d + 1) rest_of_args rest_of_reps
628 -- ^^^ for the PUSH_APPLY_ instruction
629 returnBc (push_code `appOL` (push_apply `consOL` instrs))
631 push_seq d [] = return (d, nilOL)
632 push_seq d (arg:args) = do
633 (push_code, sz) <- pushAtom d p arg
634 (final_d, more_push_code) <- push_seq (d+sz) args
635 return (final_d, push_code `appOL` more_push_code)
637 -- v. similar to CgStackery.findMatch, ToDo: merge
638 findPushSeq (RepP: RepP: RepP: RepP: RepP: RepP: RepP: rest)
639 = (PUSH_APPLY_PPPPPPP, 7, rest)
640 findPushSeq (RepP: RepP: RepP: RepP: RepP: RepP: rest)
641 = (PUSH_APPLY_PPPPPP, 6, rest)
642 findPushSeq (RepP: RepP: RepP: RepP: RepP: rest)
643 = (PUSH_APPLY_PPPPP, 5, rest)
644 findPushSeq (RepP: RepP: RepP: RepP: rest)
645 = (PUSH_APPLY_PPPP, 4, rest)
646 findPushSeq (RepP: RepP: RepP: rest)
647 = (PUSH_APPLY_PPP, 3, rest)
648 findPushSeq (RepP: RepP: rest)
649 = (PUSH_APPLY_PP, 2, rest)
650 findPushSeq (RepP: rest)
651 = (PUSH_APPLY_P, 1, rest)
652 findPushSeq (RepV: rest)
653 = (PUSH_APPLY_V, 1, rest)
654 findPushSeq (RepN: rest)
655 = (PUSH_APPLY_N, 1, rest)
656 findPushSeq (RepF: rest)
657 = (PUSH_APPLY_F, 1, rest)
658 findPushSeq (RepD: rest)
659 = (PUSH_APPLY_D, 1, rest)
660 findPushSeq (RepL: rest)
661 = (PUSH_APPLY_L, 1, rest)
663 = panic "ByteCodeGen.findPushSeq"
665 -- -----------------------------------------------------------------------------
668 doCase :: Int -> Sequel -> BCEnv
669 -> AnnExpr Id VarSet -> Id -> [AnnAlt Id VarSet]
670 -> Bool -- True <=> is an unboxed tuple case, don't enter the result
672 doCase d s p (_,scrut)
673 bndr alts is_unboxed_tuple
675 -- Top of stack is the return itbl, as usual.
676 -- underneath it is the pointer to the alt_code BCO.
677 -- When an alt is entered, it assumes the returned value is
678 -- on top of the itbl.
681 -- An unlifted value gets an extra info table pushed on top
682 -- when it is returned.
683 unlifted_itbl_sizeW | isAlgCase = 0
686 -- depth of stack after the return value has been pushed
687 d_bndr = d + ret_frame_sizeW + idSizeW bndr
689 -- depth of stack after the extra info table for an unboxed return
690 -- has been pushed, if any. This is the stack depth at the
692 d_alts = d_bndr + unlifted_itbl_sizeW
694 -- Env in which to compile the alts, not including
695 -- any vars bound by the alts themselves
696 p_alts = addToFM p bndr (d_bndr - 1)
698 bndr_ty = idType bndr
699 isAlgCase = not (isUnLiftedType bndr_ty) && not is_unboxed_tuple
701 -- given an alt, return a discr and code for it.
702 codeALt alt@(DEFAULT, _, (_,rhs))
703 = schemeE d_alts s p_alts rhs `thenBc` \ rhs_code ->
704 returnBc (NoDiscr, rhs_code)
705 codeAlt alt@(discr, bndrs, (_,rhs))
706 -- primitive or nullary constructor alt: no need to UNPACK
707 | null real_bndrs = do
708 rhs_code <- schemeE d_alts s p_alts rhs
709 returnBc (my_discr alt, rhs_code)
710 -- algebraic alt with some binders
711 | ASSERT(isAlgCase) otherwise =
713 (ptrs,nptrs) = partition (isFollowableRep.idPrimRep) real_bndrs
714 ptr_sizes = map idSizeW ptrs
715 nptrs_sizes = map idSizeW nptrs
716 bind_sizes = ptr_sizes ++ nptrs_sizes
717 size = sum ptr_sizes + sum nptrs_sizes
718 -- the UNPACK instruction unpacks in reverse order...
719 p' = addListToFM p_alts
720 (zip (reverse (ptrs ++ nptrs))
721 (mkStackOffsets d_alts (reverse bind_sizes)))
723 rhs_code <- schemeE (d_alts+size) s p' rhs
724 return (my_discr alt, unitOL (UNPACK size) `appOL` rhs_code)
726 real_bndrs = filter (not.isTyVar) bndrs
729 my_discr (DEFAULT, binds, rhs) = NoDiscr {-shouldn't really happen-}
730 my_discr (DataAlt dc, binds, rhs)
731 | isUnboxedTupleCon dc
732 = unboxedTupleException
734 = DiscrP (dataConTag dc - fIRST_TAG)
735 my_discr (LitAlt l, binds, rhs)
736 = case l of MachInt i -> DiscrI (fromInteger i)
737 MachFloat r -> DiscrF (fromRational r)
738 MachDouble r -> DiscrD (fromRational r)
739 MachChar i -> DiscrI i
740 _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
743 | not isAlgCase = Nothing
745 = case [dc | (DataAlt dc, _, _) <- alts] of
747 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
749 -- the bitmap is relative to stack depth d, i.e. before the
750 -- BCO, info table and return value are pushed on.
751 -- This bit of code is v. similar to buildLivenessMask in CgBindery,
752 -- except that here we build the bitmap from the known bindings of
753 -- things that are pointers, whereas in CgBindery the code builds the
754 -- bitmap from the free slots and unboxed bindings.
756 bitmap = intsToBitmap d{-size-} (sortLt (<) rel_slots)
759 rel_slots = concat (map spread binds)
761 | isFollowableRep (idPrimRep id) = [ rel_offset ]
763 where rel_offset = d - offset - 1
766 alt_stuff <- mapM codeAlt alts
767 alt_final <- mkMultiBranch maybe_ncons alt_stuff
769 alt_bco_name = getName bndr
770 alt_bco = mkProtoBCO alt_bco_name alt_final (Left alts)
771 0{-no arity-} d{-bitmap size-} bitmap
773 -- trace ("case: bndr = " ++ showSDocDebug (ppr bndr) ++ "\ndepth = " ++ show d ++ "\nenv = \n" ++ showSDocDebug (ppBCEnv p) ++
774 -- "\n bitmap = " ++ show bitmap) $ do
775 scrut_code <- schemeE (d + ret_frame_sizeW) (d + ret_frame_sizeW) p scrut
776 alt_bco' <- emitBc alt_bco
778 | isAlgCase = PUSH_ALTS alt_bco'
779 | otherwise = PUSH_ALTS_UNLIFTED alt_bco' (typePrimRep bndr_ty)
780 returnBc (push_alts `consOL` scrut_code)
783 -- -----------------------------------------------------------------------------
784 -- Deal with a CCall.
786 -- Taggedly push the args onto the stack R->L,
787 -- deferencing ForeignObj#s and (ToDo: adjusting addrs to point to
788 -- payloads in Ptr/Byte arrays). Then, generate the marshalling
789 -- (machine) code for the ccall, and create bytecodes to call that and
790 -- then return in the right way.
792 generateCCall :: Int -> Sequel -- stack and sequel depths
794 -> CCallSpec -- where to call
795 -> Id -- of target, for type info
796 -> [AnnExpr' Id VarSet] -- args (atoms)
799 generateCCall d0 s p ccall_spec@(CCallSpec target cconv safety) fn args_r_to_l
802 addr_sizeW = getPrimRepSize AddrRep
804 -- Get the args on the stack, with tags and suitably
805 -- dereferenced for the CCall. For each arg, return the
806 -- depth to the first word of the bits for that arg, and the
807 -- PrimRep of what was actually pushed.
809 pargs d [] = returnBc []
811 = let arg_ty = repType (exprType (deAnnotate' a))
813 in case splitTyConApp_maybe arg_ty of
814 -- Don't push the FO; instead push the Addr# it
817 | t == arrayPrimTyCon || t == mutableArrayPrimTyCon
818 -> pargs (d + addr_sizeW) az `thenBc` \ rest ->
819 parg_ArrayishRep arrPtrsHdrSize d p a
821 returnBc ((code,AddrRep):rest)
823 | t == byteArrayPrimTyCon || t == mutableByteArrayPrimTyCon
824 -> pargs (d + addr_sizeW) az `thenBc` \ rest ->
825 parg_ArrayishRep arrWordsHdrSize d p a
827 returnBc ((code,AddrRep):rest)
829 -- Default case: push taggedly, but otherwise intact.
831 -> pushAtom d p a `thenBc` \ (code_a, sz_a) ->
832 pargs (d+sz_a) az `thenBc` \ rest ->
833 returnBc ((code_a, atomRep a) : rest)
835 -- Do magic for Ptr/Byte arrays. Push a ptr to the array on
836 -- the stack but then advance it over the headers, so as to
837 -- point to the payload.
838 parg_ArrayishRep hdrSizeW d p a
839 = pushAtom d p a `thenBc` \ (push_fo, _) ->
840 -- The ptr points at the header. Advance it over the
841 -- header and then pretend this is an Addr#.
842 returnBc (push_fo `snocOL`
843 SWIZZLE 0 (hdrSizeW * getPrimRepSize WordRep
847 pargs d0 args_r_to_l `thenBc` \ code_n_reps ->
849 (pushs_arg, a_reps_pushed_r_to_l) = unzip code_n_reps
851 push_args = concatOL pushs_arg
852 d_after_args = d0 + sum (map getPrimRepSize a_reps_pushed_r_to_l)
854 | null a_reps_pushed_r_to_l || head a_reps_pushed_r_to_l /= VoidRep
855 = panic "ByteCodeGen.generateCCall: missing or invalid World token?"
857 = reverse (tail a_reps_pushed_r_to_l)
859 -- Now: a_reps_pushed_RAW are the reps which are actually on the stack.
860 -- push_args is the code to do that.
861 -- d_after_args is the stack depth once the args are on.
863 -- Get the result rep.
864 (returns_void, r_rep)
865 = case maybe_getCCallReturnRep (idType fn) of
866 Nothing -> (True, VoidRep)
867 Just rr -> (False, rr)
869 Because the Haskell stack grows down, the a_reps refer to
870 lowest to highest addresses in that order. The args for the call
871 are on the stack. Now push an unboxed Addr# indicating
872 the C function to call. Then push a dummy placeholder for the
873 result. Finally, emit a CCALL insn with an offset pointing to the
874 Addr# just pushed, and a literal field holding the mallocville
875 address of the piece of marshalling code we generate.
876 So, just prior to the CCALL insn, the stack looks like this
877 (growing down, as usual):
882 Addr# address_of_C_fn
883 <placeholder-for-result#> (must be an unboxed type)
885 The interpreter then calls the marshall code mentioned
886 in the CCALL insn, passing it (& <placeholder-for-result#>),
887 that is, the addr of the topmost word in the stack.
888 When this returns, the placeholder will have been
889 filled in. The placeholder is slid down to the sequel
890 depth, and we RETURN.
892 This arrangement makes it simple to do f-i-dynamic since the Addr#
893 value is the first arg anyway.
895 The marshalling code is generated specifically for this
896 call site, and so knows exactly the (Haskell) stack
897 offsets of the args, fn address and placeholder. It
898 copies the args to the C stack, calls the stacked addr,
899 and parks the result back in the placeholder. The interpreter
900 calls it as a normal C call, assuming it has a signature
901 void marshall_code ( StgWord* ptr_to_top_of_stack )
903 -- resolve static address
907 -> returnBc (False, panic "ByteCodeGen.generateCCall(dyn)")
909 -> ioToBc (lookupStaticPtr target) `thenBc` \res ->
912 -> pprPanic "ByteCodeGen.generateCCall: casm" (ppr ccall_spec)
914 get_target_info `thenBc` \ (is_static, static_target_addr) ->
917 -- Get the arg reps, zapping the leading Addr# in the dynamic case
918 a_reps -- | trace (showSDoc (ppr a_reps_pushed_RAW)) False = error "???"
919 | is_static = a_reps_pushed_RAW
920 | otherwise = if null a_reps_pushed_RAW
921 then panic "ByteCodeGen.generateCCall: dyn with no args"
922 else tail a_reps_pushed_RAW
925 (push_Addr, d_after_Addr)
927 = (toOL [PUSH_UBX (Right static_target_addr) addr_sizeW],
928 d_after_args + addr_sizeW)
929 | otherwise -- is already on the stack
930 = (nilOL, d_after_args)
932 -- Push the return placeholder. For a call returning nothing,
933 -- this is a VoidRep (tag).
934 r_sizeW = getPrimRepSize r_rep
935 d_after_r = d_after_Addr + r_sizeW
936 r_lit = mkDummyLiteral r_rep
937 push_r = (if returns_void
939 else unitOL (PUSH_UBX (Left r_lit) r_sizeW))
941 -- generate the marshalling code we're going to call
944 arg1_offW = r_sizeW + addr_sizeW
945 args_offW = map (arg1_offW +)
946 (init (scanl (+) 0 (map getPrimRepSize a_reps)))
948 ioToBc (mkMarshalCode cconv
949 (r_offW, r_rep) addr_offW
950 (zip args_offW a_reps)) `thenBc` \ addr_of_marshaller ->
951 recordMallocBc addr_of_marshaller `thenBc_`
953 -- Offset of the next stack frame down the stack. The CCALL
954 -- instruction needs to describe the chunk of stack containing
955 -- the ccall args to the GC, so it needs to know how large it
956 -- is. See comment in Interpreter.c with the CCALL instruction.
957 stk_offset = d_after_r - s
960 do_call = unitOL (CCALL stk_offset (castPtr addr_of_marshaller))
962 wrapup = mkSLIDE r_sizeW (d_after_r - r_sizeW - s)
963 `snocOL` RETURN_UBX r_rep
965 --trace (show (arg1_offW, args_offW , (map getPrimRepSize a_reps) )) $
968 push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup
972 -- Make a dummy literal, to be used as a placeholder for FFI return
973 -- values on the stack.
974 mkDummyLiteral :: PrimRep -> Literal
977 CharRep -> MachChar 0
979 WordRep -> MachWord 0
980 DoubleRep -> MachDouble 0
981 FloatRep -> MachFloat 0
982 AddrRep | getPrimRepSize AddrRep == getPrimRepSize WordRep -> MachWord 0
983 _ -> moan64 "mkDummyLiteral" (ppr pr)
987 -- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld
988 -- -> (# GHC.Prim.State# GHC.Prim.RealWorld, GHC.Prim.Int# #)
991 -- and check that an unboxed pair is returned wherein the first arg is VoidRep'd.
993 -- Alternatively, for call-targets returning nothing, convert
995 -- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld
996 -- -> (# GHC.Prim.State# GHC.Prim.RealWorld #)
1000 maybe_getCCallReturnRep :: Type -> Maybe PrimRep
1001 maybe_getCCallReturnRep fn_ty
1002 = let (a_tys, r_ty) = splitFunTys (dropForAlls fn_ty)
1004 = if isSingleton r_reps then Nothing else Just (r_reps !! 1)
1006 = case splitTyConApp_maybe (repType r_ty) of
1007 (Just (tyc, tys)) -> (tyc, map typePrimRep tys)
1009 ok = ( ( r_reps `lengthIs` 2 && VoidRep == head r_reps)
1010 || r_reps == [VoidRep] )
1011 && isUnboxedTupleTyCon r_tycon
1012 && case maybe_r_rep_to_go of
1014 Just r_rep -> r_rep /= PtrRep
1015 -- if it was, it would be impossible
1016 -- to create a valid return value
1017 -- placeholder on the stack
1018 blargh = pprPanic "maybe_getCCallReturn: can't handle:"
1021 --trace (showSDoc (ppr (a_reps, r_reps))) $
1022 if ok then maybe_r_rep_to_go else blargh
1024 -- Compile code which expects an unboxed Int on the top of stack,
1025 -- (call it i), and pushes the i'th closure in the supplied list
1026 -- as a consequence.
1027 implement_tagToId :: [Name] -> BcM BCInstrList
1028 implement_tagToId names
1029 = ASSERT( notNull names )
1030 getLabelsBc (length names) `thenBc` \ labels ->
1031 getLabelBc `thenBc` \ label_fail ->
1032 getLabelBc `thenBc` \ label_exit ->
1033 zip4 labels (tail labels ++ [label_fail])
1034 [0 ..] names `bind` \ infos ->
1035 map (mkStep label_exit) infos `bind` \ steps ->
1036 returnBc (concatOL steps
1038 toOL [LABEL label_fail, CASEFAIL, LABEL label_exit])
1040 mkStep l_exit (my_label, next_label, n, name_for_n)
1041 = toOL [LABEL my_label,
1042 TESTEQ_I n next_label,
1047 -- -----------------------------------------------------------------------------
1050 -- Push an atom onto the stack, returning suitable code & number of
1051 -- stack words used.
1053 -- The env p must map each variable to the highest- numbered stack
1054 -- slot for it. For example, if the stack has depth 4 and we
1055 -- tagged-ly push (v :: Int#) on it, the value will be in stack[4],
1056 -- the tag in stack[5], the stack will have depth 6, and p must map v
1057 -- to 5 and not to 4. Stack locations are numbered from zero, so a
1058 -- depth 6 stack has valid words 0 .. 5.
1060 pushAtom :: Int -> BCEnv -> AnnExpr' Id VarSet -> BcM (BCInstrList, Int)
1062 pushAtom d p (AnnApp f (_, AnnType _))
1063 = pushAtom d p (snd f)
1065 pushAtom d p (AnnNote note e)
1066 = pushAtom d p (snd e)
1068 pushAtom d p (AnnLam x e)
1070 = pushAtom d p (snd e)
1072 pushAtom d p (AnnVar v)
1074 | idPrimRep v == VoidRep
1075 = returnBc (nilOL, 0)
1078 = pprPanic "pushAtom: shouldn't get an FCallId here" (ppr v)
1080 | Just primop <- isPrimOpId_maybe v
1081 = returnBc (unitOL (PUSH_PRIMOP primop), 1)
1085 -- d - d_v the number of words between the TOS
1086 -- and the 1st slot of the object
1088 -- d - d_v - 1 the offset from the TOS of the 1st slot
1090 -- d - d_v - 1 + sz - 1 the offset from the TOS of the last slot
1093 -- Having found the last slot, we proceed to copy the right number of
1094 -- slots on to the top of the stack.
1097 = case lookupBCEnv_maybe p v of
1098 Just d_v -> (toOL (nOfThem sz (PUSH_L (d-d_v+sz-2))), sz)
1099 Nothing -> ASSERT(sz == 1) (unitOL (PUSH_G nm), sz)
1101 nm = case isDataConId_maybe v of
1103 Nothing -> getName v
1110 pushAtom d p (AnnLit lit)
1112 MachLabel fs -> code CodePtrRep
1113 MachWord w -> code WordRep
1114 MachInt i -> code IntRep
1115 MachFloat r -> code FloatRep
1116 MachDouble r -> code DoubleRep
1117 MachChar c -> code CharRep
1118 MachStr s -> pushStr s
1121 = let size_host_words = getPrimRepSize rep
1122 in returnBc (unitOL (PUSH_UBX (Left lit) size_host_words),
1126 = let getMallocvilleAddr
1128 FastString _ l ba ->
1129 -- sigh, a string in the heap is no good to us.
1130 -- We need a static C pointer, since the type of
1131 -- a string literal is Addr#. So, copy the string
1132 -- into C land and remember the pointer so we can
1135 -- CAREFUL! Chars are 32 bits in ghc 4.09+
1136 in ioToBc (mallocBytes (n+1)) `thenBc` \ ptr ->
1137 recordMallocBc ptr `thenBc_`
1139 do memcpy ptr ba (fromIntegral n)
1140 pokeByteOff ptr n (fromIntegral (ord '\0') :: Word8)
1143 other -> panic "ByteCodeGen.pushAtom.pushStr"
1145 getMallocvilleAddr `thenBc` \ addr ->
1146 -- Get the addr on the stack, untaggedly
1147 returnBc (unitOL (PUSH_UBX (Right addr) 1), 1)
1150 = pprPanic "ByteCodeGen.pushAtom"
1151 (pprCoreExpr (deAnnotate (undefined, other)))
1153 foreign import ccall unsafe "memcpy"
1154 memcpy :: Ptr a -> ByteArray# -> CInt -> IO ()
1157 -- -----------------------------------------------------------------------------
1158 -- Given a bunch of alts code and their discrs, do the donkey work
1159 -- of making a multiway branch using a switch tree.
1160 -- What a load of hassle!
1162 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
1163 -- a hint; generates better code
1164 -- Nothing is always safe
1165 -> [(Discr, BCInstrList)]
1167 mkMultiBranch maybe_ncons raw_ways
1168 = let d_way = filter (isNoDiscr.fst) raw_ways
1169 notd_ways = naturalMergeSortLe
1170 (\w1 w2 -> leAlt (fst w1) (fst w2))
1171 (filter (not.isNoDiscr.fst) raw_ways)
1173 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
1174 mkTree [] range_lo range_hi = returnBc the_default
1176 mkTree [val] range_lo range_hi
1177 | range_lo `eqAlt` range_hi
1178 = returnBc (snd val)
1180 = getLabelBc `thenBc` \ label_neq ->
1181 returnBc (mkTestEQ (fst val) label_neq
1183 `appOL` unitOL (LABEL label_neq)
1184 `appOL` the_default))
1186 mkTree vals range_lo range_hi
1187 = let n = length vals `div` 2
1188 vals_lo = take n vals
1189 vals_hi = drop n vals
1190 v_mid = fst (head vals_hi)
1192 getLabelBc `thenBc` \ label_geq ->
1193 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
1194 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
1195 returnBc (mkTestLT v_mid label_geq
1197 `appOL` unitOL (LABEL label_geq)
1201 = case d_way of [] -> unitOL CASEFAIL
1204 -- None of these will be needed if there are no non-default alts
1205 (mkTestLT, mkTestEQ, init_lo, init_hi)
1207 = panic "mkMultiBranch: awesome foursome"
1209 = case fst (head notd_ways) of {
1210 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
1211 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
1214 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
1215 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
1218 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
1219 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
1222 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
1223 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
1225 DiscrP algMaxBound )
1228 (algMinBound, algMaxBound)
1229 = case maybe_ncons of
1230 Just n -> (0, n - 1)
1231 Nothing -> (minBound, maxBound)
1233 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
1234 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
1235 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
1236 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
1237 NoDiscr `eqAlt` NoDiscr = True
1240 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
1241 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
1242 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
1243 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
1244 NoDiscr `leAlt` NoDiscr = True
1247 isNoDiscr NoDiscr = True
1250 dec (DiscrI i) = DiscrI (i-1)
1251 dec (DiscrP i) = DiscrP (i-1)
1252 dec other = other -- not really right, but if you
1253 -- do cases on floating values, you'll get what you deserve
1255 -- same snotty comment applies to the following
1257 minD, maxD :: Double
1263 mkTree notd_ways init_lo init_hi
1266 -- -----------------------------------------------------------------------------
1267 -- Supporting junk for the compilation schemes
1269 -- Describes case alts
1277 instance Outputable Discr where
1278 ppr (DiscrI i) = int i
1279 ppr (DiscrF f) = text (show f)
1280 ppr (DiscrD d) = text (show d)
1281 ppr (DiscrP i) = int i
1282 ppr NoDiscr = text "DEF"
1285 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
1286 lookupBCEnv_maybe = lookupFM
1288 idSizeW :: Id -> Int
1289 idSizeW id = getPrimRepSize (typePrimRep (idType id))
1291 unboxedTupleException :: a
1292 unboxedTupleException
1295 ("Bytecode generator can't handle unboxed tuples. Possibly due\n" ++
1296 "\tto foreign import/export decls in source. Workaround:\n" ++
1297 "\tcompile this module to a .o file, then restart session."))
1300 mkSLIDE n d = if d == 0 then nilOL else unitOL (SLIDE n d)
1303 splitApp :: AnnExpr' id ann -> (AnnExpr' id ann, [AnnExpr' id ann])
1304 -- The arguments are returned in *right-to-left* order
1305 splitApp (AnnApp (_,f) (_,a))
1306 | isTypeAtom a = splitApp f
1307 | otherwise = case splitApp f of
1308 (f', as) -> (f', a:as)
1309 splitApp (AnnNote n (_,e)) = splitApp e
1310 splitApp e = (e, [])
1313 isTypeAtom :: AnnExpr' id ann -> Bool
1314 isTypeAtom (AnnType _) = True
1315 isTypeAtom _ = False
1317 isVoidRepAtom :: AnnExpr' id ann -> Bool
1318 isVoidRepAtom (AnnVar v) = typePrimRep (idType v) == VoidRep
1319 isVoidRepAtom (AnnNote n (_,e)) = isVoidRepAtom e
1320 isVoidRepAtom _ = False
1322 atomRep :: AnnExpr' Id ann -> PrimRep
1323 atomRep (AnnVar v) = typePrimRep (idType v)
1324 atomRep (AnnLit l) = literalPrimRep l
1325 atomRep (AnnNote n b) = atomRep (snd b)
1326 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
1327 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
1328 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
1330 isPtrAtom :: AnnExpr' Id ann -> Bool
1331 isPtrAtom e = isFollowableRep (atomRep e)
1333 -- Let szsw be the sizes in words of some items pushed onto the stack,
1334 -- which has initial depth d'. Return the values which the stack environment
1335 -- should map these items to.
1336 mkStackOffsets :: Int -> [Int] -> [Int]
1337 mkStackOffsets original_depth szsw
1338 = map (subtract 1) (tail (scanl (+) original_depth szsw))
1340 -- -----------------------------------------------------------------------------
1341 -- The bytecode generator's monad
1345 nextlabel :: Int, -- for generating local labels
1346 malloced :: [Ptr ()] } -- ptrs malloced for current BCO
1347 -- Should be free()d when it is GCd
1349 newtype BcM r = BcM (BcM_State -> IO (BcM_State, r))
1351 ioToBc :: IO a -> BcM a
1352 ioToBc io = BcM $ \st -> do
1356 runBc :: BcM r -> IO (BcM_State, r)
1357 runBc (BcM m) = m (BcM_State 0 [])
1359 thenBc :: BcM a -> (a -> BcM b) -> BcM b
1360 thenBc (BcM expr) cont = BcM $ \st0 -> do
1361 (st1, q) <- expr st0
1366 thenBc_ :: BcM a -> BcM b -> BcM b
1367 thenBc_ (BcM expr) (BcM cont) = BcM $ \st0 -> do
1368 (st1, q) <- expr st0
1369 (st2, r) <- cont st1
1372 returnBc :: a -> BcM a
1373 returnBc result = BcM $ \st -> (return (st, result))
1375 instance Monad BcM where
1380 emitBc :: ([Ptr ()] -> ProtoBCO Name) -> BcM (ProtoBCO Name)
1382 = BcM $ \st -> return (st{malloced=[]}, bco (malloced st))
1384 recordMallocBc :: Ptr a -> BcM ()
1386 = BcM $ \st -> return (st{malloced = castPtr a : malloced st}, ())
1388 getLabelBc :: BcM Int
1390 = BcM $ \st -> return (st{nextlabel = 1 + nextlabel st}, nextlabel st)
1392 getLabelsBc :: Int -> BcM [Int]
1394 = BcM $ \st -> let ctr = nextlabel st
1395 in return (st{nextlabel = ctr+n}, [ctr .. ctr+n-1])