2 % (c) The University of Glasgow 2000
4 \section[ByteCodeGen]{Generate bytecode from Core}
7 module ByteCodeGen ( byteCodeGen, linkIModules ) 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, plusFM )
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,
26 import TyCon ( TyCon, tyConFamilySize, isDataTyCon, tyConDataCons )
27 import Class ( Class, classTyCon )
28 import Util ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem, global )
29 import Var ( isTyVar )
30 import VarSet ( VarSet, varSetElems )
31 import PrimRep ( getPrimRepSize, isFollowableRep )
32 import Constants ( wORD_SIZE )
33 import CmdLineOpts ( DynFlags, DynFlag(..) )
34 import ErrUtils ( showPass, dumpIfSet_dyn )
35 import ClosureInfo ( mkVirtHeapOffsets )
37 import List ( intersperse )
38 import Monad ( foldM )
40 import MArray ( MArray(..), IOArray, IOUArray, HasBounds(..), freeze,
42 castSTUArray, readWord32Array,
43 newFloatArray, writeFloatArray,
44 newDoubleArray, writeDoubleArray,
45 newIntArray, writeIntArray,
46 newAddrArray, writeAddrArray )
47 import Foreign ( Storable(..), Word8, Word16, Word32, Ptr(..),
48 malloc, castPtr, plusPtr )
49 import Addr ( Addr, addrToInt, nullAddr )
50 import Bits ( Bits(..), shiftR )
52 import PrelGHC ( BCO#, newBCO#, unsafeCoerce#, ByteArray#, Array# )
53 import IOExts ( IORef, readIORef, writeIORef, fixIO )
55 import PrelArr ( Array(..) )
56 import PrelIOBase ( IO(..) )
62 -- visible from outside
63 byteCodeGen :: DynFlags
66 -> IO ([UnlinkedBCO], ItblEnv)
67 byteCodeGen dflags binds local_tycons local_classes
68 = do showPass dflags "ByteCodeGen"
69 let tycs = local_tycons ++ map classTyCon local_classes
70 itblenv <- mkITbls tycs
72 let flatBinds = concatMap getBind binds
73 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
74 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
75 final_state = runBc (BcM_State [] 0)
76 (mapBc schemeR flatBinds `thenBc_` returnBc ())
77 (BcM_State proto_bcos final_ctr) = final_state
79 dumpIfSet_dyn dflags Opt_D_dump_BCOs
80 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
82 bcos <- mapM assembleBCO proto_bcos
84 return (bcos, itblenv)
89 Int (IOUArray Int Word16) -- insns
90 Int (IOUArray Int Word32) -- literals
91 Int (IOArray Int Name) -- ptrs
92 Int (IOArray Int Name) -- itbl refs
94 nameOfUnlinkedBCO (UnlinkedBCO nm _ _ _ _ _ _ _ _) = nm
96 -- needs a proper home
97 type ItblEnv = FiniteMap Name (Ptr StgInfoTable)
98 type ClosureEnv = FiniteMap Name HValue
99 data HValue = HValue -- dummy type, actually a pointer to some Real Code.
104 %************************************************************************
106 \subsection{Bytecodes, and Outputery.}
108 %************************************************************************
112 type LocalLabel = Int
114 data UnboxedLit = UnboxedI Int | UnboxedF Float | UnboxedD Double
117 -- Messing with the stack
119 -- Push locals (existing bits of the stack)
120 | PUSH_L Int{-offset-}
121 | PUSH_LL Int Int{-2 offsets-}
122 | PUSH_LLL Int Int Int{-3 offsets-}
125 -- Push an alt continuation
126 | PUSH_AS Name PrimRep -- push alts and BCO_ptr_ret_info
127 -- PrimRep so we know which itbl
129 | PUSH_UBX Literal Int
130 -- push this int/float/double, NO TAG, on the stack
131 -- Int is # of items in literal pool to push
132 | PUSH_TAG Int -- push this tag on the stack
134 | SLIDE Int{-this many-} Int{-down by this much-}
135 -- To do with the heap
136 | ALLOC Int -- make an AP_UPD with this many payload words, zeroed
137 | MKAP Int{-ptr to AP_UPD is this far down stack-} Int{-# words-}
138 | UNPACK Int -- unpack N ptr words from t.o.s Constr
139 | UPK_TAG Int Int Int
140 -- unpack N non-ptr words from offset M in constructor
141 -- K words down the stack
143 -- after assembly, the DataCon is an index into the
145 -- For doing case trees
147 | TESTLT_I Int LocalLabel
148 | TESTEQ_I Int LocalLabel
149 | TESTLT_F Float LocalLabel
150 | TESTEQ_F Float LocalLabel
151 | TESTLT_D Double LocalLabel
152 | TESTEQ_D Double LocalLabel
153 | TESTLT_P Int LocalLabel
154 | TESTEQ_P Int LocalLabel
156 -- To Infinity And Beyond
158 | RETURN -- unboxed value on TOS. Use tag to find underlying ret itbl
159 -- and return as per that.
162 instance Outputable BCInstr where
163 ppr (ARGCHECK n) = text "ARGCHECK" <+> int n
164 ppr (PUSH_L offset) = text "PUSH_L " <+> int offset
165 ppr (PUSH_LL o1 o2) = text "PUSH_LL " <+> int o1 <+> int o2
166 ppr (PUSH_LLL o1 o2 o3) = text "PUSH_LLL" <+> int o1 <+> int o2 <+> int o3
167 ppr (PUSH_G nm) = text "PUSH_G " <+> ppr nm
168 ppr (PUSH_AS nm pk) = text "PUSH_AS " <+> ppr nm <+> ppr pk
169 ppr (SLIDE n d) = text "SLIDE " <+> int n <+> int d
170 ppr (ALLOC sz) = text "ALLOC " <+> int sz
171 ppr (MKAP offset sz) = text "MKAP " <+> int offset <+> int sz
172 ppr (UNPACK sz) = text "UNPACK " <+> int sz
173 ppr (PACK dcon sz) = text "PACK " <+> ppr dcon <+> ppr sz
174 ppr (LABEL lab) = text "__" <> int lab <> colon
175 ppr (TESTLT_I i lab) = text "TESTLT_I" <+> int i <+> text "__" <> int lab
176 ppr (TESTEQ_I i lab) = text "TESTEQ_I" <+> int i <+> text "__" <> int lab
177 ppr (TESTLT_F f lab) = text "TESTLT_F" <+> float f <+> text "__" <> int lab
178 ppr (TESTEQ_F f lab) = text "TESTEQ_F" <+> float f <+> text "__" <> int lab
179 ppr (TESTLT_D d lab) = text "TESTLT_D" <+> double d <+> text "__" <> int lab
180 ppr (TESTEQ_D d lab) = text "TESTEQ_D" <+> double d <+> text "__" <> int lab
181 ppr (TESTLT_P i lab) = text "TESTLT_P" <+> int i <+> text "__" <> int lab
182 ppr (TESTEQ_P i lab) = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
183 ppr CASEFAIL = text "CASEFAIL"
184 ppr ENTER = text "ENTER"
185 ppr RETURN = text "RETURN"
187 pprAltCode discrs_n_codes
188 = vcat (map f discrs_n_codes)
189 where f (discr, code) = ppr discr <> colon <+> vcat (map ppr (fromOL code))
191 instance Outputable a => Outputable (ProtoBCO a) where
192 ppr (ProtoBCO name instrs origin)
193 = (text "ProtoBCO" <+> ppr name <> colon)
194 $$ nest 6 (vcat (map ppr instrs))
196 Left alts -> vcat (map (pprCoreAlt.deAnnAlt) alts)
197 Right rhs -> pprCoreExpr (deAnnotate rhs)
200 %************************************************************************
202 \subsection{Compilation schema for the bytecode generator.}
204 %************************************************************************
208 type BCInstrList = OrdList BCInstr
211 = ProtoBCO a -- name, in some sense
213 -- what the BCO came from
214 (Either [AnnAlt Id VarSet]
218 type Sequel = Int -- back off to this depth before ENTER
220 -- Maps Ids to the offset from the stack _base_ so we don't have
221 -- to mess with it after each push/pop.
222 type BCEnv = FiniteMap Id Int -- To find vars on the stack
225 -- Create a BCO and do a spot of peephole optimisation on the insns
227 mkProtoBCO nm instrs_ordlist origin
228 = ProtoBCO nm (peep (fromOL instrs_ordlist)) origin
230 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
231 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
232 peep (PUSH_L off1 : PUSH_L off2 : rest)
233 = PUSH_LL off1 off2 : peep rest
240 -- Compile code for the right hand side of a let binding.
241 -- Park the resulting BCO in the monad. Also requires the
242 -- variable to which this value was bound, so as to give the
243 -- resulting BCO a name.
244 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
245 schemeR (nm, rhs) = schemeR_wrk rhs nm (collect [] rhs)
247 collect xs (_, AnnLam x e)
248 = collect (if isTyVar x then xs else (x:xs)) e
249 collect xs not_lambda
250 = (reverse xs, not_lambda)
252 schemeR_wrk original_body nm (args, body)
253 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
254 all_args = fvs ++ reverse args
255 szsw_args = map taggedIdSizeW all_args
256 szw_args = sum szsw_args
257 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
258 argcheck = if null args then nilOL else unitOL (ARGCHECK szw_args)
260 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
261 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
263 -- Let szsw be the sizes in words of some items pushed onto the stack,
264 -- which has initial depth d'. Return the values which the stack environment
265 -- should map these items to.
266 mkStackOffsets :: Int -> [Int] -> [Int]
267 mkStackOffsets original_depth szsw
268 = map (subtract 1) (tail (scanl (+) original_depth szsw))
270 -- Compile code to apply the given expression to the remaining args
271 -- on the stack, returning a HNF.
272 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
274 -- Delegate tail-calls to schemeT.
275 schemeE d s p e@(fvs, AnnApp f a)
276 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
277 schemeE d s p e@(fvs, AnnVar v)
278 | isFollowableRep (typePrimRep (idType v))
279 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
281 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
282 let (push, szw) = pushAtom True d p (AnnVar v)
283 in returnBc (push -- value onto stack
284 `snocOL` SLIDE szw (d-s) -- clear to sequel
285 `snocOL` RETURN) -- go
287 schemeE d s p (fvs, AnnLit literal)
288 = let (push, szw) = pushAtom True d p (AnnLit literal)
289 in returnBc (push -- value onto stack
290 `snocOL` SLIDE szw (d-s) -- clear to sequel
291 `snocOL` RETURN) -- go
293 schemeE d s p (fvs, AnnLet binds b)
294 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
295 AnnRec xs_n_rhss -> unzip xs_n_rhss
297 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
298 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
300 -- This p', d' defn is safe because all the items being pushed
301 -- are ptrs, so all have size 1. d' and p' reflect the stack
302 -- after the closures have been allocated in the heap (but not
303 -- filled in), and pointers to them parked on the stack.
304 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
307 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
308 zipE = zipEqual "schemeE"
309 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
311 -- ToDo: don't build thunks for things with no free variables
312 buildThunk dd ([], size, id, off)
313 = PUSH_G (getName id)
314 `consOL` unitOL (MKAP (off+size-1) size)
315 buildThunk dd ((fv:fvs), size, id, off)
316 = case pushAtom True dd p' (AnnVar fv) of
317 (push_code, pushed_szw)
319 buildThunk (dd+pushed_szw) (fvs, size, id, off)
321 thunkCode = concatOL (map (buildThunk d') infos)
322 allocCode = toOL (map ALLOC sizes)
324 schemeE d' s p' b `thenBc` \ bodyCode ->
325 mapBc schemeR (zip xs rhss) `thenBc_`
326 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
329 schemeE d s p (fvs, AnnCase scrut bndr alts)
331 -- Top of stack is the return itbl, as usual.
332 -- underneath it is the pointer to the alt_code BCO.
333 -- When an alt is entered, it assumes the returned value is
334 -- on top of the itbl.
337 -- Env and depth in which to compile the alts, not including
338 -- any vars bound by the alts themselves
339 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
340 p' = addToFM p bndr (d' - 1)
342 scrut_primrep = typePrimRep (idType bndr)
344 = case scrut_primrep of
345 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
347 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
349 -- given an alt, return a discr and code for it.
350 codeAlt alt@(discr, binds_f, rhs)
352 = let binds_r = reverse binds_f
353 binds_r_szsw = map untaggedIdSizeW binds_r
354 binds_szw = sum binds_r_szsw
356 p' (zip binds_r (mkStackOffsets d' binds_r_szsw))
358 unpack_code = mkUnpackCode 0 0 (map (typePrimRep.idType) binds_f)
359 in schemeE d'' s p'' rhs `thenBc` \ rhs_code ->
360 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
362 = ASSERT(null binds_f)
363 schemeE d' s p' rhs `thenBc` \ rhs_code ->
364 returnBc (my_discr alt, rhs_code)
366 my_discr (DEFAULT, binds, rhs) = NoDiscr
367 my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc)
368 my_discr (LitAlt l, binds, rhs)
369 = case l of MachInt i -> DiscrI (fromInteger i)
370 MachFloat r -> DiscrF (fromRational r)
371 MachDouble r -> DiscrD (fromRational r)
374 | not isAlgCase = Nothing
376 = case [dc | (DataAlt dc, _, _) <- alts] of
378 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
381 mapBc codeAlt alts `thenBc` \ alt_stuff ->
382 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
384 alt_bco_name = getName bndr
385 alt_bco = mkProtoBCO alt_bco_name alt_final (Left alts)
387 schemeE (d + ret_frame_sizeW)
388 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
390 emitBc alt_bco `thenBc_`
391 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
394 schemeE d s p (fvs, AnnNote note body)
398 = pprPanic "ByteCodeGen.schemeE: unhandled case"
399 (pprCoreExpr (deAnnotate other))
402 -- Compile code to do a tail call. Doesn't need to be monadic.
403 schemeT :: Bool -- do tagging?
404 -> Int -- Stack depth
405 -> Sequel -- Sequel depth
406 -> Int -- # arg words so far
407 -> BCEnv -- stack env
411 schemeT enTag d s narg_words p (_, AnnApp f a)
413 AnnType _ -> schemeT enTag d s narg_words p f
415 -> let (push, arg_words) = pushAtom enTag d p (snd a)
417 `appOL` schemeT enTag (d+arg_words) s (narg_words+arg_words) p f
419 schemeT enTag d s narg_words p (_, AnnVar f)
420 | Just con <- isDataConId_maybe f
421 = ASSERT(enTag == False)
422 PACK con narg_words `consOL` (mkSLIDE 1 (d-s-1) `snocOL` ENTER)
424 = ASSERT(enTag == True)
425 let (push, arg_words) = pushAtom True d p (AnnVar f)
427 `appOL` mkSLIDE (narg_words+arg_words) (d - s - narg_words)
431 = if d == 0 then nilOL else unitOL (SLIDE n d)
433 should_args_be_tagged (_, AnnVar v)
434 = case isDataConId_maybe v of
435 Just dcon -> False; Nothing -> True
436 should_args_be_tagged (_, AnnApp f a)
437 = should_args_be_tagged f
438 should_args_be_tagged (_, other)
439 = panic "should_args_be_tagged: tail call to non-con, non-var"
442 -- Make code to unpack a constructor onto the stack, adding
443 -- tags for the unboxed bits. Takes the PrimReps of the constructor's
444 -- arguments, and a travelling offset along both the constructor
445 -- (off_h) and the stack (off_s).
446 mkUnpackCode :: Int -> Int -> [PrimRep] -> BCInstrList
447 mkUnpackCode off_h off_s [] = nilOL
448 mkUnpackCode off_h off_s (r:rs)
450 = let (rs_ptr, rs_nptr) = span isFollowableRep (r:rs)
451 ptrs_szw = sum (map untaggedSizeW rs_ptr)
452 in ASSERT(ptrs_szw == length rs_ptr)
456 `consOL` mkUnpackCode (off_h + ptrs_szw) (off_s + ptrs_szw) rs_nptr
461 DoubleRep -> approved
463 approved = UPK_TAG usizeW off_h off_s `consOL` theRest
464 theRest = mkUnpackCode (off_h + usizeW) (off_s + tsizeW) rs
465 usizeW = untaggedSizeW r
466 tsizeW = taggedSizeW r
468 -- Push an atom onto the stack, returning suitable code & number of
469 -- stack words used. Pushes it either tagged or untagged, since
470 -- pushAtom is used to set up the stack prior to copying into the
471 -- heap for both APs (requiring tags) and constructors (which don't).
473 -- NB this means NO GC between pushing atoms for a constructor and
474 -- copying them into the heap. It probably also means that
475 -- tail calls MUST be of the form atom{atom ... atom} since if the
476 -- expression head was allowed to be arbitrary, there could be GC
477 -- in between pushing the arg atoms and completing the head.
478 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
479 -- isn't a problem; but only if arbitrary graph construction for the
480 -- head doesn't leave this BCO, since GC might happen at the start of
481 -- each BCO (we consult doYouWantToGC there).
483 -- Blargh. JRS 001206
485 -- NB (further) that the env p must map each variable to the highest-
486 -- numbered stack slot for it. For example, if the stack has depth 4
487 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
488 -- the tag in stack[5], the stack will have depth 6, and p must map v to
489 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
490 -- 6 stack has valid words 0 .. 5.
492 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
493 pushAtom tagged d p (AnnVar v)
494 = let str = "\npushAtom " ++ showSDocDebug (ppr v) ++ ", depth = " ++ show d
496 showSDocDebug (nest 4 (vcat (map ppr (fmToList p))))
498 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
499 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
500 str' = if str == str then str else str
503 = case lookupBCEnv_maybe p v of
504 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
505 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
508 sz_t = taggedIdSizeW v
509 sz_u = untaggedIdSizeW v
510 nwords = if tagged then sz_t else sz_u
515 pushAtom True d p (AnnLit lit)
516 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
517 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
519 pushAtom False d p (AnnLit lit)
521 MachInt i -> code IntRep
522 MachFloat r -> code FloatRep
523 MachDouble r -> code DoubleRep
526 = let size_host_words = untaggedSizeW rep
527 size_in_word32s = (size_host_words * wORD_SIZE) `div` 4
528 in (unitOL (PUSH_UBX lit size_in_word32s), size_host_words)
530 pushAtom tagged d p (AnnApp f (_, AnnType _))
531 = pushAtom tagged d p (snd f)
533 pushAtom tagged d p other
534 = pprPanic "ByteCodeGen.pushAtom"
535 (pprCoreExpr (deAnnotate (undefined, other)))
538 -- Given a bunch of alts code and their discrs, do the donkey work
539 -- of making a multiway branch using a switch tree.
540 -- What a load of hassle!
541 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
542 -- a hint; generates better code
543 -- Nothing is always safe
544 -> [(Discr, BCInstrList)]
546 mkMultiBranch maybe_ncons raw_ways
547 = let d_way = filter (isNoDiscr.fst) raw_ways
548 notd_ways = naturalMergeSortLe
549 (\w1 w2 -> leAlt (fst w1) (fst w2))
550 (filter (not.isNoDiscr.fst) raw_ways)
552 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
553 mkTree [] range_lo range_hi = returnBc the_default
555 mkTree [val] range_lo range_hi
556 | range_lo `eqAlt` range_hi
559 = getLabelBc `thenBc` \ label_neq ->
560 returnBc (mkTestEQ (fst val) label_neq
562 `appOL` unitOL (LABEL label_neq)
563 `appOL` the_default))
565 mkTree vals range_lo range_hi
566 = let n = length vals `div` 2
567 vals_lo = take n vals
568 vals_hi = drop n vals
569 v_mid = fst (head vals_hi)
571 getLabelBc `thenBc` \ label_geq ->
572 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
573 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
574 returnBc (mkTestLT v_mid label_geq
576 `appOL` unitOL (LABEL label_geq)
580 = case d_way of [] -> unitOL CASEFAIL
583 -- None of these will be needed if there are no non-default alts
584 (mkTestLT, mkTestEQ, init_lo, init_hi)
586 = panic "mkMultiBranch: awesome foursome"
588 = case fst (head notd_ways) of {
589 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
590 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
593 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
594 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
597 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
598 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
601 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
602 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
607 (algMinBound, algMaxBound)
608 = case maybe_ncons of
609 Just n -> (fIRST_TAG, fIRST_TAG + n - 1)
610 Nothing -> (minBound, maxBound)
612 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
613 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
614 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
615 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
616 NoDiscr `eqAlt` NoDiscr = True
619 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
620 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
621 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
622 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
623 NoDiscr `leAlt` NoDiscr = True
626 isNoDiscr NoDiscr = True
629 dec (DiscrI i) = DiscrI (i-1)
630 dec (DiscrP i) = DiscrP (i-1)
631 dec other = other -- not really right, but if you
632 -- do cases on floating values, you'll get what you deserve
634 -- same snotty comment applies to the following
642 mkTree notd_ways init_lo init_hi
646 %************************************************************************
648 \subsection{Supporting junk for the compilation schemes}
650 %************************************************************************
654 -- Describes case alts
662 instance Outputable Discr where
663 ppr (DiscrI i) = int i
664 ppr (DiscrF f) = text (show f)
665 ppr (DiscrD d) = text (show d)
666 ppr (DiscrP i) = int i
667 ppr NoDiscr = text "DEF"
670 -- Find things in the BCEnv (the what's-on-the-stack-env)
671 -- See comment preceding pushAtom for precise meaning of env contents
672 lookupBCEnv :: BCEnv -> Id -> Int
674 = case lookupFM env nm of
675 Nothing -> pprPanic "lookupBCEnv"
676 (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
679 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
680 lookupBCEnv_maybe = lookupFM
683 -- When I push one of these on the stack, how much does Sp move by?
684 taggedSizeW :: PrimRep -> Int
686 | isFollowableRep pr = 1
687 | otherwise = 1{-the tag-} + getPrimRepSize pr
690 -- The plain size of something, without tag.
691 untaggedSizeW :: PrimRep -> Int
693 | isFollowableRep pr = 1
694 | otherwise = getPrimRepSize pr
697 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
698 taggedIdSizeW = taggedSizeW . typePrimRep . idType
699 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
703 %************************************************************************
705 \subsection{The bytecode generator's monad}
707 %************************************************************************
711 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
712 nextlabel :: Int } -- for generating local labels
714 type BcM result = BcM_State -> (result, BcM_State)
716 mkBcM_State :: [ProtoBCO Name] -> Int -> BcM_State
717 mkBcM_State = BcM_State
719 runBc :: BcM_State -> BcM () -> BcM_State
720 runBc init_st m = case m init_st of { (r,st) -> st }
722 thenBc :: BcM a -> (a -> BcM b) -> BcM b
724 = case expr st of { (result, st') -> cont result st' }
726 thenBc_ :: BcM a -> BcM b -> BcM b
728 = case expr st of { (result, st') -> cont st' }
730 returnBc :: a -> BcM a
731 returnBc result st = (result, st)
733 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
734 mapBc f [] = returnBc []
736 = f x `thenBc` \ r ->
737 mapBc f xs `thenBc` \ rs ->
740 emitBc :: ProtoBCO Name -> BcM ()
742 = ((), st{bcos = bco : bcos st})
744 getLabelBc :: BcM Int
746 = (nextlabel st, st{nextlabel = 1 + nextlabel st})
750 %************************************************************************
752 \subsection{The bytecode assembler}
754 %************************************************************************
756 The object format for bytecodes is: 16 bits for the opcode, and 16 for
757 each field -- so the code can be considered a sequence of 16-bit ints.
758 Each field denotes either a stack offset or number of items on the
759 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
760 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
764 -- Top level assembler fn.
765 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
767 assembleBCO (ProtoBCO nm instrs origin)
769 -- pass 1: collect up the offsets of the local labels
770 label_env = mkLabelEnv emptyFM 0 instrs
772 mkLabelEnv env i_offset [] = env
773 mkLabelEnv env i_offset (i:is)
775 = case i of LABEL n -> addToFM env n i_offset ; _ -> env
776 in mkLabelEnv new_env (i_offset + instrSizeB i) is
779 = case lookupFM label_env lab of
780 Just bco_offset -> bco_offset
781 Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
788 do insns <- newXIOUArray init_n_insns :: IO (XIOUArray Word16)
789 lits <- newXIOUArray init_n_lits :: IO (XIOUArray Word32)
790 ptrs <- newXIOArray init_n_ptrs -- :: IO (XIOArray Name)
791 itbls <- newXIOArray init_n_itbls -- :: IO (XIOArray Name)
793 -- pass 2: generate the instruction, ptr and nonptr bits
794 let init_asm_state = (insns,lits,ptrs,itbls)
795 final_asm_state <- mkBits findLabel init_asm_state instrs
797 -- unwrap the expandable arrays
798 let final_insns = stuffXIOU insns
799 final_lits = stuffXIOU lits
800 final_ptrs = stuffXIO ptrs
801 final_itbls = stuffXIO itbls
803 return (UnlinkedBCO nm
804 (usedXIOU insns) final_insns
805 (usedXIOU lits) final_lits
806 (usedXIO ptrs) final_ptrs
807 (usedXIO itbls) final_itbls)
810 -- instrs nonptrs ptrs itbls
811 type AsmState = (XIOUArray Word16, XIOUArray Word32, XIOArray Name, XIOArray Name)
814 -- This is where all the action is (pass 2 of the assembler)
815 mkBits :: (Int -> Int) -- label finder
817 -> [BCInstr] -- instructions (in)
820 mkBits findLabel st proto_insns
821 = foldM doInstr st proto_insns
823 doInstr :: AsmState -> BCInstr -> IO AsmState
826 ARGCHECK n -> instr2 st i_ARGCHECK n
827 PUSH_L o1 -> instr2 st i_PUSH_L o1
828 PUSH_LL o1 o2 -> instr3 st i_PUSH_LL o1 o2
829 PUSH_LLL o1 o2 o3 -> instr4 st i_PUSH_LLL o1 o2 o3
830 PUSH_G nm -> do (p, st2) <- ptr st nm
831 instr2 st2 i_PUSH_G p
832 PUSH_AS nm pk -> do (p, st2) <- ptr st nm
833 (np, st3) <- ret_itbl st2 pk
834 instr3 st3 i_PUSH_AS p np
835 PUSH_UBX lit nw32s -> do (np, st2) <- literal st lit
836 instr3 st2 i_PUSH_UBX np nw32s
837 PUSH_TAG tag -> instr2 st i_PUSH_TAG tag
838 SLIDE n by -> instr3 st i_SLIDE n by
839 ALLOC n -> instr2 st i_ALLOC n
840 MKAP off sz -> instr3 st i_MKAP off sz
841 UNPACK n -> instr2 st i_UNPACK n
842 UPK_TAG n m k -> instr4 st i_UPK_TAG n m k
843 PACK dcon sz -> do (itbl_no,st2) <- itbl st dcon
844 instr3 st2 i_PACK itbl_no sz
845 LABEL lab -> return st
846 TESTLT_I i l -> do (np, st2) <- int st i
847 instr3 st2 i_TESTLT_I np (findLabel l)
848 TESTEQ_I i l -> do (np, st2) <- int st i
849 instr3 st2 i_TESTEQ_I np (findLabel l)
850 TESTLT_F f l -> do (np, st2) <- float st f
851 instr3 st2 i_TESTLT_F np (findLabel l)
852 TESTEQ_F f l -> do (np, st2) <- float st f
853 instr3 st2 i_TESTEQ_F np (findLabel l)
854 TESTLT_D d l -> do (np, st2) <- double st d
855 instr3 st2 i_TESTLT_D np (findLabel l)
856 TESTEQ_D d l -> do (np, st2) <- double st d
857 instr3 st2 i_TESTEQ_D np (findLabel l)
858 TESTLT_P i l -> do (np, st2) <- int st i
859 instr3 st2 i_TESTLT_P np (findLabel l)
860 TESTEQ_P i l -> do (np, st2) <- int st i
861 instr3 st2 i_TESTEQ_P np (findLabel l)
862 CASEFAIL -> instr1 st i_CASEFAIL
863 ENTER -> instr1 st i_ENTER
864 RETURN -> instr1 st i_RETURN
869 instr1 (st_i0,st_l0,st_p0,st_I0) i1
870 = do st_i1 <- addToXIOUArray st_i0 (i2s i1)
871 return (st_i1,st_l0,st_p0,st_I0)
873 instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
874 = do st_i1 <- addToXIOUArray st_i0 (i2s i1)
875 st_i2 <- addToXIOUArray st_i1 (i2s i2)
876 return (st_i2,st_l0,st_p0,st_I0)
878 instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
879 = do st_i1 <- addToXIOUArray st_i0 (i2s i1)
880 st_i2 <- addToXIOUArray st_i1 (i2s i2)
881 st_i3 <- addToXIOUArray st_i2 (i2s i3)
882 return (st_i3,st_l0,st_p0,st_I0)
884 instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
885 = do st_i1 <- addToXIOUArray st_i0 (i2s i1)
886 st_i2 <- addToXIOUArray st_i1 (i2s i2)
887 st_i3 <- addToXIOUArray st_i2 (i2s i3)
888 st_i4 <- addToXIOUArray st_i3 (i2s i4)
889 return (st_i4,st_l0,st_p0,st_I0)
891 float (st_i0,st_l0,st_p0,st_I0) f
892 = do let w32s = mkLitF f
893 st_l1 <- addListToXIOUArray st_l0 w32s
894 return (usedXIOU st_l0, (st_i0,st_l1,st_p0,st_I0))
896 double (st_i0,st_l0,st_p0,st_I0) d
897 = do let w32s = mkLitD d
898 st_l1 <- addListToXIOUArray st_l0 w32s
899 return (usedXIOU st_l0, (st_i0,st_l1,st_p0,st_I0))
901 int (st_i0,st_l0,st_p0,st_I0) i
902 = do let w32s = mkLitI i
903 st_l1 <- addListToXIOUArray st_l0 w32s
904 return (usedXIOU st_l0, (st_i0,st_l1,st_p0,st_I0))
906 addr (st_i0,st_l0,st_p0,st_I0) a
907 = do let w32s = mkLitA a
908 st_l1 <- addListToXIOUArray st_l0 w32s
909 return (usedXIOU st_l0, (st_i0,st_l1,st_p0,st_I0))
911 ptr (st_i0,st_l0,st_p0,st_I0) p
912 = do st_p1 <- addToXIOArray st_p0 p
913 return (usedXIO st_p0, (st_i0,st_l0,st_p1,st_I0))
915 itbl (st_i0,st_l0,st_p0,st_I0) dcon
916 = do st_I1 <- addToXIOArray st_I0 (getName dcon)
917 return (usedXIO st_I0, (st_i0,st_l0,st_p0,st_I1))
919 literal st (MachInt j) = int st (fromIntegral j)
920 literal st (MachFloat r) = float st (fromRational r)
921 literal st (MachDouble r) = double st (fromRational r)
924 = addr st ret_itbl_addr
928 IntRep -> stg_ctoi_ret_R1_info
929 FloatRep -> stg_ctoi_ret_F1_info
930 DoubleRep -> stg_ctoi_ret_D1_info
932 stg_ctoi_ret_F1_info = nullAddr
933 stg_ctoi_ret_D1_info = nullAddr
935 foreign label "stg_ctoi_ret_R1_info" stg_ctoi_ret_R1_info :: Addr
936 --foreign label "stg_ctoi_ret_F1_info" stg_ctoi_ret_F1_info :: Addr
937 --foreign label "stg_ctoi_ret_D1_info" stg_ctoi_ret_D1_info :: Addr
939 -- The size in bytes of an instruction.
940 instrSizeB :: BCInstr -> Int
967 -- Sizes of Int, Float and Double literals, in units of 32-bitses
968 intLitSz32s, floatLitSz32s, doubleLitSz32s, addrLitSz32s :: Int
969 intLitSz32s = wORD_SIZE `div` 4
970 floatLitSz32s = 1 -- Assume IEEE floats
972 addrLitSz32s = intLitSz32s
974 -- Make lists of 32-bit words for literals, so that when the
975 -- words are placed in memory at increasing addresses, the
976 -- bit pattern is correct for the host's word size and endianness.
977 mkLitI :: Int -> [Word32]
978 mkLitF :: Float -> [Word32]
979 mkLitD :: Double -> [Word32]
980 mkLitA :: Addr -> [Word32]
984 arr <- newFloatArray ((0::Int),0)
985 writeFloatArray arr 0 f
986 f_arr <- castSTUArray arr
987 w0 <- readWord32Array f_arr 0
993 arr <- newDoubleArray ((0::Int),0)
994 writeDoubleArray arr 0 d
995 d_arr <- castSTUArray arr
996 w0 <- readWord32Array d_arr 0
997 w1 <- readWord32Array d_arr 1
1004 arr <- newIntArray ((0::Int),0)
1005 writeIntArray arr 0 i
1006 i_arr <- castSTUArray arr
1007 w0 <- readWord32Array i_arr 0
1012 arr <- newIntArray ((0::Int),0)
1013 writeIntArray arr 0 i
1014 i_arr <- castSTUArray arr
1015 w0 <- readWord32Array i_arr 0
1016 w1 <- readWord32Array i_arr 1
1023 arr <- newAddrArray ((0::Int),0)
1024 writeAddrArray arr 0 a
1025 a_arr <- castSTUArray arr
1026 w0 <- readWord32Array a_arr 0
1031 arr <- newAddrArray ((0::Int),0)
1032 writeAddrArray arr 0 a
1033 a_arr <- castSTUArray arr
1034 w0 <- readWord32Array a_arr 0
1035 w1 <- readWord32Array a_arr 1
1041 -- Zero-based expandable arrays
1043 = XIOUArray { usedXIOU :: Int, stuffXIOU :: (IOUArray Int ele) }
1045 = XIOArray { usedXIO :: Int , stuffXIO :: (IOArray Int ele) }
1048 = do arr <- newArray (0, size-1)
1049 return (XIOUArray 0 arr)
1051 addListToXIOUArray xarr []
1053 addListToXIOUArray xarr (x:xs)
1054 = addToXIOUArray xarr x >>= \ xarr' -> addListToXIOUArray xarr' xs
1057 addToXIOUArray :: MArray IOUArray a IO
1058 => XIOUArray a -> a -> IO (XIOUArray a)
1059 addToXIOUArray (XIOUArray n_arr arr) x
1060 = case bounds arr of
1061 (lo, hi) -> ASSERT(lo == 0)
1063 then do new_arr <- newArray (0, 2*hi-1)
1065 addToXIOUArray (XIOUArray n_arr new_arr) x
1066 else do writeArray arr n_arr x
1067 return (XIOUArray (n_arr+1) arr)
1069 copy :: MArray IOUArray a IO
1070 => Int -> IOUArray Int a -> IOUArray Int a -> IO ()
1073 | otherwise = do nx <- readArray src n
1080 = do arr <- newArray (0, size-1)
1081 return (XIOArray 0 arr)
1083 addToXIOArray :: XIOArray a -> a -> IO (XIOArray a)
1084 addToXIOArray (XIOArray n_arr arr) x
1085 = case bounds arr of
1086 (lo, hi) -> ASSERT(lo == 0)
1088 then do new_arr <- newArray (0, 2*hi-1)
1090 addToXIOArray (XIOArray n_arr new_arr) x
1091 else do writeArray arr n_arr x
1092 return (XIOArray (n_arr+1) arr)
1094 copy :: Int -> IOArray Int a -> IOArray Int a -> IO ()
1097 | otherwise = do nx <- readArray src n
1103 %************************************************************************
1105 \subsection{Linking interpretables into something we can run}
1107 %************************************************************************
1113 = UnlinkedBCO Int (IOUArray Int Word16) -- #insns insns
1114 Int (IOUArray Int Word32) -- #literals literals
1115 Int (IOArray Int Name) -- #ptrs ptrs
1116 Int (IOArray Int Name) -- #itblrefs itblrefs
1118 data BCO# = BCO# ByteArray# -- instrs :: array Word16#
1119 ByteArray# -- literals :: array Word32#
1120 PtrArray# -- ptrs :: Array HValue
1121 ByteArray# -- itbls :: Array Addr#
1124 data LinkedBCO = LinkedBCO BCO#
1128 GLOBAL_VAR(v_cafTable, [], [HValue])
1130 addCAF :: HValue -> IO ()
1131 addCAF x = do xs <- readIORef v_cafTable; writeIORef v_cafTable (x:xs)
1133 linkIModules :: ItblEnv -- incoming global itbl env; returned updated
1134 -> ClosureEnv -- incoming global closure env; returned updated
1135 -> [([UnlinkedBCO], ItblEnv)]
1136 -> IO ([HValue], ItblEnv, ClosureEnv)
1137 linkIModules gie gce mods = do
1138 let (bcoss, ies) = unzip mods
1140 top_level_binders = map nameOfUnlinkedBCO bcos
1141 final_gie = foldr plusFM gie ies
1143 (new_bcos, new_gce) <-
1144 fixIO (\ ~(new_bcos, new_gce) -> do
1146 new_bcos <- linkBCOs final_gie new_gce bcos
1148 let new_gce = addListToFM gce (zip top_level_binders new_bcos)
1150 return (new_bcos, new_gce))
1152 return (new_bcos, final_gie, new_gce)
1156 linkBCOs :: ItblEnv -> ClosureEnv -> [UnlinkedBCO]
1157 -> IO [HValue] -- IO [BCO#] really
1158 linkBCOs ie ce binds = mapM (linkBCO ie ce) binds
1160 linkBCO ie ce (UnlinkedBCO nm
1161 n_insns insns n_literals literals
1162 n_ptrs ptrs n_itbls itbls)
1163 = do linked_ptrs <- mapArray (lookupCE ce) ptrs
1164 linked_itbls <- mapArray (lookupIE ie) itbls
1166 ptrs_froz <- freeze linked_ptrs
1167 let ptrs_parr = case ptrs_froz of Array lo hi parr -> parr
1169 insns_froz <- freeze insns
1170 let insns_barr = case insns_froz of UArray lo hi barr -> barr
1172 literals_froz <- freeze literals
1173 let literals_barr = case literals_froz of UArray lo hi barr -> barr
1175 itbls_froz <- freeze linked_itbls
1176 let itbls_barr = case itbls_froz of UArray lo hi barr -> barr
1178 BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
1180 return (unsafeCoerce# bco#)
1184 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
1185 newBCO a b c d = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
1188 lookupCE :: ClosureEnv -> Name -> HValue
1190 = case lookupFM ce nm of
1191 Just aa -> unsafeCoerce# aa
1192 Nothing -> pprPanic "ByteCodeGen.lookupCE" (ppr nm)
1194 lookupIE :: ItblEnv -> Name -> Addr
1196 = case lookupFM ie nm of
1198 Nothing -> pprPanic "ByteCodeGen.lookupIE" (ppr nm)
1204 case lookupFM ie con of
1205 Just (Ptr addr) -> return addr
1207 -- try looking up in the object files.
1208 m <- lookupSymbol (nameToCLabel con "con_info")
1210 Just addr -> return addr
1211 Nothing -> pprPanic "linkIExpr" (ppr con)
1213 -- nullary constructors don't have normal _con_info tables.
1214 lookupNullaryCon ie con =
1215 case lookupFM ie con of
1216 Just (Ptr addr) -> return (ConApp addr)
1218 -- try looking up in the object files.
1219 m <- lookupSymbol (nameToCLabel con "closure")
1221 Just (A# addr) -> return (Native (unsafeCoerce# addr))
1222 Nothing -> pprPanic "lookupNullaryCon" (ppr con)
1225 lookupNative ce var =
1226 unsafeInterleaveIO (do
1227 case lookupFM ce var of
1228 Just e -> return (Native e)
1230 -- try looking up in the object files.
1231 let lbl = (nameToCLabel var "closure")
1232 m <- lookupSymbol lbl
1235 -> do addCAF (unsafeCoerce# addr)
1236 return (Native (unsafeCoerce# addr))
1237 Nothing -> pprPanic "linkIExpr" (ppr var)
1240 -- some VarI/VarP refer to top-level interpreted functions; we change
1241 -- them into Natives here.
1243 unsafeInterleaveIO (
1244 case lookupFM ce (getName v) of
1245 Nothing -> return (f v)
1246 Just e -> return (Native e)
1249 -- HACK!!! ToDo: cleaner
1250 nameToCLabel :: Name -> String{-suffix-} -> String
1251 nameToCLabel n suffix =
1252 _UNPK_(moduleNameFS (rdrNameModule rn))
1253 ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
1254 where rn = toRdrName n
1258 %************************************************************************
1260 \subsection{Manufacturing of info tables for DataCons}
1262 %************************************************************************
1266 #if __GLASGOW_HASKELL__ <= 408
1269 type ItblPtr = Ptr StgInfoTable
1272 -- Make info tables for the data decls in this module
1273 mkITbls :: [TyCon] -> IO ItblEnv
1274 mkITbls [] = return emptyFM
1275 mkITbls (tc:tcs) = do itbls <- mkITbl tc
1276 itbls2 <- mkITbls tcs
1277 return (itbls `plusFM` itbls2)
1279 mkITbl :: TyCon -> IO ItblEnv
1281 -- | trace ("TYCON: " ++ showSDoc (ppr tc)) False
1283 | not (isDataTyCon tc)
1285 | n == length dcs -- paranoia; this is an assertion.
1286 = make_constr_itbls dcs
1288 dcs = tyConDataCons tc
1289 n = tyConFamilySize tc
1292 cONSTR = 1 -- as defined in ghc/includes/ClosureTypes.h
1294 -- Assumes constructors are numbered from zero, not one
1295 make_constr_itbls :: [DataCon] -> IO ItblEnv
1296 make_constr_itbls cons
1298 = do is <- mapM mk_vecret_itbl (zip cons [0..])
1299 return (listToFM is)
1301 = do is <- mapM mk_dirret_itbl (zip cons [0..])
1302 return (listToFM is)
1304 mk_vecret_itbl (dcon, conNo)
1305 = mk_itbl dcon conNo (vecret_entry conNo)
1306 mk_dirret_itbl (dcon, conNo)
1307 = mk_itbl dcon conNo stg_interp_constr_entry
1309 mk_itbl :: DataCon -> Int -> Addr -> IO (Name,ItblPtr)
1310 mk_itbl dcon conNo entry_addr
1311 = let (tot_wds, ptr_wds, _)
1312 = mkVirtHeapOffsets typePrimRep (dataConRepArgTys dcon)
1314 nptrs = tot_wds - ptr_wds
1315 itbl = StgInfoTable {
1316 ptrs = fromIntegral ptrs, nptrs = fromIntegral nptrs,
1317 tipe = fromIntegral cONSTR,
1318 srtlen = fromIntegral conNo,
1319 code0 = fromIntegral code0, code1 = fromIntegral code1,
1320 code2 = fromIntegral code2, code3 = fromIntegral code3,
1321 code4 = fromIntegral code4, code5 = fromIntegral code5,
1322 code6 = fromIntegral code6, code7 = fromIntegral code7
1324 -- Make a piece of code to jump to "entry_label".
1325 -- This is the only arch-dependent bit.
1326 -- On x86, if entry_label has an address 0xWWXXYYZZ,
1327 -- emit movl $0xWWXXYYZZ,%eax ; jmp *%eax
1329 -- B8 ZZ YY XX WW FF E0
1330 (code0,code1,code2,code3,code4,code5,code6,code7)
1331 = (0xB8, byte 0 entry_addr_w, byte 1 entry_addr_w,
1332 byte 2 entry_addr_w, byte 3 entry_addr_w,
1336 entry_addr_w :: Word32
1337 entry_addr_w = fromIntegral (addrToInt entry_addr)
1340 --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl))
1341 --putStrLn ("# ptrs of itbl is " ++ show ptrs)
1342 --putStrLn ("# nptrs of itbl is " ++ show nptrs)
1344 return (getName dcon, addr `plusPtr` 8)
1347 byte :: Int -> Word32 -> Word32
1348 byte 0 w = w .&. 0xFF
1349 byte 1 w = (w `shiftR` 8) .&. 0xFF
1350 byte 2 w = (w `shiftR` 16) .&. 0xFF
1351 byte 3 w = (w `shiftR` 24) .&. 0xFF
1354 vecret_entry 0 = stg_interp_constr1_entry
1355 vecret_entry 1 = stg_interp_constr2_entry
1356 vecret_entry 2 = stg_interp_constr3_entry
1357 vecret_entry 3 = stg_interp_constr4_entry
1358 vecret_entry 4 = stg_interp_constr5_entry
1359 vecret_entry 5 = stg_interp_constr6_entry
1360 vecret_entry 6 = stg_interp_constr7_entry
1361 vecret_entry 7 = stg_interp_constr8_entry
1363 -- entry point for direct returns for created constr itbls
1364 foreign label "stg_interp_constr_entry" stg_interp_constr_entry :: Addr
1365 -- and the 8 vectored ones
1366 foreign label "stg_interp_constr1_entry" stg_interp_constr1_entry :: Addr
1367 foreign label "stg_interp_constr2_entry" stg_interp_constr2_entry :: Addr
1368 foreign label "stg_interp_constr3_entry" stg_interp_constr3_entry :: Addr
1369 foreign label "stg_interp_constr4_entry" stg_interp_constr4_entry :: Addr
1370 foreign label "stg_interp_constr5_entry" stg_interp_constr5_entry :: Addr
1371 foreign label "stg_interp_constr6_entry" stg_interp_constr6_entry :: Addr
1372 foreign label "stg_interp_constr7_entry" stg_interp_constr7_entry :: Addr
1373 foreign label "stg_interp_constr8_entry" stg_interp_constr8_entry :: Addr
1377 data Constructor = Constructor Int{-ptrs-} Int{-nptrs-}
1380 -- Ultra-minimalist version specially for constructors
1381 data StgInfoTable = StgInfoTable {
1386 code0, code1, code2, code3, code4, code5, code6, code7 :: Word8
1390 instance Storable StgInfoTable where
1393 = (sum . map (\f -> f itbl))
1394 [fieldSz ptrs, fieldSz nptrs, fieldSz srtlen, fieldSz tipe,
1395 fieldSz code0, fieldSz code1, fieldSz code2, fieldSz code3,
1396 fieldSz code4, fieldSz code5, fieldSz code6, fieldSz code7]
1399 = (sum . map (\f -> f itbl))
1400 [fieldAl ptrs, fieldAl nptrs, fieldAl srtlen, fieldAl tipe,
1401 fieldAl code0, fieldAl code1, fieldAl code2, fieldAl code3,
1402 fieldAl code4, fieldAl code5, fieldAl code6, fieldAl code7]
1405 = do a1 <- store (ptrs itbl) (castPtr a0)
1406 a2 <- store (nptrs itbl) a1
1407 a3 <- store (tipe itbl) a2
1408 a4 <- store (srtlen itbl) a3
1409 a5 <- store (code0 itbl) a4
1410 a6 <- store (code1 itbl) a5
1411 a7 <- store (code2 itbl) a6
1412 a8 <- store (code3 itbl) a7
1413 a9 <- store (code4 itbl) a8
1414 aA <- store (code5 itbl) a9
1415 aB <- store (code6 itbl) aA
1416 aC <- store (code7 itbl) aB
1420 = do (a1,ptrs) <- load (castPtr a0)
1421 (a2,nptrs) <- load a1
1422 (a3,tipe) <- load a2
1423 (a4,srtlen) <- load a3
1424 (a5,code0) <- load a4
1425 (a6,code1) <- load a5
1426 (a7,code2) <- load a6
1427 (a8,code3) <- load a7
1428 (a9,code4) <- load a8
1429 (aA,code5) <- load a9
1430 (aB,code6) <- load aA
1431 (aC,code7) <- load aB
1432 return StgInfoTable { ptrs = ptrs, nptrs = nptrs,
1433 srtlen = srtlen, tipe = tipe,
1434 code0 = code0, code1 = code1, code2 = code2,
1435 code3 = code3, code4 = code4, code5 = code5,
1436 code6 = code6, code7 = code7 }
1438 fieldSz :: (Storable a, Storable b) => (a -> b) -> a -> Int
1439 fieldSz sel x = sizeOf (sel x)
1441 fieldAl :: (Storable a, Storable b) => (a -> b) -> a -> Int
1442 fieldAl sel x = alignment (sel x)
1444 store :: Storable a => a -> Ptr a -> IO (Ptr b)
1445 store x addr = do poke addr x
1446 return (castPtr (addr `plusPtr` sizeOf x))
1448 load :: Storable a => Ptr a -> IO (Ptr b, a)
1449 load addr = do x <- peek addr
1450 return (castPtr (addr `plusPtr` sizeOf x), x)
1454 %************************************************************************
1456 \subsection{Connect to actual values for bytecode opcodes}
1458 %************************************************************************
1462 #include "Bytecodes.h"
1464 i_ARGCHECK = (bci_ARGCHECK :: Int)
1465 i_PUSH_L = (bci_PUSH_L :: Int)
1466 i_PUSH_LL = (bci_PUSH_LL :: Int)
1467 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
1468 i_PUSH_G = (bci_PUSH_G :: Int)
1469 i_PUSH_AS = (bci_PUSH_AS :: Int)
1470 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
1471 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
1472 i_SLIDE = (bci_SLIDE :: Int)
1473 i_ALLOC = (bci_ALLOC :: Int)
1474 i_MKAP = (bci_MKAP :: Int)
1475 i_UNPACK = (bci_UNPACK :: Int)
1476 i_UPK_TAG = (bci_UPK_TAG :: Int)
1477 i_PACK = (bci_PACK :: Int)
1478 i_LABEL = (bci_LABEL :: Int)
1479 i_TESTLT_I = (bci_TESTLT_I :: Int)
1480 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
1481 i_TESTLT_F = (bci_TESTLT_F :: Int)
1482 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
1483 i_TESTLT_D = (bci_TESTLT_D :: Int)
1484 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
1485 i_TESTLT_P = (bci_TESTLT_P :: Int)
1486 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
1487 i_CASEFAIL = (bci_CASEFAIL :: Int)
1488 i_ENTER = (bci_ENTER :: Int)
1489 i_RETURN = (bci_RETURN :: Int)