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,
10 linkIModules, linkIExpr
13 #include "HsVersions.h"
16 import Name ( Name, getName, mkSysLocalName )
17 import Id ( Id, idType, isDataConId_maybe, mkVanillaId,
18 isPrimOpId_maybe, idPrimRep )
19 import OrdList ( OrdList, consOL, snocOL, appOL, unitOL,
20 nilOL, toOL, concatOL, fromOL )
21 import FiniteMap ( FiniteMap, addListToFM, listToFM,
22 addToFM, lookupFM, fmToList, plusFM )
24 import PprCore ( pprCoreExpr )
25 import Literal ( Literal(..), literalPrimRep )
26 import PrimRep ( PrimRep(..) )
27 import PrimOp ( PrimOp(..) )
28 import CoreFVs ( freeVars )
29 import Type ( typePrimRep )
30 import DataCon ( dataConTag, fIRST_TAG, dataConTyCon,
31 dataConWrapId, isUnboxedTupleCon )
32 import TyCon ( TyCon, tyConFamilySize )
33 import Class ( Class, classTyCon )
34 import Util ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem )
35 import Var ( isTyVar )
36 import VarSet ( VarSet, varSetElems )
37 import PrimRep ( getPrimRepSize, isFollowableRep )
38 import CmdLineOpts ( DynFlags, DynFlag(..) )
39 import ErrUtils ( showPass, dumpIfSet_dyn )
40 import Unique ( mkPseudoUnique3 )
41 import FastString ( FastString(..) )
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, linkSomeBCOs, filterNameMap,
47 iNTERP_STACK_CHECK_THRESH )
49 import List ( intersperse, sortBy )
50 import Foreign ( Ptr(..), mallocBytes )
51 import Addr ( Addr(..), addrToInt, writeCharOffAddr )
52 import CTypes ( CInt )
54 import PrelBase ( Int(..) )
55 import PrelGHC ( ByteArray# )
56 import IOExts ( unsafePerformIO )
57 import PrelIOBase ( IO(..) )
61 %************************************************************************
63 \subsection{Functions visible from outside this module.}
65 %************************************************************************
69 byteCodeGen :: DynFlags
72 -> IO ([UnlinkedBCO], ItblEnv)
73 byteCodeGen dflags binds local_tycons local_classes
74 = do showPass dflags "ByteCodeGen"
75 let tycs = local_tycons ++ map classTyCon local_classes
76 itblenv <- mkITbls tycs
78 let flatBinds = concatMap getBind binds
79 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
80 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
81 final_state = runBc (BcM_State [] 0)
82 (mapBc (schemeR True) flatBinds
83 `thenBc_` returnBc ())
84 (BcM_State proto_bcos final_ctr) = final_state
86 dumpIfSet_dyn dflags Opt_D_dump_BCOs
87 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
89 bcos <- mapM assembleBCO proto_bcos
91 return (bcos, itblenv)
94 -- Returns: (the root BCO for this expression,
95 -- a list of auxilary BCOs resulting from compiling closures)
96 coreExprToBCOs :: DynFlags
99 coreExprToBCOs dflags expr
100 = do showPass dflags "ByteCodeGen"
102 -- create a totally bogus name for the top-level BCO; this
103 -- should be harmless, since it's never used for anything
104 let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
105 let invented_id = mkVanillaId invented_name (panic "invented_id's type")
107 let (BcM_State all_proto_bcos final_ctr)
108 = runBc (BcM_State [] 0)
109 (schemeR True (invented_id, freeVars expr))
110 dumpIfSet_dyn dflags Opt_D_dump_BCOs
111 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
114 = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
115 [root_bco] -> root_bco
117 = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
119 auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
120 root_bco <- assembleBCO root_proto_bco
122 return (root_bco, auxiliary_bcos)
126 linkIModules :: ItblEnv -- incoming global itbl env; returned updated
127 -> ClosureEnv -- incoming global closure env; returned updated
128 -> [([UnlinkedBCO], ItblEnv)]
129 -> IO ([HValue], ItblEnv, ClosureEnv)
130 linkIModules gie gce mods
131 = do let (bcoss, ies) = unzip mods
133 final_gie = foldr plusFM gie ies
134 (final_gce, linked_bcos) <- linkSomeBCOs True final_gie gce bcos
135 return (linked_bcos, final_gie, final_gce)
138 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
139 -> IO HValue -- IO BCO# really
140 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
141 = do (aux_ce, _) <- linkSomeBCOs False ie ce aux_ul_bcos
142 (_, [root_bco]) <- linkSomeBCOs False ie aux_ce [root_ul_bco]
146 %************************************************************************
148 \subsection{Compilation schema for the bytecode generator.}
150 %************************************************************************
154 type BCInstrList = OrdList BCInstr
156 type Sequel = Int -- back off to this depth before ENTER
158 -- Maps Ids to the offset from the stack _base_ so we don't have
159 -- to mess with it after each push/pop.
160 type BCEnv = FiniteMap Id Int -- To find vars on the stack
162 ppBCEnv :: BCEnv -> SDoc
165 $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
168 pp_one (var, offset) = int offset <> colon <+> ppr var
169 cmp_snd x y = compare (snd x) (snd y)
171 -- Create a BCO and do a spot of peephole optimisation on the insns
173 mkProtoBCO nm instrs_ordlist origin
174 = ProtoBCO nm maybe_with_stack_check origin
176 -- Overestimate the stack usage (in words) of this BCO,
177 -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
178 -- stack check. (The interpreter always does a stack check
179 -- for iNTERP_STACK_CHECK_THRESH words at the start of each
180 -- BCO anyway, so we only need to add an explicit on in the
181 -- (hopefully rare) cases when the (overestimated) stack use
182 -- exceeds iNTERP_STACK_CHECK_THRESH.
183 maybe_with_stack_check
184 | stack_overest >= 65535
185 = pprPanic "mkProtoBCO: stack use won't fit in 16 bits"
187 | stack_overest >= iNTERP_STACK_CHECK_THRESH
188 = (STKCHECK stack_overest) : peep_d
190 = peep_d -- the supposedly common case
192 stack_overest = sum (map bciStackUse peep_d)
193 + 10 {- just to be really really sure -}
196 -- Merge local pushes
197 peep_d = peep (fromOL instrs_ordlist)
199 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
200 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
201 peep (PUSH_L off1 : PUSH_L off2 : rest)
202 = PUSH_LL off1 (off2-1) : peep rest
209 -- Compile code for the right hand side of a let binding.
210 -- Park the resulting BCO in the monad. Also requires the
211 -- variable to which this value was bound, so as to give the
212 -- resulting BCO a name. Bool indicates top-levelness.
214 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
215 schemeR is_top (nm, rhs)
219 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
220 $$ pprCoreExpr (deAnnotate rhs)
226 = schemeR_wrk is_top rhs nm (collect [] rhs)
229 collect xs (_, AnnNote note e)
231 collect xs (_, AnnLam x e)
232 = collect (if isTyVar x then xs else (x:xs)) e
233 collect xs not_lambda
234 = (reverse xs, not_lambda)
236 schemeR_wrk is_top original_body nm (args, body)
237 | Just dcon <- maybe_toplevel_null_con_rhs
238 = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
239 emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
240 (Right original_body))
244 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
245 all_args = reverse args ++ fvs
246 szsw_args = map taggedIdSizeW all_args
247 szw_args = sum szsw_args
248 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
249 argcheck = unitOL (ARGCHECK szw_args)
251 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
252 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code)
253 (Right original_body))
256 maybe_toplevel_null_con_rhs
257 | is_top && null args
260 -> case isDataConId_maybe v_wrk of
262 Just dc_wrk | nm == dataConWrapId dc_wrk
270 -- Let szsw be the sizes in words of some items pushed onto the stack,
271 -- which has initial depth d'. Return the values which the stack environment
272 -- should map these items to.
273 mkStackOffsets :: Int -> [Int] -> [Int]
274 mkStackOffsets original_depth szsw
275 = map (subtract 1) (tail (scanl (+) original_depth szsw))
277 -- Compile code to apply the given expression to the remaining args
278 -- on the stack, returning a HNF.
279 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
281 -- Delegate tail-calls to schemeT.
282 schemeE d s p e@(fvs, AnnApp f a)
283 = returnBc (schemeT d s p (fvs, AnnApp f a))
284 schemeE d s p e@(fvs, AnnVar v)
285 | isFollowableRep v_rep
286 = returnBc (schemeT d s p (fvs, AnnVar v))
289 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
290 let (push, szw) = pushAtom True d p (AnnVar v)
291 in returnBc (push -- value onto stack
292 `appOL` mkSLIDE szw (d-s) -- clear to sequel
293 `snocOL` RETURN v_rep) -- go
295 v_rep = typePrimRep (idType v)
297 schemeE d s p (fvs, AnnLit literal)
298 = let (push, szw) = pushAtom True d p (AnnLit literal)
299 l_rep = literalPrimRep literal
300 in returnBc (push -- value onto stack
301 `appOL` mkSLIDE szw (d-s) -- clear to sequel
302 `snocOL` RETURN l_rep) -- go
304 schemeE d s p (fvs, AnnLet binds b)
305 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
306 AnnRec xs_n_rhss -> unzip xs_n_rhss
308 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
310 -- Sizes of tagged free vars, + 1 for the fn
311 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
313 -- This p', d' defn is safe because all the items being pushed
314 -- are ptrs, so all have size 1. d' and p' reflect the stack
315 -- after the closures have been allocated in the heap (but not
316 -- filled in), and pointers to them parked on the stack.
317 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
320 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
321 zipE = zipEqual "schemeE"
322 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
324 -- ToDo: don't build thunks for things with no free variables
325 buildThunk dd ([], size, id, off)
326 = PUSH_G (Left (getName id))
327 `consOL` unitOL (MKAP (off+size-1) size)
328 buildThunk dd ((fv:fvs), size, id, off)
329 = case pushAtom True dd p' (AnnVar fv) of
330 (push_code, pushed_szw)
332 buildThunk (dd+pushed_szw) (fvs, size, id, off)
334 thunkCode = concatOL (map (buildThunk d') infos)
335 allocCode = toOL (map ALLOC sizes)
337 schemeE d' s p' b `thenBc` \ bodyCode ->
338 mapBc (schemeR False) (zip xs rhss) `thenBc_`
339 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
342 schemeE d s p (fvs, AnnCase scrut bndr alts)
344 -- Top of stack is the return itbl, as usual.
345 -- underneath it is the pointer to the alt_code BCO.
346 -- When an alt is entered, it assumes the returned value is
347 -- on top of the itbl.
350 -- Env and depth in which to compile the alts, not including
351 -- any vars bound by the alts themselves
352 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
353 p' = addToFM p bndr (d' - 1)
355 scrut_primrep = typePrimRep (idType bndr)
357 = case scrut_primrep of
358 CharRep -> False ; AddrRep -> False ; WordRep -> False
359 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
361 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
363 -- given an alt, return a discr and code for it.
364 codeAlt alt@(discr, binds_f, rhs)
366 = let (unpack_code, d_after_unpack, p_after_unpack)
367 = mkUnpackCode binds_f d' p'
368 in schemeE d_after_unpack s p_after_unpack rhs
369 `thenBc` \ rhs_code ->
370 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
372 = ASSERT(null binds_f)
373 schemeE d' s p' rhs `thenBc` \ rhs_code ->
374 returnBc (my_discr alt, rhs_code)
376 my_discr (DEFAULT, binds, rhs) = NoDiscr
377 my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc - fIRST_TAG)
378 my_discr (LitAlt l, binds, rhs)
379 = case l of MachInt i -> DiscrI (fromInteger i)
380 MachFloat r -> DiscrF (fromRational r)
381 MachDouble r -> DiscrD (fromRational r)
382 MachChar i -> DiscrI i
383 _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
386 | not isAlgCase = Nothing
388 = case [dc | (DataAlt dc, _, _) <- alts] of
390 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
393 mapBc codeAlt alts `thenBc` \ alt_stuff ->
394 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
396 alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
397 alt_bco_name = getName bndr
398 alt_bco = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
400 schemeE (d + ret_frame_sizeW)
401 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
403 emitBc alt_bco `thenBc_`
404 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
407 schemeE d s p (fvs, AnnNote note body)
411 = pprPanic "ByteCodeGen.schemeE: unhandled case"
412 (pprCoreExpr (deAnnotate other))
415 -- Compile code to do a tail call. Three cases:
417 -- 1. A nullary constructor. Push its closure on the stack
418 -- and SLIDE and RETURN.
420 -- 2. Application of a non-nullary constructor, by defn saturated.
421 -- Split the args into ptrs and non-ptrs, and push the nonptrs,
422 -- then the ptrs, and then do PACK and RETURN.
424 -- 3. Otherwise, it must be a function call. Push the args
425 -- right to left, SLIDE and ENTER.
427 schemeT :: Int -- Stack depth
428 -> Sequel -- Sequel depth
429 -> BCEnv -- stack env
434 -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
435 -- = panic "schemeT ?!?!"
438 | is_con_call && null args_r_to_l
439 = (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
444 = if is_con_call && isUnboxedTupleCon con
445 then pprPanic "Bytecode generator can't handle unboxed tuple constructor"
450 -- Extract the args (R->L) and fn
451 (args_r_to_l_raw, fn) = chomp app
455 AnnApp f a -> case chomp f of (az, f) -> (snd a:az, f)
456 AnnNote n e -> chomp e
457 other -> pprPanic "schemeT"
458 (ppr (deAnnotate (panic "schemeT.chomp", other)))
460 args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
461 isTypeAtom (AnnType _) = True
464 -- decide if this is a constructor call, and rearrange
465 -- args appropriately.
466 maybe_dcon = isDataConId_maybe fn
467 is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
468 (Just con) = maybe_dcon
474 = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
475 where isPtr = isFollowableRep . atomRep
477 -- make code to push the args and then do the SLIDE-ENTER thing
478 code = do_pushery d args_final_r_to_l
480 tag_when_push = not is_con_call
481 narg_words = sum (map (get_arg_szw . atomRep) args_r_to_l)
482 get_arg_szw = if tag_when_push then taggedSizeW else untaggedSizeW
484 do_pushery d (arg:args)
485 = let (push, arg_words) = pushAtom tag_when_push d p arg
486 in push `appOL` do_pushery (d+arg_words) args
489 Just con -> PACK con narg_words `consOL` (
490 mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
492 -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
494 `appOL` mkSLIDE (narg_words+arg_words)
499 = if d == 0 then nilOL else unitOL (SLIDE n d)
501 atomRep (AnnVar v) = typePrimRep (idType v)
502 atomRep (AnnLit l) = literalPrimRep l
503 atomRep (AnnNote n b) = atomRep (snd b)
504 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
505 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
506 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
509 -- Make code to unpack the top-of-stack constructor onto the stack,
510 -- adding tags for the unboxed bits. Takes the PrimReps of the
511 -- constructor's arguments. off_h and off_s are travelling offsets
512 -- along the constructor and the stack.
514 -- Supposing a constructor in the heap has layout
516 -- Itbl p_1 ... p_i np_1 ... np_j
518 -- then we add to the stack, shown growing down, the following:
530 -- so that in the common case (ptrs only) a single UNPACK instr can
531 -- copy all the payload of the constr onto the stack with no further ado.
533 mkUnpackCode :: [Id] -- constr args
534 -> Int -- depth before unpack
535 -> BCEnv -- env before unpack
536 -> (BCInstrList, Int, BCEnv)
537 mkUnpackCode vars d p
538 = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
539 -- ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
541 (code_p `appOL` code_np, d', p')
545 vreps = [(var, typePrimRep (idType var)) | var <- vars]
547 -- ptrs and nonptrs, forward
548 vreps_p = filter (isFollowableRep.snd) vreps
549 vreps_np = filter (not.isFollowableRep.snd) vreps
551 -- the order in which we will augment the environment
552 vreps_env = reverse vreps_p ++ reverse vreps_np
555 vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
556 p' = addListToFM p (zip (map fst vreps_env)
557 (mkStackOffsets d vreps_env_tszsw))
558 d' = d + sum vreps_env_tszsw
560 -- code to unpack the ptrs
561 ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
562 code_p | null vreps_p = nilOL
563 | otherwise = unitOL (UNPACK ptrs_szw)
565 -- code to unpack the nonptrs
566 vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
567 code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
568 do_nptrs off_h off_s [] = nilOL
569 do_nptrs off_h off_s (npr:nprs)
571 IntRep -> approved ; FloatRep -> approved
572 DoubleRep -> approved ; AddrRep -> approved
574 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
576 approved = UPK_TAG usizeW (off_h-usizeW) off_s `consOL` theRest
577 theRest = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
578 usizeW = untaggedSizeW npr
579 tsizeW = taggedSizeW npr
582 -- Push an atom onto the stack, returning suitable code & number of
583 -- stack words used. Pushes it either tagged or untagged, since
584 -- pushAtom is used to set up the stack prior to copying into the
585 -- heap for both APs (requiring tags) and constructors (which don't).
587 -- NB this means NO GC between pushing atoms for a constructor and
588 -- copying them into the heap. It probably also means that
589 -- tail calls MUST be of the form atom{atom ... atom} since if the
590 -- expression head was allowed to be arbitrary, there could be GC
591 -- in between pushing the arg atoms and completing the head.
592 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
593 -- isn't a problem; but only if arbitrary graph construction for the
594 -- head doesn't leave this BCO, since GC might happen at the start of
595 -- each BCO (we consult doYouWantToGC there).
597 -- Blargh. JRS 001206
599 -- NB (further) that the env p must map each variable to the highest-
600 -- numbered stack slot for it. For example, if the stack has depth 4
601 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
602 -- the tag in stack[5], the stack will have depth 6, and p must map v to
603 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
604 -- 6 stack has valid words 0 .. 5.
606 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
607 pushAtom tagged d p (AnnVar v)
609 | idPrimRep v == VoidRep
611 (unitOL (PUSH_TAG 0), 1)
613 | Just primop <- isPrimOpId_maybe v
615 CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
616 other -> (unitOL (PUSH_G (Right primop)), 1)
619 = let str = "\npushAtom " ++ showSDocDebug (ppr v)
620 ++ " :: " ++ showSDocDebug (pprType (idType v))
621 ++ ", depth = " ++ show d
622 ++ ", tagged = " ++ show tagged ++ ", env =\n" ++
623 showSDocDebug (ppBCEnv p)
624 ++ " --> words: " ++ show (snd result) ++ "\n" ++
625 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
626 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
628 cmp_snd x y = compare (snd x) (snd y)
629 str' = if str == str then str else str
632 = case lookupBCEnv_maybe p v of
633 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
634 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
636 nm = case isDataConId_maybe v of
640 sz_t = taggedIdSizeW v
641 sz_u = untaggedIdSizeW v
642 nwords = if tagged then sz_t else sz_u
647 pushAtom True d p (AnnLit lit)
648 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
649 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
651 pushAtom False d p (AnnLit lit)
653 MachWord w -> code WordRep
654 MachInt i -> code IntRep
655 MachFloat r -> code FloatRep
656 MachDouble r -> code DoubleRep
657 MachChar c -> code CharRep
658 MachStr s -> pushStr s
661 = let size_host_words = untaggedSizeW rep
662 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
665 = let mallocvilleAddr
670 -- sigh, a string in the heap is no good to us.
671 -- We need a static C pointer, since the type of
672 -- a string literal is Addr#. So, copy the string
673 -- into C land and introduce a memory leak
676 -- CAREFUL! Chars are 32 bits in ghc 4.09+
678 do (Ptr a#) <- mallocBytes (n+1)
679 strncpy (Ptr a#) ba (fromIntegral n)
680 writeCharOffAddr (A# a#) n '\0'
683 _ -> panic "StgInterp.lit2expr: unhandled string constant type"
686 = MachInt (toInteger (addrToInt mallocvilleAddr))
688 -- Get the addr on the stack, untaggedly
689 (unitOL (PUSH_UBX addrLit 1), 1)
695 pushAtom tagged d p (AnnApp f (_, AnnType _))
696 = pushAtom tagged d p (snd f)
698 pushAtom tagged d p (AnnNote note e)
699 = pushAtom tagged d p (snd e)
701 pushAtom tagged d p (AnnLam x e)
703 = pushAtom tagged d p (snd e)
705 pushAtom tagged d p other
706 = pprPanic "ByteCodeGen.pushAtom"
707 (pprCoreExpr (deAnnotate (undefined, other)))
709 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
712 -- Given a bunch of alts code and their discrs, do the donkey work
713 -- of making a multiway branch using a switch tree.
714 -- What a load of hassle!
715 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
716 -- a hint; generates better code
717 -- Nothing is always safe
718 -> [(Discr, BCInstrList)]
720 mkMultiBranch maybe_ncons raw_ways
721 = let d_way = filter (isNoDiscr.fst) raw_ways
722 notd_ways = naturalMergeSortLe
723 (\w1 w2 -> leAlt (fst w1) (fst w2))
724 (filter (not.isNoDiscr.fst) raw_ways)
726 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
727 mkTree [] range_lo range_hi = returnBc the_default
729 mkTree [val] range_lo range_hi
730 | range_lo `eqAlt` range_hi
733 = getLabelBc `thenBc` \ label_neq ->
734 returnBc (mkTestEQ (fst val) label_neq
736 `appOL` unitOL (LABEL label_neq)
737 `appOL` the_default))
739 mkTree vals range_lo range_hi
740 = let n = length vals `div` 2
741 vals_lo = take n vals
742 vals_hi = drop n vals
743 v_mid = fst (head vals_hi)
745 getLabelBc `thenBc` \ label_geq ->
746 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
747 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
748 returnBc (mkTestLT v_mid label_geq
750 `appOL` unitOL (LABEL label_geq)
754 = case d_way of [] -> unitOL CASEFAIL
757 -- None of these will be needed if there are no non-default alts
758 (mkTestLT, mkTestEQ, init_lo, init_hi)
760 = panic "mkMultiBranch: awesome foursome"
762 = case fst (head notd_ways) of {
763 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
764 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
767 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
768 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
771 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
772 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
775 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
776 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
781 (algMinBound, algMaxBound)
782 = case maybe_ncons of
784 Nothing -> (minBound, maxBound)
786 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
787 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
788 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
789 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
790 NoDiscr `eqAlt` NoDiscr = True
793 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
794 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
795 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
796 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
797 NoDiscr `leAlt` NoDiscr = True
800 isNoDiscr NoDiscr = True
803 dec (DiscrI i) = DiscrI (i-1)
804 dec (DiscrP i) = DiscrP (i-1)
805 dec other = other -- not really right, but if you
806 -- do cases on floating values, you'll get what you deserve
808 -- same snotty comment applies to the following
816 mkTree notd_ways init_lo init_hi
820 %************************************************************************
822 \subsection{Supporting junk for the compilation schemes}
824 %************************************************************************
828 -- Describes case alts
836 instance Outputable Discr where
837 ppr (DiscrI i) = int i
838 ppr (DiscrF f) = text (show f)
839 ppr (DiscrD d) = text (show d)
840 ppr (DiscrP i) = int i
841 ppr NoDiscr = text "DEF"
844 -- Find things in the BCEnv (the what's-on-the-stack-env)
845 -- See comment preceding pushAtom for precise meaning of env contents
846 --lookupBCEnv :: BCEnv -> Id -> Int
848 -- = case lookupFM env nm of
849 -- Nothing -> pprPanic "lookupBCEnv"
850 -- (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
853 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
854 lookupBCEnv_maybe = lookupFM
857 -- When I push one of these on the stack, how much does Sp move by?
858 taggedSizeW :: PrimRep -> Int
860 | isFollowableRep pr = 1
861 | otherwise = 1{-the tag-} + getPrimRepSize pr
864 -- The plain size of something, without tag.
865 untaggedSizeW :: PrimRep -> Int
867 | isFollowableRep pr = 1
868 | otherwise = getPrimRepSize pr
871 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
872 taggedIdSizeW = taggedSizeW . typePrimRep . idType
873 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
877 %************************************************************************
879 \subsection{The bytecode generator's monad}
881 %************************************************************************
885 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
886 nextlabel :: Int } -- for generating local labels
888 type BcM result = BcM_State -> (result, BcM_State)
890 runBc :: BcM_State -> BcM () -> BcM_State
891 runBc init_st m = case m init_st of { (r,st) -> st }
893 thenBc :: BcM a -> (a -> BcM b) -> BcM b
895 = case expr st of { (result, st') -> cont result st' }
897 thenBc_ :: BcM a -> BcM b -> BcM b
899 = case expr st of { (result, st') -> cont st' }
901 returnBc :: a -> BcM a
902 returnBc result st = (result, st)
904 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
905 mapBc f [] = returnBc []
907 = f x `thenBc` \ r ->
908 mapBc f xs `thenBc` \ rs ->
911 emitBc :: ProtoBCO Name -> BcM ()
913 = ((), st{bcos = bco : bcos st})
915 getLabelBc :: BcM Int
917 = (nextlabel st, st{nextlabel = 1 + nextlabel st})