2 % (c) The University of Glasgow 2000
4 \section[ByteCodeGen]{Generate bytecode from Core}
7 module ByteCodeGen ( byteCodeGen, assembleBCO ) where
9 #include "HsVersions.h"
12 import Name ( Name, getName )
13 import Id ( Id, idType, isDataConId_maybe )
14 import OrdList ( OrdList, consOL, snocOL, appOL, unitOL,
15 nilOL, toOL, concatOL, fromOL )
16 import FiniteMap ( FiniteMap, addListToFM, listToFM,
17 addToFM, lookupFM, fmToList, emptyFM )
19 import PprCore ( pprCoreExpr, pprCoreAlt )
20 import Literal ( Literal(..) )
21 import PrimRep ( PrimRep(..) )
22 import CoreFVs ( freeVars )
23 import Type ( typePrimRep )
24 import DataCon ( DataCon, dataConTag, fIRST_TAG, dataConTyCon )
25 import TyCon ( tyConFamilySize )
26 import Util ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem )
27 import Var ( isTyVar )
28 import VarSet ( VarSet, varSetElems )
29 import PrimRep ( getPrimRepSize, isFollowableRep )
30 import Constants ( wORD_SIZE )
32 import Monad ( foldM )
33 import Foreign ( Addr, Word16, Word32, nullAddr )
35 --import MutableArray ( readWord32Array,
36 -- newFloatArray, writeFloatArray,
37 -- newDoubleArray, writeDoubleArray,
38 -- newIntArray, writeIntArray,
39 -- newAddrArray, writeAddrArray )
47 byteCodeGen :: [CoreBind] -> [ProtoBCO Name]
49 = let flatBinds = concatMap getBind binds
50 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
51 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
52 final_state = runBc (BcM_State [] 0)
53 (mapBc schemeR flatBinds `thenBc_` returnBc ())
56 BcM_State bcos final_ctr -> bcos
60 %************************************************************************
62 \subsection{Bytecodes, and Outputery.}
64 %************************************************************************
70 data UnboxedLit = UnboxedI Int | UnboxedF Float | UnboxedD Double
73 -- Messing with the stack
75 -- Push locals (existing bits of the stack)
76 | PUSH_L Int{-offset-}
77 | PUSH_LL Int Int{-2 offsets-}
78 | PUSH_LLL Int Int Int{-3 offsets-}
81 -- Push an alt continuation
82 | PUSH_AS Name PrimRep -- push alts and BCO_ptr_ret_info
83 -- PrimRep so we know which itbl
85 | PUSH_UBX Literal -- push this int/float/double, NO TAG, on the stack
86 | PUSH_TAG Int -- push this tag on the stack
88 | SLIDE Int{-this many-} Int{-down by this much-}
89 -- To do with the heap
90 | ALLOC Int -- make an AP_UPD with this many payload words, zeroed
91 | MKAP Int{-ptr to AP_UPD is this far down stack-} Int{-# words-}
92 | UNPACK Int -- unpack N ptr words from t.o.s Constr
94 -- unpack N non-ptr words from offset M in constructor
95 -- K words down the stack
97 -- For doing case trees
99 | TESTLT_I Int LocalLabel
100 | TESTEQ_I Int LocalLabel
101 | TESTLT_F Float LocalLabel
102 | TESTEQ_F Float LocalLabel
103 | TESTLT_D Double LocalLabel
104 | TESTEQ_D Double LocalLabel
105 | TESTLT_P Int LocalLabel
106 | TESTEQ_P Int LocalLabel
108 -- To Infinity And Beyond
110 | RETURN -- unboxed value on TOS. Use tag to find underlying ret itbl
111 -- and return as per that.
114 instance Outputable BCInstr where
115 ppr (ARGCHECK n) = text "ARGCHECK" <+> int n
116 ppr (PUSH_L offset) = text "PUSH_L " <+> int offset
117 ppr (PUSH_LL o1 o2) = text "PUSH_LL " <+> int o1 <+> int o2
118 ppr (PUSH_LLL o1 o2 o3) = text "PUSH_LLL" <+> int o1 <+> int o2 <+> int o3
119 ppr (PUSH_G nm) = text "PUSH_G " <+> ppr nm
120 ppr (PUSH_AS nm pk) = text "PUSH_AS " <+> ppr nm <+> ppr pk
121 ppr (SLIDE n d) = text "SLIDE " <+> int n <+> int d
122 ppr (ALLOC sz) = text "ALLOC " <+> int sz
123 ppr (MKAP offset sz) = text "MKAP " <+> int offset <+> int sz
124 ppr (UNPACK sz) = text "UNPACK " <+> int sz
125 ppr (PACK dcon sz) = text "PACK " <+> ppr dcon <+> ppr sz
126 ppr (LABEL lab) = text "__" <> int lab <> colon
127 ppr (TESTLT_I i lab) = text "TESTLT_I" <+> int i <+> text "__" <> int lab
128 ppr (TESTEQ_I i lab) = text "TESTEQ_I" <+> int i <+> text "__" <> int lab
129 ppr (TESTLT_F f lab) = text "TESTLT_F" <+> float f <+> text "__" <> int lab
130 ppr (TESTEQ_F f lab) = text "TESTEQ_F" <+> float f <+> text "__" <> int lab
131 ppr (TESTLT_D d lab) = text "TESTLT_D" <+> double d <+> text "__" <> int lab
132 ppr (TESTEQ_D d lab) = text "TESTEQ_D" <+> double d <+> text "__" <> int lab
133 ppr (TESTLT_P i lab) = text "TESTLT_P" <+> int i <+> text "__" <> int lab
134 ppr (TESTEQ_P i lab) = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
135 ppr CASEFAIL = text "CASEFAIL"
136 ppr ENTER = text "ENTER"
137 ppr RETURN = text "RETURN"
139 pprAltCode discrs_n_codes
140 = vcat (map f discrs_n_codes)
141 where f (discr, code) = ppr discr <> colon <+> vcat (map ppr (fromOL code))
143 instance Outputable a => Outputable (ProtoBCO a) where
144 ppr (ProtoBCO name instrs origin)
145 = (text "ProtoBCO" <+> ppr name <> colon)
146 $$ nest 6 (vcat (map ppr instrs))
148 Left alts -> vcat (map (pprCoreAlt.deAnnAlt) alts)
149 Right rhs -> pprCoreExpr (deAnnotate rhs)
152 %************************************************************************
154 \subsection{Compilation schema for the bytecode generator.}
156 %************************************************************************
160 type BCInstrList = OrdList BCInstr
163 = ProtoBCO a -- name, in some sense
165 -- what the BCO came from
166 (Either [AnnAlt Id VarSet]
170 type Sequel = Int -- back off to this depth before ENTER
172 -- Maps Ids to the offset from the stack _base_ so we don't have
173 -- to mess with it after each push/pop.
174 type BCEnv = FiniteMap Id Int -- To find vars on the stack
177 -- Create a BCO and do a spot of peephole optimisation on the insns
179 mkProtoBCO nm instrs_ordlist origin
180 = ProtoBCO nm (peep (fromOL instrs_ordlist)) origin
182 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
183 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
184 peep (PUSH_L off1 : PUSH_L off2 : rest)
185 = PUSH_LL off1 off2 : peep rest
192 -- Compile code for the right hand side of a let binding.
193 -- Park the resulting BCO in the monad. Also requires the
194 -- variable to which this value was bound, so as to give the
195 -- resulting BCO a name.
196 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
197 schemeR (nm, rhs) = schemeR_wrk rhs nm (collect [] rhs)
199 collect xs (_, AnnLam x e)
200 = collect (if isTyVar x then xs else (x:xs)) e
201 collect xs not_lambda
202 = (reverse xs, not_lambda)
204 schemeR_wrk original_body nm (args, body)
205 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
206 all_args = fvs ++ reverse args
207 szsw_args = map taggedIdSizeW all_args
208 szw_args = sum szsw_args
209 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
210 argcheck = if null args then nilOL else unitOL (ARGCHECK szw_args)
212 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
213 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
215 -- Let szsw be the sizes in words of some items pushed onto the stack,
216 -- which has initial depth d'. Return the values which the stack environment
217 -- should map these items to.
218 mkStackOffsets :: Int -> [Int] -> [Int]
219 mkStackOffsets original_depth szsw
220 = map (subtract 1) (tail (scanl (+) original_depth szsw))
222 -- Compile code to apply the given expression to the remaining args
223 -- on the stack, returning a HNF.
224 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
226 -- Delegate tail-calls to schemeT.
227 schemeE d s p e@(fvs, AnnApp f a)
228 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
229 schemeE d s p e@(fvs, AnnVar v)
230 | isFollowableRep (typePrimRep (idType v))
231 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
233 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
234 let (push, szw) = pushAtom True d p (AnnVar v)
235 in returnBc (push -- value onto stack
236 `snocOL` SLIDE szw (d-s) -- clear to sequel
237 `snocOL` RETURN) -- go
239 schemeE d s p (fvs, AnnLit literal)
240 = let (push, szw) = pushAtom True d p (AnnLit literal)
241 in returnBc (push -- value onto stack
242 `snocOL` SLIDE szw (d-s) -- clear to sequel
243 `snocOL` RETURN) -- go
245 schemeE d s p (fvs, AnnLet binds b)
246 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
247 AnnRec xs_n_rhss -> unzip xs_n_rhss
249 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
250 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
252 -- This p', d' defn is safe because all the items being pushed
253 -- are ptrs, so all have size 1. d' and p' reflect the stack
254 -- after the closures have been allocated in the heap (but not
255 -- filled in), and pointers to them parked on the stack.
256 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
259 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
260 zipE = zipEqual "schemeE"
261 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
263 -- ToDo: don't build thunks for things with no free variables
264 buildThunk dd ([], size, id, off)
265 = PUSH_G (getName id)
266 `consOL` unitOL (MKAP (off+size-1) size)
267 buildThunk dd ((fv:fvs), size, id, off)
268 = case pushAtom True dd p' (AnnVar fv) of
269 (push_code, pushed_szw)
271 buildThunk (dd+pushed_szw) (fvs, size, id, off)
273 thunkCode = concatOL (map (buildThunk d') infos)
274 allocCode = toOL (map ALLOC sizes)
276 schemeE d' s p' b `thenBc` \ bodyCode ->
277 mapBc schemeR (zip xs rhss) `thenBc_`
278 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
281 schemeE d s p (fvs, AnnCase scrut bndr alts)
283 -- Top of stack is the return itbl, as usual.
284 -- underneath it is the pointer to the alt_code BCO.
285 -- When an alt is entered, it assumes the returned value is
286 -- on top of the itbl.
289 -- Env and depth in which to compile the alts, not including
290 -- any vars bound by the alts themselves
291 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
292 p' = addToFM p bndr (d' - 1)
294 scrut_primrep = typePrimRep (idType bndr)
296 = case scrut_primrep of
297 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
299 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
301 -- given an alt, return a discr and code for it.
302 codeAlt alt@(discr, binds_f, rhs)
304 = let binds_r = reverse binds_f
305 binds_r_szsw = map untaggedIdSizeW binds_r
306 binds_szw = sum binds_r_szsw
308 p' (zip binds_r (mkStackOffsets d' binds_r_szsw))
310 unpack_code = mkUnpackCode 0 0 (map (typePrimRep.idType) binds_f)
311 in schemeE d'' s p'' rhs `thenBc` \ rhs_code ->
312 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
314 = ASSERT(null binds_f)
315 schemeE d' s p' rhs `thenBc` \ rhs_code ->
316 returnBc (my_discr alt, rhs_code)
318 my_discr (DEFAULT, binds, rhs) = NoDiscr
319 my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc)
320 my_discr (LitAlt l, binds, rhs)
321 = case l of MachInt i -> DiscrI (fromInteger i)
322 MachFloat r -> DiscrF (fromRational r)
323 MachDouble r -> DiscrD (fromRational r)
326 | not isAlgCase = Nothing
328 = case [dc | (DataAlt dc, _, _) <- alts] of
330 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
333 mapBc codeAlt alts `thenBc` \ alt_stuff ->
334 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
336 alt_bco_name = getName bndr
337 alt_bco = mkProtoBCO alt_bco_name alt_final (Left alts)
339 schemeE (d + ret_frame_sizeW)
340 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
342 emitBc alt_bco `thenBc_`
343 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
346 schemeE d s p (fvs, AnnNote note body)
350 = pprPanic "ByteCodeGen.schemeE: unhandled case"
351 (pprCoreExpr (deAnnotate other))
354 -- Compile code to do a tail call. Doesn't need to be monadic.
355 schemeT :: Bool -- do tagging?
356 -> Int -- Stack depth
357 -> Sequel -- Sequel depth
358 -> Int -- # arg words so far
359 -> BCEnv -- stack env
360 -> AnnExpr Id VarSet -> BCInstrList
362 schemeT enTag d s narg_words p (_, AnnApp f a)
364 AnnType _ -> schemeT enTag d s narg_words p f
366 -> let (push, arg_words) = pushAtom enTag d p (snd a)
368 `appOL` schemeT enTag (d+arg_words) s (narg_words+arg_words) p f
370 schemeT enTag d s narg_words p (_, AnnVar f)
371 | Just con <- isDataConId_maybe f
372 = ASSERT(enTag == False)
373 PACK con narg_words `consOL` (mkSLIDE 1 (d-s-1) `snocOL` ENTER)
375 = ASSERT(enTag == True)
376 let (push, arg_words) = pushAtom True d p (AnnVar f)
378 `appOL` mkSLIDE (narg_words+arg_words) (d - s - narg_words)
382 = if d == 0 then nilOL else unitOL (SLIDE n d)
384 should_args_be_tagged (_, AnnVar v)
385 = case isDataConId_maybe v of
386 Just dcon -> False; Nothing -> True
387 should_args_be_tagged (_, AnnApp f a)
388 = should_args_be_tagged f
389 should_args_be_tagged (_, other)
390 = panic "should_args_be_tagged: tail call to non-con, non-var"
393 -- Make code to unpack a constructor onto the stack, adding
394 -- tags for the unboxed bits. Takes the PrimReps of the constructor's
395 -- arguments, and a travelling offset along both the constructor
396 -- (off_h) and the stack (off_s).
397 mkUnpackCode :: Int -> Int -> [PrimRep] -> BCInstrList
398 mkUnpackCode off_h off_s [] = nilOL
399 mkUnpackCode off_h off_s (r:rs)
401 = let (rs_ptr, rs_nptr) = span isFollowableRep (r:rs)
402 ptrs_szw = sum (map untaggedSizeW rs_ptr)
403 in ASSERT(ptrs_szw == length rs_ptr)
407 `consOL` mkUnpackCode (off_h + ptrs_szw) (off_s + ptrs_szw) rs_nptr
412 DoubleRep -> approved
414 approved = UPK_TAG usizeW off_h off_s `consOL` theRest
415 theRest = mkUnpackCode (off_h + usizeW) (off_s + tsizeW) rs
416 usizeW = untaggedSizeW r
417 tsizeW = taggedSizeW r
419 -- Push an atom onto the stack, returning suitable code & number of
420 -- stack words used. Pushes it either tagged or untagged, since
421 -- pushAtom is used to set up the stack prior to copying into the
422 -- heap for both APs (requiring tags) and constructors (which don't).
424 -- NB this means NO GC between pushing atoms for a constructor and
425 -- copying them into the heap. It probably also means that
426 -- tail calls MUST be of the form atom{atom ... atom} since if the
427 -- expression head was allowed to be arbitrary, there could be GC
428 -- in between pushing the arg atoms and completing the head.
429 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
430 -- isn't a problem; but only if arbitrary graph construction for the
431 -- head doesn't leave this BCO, since GC might happen at the start of
432 -- each BCO (we consult doYouWantToGC there).
434 -- Blargh. JRS 001206
436 -- NB (further) that the env p must map each variable to the highest-
437 -- numbered stack slot for it. For example, if the stack has depth 4
438 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
439 -- the tag in stack[5], the stack will have depth 6, and p must map v to
440 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
441 -- 6 stack has valid words 0 .. 5.
443 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
444 pushAtom tagged d p (AnnVar v)
445 = let str = "\npushAtom " ++ showSDocDebug (ppr v) ++ ", depth = " ++ show d
447 showSDocDebug (nest 4 (vcat (map ppr (fmToList p))))
449 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
450 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
451 str' = if str == str then str else str
454 = case lookupBCEnv_maybe p v of
455 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
456 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
459 sz_t = taggedIdSizeW v
460 sz_u = untaggedIdSizeW v
461 nwords = if tagged then sz_t else sz_u
466 pushAtom True d p (AnnLit lit)
467 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
468 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
470 pushAtom False d p (AnnLit lit)
472 MachInt i -> (code, untaggedSizeW IntRep)
473 MachFloat r -> (code, untaggedSizeW FloatRep)
474 MachDouble r -> (code, untaggedSizeW DoubleRep)
476 code = unitOL (PUSH_UBX lit)
478 pushAtom tagged d p (AnnApp f (_, AnnType _))
479 = pushAtom tagged d p (snd f)
481 pushAtom tagged d p other
482 = pprPanic "ByteCodeGen.pushAtom"
483 (pprCoreExpr (deAnnotate (undefined, other)))
486 -- Given a bunch of alts code and their discrs, do the donkey work
487 -- of making a multiway branch using a switch tree.
488 -- What a load of hassle!
489 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
490 -- a hint; generates better code
491 -- Nothing is always safe
492 -> [(Discr, BCInstrList)]
494 mkMultiBranch maybe_ncons raw_ways
495 = let d_way = filter (isNoDiscr.fst) raw_ways
496 notd_ways = naturalMergeSortLe
497 (\w1 w2 -> leAlt (fst w1) (fst w2))
498 (filter (not.isNoDiscr.fst) raw_ways)
500 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
501 mkTree [] range_lo range_hi = returnBc the_default
503 mkTree [val] range_lo range_hi
504 | range_lo `eqAlt` range_hi
507 = getLabelBc `thenBc` \ label_neq ->
508 returnBc (mkTestEQ (fst val) label_neq
510 `appOL` unitOL (LABEL label_neq)
511 `appOL` the_default))
513 mkTree vals range_lo range_hi
514 = let n = length vals `div` 2
515 vals_lo = take n vals
516 vals_hi = drop n vals
517 v_mid = fst (head vals_hi)
519 getLabelBc `thenBc` \ label_geq ->
520 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
521 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
522 returnBc (mkTestLT v_mid label_geq
524 `appOL` unitOL (LABEL label_geq)
528 = case d_way of [] -> unitOL CASEFAIL
531 -- None of these will be needed if there are no non-default alts
532 (mkTestLT, mkTestEQ, init_lo, init_hi)
534 = panic "mkMultiBranch: awesome foursome"
536 = case fst (head notd_ways) of {
537 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
538 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
541 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
542 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
545 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
546 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
549 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
550 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
555 (algMinBound, algMaxBound)
556 = case maybe_ncons of
557 Just n -> (fIRST_TAG, fIRST_TAG + n - 1)
558 Nothing -> (minBound, maxBound)
560 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
561 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
562 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
563 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
564 NoDiscr `eqAlt` NoDiscr = True
567 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
568 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
569 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
570 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
571 NoDiscr `leAlt` NoDiscr = True
574 isNoDiscr NoDiscr = True
577 dec (DiscrI i) = DiscrI (i-1)
578 dec (DiscrP i) = DiscrP (i-1)
579 dec other = other -- not really right, but if you
580 -- do cases on floating values, you'll get what you deserve
582 -- same snotty comment applies to the following
590 mkTree notd_ways init_lo init_hi
594 %************************************************************************
596 \subsection{Supporting junk for the compilation schemes}
598 %************************************************************************
602 -- Describes case alts
610 instance Outputable Discr where
611 ppr (DiscrI i) = int i
612 ppr (DiscrF f) = text (show f)
613 ppr (DiscrD d) = text (show d)
614 ppr (DiscrP i) = int i
615 ppr NoDiscr = text "DEF"
618 -- Find things in the BCEnv (the what's-on-the-stack-env)
619 -- See comment preceding pushAtom for precise meaning of env contents
620 lookupBCEnv :: BCEnv -> Id -> Int
622 = case lookupFM env nm of
623 Nothing -> pprPanic "lookupBCEnv"
624 (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
627 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
628 lookupBCEnv_maybe = lookupFM
631 -- When I push one of these on the stack, how much does Sp move by?
632 taggedSizeW :: PrimRep -> Int
634 | isFollowableRep pr = 1
635 | otherwise = 1{-the tag-} + getPrimRepSize pr
638 -- The plain size of something, without tag.
639 untaggedSizeW :: PrimRep -> Int
641 | isFollowableRep pr = 1
642 | otherwise = getPrimRepSize pr
645 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
646 taggedIdSizeW = taggedSizeW . typePrimRep . idType
647 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
651 %************************************************************************
653 \subsection{The bytecode generator's monad}
655 %************************************************************************
659 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
660 nextlabel :: Int } -- for generating local labels
662 type BcM result = BcM_State -> (result, BcM_State)
664 mkBcM_State :: [ProtoBCO Name] -> Int -> BcM_State
665 mkBcM_State = BcM_State
667 runBc :: BcM_State -> BcM () -> BcM_State
668 runBc init_st m = case m init_st of { (r,st) -> st }
670 thenBc :: BcM a -> (a -> BcM b) -> BcM b
672 = case expr st of { (result, st') -> cont result st' }
674 thenBc_ :: BcM a -> BcM b -> BcM b
676 = case expr st of { (result, st') -> cont st' }
678 returnBc :: a -> BcM a
679 returnBc result st = (result, st)
681 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
682 mapBc f [] = returnBc []
684 = f x `thenBc` \ r ->
685 mapBc f xs `thenBc` \ rs ->
688 emitBc :: ProtoBCO Name -> BcM ()
690 = ((), st{bcos = bco : bcos st})
692 getLabelBc :: BcM Int
694 = (nextlabel st, st{nextlabel = 1 + nextlabel st})
698 %************************************************************************
700 \subsection{The bytecode assembler}
702 %************************************************************************
704 The object format for bytecodes is: 16 bits for the opcode, and 16 for
705 each field -- so the code can be considered a sequence of 16-bit ints.
706 Each field denotes either a stack offset or number of items on the
707 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
708 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
712 -- An (almost) assembled BCO.
713 data BCO a = BCO [Word16] -- instructions
714 [Word32] -- literal pool
715 [a] -- Names or HValues
717 -- Top level assembler fn.
718 assembleBCO :: ProtoBCO Name -> IO AsmState
719 assembleBCO (ProtoBCO nm instrs origin)
721 -- pass 1: collect up the offsets of the local labels
722 label_env = mkLabelEnv emptyFM 0 instrs
724 mkLabelEnv env i_offset [] = env
725 mkLabelEnv env i_offset (i:is)
727 = case i of LABEL n -> addToFM env n i_offset ; _ -> env
728 in mkLabelEnv new_env (i_offset + instrSizeB i) is
731 = case lookupFM label_env lab of
732 Just bco_offset -> bco_offset
733 Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
739 do insns <- newXIOUArray init_n_insns :: IO (XIOUArray Word16)
740 lits <- newXIOUArray init_n_lits :: IO (XIOUArray Word32)
741 ptrs <- newXIOArray init_n_ptrs -- :: IO (XIOArray Name)
743 -- pass 2: generate the instruction, ptr and nonptr bits
744 let init_asm_state = (insns,lits,ptrs)
745 final_asm_state <- mkBits findLabel init_asm_state instrs
747 return final_asm_state
750 -- instrs nonptrs ptrs
751 type AsmState = (XIOUArray Word16, XIOUArray Word32, XIOArray Name)
754 -- This is where all the action is (pass 2 of the assembler)
755 mkBits :: (Int -> Int) -- label finder
757 -> [BCInstr] -- instructions (in)
760 mkBits findLabel st proto_insns
761 = foldM doInstr st proto_insns
763 doInstr :: AsmState -> BCInstr -> IO AsmState
766 ARGCHECK n -> instr2 st i_ARGCHECK n
768 PUSH_L o1 -> do { instr2 i_PUSH_L o1 }
769 PUSH_LL o1 o2 -> do { instr3 i_PUSH_LL o1 o2 }
770 PUSH_LLL o1 o2 o3 -> do { instr4 i_PUSH_LLL o1 o2 o3 }
771 PUSH_G nm -> do { p <- ptr nm; instr2 i_PUSH_G p }
772 PUSH_AS nm pk -> do { p <- ptr nm ; np <- ret_itbl pk;
773 instr3 i_PUSH_AS p np }
774 PUSH_UBX lit -> do { np <- literal lit; instr2 i_PUSH_UBX np }
775 PUSH_TAG tag -> do { instr2 i_PUSH_TAG tag }
776 SLIDE n by -> do { instr3 i_SLIDE n by }
777 ALLOC n -> do { instr2 i_ALLOC n }
778 MKAP off sz -> do { instr3 i_MKAP off sz }
779 UNPACK n -> do { instr2 i_UNPACK n }
780 UPK_TAG n m k -> do { instr4 i_UPK_TAG n m k }
781 PACK dcon sz -> do { np <- itbl dcon; instr3 i_PACK np sz }
782 LABEL lab -> do { instr0 }
783 TESTLT_I i l -> do { np <- int i; instr3 i_TESTLT_I np (findLabel l) }
784 TESTRQ_I i l -> do { np <- int i; instr3 i_TESTEQ_I np (findLabel l) }
785 TESTLT_F f l -> do { np <- float f; instr3 i_TESTLT_F np (findLabel l) }
786 TESTEQ_F f l -> do { np <- float f; instr3 i_TESTEQ_F np (findLabel l) }
787 TESTLT_D d l -> do { np <- double d; instr3 i_TESTLT_D np (findLabel l) }
788 TESTEQ_D d l -> do { np <- double d; instr3 i_TESTEQ_D np (findLabel l) }
789 TESTLT_P i l -> do { np <- int i; instr3 i_TESTLT_P np (findLabel l) }
790 TESTEQ_P i l -> do { np <- int i; instr3 i_TESTEQ_P np (findLabel l) }
791 CASEFAIL -> do { instr1 i_CASEFAIL }
792 ENTER -> do { instr1 i_ENTER }
795 instr2 (st_i0,st_l0,st_p0) i1 i2
796 = do st_i1 <- addToXIOUArray st_i0 (i2s i1)
797 st_i2 <- addToXIOUArray st_i1 (i2s i2)
798 return (st_i2,st_l0,st_p0)
804 instr2 i1 i2 = instr i1 >> instr i2
805 instr3 i1 i2 i3 = instr2 i1 i2 >> instr i3
806 instr4 i1 i2 i3 i4 = instr2 i1 i2 >> instr2 i3 i4
808 instr :: Word16 -> IO Ctrs
810 = do n_is <- readIORef v_n_is
812 writeIORef v_n_is (n_is+1)
815 nop = go n_is n_lits n_ptrs instrs
818 = do writeInstr r_is i1 n_is
819 next (n_is+1) n_lits n_ptrs instrs
821 = do writeInstr r_is i1 n_is
822 writeInstr r_is i1 (n_is+1)
823 next (n_is+2) n_lits n_ptrs instrs
825 = do writeInstr r_is i1 n_is
826 writeInstr r_is i2 (n_is+1)
827 writeInstr r_is i3 (n_is+2)
828 next (n_is+3) n_lits n_ptrs instrs
830 ptr p n_is n_lits n_ptrs instrs
831 = do writeArray r_ptrs p n_ptrs
832 mkBits n_is n_lits (n_ptrs+1) instrs
834 int i n_is n_lits n_ptrs instrs
835 = do n_lits <- doILit r_lits i n_lits
836 mkBits n_is n_lits n_ptrs instrs
838 float f n_is n_lits n_ptrs instrs
839 = do n_lits <- doFLit r_lits f n_lits
840 mkBits n_is n_lits n_ptrs instrs
842 double d n_is n_lits n_ptrs instrs
843 = do n_lits <- doDLit r_lits d n_lits
844 mkBits n_is n_lits n_ptrs instrs
846 addr a n_is n_lits n_ptrs instrs
847 = do n_lits <- doALit r_lits a n_lits
848 mkBits n_is n_lits n_ptrs instrs
851 --writeInstr :: MutableByteArray# -> Int -> Int -> IO ()
852 --writeInstr arr# ix e = IO $ \s ->
853 -- case writeWord16Array# arr# ix e of
857 -- The size in bytes of an instruction.
858 instrSizeB :: BCInstr -> Int
885 -- Sizes of Int, Float and Double literals, in units of 32-bitses
886 intLitSz32s, floatLitSz32s, doubleLitSz32s, addrLitSz32s :: Int
887 intLitSz32s = wORD_SIZE `div` 4
888 floatLitSz32s = 1 -- Assume IEEE floats
890 addrLitSz32s = intLitSz32s
892 -- Make lists of 32-bit words for literals, so that when the
893 -- words are placed in memory at increasing addresses, the
894 -- bit pattern is correct for the host's word size and endianness.
895 mkILit :: Int -> [Word32]
896 mkFLit :: Float -> [Word32]
897 mkDLit :: Double -> [Word32]
898 mkALit :: Addr -> [Word32]
902 arr <- newFloatArray ((0::Int),0)
903 writeFloatArray arr 0 f
904 f_arr <- castSTUArray arr
905 w0 <- readWord32Array f_arr 0
911 arr <- newDoubleArray ((0::Int),0)
912 writeDoubleArray arr 0 d
913 d_arr <- castSTUArray arr
914 w0 <- readWord32Array d_arr 0
915 w1 <- readWord32Array d_arr 1
922 arr <- newIntArray ((0::Int),0)
923 writeIntArray arr 0 i
924 i_arr <- castSTUArray arr
925 w0 <- readWord32Array i_arr 0
930 arr <- newIntArray ((0::Int),0)
931 writeIntArray arr 0 i
932 i_arr <- castSTUArray arr
933 w0 <- readWord32Array i_arr 0
934 w1 <- readWord32Array i_arr 1
941 arr <- newAddrArray ((0::Int),0)
942 writeAddrArray arr 0 a
943 a_arr <- castSTUArray arr
944 w0 <- readWord32Array a_arr 0
949 arr <- newAddrArray ((0::Int),0)
950 writeAddrArray arr 0 a
951 a_arr <- castSTUArray arr
952 w0 <- readWord32Array a_arr 0
953 w1 <- readWord32Array a_arr 1
959 -- Zero-based expandable arrays
960 data XIOUArray ele = XIOUArray Int (IOUArray Int ele)
961 data XIOArray ele = XIOArray Int (IOArray Int ele)
964 = do arr <- newArray (0, size-1)
965 return (XIOUArray 0 arr)
967 addToXIOUArray :: MArray IOUArray a IO
968 => XIOUArray a -> a -> IO (XIOUArray a)
969 addToXIOUArray (XIOUArray n_arr arr) x
971 (lo, hi) -> ASSERT(lo == 0)
973 then do new_arr <- newArray (0, 2*hi-1)
975 addToXIOUArray (XIOUArray n_arr new_arr) x
976 else do writeArray arr n_arr x
977 return (XIOUArray (n_arr+1) arr)
979 copy :: MArray IOUArray a IO
980 => Int -> IOUArray Int a -> IOUArray Int a -> IO ()
983 | otherwise = do nx <- readArray src n
990 = do arr <- newArray (0, size-1)
991 return (XIOArray 0 arr)
993 addToXIOArray :: XIOArray a -> a -> IO (XIOArray a)
994 addToXIOArray (XIOArray n_arr arr) x
996 (lo, hi) -> ASSERT(lo == 0)
998 then do new_arr <- newArray (0, 2*hi-1)
1000 addToXIOArray (XIOArray n_arr new_arr) x
1001 else do writeArray arr n_arr x
1002 return (XIOArray (n_arr+1) arr)
1004 copy :: Int -> IOArray Int a -> IOArray Int a -> IO ()
1007 | otherwise = do nx <- readArray src n
1012 #include "Bytecodes.h"
1014 i_ARGCHECK = (bci_ARGCHECK :: Int)
1015 i_PUSH_L = (bci_PUSH_L :: Int)
1016 i_PUSH_LL = (bci_PUSH_LL :: Int)
1017 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
1018 i_PUSH_G = (bci_PUSH_G :: Int)
1019 i_PUSH_AS = (bci_PUSH_AS :: Int)
1020 i_PUSHT_I = (bci_PUSHT_I :: Int)
1021 i_PUSHT_F = (bci_PUSHT_F :: Int)
1022 i_PUSHT_D = (bci_PUSHT_D :: Int)
1023 i_PUSHU_I = (bci_PUSHU_I :: Int)
1024 i_PUSHU_F = (bci_PUSHU_F :: Int)
1025 i_PUSHU_D = (bci_PUSHU_D :: Int)
1026 i_SLIDE = (bci_SLIDE :: Int)
1027 i_ALLOC = (bci_ALLOC :: Int)
1028 i_MKAP = (bci_MKAP :: Int)
1029 i_UNPACK = (bci_UNPACK :: Int)
1030 i_PACK = (bci_PACK :: Int)
1031 i_LABEL = (bci_LABEL :: Int)
1032 i_TESTLT_I = (bci_TESTLT_I :: Int)
1033 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
1034 i_TESTLT_F = (bci_TESTLT_F :: Int)
1035 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
1036 i_TESTLT_D = (bci_TESTLT_D :: Int)
1037 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
1038 i_TESTLT_P = (bci_TESTLT_P :: Int)
1039 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
1040 i_CASEFAIL = (bci_CASEFAIL :: Int)
1041 i_ENTER = (bci_ENTER :: Int)
1042 i_RETURN = (bci_RETURN :: Int)