2 % (c) The University of Glasgow 2000
4 \section[ByteCodeGen]{Generate bytecode from Core}
7 module ByteCodeGen ( UnlinkedBCO, UnlinkedBCOExpr, ItblEnv, ClosureEnv, HValue,
9 byteCodeGen, coreExprToBCOs
12 #include "HsVersions.h"
15 import Name ( Name, getName )
16 import Id ( Id, idType, isDataConId_maybe, isPrimOpId_maybe,
17 idPrimRep, mkSysLocal, idName )
18 import OrdList ( OrdList, consOL, snocOL, appOL, unitOL,
19 nilOL, toOL, concatOL, fromOL )
20 import FiniteMap ( FiniteMap, addListToFM, listToFM,
21 addToFM, lookupFM, fmToList )
23 import PprCore ( pprCoreExpr )
24 import Literal ( Literal(..), literalPrimRep )
25 import PrimRep ( PrimRep(..) )
26 import PrimOp ( PrimOp(..) )
27 import CoreFVs ( freeVars )
28 import Type ( typePrimRep, splitTyConApp_maybe )
29 import DataCon ( dataConTag, fIRST_TAG, dataConTyCon,
30 dataConWrapId, isUnboxedTupleCon )
31 import TyCon ( TyCon(..), tyConFamilySize, isDataTyCon, tyConDataCons )
32 import Class ( Class, classTyCon )
33 import Util ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem )
34 import Var ( isTyVar )
35 import VarSet ( VarSet, varSetElems )
36 import PrimRep ( getPrimRepSize, isFollowableRep )
37 import CmdLineOpts ( DynFlags, DynFlag(..) )
38 import ErrUtils ( showPass, dumpIfSet_dyn )
39 import Unique ( mkPseudoUnique3 )
40 import FastString ( FastString(..) )
41 import Panic ( GhcException(..) )
42 import PprType ( pprType )
43 import ByteCodeInstr ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO, bciStackUse )
44 import ByteCodeItbls ( ItblEnv, mkITbls )
45 import ByteCodeLink ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
46 ClosureEnv, HValue, filterNameMap,
47 iNTERP_STACK_CHECK_THRESH )
49 import List ( intersperse, sortBy, zip4 )
50 import Foreign ( Ptr(..), mallocBytes )
51 import Addr ( Addr(..), addrToInt, writeCharOffAddr )
52 import CTypes ( CInt )
53 import Exception ( throwDyn )
55 import PrelBase ( Int(..) )
56 import PrelGHC ( ByteArray# )
57 import IOExts ( unsafePerformIO )
58 import PrelIOBase ( IO(..) )
62 %************************************************************************
64 \subsection{Functions visible from outside this module.}
66 %************************************************************************
70 byteCodeGen :: DynFlags
73 -> IO ([UnlinkedBCO], ItblEnv)
74 byteCodeGen dflags binds local_tycons local_classes
75 = do showPass dflags "ByteCodeGen"
76 let tycs = local_tycons ++ map classTyCon local_classes
77 itblenv <- mkITbls tycs
79 let flatBinds = concatMap getBind binds
80 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
81 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
82 final_state = runBc (BcM_State [] 0)
83 (mapBc (schemeR True) flatBinds
84 `thenBc_` returnBc ())
85 (BcM_State proto_bcos final_ctr) = final_state
87 dumpIfSet_dyn dflags Opt_D_dump_BCOs
88 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
90 bcos <- mapM assembleBCO proto_bcos
92 return (bcos, itblenv)
95 -- Returns: (the root BCO for this expression,
96 -- a list of auxilary BCOs resulting from compiling closures)
97 coreExprToBCOs :: DynFlags
100 coreExprToBCOs dflags expr
101 = do showPass dflags "ByteCodeGen"
103 -- create a totally bogus name for the top-level BCO; this
104 -- should be harmless, since it's never used for anything
105 let invented_id = mkSysLocal SLIT("Expr-Top-Level") (mkPseudoUnique3 0)
106 (panic "invented_id's type")
107 let invented_name = idName invented_id
109 let (BcM_State all_proto_bcos final_ctr)
110 = runBc (BcM_State [] 0)
111 (schemeR True (invented_id, freeVars expr))
112 dumpIfSet_dyn dflags Opt_D_dump_BCOs
113 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
116 = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
117 [root_bco] -> root_bco
119 = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
121 auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
122 root_bco <- assembleBCO root_proto_bco
124 return (root_bco, auxiliary_bcos)
127 %************************************************************************
129 \subsection{Compilation schema for the bytecode generator.}
131 %************************************************************************
135 type BCInstrList = OrdList BCInstr
137 type Sequel = Int -- back off to this depth before ENTER
139 -- Maps Ids to the offset from the stack _base_ so we don't have
140 -- to mess with it after each push/pop.
141 type BCEnv = FiniteMap Id Int -- To find vars on the stack
143 ppBCEnv :: BCEnv -> SDoc
146 $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
149 pp_one (var, offset) = int offset <> colon <+> ppr var
150 cmp_snd x y = compare (snd x) (snd y)
152 -- Create a BCO and do a spot of peephole optimisation on the insns
154 mkProtoBCO nm instrs_ordlist origin
155 = ProtoBCO nm maybe_with_stack_check origin
157 -- Overestimate the stack usage (in words) of this BCO,
158 -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
159 -- stack check. (The interpreter always does a stack check
160 -- for iNTERP_STACK_CHECK_THRESH words at the start of each
161 -- BCO anyway, so we only need to add an explicit on in the
162 -- (hopefully rare) cases when the (overestimated) stack use
163 -- exceeds iNTERP_STACK_CHECK_THRESH.
164 maybe_with_stack_check
165 | stack_overest >= 65535
166 = pprPanic "mkProtoBCO: stack use won't fit in 16 bits"
168 | stack_overest >= iNTERP_STACK_CHECK_THRESH
169 = (STKCHECK stack_overest) : peep_d
171 = peep_d -- the supposedly common case
173 stack_overest = sum (map bciStackUse peep_d)
174 + 10 {- just to be really really sure -}
177 -- Merge local pushes
178 peep_d = peep (fromOL instrs_ordlist)
180 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
181 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
182 peep (PUSH_L off1 : PUSH_L off2 : rest)
183 = PUSH_LL off1 (off2-1) : peep rest
190 -- Compile code for the right hand side of a let binding.
191 -- Park the resulting BCO in the monad. Also requires the
192 -- variable to which this value was bound, so as to give the
193 -- resulting BCO a name. Bool indicates top-levelness.
195 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
196 schemeR is_top (nm, rhs)
200 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
201 $$ pprCoreExpr (deAnnotate rhs)
207 = schemeR_wrk is_top rhs nm (collect [] rhs)
210 collect xs (_, AnnNote note e)
212 collect xs (_, AnnLam x e)
213 = collect (if isTyVar x then xs else (x:xs)) e
214 collect xs not_lambda
215 = (reverse xs, not_lambda)
217 schemeR_wrk is_top original_body nm (args, body)
218 | Just dcon <- maybe_toplevel_null_con_rhs
219 = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
220 emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
221 (Right original_body))
225 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
226 all_args = reverse args ++ fvs
227 szsw_args = map taggedIdSizeW all_args
228 szw_args = sum szsw_args
229 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
230 argcheck = unitOL (ARGCHECK szw_args)
232 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
233 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code)
234 (Right original_body))
237 maybe_toplevel_null_con_rhs
238 | is_top && null args
241 -> case isDataConId_maybe v_wrk of
243 Just dc_wrk | nm == dataConWrapId dc_wrk
251 -- Let szsw be the sizes in words of some items pushed onto the stack,
252 -- which has initial depth d'. Return the values which the stack environment
253 -- should map these items to.
254 mkStackOffsets :: Int -> [Int] -> [Int]
255 mkStackOffsets original_depth szsw
256 = map (subtract 1) (tail (scanl (+) original_depth szsw))
258 -- Compile code to apply the given expression to the remaining args
259 -- on the stack, returning a HNF.
260 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
262 -- Delegate tail-calls to schemeT.
263 schemeE d s p e@(fvs, AnnApp f a)
264 = schemeT d s p (fvs, AnnApp f a)
265 schemeE d s p e@(fvs, AnnVar v)
266 | isFollowableRep v_rep
267 = schemeT d s p (fvs, AnnVar v)
270 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
271 let (push, szw) = pushAtom True d p (AnnVar v)
272 in returnBc (push -- value onto stack
273 `appOL` mkSLIDE szw (d-s) -- clear to sequel
274 `snocOL` RETURN v_rep) -- go
276 v_rep = typePrimRep (idType v)
278 schemeE d s p (fvs, AnnLit literal)
279 = let (push, szw) = pushAtom True d p (AnnLit literal)
280 l_rep = literalPrimRep literal
281 in returnBc (push -- value onto stack
282 `appOL` mkSLIDE szw (d-s) -- clear to sequel
283 `snocOL` RETURN l_rep) -- go
285 schemeE d s p (fvs, AnnLet binds b)
286 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
287 AnnRec xs_n_rhss -> unzip xs_n_rhss
289 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
291 -- Sizes of tagged free vars, + 1 for the fn
292 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
294 -- This p', d' defn is safe because all the items being pushed
295 -- are ptrs, so all have size 1. d' and p' reflect the stack
296 -- after the closures have been allocated in the heap (but not
297 -- filled in), and pointers to them parked on the stack.
298 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
301 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
302 zipE = zipEqual "schemeE"
303 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
305 -- ToDo: don't build thunks for things with no free variables
306 buildThunk dd ([], size, id, off)
307 = PUSH_G (Left (getName id))
308 `consOL` unitOL (MKAP (off+size-1) size)
309 buildThunk dd ((fv:fvs), size, id, off)
310 = case pushAtom True dd p' (AnnVar fv) of
311 (push_code, pushed_szw)
313 buildThunk (dd+pushed_szw) (fvs, size, id, off)
315 thunkCode = concatOL (map (buildThunk d') infos)
316 allocCode = toOL (map ALLOC sizes)
318 schemeE d' s p' b `thenBc` \ bodyCode ->
319 mapBc (schemeR False) (zip xs rhss) `thenBc_`
320 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
323 schemeE d s p (fvs, AnnCase scrut bndr alts)
325 -- Top of stack is the return itbl, as usual.
326 -- underneath it is the pointer to the alt_code BCO.
327 -- When an alt is entered, it assumes the returned value is
328 -- on top of the itbl.
331 -- Env and depth in which to compile the alts, not including
332 -- any vars bound by the alts themselves
333 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
334 p' = addToFM p bndr (d' - 1)
336 scrut_primrep = typePrimRep (idType bndr)
338 = case scrut_primrep of
339 CharRep -> False ; AddrRep -> False ; WordRep -> False
340 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
343 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
345 -- given an alt, return a discr and code for it.
346 codeAlt alt@(discr, binds_f, rhs)
348 = let (unpack_code, d_after_unpack, p_after_unpack)
349 = mkUnpackCode binds_f d' p'
350 in schemeE d_after_unpack s p_after_unpack rhs
351 `thenBc` \ rhs_code ->
352 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
354 = ASSERT(null binds_f)
355 schemeE d' s p' rhs `thenBc` \ rhs_code ->
356 returnBc (my_discr alt, rhs_code)
358 my_discr (DEFAULT, binds, rhs) = NoDiscr
359 my_discr (DataAlt dc, binds, rhs)
360 | isUnboxedTupleCon dc
361 = unboxedTupleException
363 = DiscrP (dataConTag dc - fIRST_TAG)
364 my_discr (LitAlt l, binds, rhs)
365 = case l of MachInt i -> DiscrI (fromInteger i)
366 MachFloat r -> DiscrF (fromRational r)
367 MachDouble r -> DiscrD (fromRational r)
368 MachChar i -> DiscrI i
369 _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
372 | not isAlgCase = Nothing
374 = case [dc | (DataAlt dc, _, _) <- alts] of
376 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
379 mapBc codeAlt alts `thenBc` \ alt_stuff ->
380 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
382 alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
383 alt_bco_name = getName bndr
384 alt_bco = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
386 schemeE (d + ret_frame_sizeW)
387 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
389 emitBc alt_bco `thenBc_`
390 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
393 schemeE d s p (fvs, AnnNote note body)
397 = pprPanic "ByteCodeGen.schemeE: unhandled case"
398 (pprCoreExpr (deAnnotate other))
401 -- Compile code to do a tail call. Specifically, push the fn,
402 -- slide the on-stack app back down to the sequel depth,
403 -- and enter. Four cases:
406 -- An application "PrelGHC.tagToEnum# <type> unboxed-int".
407 -- The int will be on the stack. Generate a code sequence
408 -- to convert it to the relevant constructor, SLIDE and ENTER.
410 -- 1. A nullary constructor. Push its closure on the stack
411 -- and SLIDE and RETURN.
413 -- 2. Application of a non-nullary constructor, by defn saturated.
414 -- Split the args into ptrs and non-ptrs, and push the nonptrs,
415 -- then the ptrs, and then do PACK and RETURN.
417 -- 3. Otherwise, it must be a function call. Push the args
418 -- right to left, SLIDE and ENTER.
420 schemeT :: Int -- Stack depth
421 -> Sequel -- Sequel depth
422 -> BCEnv -- stack env
427 -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
428 -- = panic "schemeT ?!?!"
431 | Just (arg, constr_names) <- maybe_is_tagToEnum_call
432 = pushAtom True d p arg `bind` \ (push, arg_words) ->
433 implement_tagToId constr_names `thenBc` \ tagToId_sequence ->
434 returnBc (push `appOL` tagToId_sequence
435 `appOL` mkSLIDE 1 (d+arg_words-s)
439 | is_con_call && null args_r_to_l
441 (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
447 = if is_con_call && isUnboxedTupleCon con
448 then returnBc unboxedTupleException
452 -- Detect and extract relevant info for the tagToEnum kludge.
453 maybe_is_tagToEnum_call
454 = let extract_constr_Names ty
455 = case splitTyConApp_maybe ty of
456 (Just (tyc, [])) | isDataTyCon tyc
457 -> map getName (tyConDataCons tyc)
459 -> panic "maybe_is_tagToEnum_call.extract_constr_Ids"
462 (_, AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg)
463 -> case isPrimOpId_maybe v of
465 Just primop | primop == TagToEnumOp
466 -> Just (snd arg, extract_constr_Names t)
471 -- Extract the args (R->L) and fn
472 (args_r_to_l_raw, fn) = chomp app
476 AnnApp f a -> case chomp f of (az, f) -> (snd a:az, f)
477 AnnNote n e -> chomp e
478 other -> pprPanic "schemeT"
479 (ppr (deAnnotate (panic "schemeT.chomp", other)))
481 args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
482 isTypeAtom (AnnType _) = True
485 -- decide if this is a constructor call, and rearrange
486 -- args appropriately.
487 maybe_dcon = isDataConId_maybe fn
488 is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
489 (Just con) = maybe_dcon
495 = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
496 where isPtr = isFollowableRep . atomRep
498 -- make code to push the args and then do the SLIDE-ENTER thing
499 code = do_pushery d args_final_r_to_l
501 tag_when_push = not is_con_call
502 narg_words = sum (map (get_arg_szw . atomRep) args_r_to_l)
503 get_arg_szw = if tag_when_push then taggedSizeW else untaggedSizeW
505 do_pushery d (arg:args)
506 = let (push, arg_words) = pushAtom tag_when_push d p arg
507 in push `appOL` do_pushery (d+arg_words) args
510 Just con -> PACK con narg_words `consOL` (
511 mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
513 -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
515 `appOL` mkSLIDE (narg_words+arg_words)
520 = if d == 0 then nilOL else unitOL (SLIDE n d)
525 atomRep (AnnVar v) = typePrimRep (idType v)
526 atomRep (AnnLit l) = literalPrimRep l
527 atomRep (AnnNote n b) = atomRep (snd b)
528 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
529 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
530 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
533 -- Compile code which expects an unboxed Int on the top of stack,
534 -- (call it i), and pushes the i'th closure in the supplied list
536 implement_tagToId :: [Name] -> BcM BCInstrList
537 implement_tagToId names
538 = ASSERT(not (null names))
539 getLabelsBc (length names) `thenBc` \ labels ->
540 getLabelBc `thenBc` \ label_fail ->
541 getLabelBc `thenBc` \ label_exit ->
542 zip4 labels (tail labels ++ [label_fail])
543 [0 ..] names `bind` \ infos ->
544 map (mkStep label_exit) infos `bind` \ steps ->
545 returnBc (concatOL steps
547 toOL [LABEL label_fail, CASEFAIL, LABEL label_exit])
549 mkStep l_exit (my_label, next_label, n, name_for_n)
550 = toOL [LABEL my_label,
551 TESTEQ_I n next_label,
552 PUSH_G (Left name_for_n),
556 -- Make code to unpack the top-of-stack constructor onto the stack,
557 -- adding tags for the unboxed bits. Takes the PrimReps of the
558 -- constructor's arguments. off_h and off_s are travelling offsets
559 -- along the constructor and the stack.
561 -- Supposing a constructor in the heap has layout
563 -- Itbl p_1 ... p_i np_1 ... np_j
565 -- then we add to the stack, shown growing down, the following:
577 -- so that in the common case (ptrs only) a single UNPACK instr can
578 -- copy all the payload of the constr onto the stack with no further ado.
580 mkUnpackCode :: [Id] -- constr args
581 -> Int -- depth before unpack
582 -> BCEnv -- env before unpack
583 -> (BCInstrList, Int, BCEnv)
584 mkUnpackCode vars d p
585 = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
586 -- ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
588 (code_p `appOL` code_np, d', p')
592 vreps = [(var, typePrimRep (idType var)) | var <- vars]
594 -- ptrs and nonptrs, forward
595 vreps_p = filter (isFollowableRep.snd) vreps
596 vreps_np = filter (not.isFollowableRep.snd) vreps
598 -- the order in which we will augment the environment
599 vreps_env = reverse vreps_p ++ reverse vreps_np
602 vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
603 p' = addListToFM p (zip (map fst vreps_env)
604 (mkStackOffsets d vreps_env_tszsw))
605 d' = d + sum vreps_env_tszsw
607 -- code to unpack the ptrs
608 ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
609 code_p | null vreps_p = nilOL
610 | otherwise = unitOL (UNPACK ptrs_szw)
612 -- code to unpack the nonptrs
613 vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
614 code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
615 do_nptrs off_h off_s [] = nilOL
616 do_nptrs off_h off_s (npr:nprs)
618 IntRep -> approved ; FloatRep -> approved
619 DoubleRep -> approved ; AddrRep -> approved
621 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
623 approved = UPK_TAG usizeW (off_h-usizeW) off_s `consOL` theRest
624 theRest = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
625 usizeW = untaggedSizeW npr
626 tsizeW = taggedSizeW npr
629 -- Push an atom onto the stack, returning suitable code & number of
630 -- stack words used. Pushes it either tagged or untagged, since
631 -- pushAtom is used to set up the stack prior to copying into the
632 -- heap for both APs (requiring tags) and constructors (which don't).
634 -- NB this means NO GC between pushing atoms for a constructor and
635 -- copying them into the heap. It probably also means that
636 -- tail calls MUST be of the form atom{atom ... atom} since if the
637 -- expression head was allowed to be arbitrary, there could be GC
638 -- in between pushing the arg atoms and completing the head.
639 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
640 -- isn't a problem; but only if arbitrary graph construction for the
641 -- head doesn't leave this BCO, since GC might happen at the start of
642 -- each BCO (we consult doYouWantToGC there).
644 -- Blargh. JRS 001206
646 -- NB (further) that the env p must map each variable to the highest-
647 -- numbered stack slot for it. For example, if the stack has depth 4
648 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
649 -- the tag in stack[5], the stack will have depth 6, and p must map v to
650 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
651 -- 6 stack has valid words 0 .. 5.
653 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
654 pushAtom tagged d p (AnnVar v)
656 | idPrimRep v == VoidRep
658 (unitOL (PUSH_TAG 0), 1)
660 | Just primop <- isPrimOpId_maybe v
662 CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
663 other -> (unitOL (PUSH_G (Right primop)), 1)
666 = let str = "\npushAtom " ++ showSDocDebug (ppr v)
667 ++ " :: " ++ showSDocDebug (pprType (idType v))
668 ++ ", depth = " ++ show d
669 ++ ", tagged = " ++ show tagged ++ ", env =\n" ++
670 showSDocDebug (ppBCEnv p)
671 ++ " --> words: " ++ show (snd result) ++ "\n" ++
672 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
673 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
675 cmp_snd x y = compare (snd x) (snd y)
676 str' = if str == str then str else str
679 = case lookupBCEnv_maybe p v of
680 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
681 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
683 nm = case isDataConId_maybe v of
687 sz_t = taggedIdSizeW v
688 sz_u = untaggedIdSizeW v
689 nwords = if tagged then sz_t else sz_u
694 pushAtom True d p (AnnLit lit)
695 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
696 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
698 pushAtom False d p (AnnLit lit)
700 MachWord w -> code WordRep
701 MachInt i -> code IntRep
702 MachFloat r -> code FloatRep
703 MachDouble r -> code DoubleRep
704 MachChar c -> code CharRep
705 MachStr s -> pushStr s
708 = let size_host_words = untaggedSizeW rep
709 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
712 = let mallocvilleAddr
717 -- sigh, a string in the heap is no good to us.
718 -- We need a static C pointer, since the type of
719 -- a string literal is Addr#. So, copy the string
720 -- into C land and introduce a memory leak
723 -- CAREFUL! Chars are 32 bits in ghc 4.09+
725 do (Ptr a#) <- mallocBytes (n+1)
726 strncpy (Ptr a#) ba (fromIntegral n)
727 writeCharOffAddr (A# a#) n '\0'
730 _ -> panic "StgInterp.lit2expr: unhandled string constant type"
733 = MachInt (toInteger (addrToInt mallocvilleAddr))
735 -- Get the addr on the stack, untaggedly
736 (unitOL (PUSH_UBX addrLit 1), 1)
742 pushAtom tagged d p (AnnApp f (_, AnnType _))
743 = pushAtom tagged d p (snd f)
745 pushAtom tagged d p (AnnNote note e)
746 = pushAtom tagged d p (snd e)
748 pushAtom tagged d p (AnnLam x e)
750 = pushAtom tagged d p (snd e)
752 pushAtom tagged d p other
753 = pprPanic "ByteCodeGen.pushAtom"
754 (pprCoreExpr (deAnnotate (undefined, other)))
756 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
759 -- Given a bunch of alts code and their discrs, do the donkey work
760 -- of making a multiway branch using a switch tree.
761 -- What a load of hassle!
762 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
763 -- a hint; generates better code
764 -- Nothing is always safe
765 -> [(Discr, BCInstrList)]
767 mkMultiBranch maybe_ncons raw_ways
768 = let d_way = filter (isNoDiscr.fst) raw_ways
769 notd_ways = naturalMergeSortLe
770 (\w1 w2 -> leAlt (fst w1) (fst w2))
771 (filter (not.isNoDiscr.fst) raw_ways)
773 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
774 mkTree [] range_lo range_hi = returnBc the_default
776 mkTree [val] range_lo range_hi
777 | range_lo `eqAlt` range_hi
780 = getLabelBc `thenBc` \ label_neq ->
781 returnBc (mkTestEQ (fst val) label_neq
783 `appOL` unitOL (LABEL label_neq)
784 `appOL` the_default))
786 mkTree vals range_lo range_hi
787 = let n = length vals `div` 2
788 vals_lo = take n vals
789 vals_hi = drop n vals
790 v_mid = fst (head vals_hi)
792 getLabelBc `thenBc` \ label_geq ->
793 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
794 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
795 returnBc (mkTestLT v_mid label_geq
797 `appOL` unitOL (LABEL label_geq)
801 = case d_way of [] -> unitOL CASEFAIL
804 -- None of these will be needed if there are no non-default alts
805 (mkTestLT, mkTestEQ, init_lo, init_hi)
807 = panic "mkMultiBranch: awesome foursome"
809 = case fst (head notd_ways) of {
810 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
811 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
814 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
815 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
818 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
819 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
822 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
823 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
828 (algMinBound, algMaxBound)
829 = case maybe_ncons of
831 Nothing -> (minBound, maxBound)
833 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
834 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
835 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
836 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
837 NoDiscr `eqAlt` NoDiscr = True
840 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
841 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
842 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
843 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
844 NoDiscr `leAlt` NoDiscr = True
847 isNoDiscr NoDiscr = True
850 dec (DiscrI i) = DiscrI (i-1)
851 dec (DiscrP i) = DiscrP (i-1)
852 dec other = other -- not really right, but if you
853 -- do cases on floating values, you'll get what you deserve
855 -- same snotty comment applies to the following
863 mkTree notd_ways init_lo init_hi
867 %************************************************************************
869 \subsection{Supporting junk for the compilation schemes}
871 %************************************************************************
875 -- Describes case alts
883 instance Outputable Discr where
884 ppr (DiscrI i) = int i
885 ppr (DiscrF f) = text (show f)
886 ppr (DiscrD d) = text (show d)
887 ppr (DiscrP i) = int i
888 ppr NoDiscr = text "DEF"
891 -- Find things in the BCEnv (the what's-on-the-stack-env)
892 -- See comment preceding pushAtom for precise meaning of env contents
893 --lookupBCEnv :: BCEnv -> Id -> Int
895 -- = case lookupFM env nm of
896 -- Nothing -> pprPanic "lookupBCEnv"
897 -- (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
900 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
901 lookupBCEnv_maybe = lookupFM
904 -- When I push one of these on the stack, how much does Sp move by?
905 taggedSizeW :: PrimRep -> Int
907 | isFollowableRep pr = 1
908 | otherwise = 1{-the tag-} + getPrimRepSize pr
911 -- The plain size of something, without tag.
912 untaggedSizeW :: PrimRep -> Int
914 | isFollowableRep pr = 1
915 | otherwise = getPrimRepSize pr
918 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
919 taggedIdSizeW = taggedSizeW . typePrimRep . idType
920 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
922 unboxedTupleException :: a
923 unboxedTupleException
924 = throwDyn (Panic "bytecode generator can't handle unboxed tuples")
928 %************************************************************************
930 \subsection{The bytecode generator's monad}
932 %************************************************************************
936 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
937 nextlabel :: Int } -- for generating local labels
939 type BcM result = BcM_State -> (result, BcM_State)
941 runBc :: BcM_State -> BcM () -> BcM_State
942 runBc init_st m = case m init_st of { (r,st) -> st }
944 thenBc :: BcM a -> (a -> BcM b) -> BcM b
946 = case expr st of { (result, st') -> cont result st' }
948 thenBc_ :: BcM a -> BcM b -> BcM b
950 = case expr st of { (result, st') -> cont st' }
952 returnBc :: a -> BcM a
953 returnBc result st = (result, st)
955 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
956 mapBc f [] = returnBc []
958 = f x `thenBc` \ r ->
959 mapBc f xs `thenBc` \ rs ->
962 emitBc :: ProtoBCO Name -> BcM ()
964 = ((), st{bcos = bco : bcos st})
966 getLabelBc :: BcM Int
968 = (nextlabel st, st{nextlabel = 1 + nextlabel st})
970 getLabelsBc :: Int -> BcM [Int]
972 = let ctr = nextlabel st
973 in ([ctr .. ctr+n-1], st{nextlabel = ctr+n})