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,
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, dataConWrapId )
31 import TyCon ( TyCon, tyConFamilySize )
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 PprType ( pprType )
42 import ByteCodeInstr ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO )
43 import ByteCodeItbls ( ItblEnv, mkITbls )
44 import ByteCodeLink ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
45 ClosureEnv, HValue, linkSomeBCOs, filterNameMap )
47 import List ( intersperse, sortBy )
48 import Foreign ( Ptr(..), mallocBytes )
49 import Addr ( Addr(..), addrToInt, writeCharOffAddr )
50 import CTypes ( CInt )
52 import PrelBase ( Int(..) )
53 import PrelGHC ( ByteArray# )
54 import IOExts ( unsafePerformIO )
55 import PrelIOBase ( IO(..) )
59 %************************************************************************
61 \subsection{Functions visible from outside this module.}
63 %************************************************************************
67 byteCodeGen :: DynFlags
70 -> IO ([UnlinkedBCO], ItblEnv)
71 byteCodeGen dflags binds local_tycons local_classes
72 = do showPass dflags "ByteCodeGen"
73 let tycs = local_tycons ++ map classTyCon local_classes
74 itblenv <- mkITbls tycs
76 let flatBinds = concatMap getBind binds
77 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
78 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
79 final_state = runBc (BcM_State [] 0)
80 (mapBc (schemeR True) flatBinds
81 `thenBc_` returnBc ())
82 (BcM_State proto_bcos final_ctr) = final_state
84 dumpIfSet_dyn dflags Opt_D_dump_BCOs
85 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
87 bcos <- mapM assembleBCO proto_bcos
89 return (bcos, itblenv)
92 -- Returns: (the root BCO for this expression,
93 -- a list of auxilary BCOs resulting from compiling closures)
94 coreExprToBCOs :: DynFlags
97 coreExprToBCOs dflags expr
98 = do showPass dflags "ByteCodeGen"
100 -- create a totally bogus name for the top-level BCO; this
101 -- should be harmless, since it's never used for anything
102 let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
103 let invented_id = mkVanillaId invented_name (panic "invented_id's type")
105 let (BcM_State all_proto_bcos final_ctr)
106 = runBc (BcM_State [] 0)
107 (schemeR True (invented_id, freeVars expr))
108 dumpIfSet_dyn dflags Opt_D_dump_BCOs
109 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
112 = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
113 [root_bco] -> root_bco
115 = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
117 auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
118 root_bco <- assembleBCO root_proto_bco
120 return (root_bco, auxiliary_bcos)
124 linkIModules :: ItblEnv -- incoming global itbl env; returned updated
125 -> ClosureEnv -- incoming global closure env; returned updated
126 -> [([UnlinkedBCO], ItblEnv)]
127 -> IO ([HValue], ItblEnv, ClosureEnv)
128 linkIModules gie gce mods
129 = do let (bcoss, ies) = unzip mods
131 final_gie = foldr plusFM gie ies
132 (final_gce, linked_bcos) <- linkSomeBCOs final_gie gce bcos
133 return (linked_bcos, final_gie, final_gce)
136 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
137 -> IO HValue -- IO BCO# really
138 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
139 = do (aux_ce, _) <- linkSomeBCOs ie ce aux_ul_bcos
140 (_, [root_bco]) <- linkSomeBCOs ie aux_ce [root_ul_bco]
144 %************************************************************************
146 \subsection{Compilation schema for the bytecode generator.}
148 %************************************************************************
152 type BCInstrList = OrdList BCInstr
154 type Sequel = Int -- back off to this depth before ENTER
156 -- Maps Ids to the offset from the stack _base_ so we don't have
157 -- to mess with it after each push/pop.
158 type BCEnv = FiniteMap Id Int -- To find vars on the stack
160 ppBCEnv :: BCEnv -> SDoc
163 $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
166 pp_one (var, offset) = int offset <> colon <+> ppr var
167 cmp_snd x y = compare (snd x) (snd y)
169 -- Create a BCO and do a spot of peephole optimisation on the insns
171 mkProtoBCO nm instrs_ordlist origin
172 = ProtoBCO nm (id {-peep-} (fromOL instrs_ordlist)) origin
174 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
175 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
176 peep (PUSH_L off1 : PUSH_L off2 : rest)
177 = PUSH_LL off1 off2 : peep rest
184 -- Compile code for the right hand side of a let binding.
185 -- Park the resulting BCO in the monad. Also requires the
186 -- variable to which this value was bound, so as to give the
187 -- resulting BCO a name. Bool indicates top-levelness.
189 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
190 schemeR is_top (nm, rhs)
194 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
195 $$ pprCoreExpr (deAnnotate rhs)
201 = schemeR_wrk is_top rhs nm (collect [] rhs)
204 collect xs (_, AnnNote note e)
206 collect xs (_, AnnLam x e)
207 = collect (if isTyVar x then xs else (x:xs)) e
208 collect xs not_lambda
209 = (reverse xs, not_lambda)
211 schemeR_wrk is_top original_body nm (args, body)
212 | Just dcon <- maybe_toplevel_null_con_rhs
213 = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
214 emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
215 (Right original_body))
219 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
220 all_args = reverse args ++ fvs
221 szsw_args = map taggedIdSizeW all_args
222 szw_args = sum szsw_args
223 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
224 argcheck = unitOL (ARGCHECK szw_args)
226 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
227 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code)
228 (Right original_body))
231 maybe_toplevel_null_con_rhs
232 | is_top && null args
235 -> case isDataConId_maybe v_wrk of
237 Just dc_wrk | nm == dataConWrapId dc_wrk
245 -- Let szsw be the sizes in words of some items pushed onto the stack,
246 -- which has initial depth d'. Return the values which the stack environment
247 -- should map these items to.
248 mkStackOffsets :: Int -> [Int] -> [Int]
249 mkStackOffsets original_depth szsw
250 = map (subtract 1) (tail (scanl (+) original_depth szsw))
252 -- Compile code to apply the given expression to the remaining args
253 -- on the stack, returning a HNF.
254 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
256 -- Delegate tail-calls to schemeT.
257 schemeE d s p e@(fvs, AnnApp f a)
258 = returnBc (schemeT d s p (fvs, AnnApp f a))
259 schemeE d s p e@(fvs, AnnVar v)
260 | isFollowableRep v_rep
261 = returnBc (schemeT d s p (fvs, AnnVar v))
264 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
265 let (push, szw) = pushAtom True d p (AnnVar v)
266 in returnBc (push -- value onto stack
267 `appOL` mkSLIDE szw (d-s) -- clear to sequel
268 `snocOL` RETURN v_rep) -- go
270 v_rep = typePrimRep (idType v)
272 schemeE d s p (fvs, AnnLit literal)
273 = let (push, szw) = pushAtom True d p (AnnLit literal)
274 l_rep = literalPrimRep literal
275 in returnBc (push -- value onto stack
276 `appOL` mkSLIDE szw (d-s) -- clear to sequel
277 `snocOL` RETURN l_rep) -- go
279 schemeE d s p (fvs, AnnLet binds b)
280 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
281 AnnRec xs_n_rhss -> unzip xs_n_rhss
283 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
285 -- Sizes of tagged free vars, + 1 for the fn
286 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
288 -- This p', d' defn is safe because all the items being pushed
289 -- are ptrs, so all have size 1. d' and p' reflect the stack
290 -- after the closures have been allocated in the heap (but not
291 -- filled in), and pointers to them parked on the stack.
292 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
295 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
296 zipE = zipEqual "schemeE"
297 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
299 -- ToDo: don't build thunks for things with no free variables
300 buildThunk dd ([], size, id, off)
301 = PUSH_G (Left (getName id))
302 `consOL` unitOL (MKAP (off+size-1) size)
303 buildThunk dd ((fv:fvs), size, id, off)
304 = case pushAtom True dd p' (AnnVar fv) of
305 (push_code, pushed_szw)
307 buildThunk (dd+pushed_szw) (fvs, size, id, off)
309 thunkCode = concatOL (map (buildThunk d') infos)
310 allocCode = toOL (map ALLOC sizes)
312 schemeE d' s p' b `thenBc` \ bodyCode ->
313 mapBc (schemeR False) (zip xs rhss) `thenBc_`
314 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
317 schemeE d s p (fvs, AnnCase scrut bndr alts)
319 -- Top of stack is the return itbl, as usual.
320 -- underneath it is the pointer to the alt_code BCO.
321 -- When an alt is entered, it assumes the returned value is
322 -- on top of the itbl.
325 -- Env and depth in which to compile the alts, not including
326 -- any vars bound by the alts themselves
327 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
328 p' = addToFM p bndr (d' - 1)
330 scrut_primrep = typePrimRep (idType bndr)
332 = case scrut_primrep of
333 CharRep -> False ; AddrRep -> False
334 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
336 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
338 -- given an alt, return a discr and code for it.
339 codeAlt alt@(discr, binds_f, rhs)
341 = let (unpack_code, d_after_unpack, p_after_unpack)
342 = mkUnpackCode binds_f d' p'
343 in schemeE d_after_unpack s p_after_unpack rhs
344 `thenBc` \ rhs_code ->
345 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
347 = ASSERT(null binds_f)
348 schemeE d' s p' rhs `thenBc` \ rhs_code ->
349 returnBc (my_discr alt, rhs_code)
351 my_discr (DEFAULT, binds, rhs) = NoDiscr
352 my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc - fIRST_TAG)
353 my_discr (LitAlt l, binds, rhs)
354 = case l of MachInt i -> DiscrI (fromInteger i)
355 MachFloat r -> DiscrF (fromRational r)
356 MachDouble r -> DiscrD (fromRational r)
357 MachChar i -> DiscrI i
358 _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
361 | not isAlgCase = Nothing
363 = case [dc | (DataAlt dc, _, _) <- alts] of
365 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
368 mapBc codeAlt alts `thenBc` \ alt_stuff ->
369 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
371 alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
372 alt_bco_name = getName bndr
373 alt_bco = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
375 schemeE (d + ret_frame_sizeW)
376 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
378 emitBc alt_bco `thenBc_`
379 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
382 schemeE d s p (fvs, AnnNote note body)
386 = pprPanic "ByteCodeGen.schemeE: unhandled case"
387 (pprCoreExpr (deAnnotate other))
390 -- Compile code to do a tail call. Three cases:
392 -- 1. A nullary constructor. Push its closure on the stack
393 -- and SLIDE and RETURN.
395 -- 2. Application of a non-nullary constructor, by defn saturated.
396 -- Split the args into ptrs and non-ptrs, and push the nonptrs,
397 -- then the ptrs, and then do PACK and RETURN.
399 -- 3. Otherwise, it must be a function call. Push the args
400 -- right to left, SLIDE and ENTER.
402 schemeT :: Int -- Stack depth
403 -> Sequel -- Sequel depth
404 -> BCEnv -- stack env
409 -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
410 -- = panic "schemeT ?!?!"
413 | is_con_call && null args_r_to_l
414 = (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
422 -- Extract the args (R->L) and fn
423 (args_r_to_l_raw, fn) = chomp app
427 AnnApp f a -> case chomp f of (az, f) -> (snd a:az, f)
428 other -> pprPanic "schemeT"
429 (ppr (deAnnotate (panic "schemeT.chomp", other)))
431 args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
432 isTypeAtom (AnnType _) = True
435 -- decide if this is a constructor call, and rearrange
436 -- args appropriately.
437 maybe_dcon = isDataConId_maybe fn
438 is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
439 (Just con) = maybe_dcon
445 = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
446 where isPtr = isFollowableRep . atomRep
448 -- make code to push the args and then do the SLIDE-ENTER thing
449 code = do_pushery d args_final_r_to_l
451 tag_when_push = not is_con_call
452 narg_words = sum (map (get_arg_szw . atomRep) args_r_to_l)
453 get_arg_szw = if tag_when_push then taggedSizeW else untaggedSizeW
455 do_pushery d (arg:args)
456 = let (push, arg_words) = pushAtom tag_when_push d p arg
457 in push `appOL` do_pushery (d+arg_words) args
460 Just con -> PACK con narg_words `consOL` (
461 mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
463 -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
465 `appOL` mkSLIDE (narg_words+arg_words)
470 = if d == 0 then nilOL else unitOL (SLIDE n d)
472 atomRep (AnnVar v) = typePrimRep (idType v)
473 atomRep (AnnLit l) = literalPrimRep l
474 atomRep (AnnNote n b) = atomRep (snd b)
475 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
476 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
479 -- Make code to unpack the top-of-stack constructor onto the stack,
480 -- adding tags for the unboxed bits. Takes the PrimReps of the
481 -- constructor's arguments. off_h and off_s are travelling offsets
482 -- along the constructor and the stack.
484 -- Supposing a constructor in the heap has layout
486 -- Itbl p_1 ... p_i np_1 ... np_j
488 -- then we add to the stack, shown growing down, the following:
500 -- so that in the common case (ptrs only) a single UNPACK instr can
501 -- copy all the payload of the constr onto the stack with no further ado.
503 mkUnpackCode :: [Id] -- constr args
504 -> Int -- depth before unpack
505 -> BCEnv -- env before unpack
506 -> (BCInstrList, Int, BCEnv)
507 mkUnpackCode vars d p
508 = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
509 -- ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
511 (code_p `appOL` code_np, d', p')
515 vreps = [(var, typePrimRep (idType var)) | var <- vars]
517 -- ptrs and nonptrs, forward
518 vreps_p = filter (isFollowableRep.snd) vreps
519 vreps_np = filter (not.isFollowableRep.snd) vreps
521 -- the order in which we will augment the environment
522 vreps_env = reverse vreps_p ++ reverse vreps_np
525 vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
526 p' = addListToFM p (zip (map fst vreps_env)
527 (mkStackOffsets d vreps_env_tszsw))
528 d' = d + sum vreps_env_tszsw
530 -- code to unpack the ptrs
531 ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
532 code_p | null vreps_p = nilOL
533 | otherwise = unitOL (UNPACK ptrs_szw)
535 -- code to unpack the nonptrs
536 vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
537 code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
538 do_nptrs off_h off_s [] = nilOL
539 do_nptrs off_h off_s (npr:nprs)
541 IntRep -> approved ; FloatRep -> approved
542 DoubleRep -> approved ; AddrRep -> approved
544 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
546 approved = UPK_TAG usizeW (off_h-usizeW) off_s `consOL` theRest
547 theRest = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
548 usizeW = untaggedSizeW npr
549 tsizeW = taggedSizeW npr
552 -- Push an atom onto the stack, returning suitable code & number of
553 -- stack words used. Pushes it either tagged or untagged, since
554 -- pushAtom is used to set up the stack prior to copying into the
555 -- heap for both APs (requiring tags) and constructors (which don't).
557 -- NB this means NO GC between pushing atoms for a constructor and
558 -- copying them into the heap. It probably also means that
559 -- tail calls MUST be of the form atom{atom ... atom} since if the
560 -- expression head was allowed to be arbitrary, there could be GC
561 -- in between pushing the arg atoms and completing the head.
562 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
563 -- isn't a problem; but only if arbitrary graph construction for the
564 -- head doesn't leave this BCO, since GC might happen at the start of
565 -- each BCO (we consult doYouWantToGC there).
567 -- Blargh. JRS 001206
569 -- NB (further) that the env p must map each variable to the highest-
570 -- numbered stack slot for it. For example, if the stack has depth 4
571 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
572 -- the tag in stack[5], the stack will have depth 6, and p must map v to
573 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
574 -- 6 stack has valid words 0 .. 5.
576 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
577 pushAtom tagged d p (AnnVar v)
578 | Just primop <- isPrimOpId_maybe v
580 CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
581 other -> (unitOL (PUSH_G (Right primop)), 1)
584 = let str = "\npushAtom " ++ showSDocDebug (ppr v)
585 ++ " :: " ++ showSDocDebug (pprType (idType v))
586 ++ ", depth = " ++ show d
587 ++ ", tagged = " ++ show tagged ++ ", env =\n" ++
588 showSDocDebug (ppBCEnv p)
589 ++ " --> words: " ++ show (snd result) ++ "\n" ++
590 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
591 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
593 cmp_snd x y = compare (snd x) (snd y)
594 str' = if str == str then str else str
597 = case lookupBCEnv_maybe p v of
598 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
599 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
601 nm = case isDataConId_maybe v of
605 sz_t = taggedIdSizeW v
606 sz_u = untaggedIdSizeW v
607 nwords = if tagged then sz_t else sz_u
612 pushAtom True d p (AnnLit lit)
613 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
614 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
616 pushAtom False d p (AnnLit lit)
618 MachInt i -> code IntRep
619 MachFloat r -> code FloatRep
620 MachDouble r -> code DoubleRep
621 MachChar c -> code CharRep
622 MachStr s -> pushStr s
625 = let size_host_words = untaggedSizeW rep
626 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
629 = let mallocvilleAddr
634 -- sigh, a string in the heap is no good to us.
635 -- We need a static C pointer, since the type of
636 -- a string literal is Addr#. So, copy the string
637 -- into C land and introduce a memory leak
640 -- CAREFUL! Chars are 32 bits in ghc 4.09+
642 do (Ptr a#) <- mallocBytes (n+1)
643 strncpy (Ptr a#) ba (fromIntegral n)
644 writeCharOffAddr (A# a#) n '\0'
647 _ -> panic "StgInterp.lit2expr: unhandled string constant type"
650 = MachInt (toInteger (addrToInt mallocvilleAddr))
652 -- Get the addr on the stack, untaggedly
653 (unitOL (PUSH_UBX addrLit 1), 1)
659 pushAtom tagged d p (AnnApp f (_, AnnType _))
660 = pushAtom tagged d p (snd f)
662 pushAtom tagged d p (AnnNote note e)
663 = pushAtom tagged d p (snd e)
665 pushAtom tagged d p other
666 = pprPanic "ByteCodeGen.pushAtom"
667 (pprCoreExpr (deAnnotate (undefined, other)))
669 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
672 -- Given a bunch of alts code and their discrs, do the donkey work
673 -- of making a multiway branch using a switch tree.
674 -- What a load of hassle!
675 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
676 -- a hint; generates better code
677 -- Nothing is always safe
678 -> [(Discr, BCInstrList)]
680 mkMultiBranch maybe_ncons raw_ways
681 = let d_way = filter (isNoDiscr.fst) raw_ways
682 notd_ways = naturalMergeSortLe
683 (\w1 w2 -> leAlt (fst w1) (fst w2))
684 (filter (not.isNoDiscr.fst) raw_ways)
686 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
687 mkTree [] range_lo range_hi = returnBc the_default
689 mkTree [val] range_lo range_hi
690 | range_lo `eqAlt` range_hi
693 = getLabelBc `thenBc` \ label_neq ->
694 returnBc (mkTestEQ (fst val) label_neq
696 `appOL` unitOL (LABEL label_neq)
697 `appOL` the_default))
699 mkTree vals range_lo range_hi
700 = let n = length vals `div` 2
701 vals_lo = take n vals
702 vals_hi = drop n vals
703 v_mid = fst (head vals_hi)
705 getLabelBc `thenBc` \ label_geq ->
706 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
707 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
708 returnBc (mkTestLT v_mid label_geq
710 `appOL` unitOL (LABEL label_geq)
714 = case d_way of [] -> unitOL CASEFAIL
717 -- None of these will be needed if there are no non-default alts
718 (mkTestLT, mkTestEQ, init_lo, init_hi)
720 = panic "mkMultiBranch: awesome foursome"
722 = case fst (head notd_ways) of {
723 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
724 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
727 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
728 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
731 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
732 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
735 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
736 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
741 (algMinBound, algMaxBound)
742 = case maybe_ncons of
744 Nothing -> (minBound, maxBound)
746 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
747 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
748 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
749 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
750 NoDiscr `eqAlt` NoDiscr = True
753 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
754 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
755 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
756 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
757 NoDiscr `leAlt` NoDiscr = True
760 isNoDiscr NoDiscr = True
763 dec (DiscrI i) = DiscrI (i-1)
764 dec (DiscrP i) = DiscrP (i-1)
765 dec other = other -- not really right, but if you
766 -- do cases on floating values, you'll get what you deserve
768 -- same snotty comment applies to the following
776 mkTree notd_ways init_lo init_hi
780 %************************************************************************
782 \subsection{Supporting junk for the compilation schemes}
784 %************************************************************************
788 -- Describes case alts
796 instance Outputable Discr where
797 ppr (DiscrI i) = int i
798 ppr (DiscrF f) = text (show f)
799 ppr (DiscrD d) = text (show d)
800 ppr (DiscrP i) = int i
801 ppr NoDiscr = text "DEF"
804 -- Find things in the BCEnv (the what's-on-the-stack-env)
805 -- See comment preceding pushAtom for precise meaning of env contents
806 --lookupBCEnv :: BCEnv -> Id -> Int
808 -- = case lookupFM env nm of
809 -- Nothing -> pprPanic "lookupBCEnv"
810 -- (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
813 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
814 lookupBCEnv_maybe = lookupFM
817 -- When I push one of these on the stack, how much does Sp move by?
818 taggedSizeW :: PrimRep -> Int
820 | isFollowableRep pr = 1
821 | otherwise = 1{-the tag-} + getPrimRepSize pr
824 -- The plain size of something, without tag.
825 untaggedSizeW :: PrimRep -> Int
827 | isFollowableRep pr = 1
828 | otherwise = getPrimRepSize pr
831 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
832 taggedIdSizeW = taggedSizeW . typePrimRep . idType
833 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
837 %************************************************************************
839 \subsection{The bytecode generator's monad}
841 %************************************************************************
845 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
846 nextlabel :: Int } -- for generating local labels
848 type BcM result = BcM_State -> (result, BcM_State)
850 runBc :: BcM_State -> BcM () -> BcM_State
851 runBc init_st m = case m init_st of { (r,st) -> st }
853 thenBc :: BcM a -> (a -> BcM b) -> BcM b
855 = case expr st of { (result, st') -> cont result st' }
857 thenBc_ :: BcM a -> BcM b -> BcM b
859 = case expr st of { (result, st') -> cont st' }
861 returnBc :: a -> BcM a
862 returnBc result st = (result, st)
864 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
865 mapBc f [] = returnBc []
867 = f x `thenBc` \ r ->
868 mapBc f xs `thenBc` \ rs ->
871 emitBc :: ProtoBCO Name -> BcM ()
873 = ((), st{bcos = bco : bcos st})
875 getLabelBc :: BcM Int
877 = (nextlabel st, st{nextlabel = 1 + nextlabel st})