[project @ 2001-01-09 17:36:21 by sewardj]
[ghc-hetmet.git] / ghc / compiler / ghci / ByteCodeGen.lhs
1 %
2 % (c) The University of Glasgow 2000
3 %
4 \section[ByteCodeGen]{Generate bytecode from Core}
5
6 \begin{code}
7 module ByteCodeGen ( UnlinkedBCO, UnlinkedBCOExpr, ItblEnv, ClosureEnv, HValue,
8                      filterNameMap,
9                      byteCodeGen, coreExprToBCOs, 
10                      linkIModules, linkIExpr
11                    ) where
12
13 #include "HsVersions.h"
14
15 import Outputable
16 import Name             ( Name, getName, nameModule, mkSysLocalName, toRdrName )
17 import RdrName          ( rdrNameOcc, rdrNameModule )
18 import OccName          ( occNameString )
19 import Id               ( Id, idType, isDataConId_maybe, mkVanillaId )
20 import OrdList          ( OrdList, consOL, snocOL, appOL, unitOL, 
21                           nilOL, toOL, concatOL, fromOL )
22 import FiniteMap        ( FiniteMap, addListToFM, listToFM, filterFM,
23                           addToFM, lookupFM, fmToList, emptyFM, plusFM )
24 import CoreSyn
25 import PprCore          ( pprCoreExpr, pprCoreAlt )
26 import Literal          ( Literal(..), literalPrimRep )
27 import PrimRep          ( PrimRep(..) )
28 import CoreFVs          ( freeVars )
29 import Type             ( typePrimRep )
30 import DataCon          ( DataCon, dataConTag, fIRST_TAG, dataConTyCon, 
31                           dataConRepArgTys )
32 import TyCon            ( TyCon, tyConFamilySize, isDataTyCon, tyConDataCons )
33 import Class            ( Class, classTyCon )
34 import Util             ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem, global )
35 import Var              ( isTyVar )
36 import VarSet           ( VarSet, varSetElems )
37 import PrimRep          ( getPrimRepSize, isFollowableRep )
38 import Constants        ( wORD_SIZE )
39 import CmdLineOpts      ( DynFlags, DynFlag(..) )
40 import ErrUtils         ( showPass, dumpIfSet_dyn )
41 import ClosureInfo      ( mkVirtHeapOffsets )
42 import Module           ( ModuleName, moduleName, moduleNameFS )
43 import Unique           ( mkPseudoUnique3 )
44 import Linker           ( lookupSymbol )
45 import FastString       ( FastString(..) )
46
47
48 import List             ( intersperse )
49 import Monad            ( foldM )
50 import ST               ( runST )
51 import MArray           ( castSTUArray, 
52                           newFloatArray, writeFloatArray,
53                           newDoubleArray, writeDoubleArray,
54                           newIntArray, writeIntArray,
55                           newAddrArray, writeAddrArray )
56 import Foreign          ( Storable(..), Word8, Word16, Word32, Ptr(..), 
57                           malloc, castPtr, plusPtr, mallocBytes )
58 import Addr             ( Word, addrToInt, nullAddr, writeCharOffAddr )
59 import Bits             ( Bits(..), shiftR )
60 import CTypes           ( CInt )
61
62 import PrelBase         ( Int(..) )
63 import PrelAddr         ( Addr(..) )
64 import PrelGHC          ( BCO#, newBCO#, unsafeCoerce#, 
65                           ByteArray#, Array#, addrToHValue# )
66 import IOExts           ( IORef, fixIO, unsafePerformIO )
67 import ArrayBase        
68 import PrelArr          ( Array(..) )
69 import PrelIOBase       ( IO(..) )
70
71 \end{code}
72
73 %************************************************************************
74 %*                                                                      *
75 \subsection{Functions visible from outside this module.}
76 %*                                                                      *
77 %************************************************************************
78
79 \begin{code}
80
81 byteCodeGen :: DynFlags
82             -> [CoreBind] 
83             -> [TyCon] -> [Class]
84             -> IO ([UnlinkedBCO], ItblEnv)
85 byteCodeGen dflags binds local_tycons local_classes
86    = do showPass dflags "ByteCodeGen"
87         let tycs = local_tycons ++ map classTyCon local_classes
88         itblenv <- mkITbls tycs
89
90         let flatBinds = concatMap getBind binds
91             getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
92             getBind (Rec binds)       = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
93             final_state = runBc (BcM_State [] 0) 
94                                 (mapBc schemeR flatBinds `thenBc_` returnBc ())
95             (BcM_State proto_bcos final_ctr) = final_state
96
97         dumpIfSet_dyn dflags Opt_D_dump_BCOs
98            "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
99
100         bcos <- mapM assembleBCO proto_bcos
101
102         return (bcos, itblenv)
103         
104
105 -- Returns: (the root BCO for this expression, 
106 --           a list of auxilary BCOs resulting from compiling closures)
107 coreExprToBCOs :: DynFlags
108                -> CoreExpr
109                -> IO UnlinkedBCOExpr
110 coreExprToBCOs dflags expr
111  = do showPass dflags "ByteCodeGen"
112
113       -- create a totally bogus name for the top-level BCO; this
114       -- should be harmless, since it's never used for anything
115       let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
116       let invented_id   = mkVanillaId invented_name (panic "invented_id's type")
117
118       let (BcM_State all_proto_bcos final_ctr) 
119              = runBc (BcM_State [] 0) 
120                      (schemeR (invented_id, freeVars expr))
121       dumpIfSet_dyn dflags Opt_D_dump_BCOs
122          "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
123
124       let root_proto_bco 
125              = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
126                   [root_bco] -> root_bco
127           auxiliary_proto_bcos
128              = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
129
130       auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
131       root_bco <- assembleBCO root_proto_bco
132
133       return (root_bco, auxiliary_bcos)
134
135
136 -- Linking stuff
137 linkIModules :: ItblEnv    -- incoming global itbl env; returned updated
138              -> ClosureEnv -- incoming global closure env; returned updated
139              -> [([UnlinkedBCO], ItblEnv)]
140              -> IO ([HValue], ItblEnv, ClosureEnv)
141 linkIModules gie gce mods 
142    = do let (bcoss, ies) = unzip mods
143             bcos = concat bcoss
144             final_gie = foldr plusFM gie ies
145         (final_gce, linked_bcos) <- linkSomeBCOs final_gie gce bcos
146         return (linked_bcos, final_gie, final_gce)
147
148
149 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
150           -> IO HValue    -- IO BCO# really
151 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
152    = do (aux_ce, _) <- linkSomeBCOs ie ce aux_ul_bcos
153         (_, [root_bco]) <- linkSomeBCOs ie aux_ce [root_ul_bco]
154         return root_bco
155
156 -- Link a bunch of BCOs and return them + updated closure env.
157 linkSomeBCOs :: ItblEnv -> ClosureEnv -> [UnlinkedBCO]
158                 -> IO (ClosureEnv, [HValue])
159 linkSomeBCOs ie ce_in ul_bcos
160    = do let nms = map nameOfUnlinkedBCO ul_bcos
161         hvals <- fixIO 
162                     ( \ hvs -> let ce_out = addListToFM ce_in (zipLazily nms hvs)
163                                in  mapM (linkBCO ie ce_out) ul_bcos )
164         let ce_out = addListToFM ce_in (zip nms hvals)
165         return (ce_out, hvals)
166      where
167         -- A lazier zip, in which no demand is propagated to the second
168         -- list unless some demand is propagated to the snd of one of the
169         -- result list elems.
170         zipLazily []     ys = []
171         zipLazily (x:xs) ys = (x, head ys) : zipLazily xs (tail ys)
172
173
174 data UnlinkedBCO
175    = UnlinkedBCO Name
176                  (SizedSeq Word16)      -- insns
177                  (SizedSeq Word)        -- literals
178                  (SizedSeq Name)        -- ptrs
179                  (SizedSeq Name)        -- itbl refs
180
181 nameOfUnlinkedBCO (UnlinkedBCO nm _ _ _ _) = nm
182
183 -- When translating expressions, we need to distinguish the root
184 -- BCO for the expression
185 type UnlinkedBCOExpr = (UnlinkedBCO, [UnlinkedBCO])
186
187 instance Outputable UnlinkedBCO where
188    ppr (UnlinkedBCO nm insns lits ptrs itbls)
189       = sep [text "BCO", ppr nm, text "with", 
190              int (sizeSS insns), text "insns",
191              int (sizeSS lits), text "lits",
192              int (sizeSS ptrs), text "ptrs",
193              int (sizeSS itbls), text "itbls"]
194
195
196 -- these need a proper home
197 type ItblEnv    = FiniteMap Name (Ptr StgInfoTable)
198 type ClosureEnv = FiniteMap Name HValue
199 data HValue     = HValue  -- dummy type, actually a pointer to some Real Code.
200
201 -- remove all entries for a given set of modules from the environment
202 filterNameMap :: [ModuleName] -> FiniteMap Name a -> FiniteMap Name a
203 filterNameMap mods env 
204    = filterFM (\n _ -> moduleName (nameModule n) `notElem` mods) env
205 \end{code}
206
207 %************************************************************************
208 %*                                                                      *
209 \subsection{Bytecodes, and Outputery.}
210 %*                                                                      *
211 %************************************************************************
212
213 \begin{code}
214
215 type LocalLabel = Int
216
217 data BCInstr
218    -- Messing with the stack
219    = ARGCHECK  Int
220    -- Push locals (existing bits of the stack)
221    | PUSH_L    Int{-offset-}
222    | PUSH_LL   Int Int{-2 offsets-}
223    | PUSH_LLL  Int Int Int{-3 offsets-}
224    -- Push a ptr
225    | PUSH_G    Name
226    -- Push an alt continuation
227    | PUSH_AS   Name PrimRep     -- push alts and BCO_ptr_ret_info
228                                 -- PrimRep so we know which itbl
229    -- Pushing literals
230    | PUSH_UBX  Literal  Int 
231                         -- push this int/float/double, NO TAG, on the stack
232                         -- Int is # of words to copy from literal pool
233    | PUSH_TAG  Int      -- push this tag on the stack
234
235    | SLIDE     Int{-this many-} Int{-down by this much-}
236    -- To do with the heap
237    | ALLOC     Int      -- make an AP_UPD with this many payload words, zeroed
238    | MKAP      Int{-ptr to AP_UPD is this far down stack-} Int{-# words-}
239    | UNPACK    Int      -- unpack N ptr words from t.o.s Constr
240    | UPK_TAG   Int Int Int
241                         -- unpack N non-ptr words from offset M in constructor
242                         -- K words down the stack
243    | PACK      DataCon Int
244                         -- after assembly, the DataCon is an index into the
245                         -- itbl array
246    -- For doing case trees
247    | LABEL     LocalLabel
248    | TESTLT_I  Int    LocalLabel
249    | TESTEQ_I  Int    LocalLabel
250    | TESTLT_F  Float  LocalLabel
251    | TESTEQ_F  Float  LocalLabel
252    | TESTLT_D  Double LocalLabel
253    | TESTEQ_D  Double LocalLabel
254
255    -- The Int value is a constructor number and therefore
256    -- stored in the insn stream rather than as an offset into
257    -- the literal pool.
258    | TESTLT_P  Int    LocalLabel
259    | TESTEQ_P  Int    LocalLabel
260
261    | CASEFAIL
262    -- To Infinity And Beyond
263    | ENTER
264    | RETURN     PrimRep
265                 -- unboxed value on TOS.  Use tag to find underlying ret itbl
266                 -- and return as per that.
267
268
269 instance Outputable BCInstr where
270    ppr (ARGCHECK n)          = text "ARGCHECK" <+> int n
271    ppr (PUSH_L offset)       = text "PUSH_L  " <+> int offset
272    ppr (PUSH_LL o1 o2)       = text "PUSH_LL " <+> int o1 <+> int o2
273    ppr (PUSH_LLL o1 o2 o3)   = text "PUSH_LLL" <+> int o1 <+> int o2 <+> int o3
274    ppr (PUSH_G nm)           = text "PUSH_G  " <+> ppr nm
275    ppr (PUSH_AS nm pk)       = text "PUSH_AS " <+> ppr nm <+> ppr pk
276    ppr (PUSH_UBX lit nw)     = text "PUSH_UBX" <+> parens (int nw) <+> ppr lit
277    ppr (PUSH_TAG n)          = text "PUSH_TAG" <+> int n
278    ppr (SLIDE n d)           = text "SLIDE   " <+> int n <+> int d
279    ppr (ALLOC sz)            = text "ALLOC   " <+> int sz
280    ppr (MKAP offset sz)      = text "MKAP    " <+> int sz <+> text "words," 
281                                                <+> int offset <+> text "stkoff"
282    ppr (UNPACK sz)           = text "UNPACK  " <+> int sz
283    ppr (UPK_TAG n m k)       = text "UPK_TAG " <+> int n <> text "words" 
284                                                <+> int m <> text "conoff"
285                                                <+> int k <> text "stkoff"
286    ppr (PACK dcon sz)        = text "PACK    " <+> ppr dcon <+> ppr sz
287    ppr (LABEL     lab)       = text "__"       <> int lab <> colon
288    ppr (TESTLT_I  i lab)     = text "TESTLT_I" <+> int i <+> text "__" <> int lab
289    ppr (TESTEQ_I  i lab)     = text "TESTEQ_I" <+> int i <+> text "__" <> int lab
290    ppr (TESTLT_F  f lab)     = text "TESTLT_F" <+> float f <+> text "__" <> int lab
291    ppr (TESTEQ_F  f lab)     = text "TESTEQ_F" <+> float f <+> text "__" <> int lab
292    ppr (TESTLT_D  d lab)     = text "TESTLT_D" <+> double d <+> text "__" <> int lab
293    ppr (TESTEQ_D  d lab)     = text "TESTEQ_D" <+> double d <+> text "__" <> int lab
294    ppr (TESTLT_P  i lab)     = text "TESTLT_P" <+> int i <+> text "__" <> int lab
295    ppr (TESTEQ_P  i lab)     = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
296    ppr CASEFAIL              = text "CASEFAIL"
297    ppr ENTER                 = text "ENTER"
298    ppr (RETURN pk)           = text "RETURN  " <+> ppr pk
299
300 instance Outputable a => Outputable (ProtoBCO a) where
301    ppr (ProtoBCO name instrs origin)
302       = (text "ProtoBCO" <+> ppr name <> colon)
303         $$ nest 6 (vcat (map ppr instrs))
304         $$ case origin of
305               Left alts -> vcat (map (pprCoreAlt.deAnnAlt) alts)
306               Right rhs -> pprCoreExpr (deAnnotate rhs)
307 \end{code}
308
309 %************************************************************************
310 %*                                                                      *
311 \subsection{Compilation schema for the bytecode generator.}
312 %*                                                                      *
313 %************************************************************************
314
315 \begin{code}
316
317 type BCInstrList = OrdList BCInstr
318
319 data ProtoBCO a 
320    = ProtoBCO a                         -- name, in some sense
321               [BCInstr]                 -- instrs
322                                         -- what the BCO came from
323               (Either [AnnAlt Id VarSet]
324                       (AnnExpr Id VarSet))
325
326 nameOfProtoBCO (ProtoBCO nm insns origin) = nm
327
328
329 type Sequel = Int       -- back off to this depth before ENTER
330
331 -- Maps Ids to the offset from the stack _base_ so we don't have
332 -- to mess with it after each push/pop.
333 type BCEnv = FiniteMap Id Int   -- To find vars on the stack
334
335
336 -- Create a BCO and do a spot of peephole optimisation on the insns
337 -- at the same time.
338 mkProtoBCO nm instrs_ordlist origin
339    = ProtoBCO nm (id {-peep-} (fromOL instrs_ordlist)) origin
340      where
341         peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
342            = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
343         peep (PUSH_L off1 : PUSH_L off2 : rest)
344            = PUSH_LL off1 off2 : peep rest
345         peep (i:rest)
346            = i : peep rest
347         peep []
348            = []
349
350
351 -- Compile code for the right hand side of a let binding.
352 -- Park the resulting BCO in the monad.  Also requires the
353 -- variable to which this value was bound, so as to give the
354 -- resulting BCO a name.
355 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
356 schemeR (nm, rhs) 
357
358    | trace (showSDoc (
359               (char ' '
360                $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
361                $$ pprCoreExpr (deAnnotate rhs)
362                $$ char ' '
363               ))) False
364    = undefined
365
366    | otherwise
367    = schemeR_wrk rhs nm (collect [] rhs)
368
369
370 collect xs (_, AnnNote note e)
371    = collect xs e
372 collect xs (_, AnnLam x e) 
373    = collect (if isTyVar x then xs else (x:xs)) e
374 collect xs not_lambda
375    = (reverse xs, not_lambda)
376
377 schemeR_wrk original_body nm (args, body)
378    = let fvs       = filter (not.isTyVar) (varSetElems (fst original_body))
379          all_args  = reverse args ++ fvs --ORIG: fvs ++ reverse args
380          szsw_args = map taggedIdSizeW all_args
381          szw_args  = sum szsw_args
382          p_init    = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
383          argcheck  = --if null args then nilOL else
384                      unitOL (ARGCHECK szw_args)
385      in
386      schemeE szw_args 0 p_init body             `thenBc` \ body_code ->
387      emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
388
389 -- Let szsw be the sizes in words of some items pushed onto the stack,
390 -- which has initial depth d'.  Return the values which the stack environment
391 -- should map these items to.
392 mkStackOffsets :: Int -> [Int] -> [Int]
393 mkStackOffsets original_depth szsw
394    = map (subtract 1) (tail (scanl (+) original_depth szsw))
395
396 -- Compile code to apply the given expression to the remaining args
397 -- on the stack, returning a HNF.
398 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
399
400 -- Delegate tail-calls to schemeT.
401 schemeE d s p e@(fvs, AnnApp f a) 
402    = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
403 schemeE d s p e@(fvs, AnnVar v)
404    | isFollowableRep v_rep
405    = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
406    | otherwise
407    = -- returning an unboxed value.  Heave it on the stack, SLIDE, and RETURN.
408      let (push, szw) = pushAtom True d p (AnnVar v)
409      in  returnBc (push                         -- value onto stack
410                    `snocOL` SLIDE szw (d-s)     -- clear to sequel
411                    `snocOL` RETURN v_rep)       -- go
412    where
413       v_rep = typePrimRep (idType v)
414
415 schemeE d s p (fvs, AnnLit literal)
416    = let (push, szw) = pushAtom True d p (AnnLit literal)
417          l_rep = literalPrimRep literal
418      in  returnBc (push                         -- value onto stack
419                    `snocOL` SLIDE szw (d-s)     -- clear to sequel
420                    `snocOL` RETURN l_rep)               -- go
421
422 schemeE d s p (fvs, AnnLet binds b)
423    = let (xs,rhss) = case binds of AnnNonRec x rhs  -> ([x],[rhs])
424                                    AnnRec xs_n_rhss -> unzip xs_n_rhss
425          n     = length xs
426          fvss  = map (filter (not.isTyVar).varSetElems.fst) rhss
427
428          -- Sizes of tagged free vars, + 1 for the fn
429          sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
430
431          -- This p', d' defn is safe because all the items being pushed
432          -- are ptrs, so all have size 1.  d' and p' reflect the stack
433          -- after the closures have been allocated in the heap (but not
434          -- filled in), and pointers to them parked on the stack.
435          p'    = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
436          d'    = d + n
437
438          infos = zipE4 fvss sizes xs [n, n-1 .. 1]
439          zipE  = zipEqual "schemeE"
440          zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
441
442          -- ToDo: don't build thunks for things with no free variables
443          buildThunk dd ([], size, id, off)
444             = PUSH_G (getName id) 
445               `consOL` unitOL (MKAP (off+size-1) size)
446          buildThunk dd ((fv:fvs), size, id, off)
447             = case pushAtom True dd p' (AnnVar fv) of
448                  (push_code, pushed_szw)
449                     -> push_code `appOL`
450                        buildThunk (dd+pushed_szw) (fvs, size, id, off)
451
452          thunkCode = concatOL (map (buildThunk d') infos)
453          allocCode = toOL (map ALLOC sizes)
454      in
455      schemeE d' s p' b                                  `thenBc`  \ bodyCode ->
456      mapBc schemeR (zip xs rhss)                        `thenBc_`
457      returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
458
459
460 schemeE d s p (fvs, AnnCase scrut bndr alts)
461    = let
462         -- Top of stack is the return itbl, as usual.
463         -- underneath it is the pointer to the alt_code BCO.
464         -- When an alt is entered, it assumes the returned value is
465         -- on top of the itbl.
466         ret_frame_sizeW = 2
467
468         -- Env and depth in which to compile the alts, not including
469         -- any vars bound by the alts themselves
470         d' = d + ret_frame_sizeW + taggedIdSizeW bndr
471         p' = addToFM p bndr (d' - 1)
472
473         scrut_primrep = typePrimRep (idType bndr)
474         isAlgCase
475            = case scrut_primrep of
476                 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
477                 PtrRep -> True
478                 other  -> pprPanic "ByteCodeGen.schemeE" (ppr other)
479
480         -- given an alt, return a discr and code for it.
481         codeAlt alt@(discr, binds_f, rhs)
482            | isAlgCase 
483            = let binds_r        = reverse binds_f
484                  binds_r_t_szsw = map taggedIdSizeW binds_r
485                  binds_t_szw    = sum binds_r_t_szsw
486                  p''            = addListToFM 
487                                    p' (zip binds_r (mkStackOffsets d' binds_r_t_szsw))
488                  d''            = d' + binds_t_szw
489                  unpack_code    = mkUnpackCode 0 0 (map (typePrimRep.idType) binds_f)
490              in schemeE d'' s p'' rhs   `thenBc` \ rhs_code -> 
491                 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
492            | otherwise 
493            = ASSERT(null binds_f) 
494              schemeE d' s p' rhs        `thenBc` \ rhs_code ->
495              returnBc (my_discr alt, rhs_code)
496
497         my_discr (DEFAULT, binds, rhs)  = NoDiscr
498         my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc - fIRST_TAG)
499         my_discr (LitAlt l, binds, rhs)
500            = case l of MachInt i     -> DiscrI (fromInteger i)
501                        MachFloat r   -> DiscrF (fromRational r)
502                        MachDouble r  -> DiscrD (fromRational r)
503
504         maybe_ncons 
505            | not isAlgCase = Nothing
506            | otherwise 
507            = case [dc | (DataAlt dc, _, _) <- alts] of
508                 []     -> Nothing
509                 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
510
511      in 
512      mapBc codeAlt alts                                 `thenBc` \ alt_stuff ->
513      mkMultiBranch maybe_ncons alt_stuff                `thenBc` \ alt_final ->
514      let 
515          alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
516          alt_bco_name = getName bndr
517          alt_bco      = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
518      in
519      schemeE (d + ret_frame_sizeW) 
520              (d + ret_frame_sizeW) p scrut              `thenBc` \ scrut_code ->
521
522      emitBc alt_bco                                     `thenBc_`
523      returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
524
525
526 schemeE d s p (fvs, AnnNote note body)
527    = schemeE d s p body
528
529 schemeE d s p other
530    = pprPanic "ByteCodeGen.schemeE: unhandled case" 
531                (pprCoreExpr (deAnnotate other))
532
533
534 -- Compile code to do a tail call.  Doesn't need to be monadic.
535 schemeT :: Bool         -- do tagging?
536         -> Int          -- Stack depth
537         -> Sequel       -- Sequel depth
538         -> Int          -- # arg words so far
539         -> BCEnv        -- stack env
540         -> AnnExpr Id VarSet 
541         -> BCInstrList
542
543 schemeT enTag d s narg_words p (_, AnnApp f a)
544    = case snd a of
545         AnnType _ -> schemeT enTag d s narg_words p f
546         other
547            -> let (push, arg_words) = pushAtom enTag d p (snd a)
548               in push 
549                  `appOL` schemeT enTag (d+arg_words) s (narg_words+arg_words) p f
550
551 schemeT enTag d s narg_words p (_, AnnVar f)
552    | Just con <- isDataConId_maybe f
553    = ASSERT(enTag == False)
554      --trace ("schemeT: d = " ++ show d ++ ", s = " ++ show s ++ ", naw = " ++ show narg_words) (
555      PACK con narg_words `consOL` (mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
556      --)
557    | otherwise
558    = ASSERT(enTag == True)
559      let (push, arg_words) = pushAtom True d p (AnnVar f)
560      in  push 
561          `appOL`  mkSLIDE (narg_words+arg_words) (d - s - narg_words)
562          `snocOL` ENTER
563
564 mkSLIDE n d 
565    = if d == 0 then nilOL else unitOL (SLIDE n d)
566
567 should_args_be_tagged (_, AnnVar v)
568    = case isDataConId_maybe v of
569         Just dcon -> False; Nothing -> True
570 should_args_be_tagged (_, AnnApp f a)
571    = should_args_be_tagged f
572 should_args_be_tagged (_, other)
573    = panic "should_args_be_tagged: tail call to non-con, non-var"
574
575
576 -- Make code to unpack a constructor onto the stack, adding
577 -- tags for the unboxed bits.  Takes the PrimReps of the constructor's
578 -- arguments, and a travelling offset along both the constructor
579 -- (off_h) and the stack (off_s).
580 mkUnpackCode :: Int -> Int -> [PrimRep] -> BCInstrList
581 mkUnpackCode off_h off_s [] = nilOL
582 mkUnpackCode off_h off_s (r:rs)
583    | isFollowableRep r
584    = let (rs_ptr, rs_nptr) = span isFollowableRep (r:rs)
585          ptrs_szw = sum (map untaggedSizeW rs_ptr) 
586      in  ASSERT(ptrs_szw == length rs_ptr)
587          ASSERT(off_h == 0)
588          ASSERT(off_s == 0)
589          UNPACK ptrs_szw 
590          `consOL` mkUnpackCode (off_h + ptrs_szw) (off_s + ptrs_szw) rs_nptr
591    | otherwise
592    = case r of
593         IntRep    -> approved
594         FloatRep  -> approved
595         DoubleRep -> approved
596      where
597         approved = UPK_TAG usizeW off_h off_s   `consOL` theRest
598         theRest  = mkUnpackCode (off_h + usizeW) (off_s + tsizeW) rs
599         usizeW   = untaggedSizeW r
600         tsizeW   = taggedSizeW r
601
602 -- Push an atom onto the stack, returning suitable code & number of
603 -- stack words used.  Pushes it either tagged or untagged, since 
604 -- pushAtom is used to set up the stack prior to copying into the
605 -- heap for both APs (requiring tags) and constructors (which don't).
606 --
607 -- NB this means NO GC between pushing atoms for a constructor and
608 -- copying them into the heap.  It probably also means that 
609 -- tail calls MUST be of the form atom{atom ... atom} since if the
610 -- expression head was allowed to be arbitrary, there could be GC
611 -- in between pushing the arg atoms and completing the head.
612 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
613 -- isn't a problem; but only if arbitrary graph construction for the
614 -- head doesn't leave this BCO, since GC might happen at the start of
615 -- each BCO (we consult doYouWantToGC there).
616 --
617 -- Blargh.  JRS 001206
618 --
619 -- NB (further) that the env p must map each variable to the highest-
620 -- numbered stack slot for it.  For example, if the stack has depth 4 
621 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
622 -- the tag in stack[5], the stack will have depth 6, and p must map v to
623 -- 5 and not to 4.  Stack locations are numbered from zero, so a depth
624 -- 6 stack has valid words 0 .. 5.
625
626 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
627 pushAtom tagged d p (AnnVar v) 
628    = let str = "\npushAtom " ++ showSDocDebug (ppr v) ++ ", depth = " ++ show d
629                ++ ", env =\n" ++ 
630                showSDocDebug (nest 4 (vcat (map ppr (fmToList p))))
631                ++ " -->\n" ++
632                showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
633                ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
634          str' = if str == str then str else str
635
636          result
637             = case lookupBCEnv_maybe p v of
638                  Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
639                  Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
640
641          nm = case isDataConId_maybe v of
642                  Just c  -> getName c
643                  Nothing -> getName v
644
645          sz_t   = taggedIdSizeW v
646          sz_u   = untaggedIdSizeW v
647          nwords = if tagged then sz_t else sz_u
648      in
649          --trace str'
650          result
651
652 pushAtom True d p (AnnLit lit)
653    = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
654      in  (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
655
656 pushAtom False d p (AnnLit lit)
657    = case lit of
658         MachInt i    -> code IntRep
659         MachFloat r  -> code FloatRep
660         MachDouble r -> code DoubleRep
661         MachChar c   -> code CharRep
662         MachStr s    -> pushStr s
663      where
664         code rep
665            = let size_host_words = untaggedSizeW rep
666              in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
667
668         pushStr s 
669            = let mallocvilleAddr
670                     = case s of
671                          CharStr s i -> A# s
672
673                          FastString _ l ba -> 
674                             -- sigh, a string in the heap is no good to us.
675                             -- We need a static C pointer, since the type of 
676                             -- a string literal is Addr#.  So, copy the string 
677                             -- into C land and introduce a memory leak 
678                             -- at the same time.
679                             let n = I# l
680                             -- CAREFUL!  Chars are 32 bits in ghc 4.09+
681                             in  unsafePerformIO (
682                                    do a@(Ptr addr) <- mallocBytes (n+1)
683                                       strncpy a ba (fromIntegral n)
684                                       writeCharOffAddr addr n '\0'
685                                       return addr
686                                    )
687                          _ -> panic "StgInterp.lit2expr: unhandled string constant type"
688
689                  addrLit 
690                     = MachInt (toInteger (addrToInt mallocvilleAddr))
691              in
692                 -- Get the addr on the stack, untaggedly
693                 (unitOL (PUSH_UBX addrLit 1), 1)
694
695
696
697
698
699 pushAtom tagged d p (AnnApp f (_, AnnType _))
700    = pushAtom tagged d p (snd f)
701
702 pushAtom tagged d p other
703    = pprPanic "ByteCodeGen.pushAtom" 
704               (pprCoreExpr (deAnnotate (undefined, other)))
705
706 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
707
708
709 -- Given a bunch of alts code and their discrs, do the donkey work
710 -- of making a multiway branch using a switch tree.
711 -- What a load of hassle!
712 mkMultiBranch :: Maybe Int      -- # datacons in tycon, if alg alt
713                                 -- a hint; generates better code
714                                 -- Nothing is always safe
715               -> [(Discr, BCInstrList)] 
716               -> BcM BCInstrList
717 mkMultiBranch maybe_ncons raw_ways
718    = let d_way     = filter (isNoDiscr.fst) raw_ways
719          notd_ways = naturalMergeSortLe 
720                         (\w1 w2 -> leAlt (fst w1) (fst w2))
721                         (filter (not.isNoDiscr.fst) raw_ways)
722
723          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
724          mkTree [] range_lo range_hi = returnBc the_default
725
726          mkTree [val] range_lo range_hi
727             | range_lo `eqAlt` range_hi 
728             = returnBc (snd val)
729             | otherwise
730             = getLabelBc                                `thenBc` \ label_neq ->
731               returnBc (mkTestEQ (fst val) label_neq 
732                         `consOL` (snd val
733                         `appOL`   unitOL (LABEL label_neq)
734                         `appOL`   the_default))
735
736          mkTree vals range_lo range_hi
737             = let n = length vals `div` 2
738                   vals_lo = take n vals
739                   vals_hi = drop n vals
740                   v_mid = fst (head vals_hi)
741               in
742               getLabelBc                                `thenBc` \ label_geq ->
743               mkTree vals_lo range_lo (dec v_mid)       `thenBc` \ code_lo ->
744               mkTree vals_hi v_mid range_hi             `thenBc` \ code_hi ->
745               returnBc (mkTestLT v_mid label_geq
746                         `consOL` (code_lo
747                         `appOL`   unitOL (LABEL label_geq)
748                         `appOL`   code_hi))
749  
750          the_default 
751             = case d_way of [] -> unitOL CASEFAIL
752                             [(_, def)] -> def
753
754          -- None of these will be needed if there are no non-default alts
755          (mkTestLT, mkTestEQ, init_lo, init_hi)
756             | null notd_ways
757             = panic "mkMultiBranch: awesome foursome"
758             | otherwise
759             = case fst (head notd_ways) of {
760               DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
761                             \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
762                             DiscrI minBound,
763                             DiscrI maxBound );
764               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
765                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
766                             DiscrF minF,
767                             DiscrF maxF );
768               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
769                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
770                             DiscrD minD,
771                             DiscrD maxD );
772               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
773                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
774                             DiscrP algMinBound,
775                             DiscrP algMaxBound )
776               }
777
778          (algMinBound, algMaxBound)
779             = case maybe_ncons of
780                  Just n  -> (0, n - 1)
781                  Nothing -> (minBound, maxBound)
782
783          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
784          (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
785          (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
786          (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
787          NoDiscr     `eqAlt` NoDiscr     = True
788          _           `eqAlt` _           = False
789
790          (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
791          (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
792          (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
793          (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
794          NoDiscr     `leAlt` NoDiscr     = True
795          _           `leAlt` _           = False
796
797          isNoDiscr NoDiscr = True
798          isNoDiscr _       = False
799
800          dec (DiscrI i) = DiscrI (i-1)
801          dec (DiscrP i) = DiscrP (i-1)
802          dec other      = other         -- not really right, but if you
803                 -- do cases on floating values, you'll get what you deserve
804
805          -- same snotty comment applies to the following
806          minF, maxF :: Float
807          minD, maxD :: Double
808          minF = -1.0e37
809          maxF =  1.0e37
810          minD = -1.0e308
811          maxD =  1.0e308
812      in
813          mkTree notd_ways init_lo init_hi
814
815 \end{code}
816
817 %************************************************************************
818 %*                                                                      *
819 \subsection{Supporting junk for the compilation schemes}
820 %*                                                                      *
821 %************************************************************************
822
823 \begin{code}
824
825 -- Describes case alts
826 data Discr 
827    = DiscrI Int
828    | DiscrF Float
829    | DiscrD Double
830    | DiscrP Int
831    | NoDiscr
832
833 instance Outputable Discr where
834    ppr (DiscrI i) = int i
835    ppr (DiscrF f) = text (show f)
836    ppr (DiscrD d) = text (show d)
837    ppr (DiscrP i) = int i
838    ppr NoDiscr    = text "DEF"
839
840
841 -- Find things in the BCEnv (the what's-on-the-stack-env)
842 -- See comment preceding pushAtom for precise meaning of env contents
843 --lookupBCEnv :: BCEnv -> Id -> Int
844 --lookupBCEnv env nm
845 --   = case lookupFM env nm of
846 --        Nothing -> pprPanic "lookupBCEnv" 
847 --                            (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
848 --        Just xx -> xx
849
850 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
851 lookupBCEnv_maybe = lookupFM
852
853
854 -- When I push one of these on the stack, how much does Sp move by?
855 taggedSizeW :: PrimRep -> Int
856 taggedSizeW pr
857    | isFollowableRep pr = 1
858    | otherwise          = 1{-the tag-} + getPrimRepSize pr
859
860
861 -- The plain size of something, without tag.
862 untaggedSizeW :: PrimRep -> Int
863 untaggedSizeW pr
864    | isFollowableRep pr = 1
865    | otherwise          = getPrimRepSize pr
866
867
868 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
869 taggedIdSizeW   = taggedSizeW   . typePrimRep . idType
870 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
871
872 \end{code}
873
874 %************************************************************************
875 %*                                                                      *
876 \subsection{The bytecode generator's monad}
877 %*                                                                      *
878 %************************************************************************
879
880 \begin{code}
881 data BcM_State 
882    = BcM_State { bcos      :: [ProtoBCO Name],  -- accumulates completed BCOs
883                  nextlabel :: Int }             -- for generating local labels
884
885 type BcM result = BcM_State -> (result, BcM_State)
886
887 runBc :: BcM_State -> BcM () -> BcM_State
888 runBc init_st m = case m init_st of { (r,st) -> st }
889
890 thenBc :: BcM a -> (a -> BcM b) -> BcM b
891 thenBc expr cont st
892   = case expr st of { (result, st') -> cont result st' }
893
894 thenBc_ :: BcM a -> BcM b -> BcM b
895 thenBc_ expr cont st
896   = case expr st of { (result, st') -> cont st' }
897
898 returnBc :: a -> BcM a
899 returnBc result st = (result, st)
900
901 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
902 mapBc f []     = returnBc []
903 mapBc f (x:xs)
904   = f x          `thenBc` \ r  ->
905     mapBc f xs   `thenBc` \ rs ->
906     returnBc (r:rs)
907
908 emitBc :: ProtoBCO Name -> BcM ()
909 emitBc bco st
910    = ((), st{bcos = bco : bcos st})
911
912 getLabelBc :: BcM Int
913 getLabelBc st
914    = (nextlabel st, st{nextlabel = 1 + nextlabel st})
915
916 \end{code}
917
918 %************************************************************************
919 %*                                                                      *
920 \subsection{The bytecode assembler}
921 %*                                                                      *
922 %************************************************************************
923
924 The object format for bytecodes is: 16 bits for the opcode, and 16 for
925 each field -- so the code can be considered a sequence of 16-bit ints.
926 Each field denotes either a stack offset or number of items on the
927 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
928 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
929 this BCO.
930
931 \begin{code}
932 -- Top level assembler fn.
933 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
934
935 assembleBCO (ProtoBCO nm instrs origin)
936    = let
937          -- pass 1: collect up the offsets of the local labels.
938          -- Remember that the first insn starts at offset 1 since offset 0
939          -- (eventually) will hold the total # of insns.
940          label_env = mkLabelEnv emptyFM 1 instrs
941
942          mkLabelEnv env i_offset [] = env
943          mkLabelEnv env i_offset (i:is)
944             = let new_env 
945                      = case i of LABEL n -> addToFM env n i_offset ; _ -> env
946               in  mkLabelEnv new_env (i_offset + instrSize16s i) is
947
948          findLabel lab
949             = case lookupFM label_env lab of
950                  Just bco_offset -> bco_offset
951                  Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
952      in
953      do  -- pass 2: generate the instruction, ptr and nonptr bits
954          insns <- return emptySS :: IO (SizedSeq Word16)
955          lits  <- return emptySS :: IO (SizedSeq Word)
956          ptrs  <- return emptySS :: IO (SizedSeq Name)
957          itbls <- return emptySS :: IO (SizedSeq Name)
958          let init_asm_state = (insns,lits,ptrs,itbls)
959          (final_insns, final_lits, final_ptrs, final_itbls) 
960             <- mkBits findLabel init_asm_state instrs         
961
962          return (UnlinkedBCO nm final_insns final_lits final_ptrs final_itbls)
963
964 -- instrs nonptrs ptrs itbls
965 type AsmState = (SizedSeq Word16, SizedSeq Word, SizedSeq Name, SizedSeq Name)
966
967 data SizedSeq a = SizedSeq !Int [a]
968 emptySS = SizedSeq 0 []
969 addToSS (SizedSeq n r_xs) x = return (SizedSeq (n+1) (x:r_xs))
970 addListToSS (SizedSeq n r_xs) xs 
971    = return (SizedSeq (n + length xs) (reverse xs ++ r_xs))
972 sizeSS (SizedSeq n r_xs) = n
973 listFromSS (SizedSeq n r_xs) = return (reverse r_xs)
974
975
976 -- This is where all the action is (pass 2 of the assembler)
977 mkBits :: (Int -> Int)                  -- label finder
978        -> AsmState
979        -> [BCInstr]                     -- instructions (in)
980        -> IO AsmState
981
982 mkBits findLabel st proto_insns
983   = foldM doInstr st proto_insns
984     where
985        doInstr :: AsmState -> BCInstr -> IO AsmState
986        doInstr st i
987           = case i of
988                ARGCHECK  n        -> instr2 st i_ARGCHECK n
989                PUSH_L    o1       -> instr2 st i_PUSH_L o1
990                PUSH_LL   o1 o2    -> instr3 st i_PUSH_LL o1 o2
991                PUSH_LLL  o1 o2 o3 -> instr4 st i_PUSH_LLL o1 o2 o3
992                PUSH_G    nm       -> do (p, st2) <- ptr st nm
993                                         instr2 st2 i_PUSH_G p
994                PUSH_AS   nm pk    -> do (p, st2)  <- ptr st nm
995                                         (np, st3) <- ctoi_itbl st2 pk
996                                         instr3 st3 i_PUSH_AS p np
997                PUSH_UBX  lit nws  -> do (np, st2) <- literal st lit
998                                         instr3 st2 i_PUSH_UBX np nws
999                PUSH_TAG  tag      -> instr2 st i_PUSH_TAG tag
1000                SLIDE     n by     -> instr3 st i_SLIDE n by
1001                ALLOC     n        -> instr2 st i_ALLOC n
1002                MKAP      off sz   -> instr3 st i_MKAP off sz
1003                UNPACK    n        -> instr2 st i_UNPACK n
1004                UPK_TAG   n m k    -> instr4 st i_UPK_TAG n m k
1005                PACK      dcon sz  -> do (itbl_no,st2) <- itbl st dcon
1006                                         instr3 st2 i_PACK itbl_no sz
1007                LABEL     lab      -> return st
1008                TESTLT_I  i l      -> do (np, st2) <- int st i
1009                                         instr3 st2 i_TESTLT_I np (findLabel l)
1010                TESTEQ_I  i l      -> do (np, st2) <- int st i
1011                                         instr3 st2 i_TESTEQ_I np (findLabel l)
1012                TESTLT_F  f l      -> do (np, st2) <- float st f
1013                                         instr3 st2 i_TESTLT_F np (findLabel l)
1014                TESTEQ_F  f l      -> do (np, st2) <- float st f
1015                                         instr3 st2 i_TESTEQ_F np (findLabel l)
1016                TESTLT_D  d l      -> do (np, st2) <- double st d
1017                                         instr3 st2 i_TESTLT_D np (findLabel l)
1018                TESTEQ_D  d l      -> do (np, st2) <- double st d
1019                                         instr3 st2 i_TESTEQ_D np (findLabel l)
1020                TESTLT_P  i l      -> instr3 st i_TESTLT_P i (findLabel l)
1021                TESTEQ_P  i l      -> instr3 st i_TESTEQ_P i (findLabel l)
1022                CASEFAIL           -> instr1 st i_CASEFAIL
1023                ENTER              -> instr1 st i_ENTER
1024                RETURN rep         -> do (itbl_no,st2) <- itoc_itbl st rep
1025                                         instr2 st2 i_RETURN itbl_no
1026
1027        i2s :: Int -> Word16
1028        i2s = fromIntegral
1029
1030        instr1 (st_i0,st_l0,st_p0,st_I0) i1
1031           = do st_i1 <- addToSS st_i0 (i2s i1)
1032                return (st_i1,st_l0,st_p0,st_I0)
1033
1034        instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
1035           = do st_i1 <- addToSS st_i0 (i2s i1)
1036                st_i2 <- addToSS st_i1 (i2s i2)
1037                return (st_i2,st_l0,st_p0,st_I0)
1038
1039        instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
1040           = do st_i1 <- addToSS st_i0 (i2s i1)
1041                st_i2 <- addToSS st_i1 (i2s i2)
1042                st_i3 <- addToSS st_i2 (i2s i3)
1043                return (st_i3,st_l0,st_p0,st_I0)
1044
1045        instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
1046           = do st_i1 <- addToSS st_i0 (i2s i1)
1047                st_i2 <- addToSS st_i1 (i2s i2)
1048                st_i3 <- addToSS st_i2 (i2s i3)
1049                st_i4 <- addToSS st_i3 (i2s i4)
1050                return (st_i4,st_l0,st_p0,st_I0)
1051
1052        float (st_i0,st_l0,st_p0,st_I0) f
1053           = do let ws = mkLitF f
1054                st_l1 <- addListToSS st_l0 ws
1055                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1056
1057        double (st_i0,st_l0,st_p0,st_I0) d
1058           = do let ws = mkLitD d
1059                st_l1 <- addListToSS st_l0 ws
1060                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1061
1062        int (st_i0,st_l0,st_p0,st_I0) i
1063           = do let ws = mkLitI i
1064                st_l1 <- addListToSS st_l0 ws
1065                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1066
1067        addr (st_i0,st_l0,st_p0,st_I0) a
1068           = do let ws = mkLitA a
1069                st_l1 <- addListToSS st_l0 ws
1070                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1071
1072        ptr (st_i0,st_l0,st_p0,st_I0) p
1073           = do st_p1 <- addToSS st_p0 p
1074                return (sizeSS st_p0, (st_i0,st_l0,st_p1,st_I0))
1075
1076        itbl (st_i0,st_l0,st_p0,st_I0) dcon
1077           = do st_I1 <- addToSS st_I0 (getName dcon)
1078                return (sizeSS st_I0, (st_i0,st_l0,st_p0,st_I1))
1079
1080        literal st (MachInt j)    = int st (fromIntegral j)
1081        literal st (MachFloat r)  = float st (fromRational r)
1082        literal st (MachDouble r) = double st (fromRational r)
1083        literal st (MachChar c)   = int st c
1084
1085        ctoi_itbl st pk
1086           = addr st ret_itbl_addr
1087             where
1088                ret_itbl_addr = case pk of
1089                                   PtrRep    -> stg_ctoi_ret_R1_info
1090                                   IntRep    -> stg_ctoi_ret_R1_info
1091                                   FloatRep  -> stg_ctoi_ret_F1_info
1092                                   DoubleRep -> stg_ctoi_ret_D1_info
1093                                   _ -> pprPanic "mkBits.ctoi_itbl" (ppr pk)
1094                                where  -- TEMP HACK
1095                                   stg_ctoi_ret_F1_info = nullAddr
1096                                   stg_ctoi_ret_D1_info = nullAddr
1097
1098        itoc_itbl st pk
1099           = addr st ret_itbl_addr
1100             where
1101                ret_itbl_addr = case pk of
1102                                   IntRep    -> stg_gc_unbx_r1_info
1103                                   FloatRep  -> stg_gc_f1_info
1104                                   DoubleRep -> stg_gc_d1_info
1105                      
1106 foreign label "stg_ctoi_ret_R1_info" stg_ctoi_ret_R1_info :: Addr
1107 --foreign label "stg_ctoi_ret_F1_info" stg_ctoi_ret_F1_info :: Addr
1108 --foreign label "stg_ctoi_ret_D1_info" stg_ctoi_ret_D1_info :: Addr
1109
1110 foreign label "stg_gc_unbx_r1_info" stg_gc_unbx_r1_info :: Addr
1111 foreign label "stg_gc_f1_info"      stg_gc_f1_info :: Addr
1112 foreign label "stg_gc_d1_info"      stg_gc_d1_info :: Addr
1113
1114 -- The size in 16-bit entities of an instruction.
1115 instrSize16s :: BCInstr -> Int
1116 instrSize16s instr
1117    = case instr of
1118         ARGCHECK _     -> 2
1119         PUSH_L   _     -> 2
1120         PUSH_LL  _ _   -> 3
1121         PUSH_LLL _ _ _ -> 4
1122         PUSH_G   _     -> 2
1123         PUSH_AS  _ _   -> 3
1124         PUSH_UBX _ _   -> 3
1125         PUSH_TAG _     -> 2
1126         SLIDE    _ _   -> 3
1127         ALLOC    _     -> 2
1128         MKAP     _ _   -> 3
1129         UNPACK   _     -> 2
1130         UPK_TAG  _ _ _ -> 4
1131         PACK     _ _   -> 3
1132         LABEL    _     -> 0     -- !!
1133         TESTLT_I _ _   -> 3
1134         TESTEQ_I _ _   -> 3
1135         TESTLT_F _ _   -> 3
1136         TESTEQ_F _ _   -> 3
1137         TESTLT_D _ _   -> 3
1138         TESTEQ_D _ _   -> 3
1139         TESTLT_P _ _   -> 3
1140         TESTEQ_P _ _   -> 3
1141         CASEFAIL       -> 1
1142         ENTER          -> 1
1143         RETURN   _     -> 2
1144
1145
1146 -- Make lists of host-sized words for literals, so that when the
1147 -- words are placed in memory at increasing addresses, the
1148 -- bit pattern is correct for the host's word size and endianness.
1149 mkLitI :: Int    -> [Word]
1150 mkLitF :: Float  -> [Word]
1151 mkLitD :: Double -> [Word]
1152 mkLitA :: Addr   -> [Word]
1153
1154 mkLitF f
1155    = runST (do
1156         arr <- newFloatArray ((0::Int),0)
1157         writeFloatArray arr 0 f
1158         f_arr <- castSTUArray arr
1159         w0 <- readWordArray f_arr 0
1160         return [w0]
1161      )
1162
1163 mkLitD d
1164    | wORD_SIZE == 4
1165    = runST (do
1166         arr <- newDoubleArray ((0::Int),1)
1167         writeDoubleArray arr 0 d
1168         d_arr <- castSTUArray arr
1169         w0 <- readWordArray d_arr 0
1170         w1 <- readWordArray d_arr 1
1171         return [w0,w1]
1172      )
1173    | wORD_SIZE == 8
1174    = runST (do
1175         arr <- newDoubleArray ((0::Int),0)
1176         writeDoubleArray arr 0 d
1177         d_arr <- castSTUArray arr
1178         w0 <- readWordArray d_arr 0
1179         return [w0]
1180      )
1181
1182 mkLitI i
1183    = runST (do
1184         arr <- newIntArray ((0::Int),0)
1185         writeIntArray arr 0 i
1186         i_arr <- castSTUArray arr
1187         w0 <- readWordArray i_arr 0
1188         return [w0]
1189      )
1190
1191 mkLitA a
1192    = runST (do
1193         arr <- newAddrArray ((0::Int),0)
1194         writeAddrArray arr 0 a
1195         a_arr <- castSTUArray arr
1196         w0 <- readWordArray a_arr 0
1197         return [w0]
1198      )
1199
1200 \end{code}
1201
1202 %************************************************************************
1203 %*                                                                      *
1204 \subsection{Linking interpretables into something we can run}
1205 %*                                                                      *
1206 %************************************************************************
1207
1208 \begin{code}
1209
1210 {- 
1211 data BCO# = BCO# ByteArray#             -- instrs   :: array Word16#
1212                  ByteArray#             -- literals :: array Word32#
1213                  PtrArray#              -- ptrs     :: Array HValue
1214                  ByteArray#             -- itbls    :: Array Addr#
1215 -}
1216
1217 GLOBAL_VAR(v_cafTable, [], [HValue])
1218
1219 --addCAF :: HValue -> IO ()
1220 --addCAF x = do xs <- readIORef v_cafTable; writeIORef v_cafTable (x:xs)
1221
1222 --bcosToHValue :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr -> IO HValue
1223 --bcosToHValue ie ce (root_bco, other_bcos)
1224 --   = do linked_expr <- linkIExpr ie ce (root_bco, other_bcos)
1225 --      return linked_expr
1226
1227 linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
1228    = do insns    <- listFromSS insnsSS
1229         literals <- listFromSS literalsSS
1230         ptrs     <- listFromSS ptrsSS
1231         itbls    <- listFromSS itblsSS
1232
1233         linked_ptrs  <- mapM (lookupCE ce) ptrs
1234         linked_itbls <- mapM (lookupIE ie) itbls
1235
1236         let n_insns    = sizeSS insnsSS
1237             n_literals = sizeSS literalsSS
1238             n_ptrs     = sizeSS ptrsSS
1239             n_itbls    = sizeSS itblsSS
1240
1241         let ptrs_arr = array (0, n_ptrs-1) (indexify linked_ptrs)
1242                        :: Array Int HValue
1243             ptrs_parr = case ptrs_arr of Array lo hi parr -> parr
1244
1245             itbls_arr = array (0, n_itbls-1) (indexify linked_itbls)
1246                         :: UArray Int Addr
1247             itbls_barr = case itbls_arr of UArray lo hi barr -> barr
1248
1249             insns_arr | n_insns > 65535
1250                       = panic "linkBCO: >= 64k insns in BCO"
1251                       | otherwise 
1252                       = array (0, n_insns) 
1253                               (indexify (fromIntegral n_insns:insns))
1254                         :: UArray Int Word16
1255             insns_barr = case insns_arr of UArray lo hi barr -> barr
1256
1257             literals_arr = array (0, n_literals-1) (indexify literals)
1258                            :: UArray Int Word
1259             literals_barr = case literals_arr of UArray lo hi barr -> barr
1260
1261             indexify :: [a] -> [(Int, a)]
1262             indexify xs = zip [0..] xs
1263
1264         BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
1265
1266         return (unsafeCoerce# bco#)
1267
1268
1269 data BCO = BCO BCO#
1270
1271 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
1272 newBCO a b c d
1273    = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
1274
1275
1276 lookupCE :: ClosureEnv -> Name -> IO HValue
1277 lookupCE ce nm 
1278    = case lookupFM ce nm of
1279         Just aa -> return aa
1280         Nothing 
1281            -> do m <- lookupSymbol (nameToCLabel nm "closure")
1282                  case m of
1283                     Just (A# addr) -> case addrToHValue# addr of
1284                                          (# hval #) -> return hval
1285                     Nothing        -> pprPanic "ByteCodeGen.lookupCE" (ppr nm)
1286
1287 lookupIE :: ItblEnv -> Name -> IO Addr
1288 lookupIE ie con_nm 
1289    = case lookupFM ie con_nm of
1290         Just (Ptr a) -> return a
1291         Nothing
1292            -> do -- try looking up in the object files.
1293                  m <- lookupSymbol (nameToCLabel con_nm "con_info")
1294                  case m of
1295                     Just addr -> return addr
1296                     Nothing 
1297                        -> do -- perhaps a nullary constructor?
1298                              n <- lookupSymbol (nameToCLabel con_nm "static_info")
1299                              case n of
1300                                 Just addr -> return addr
1301                                 Nothing -> pprPanic "ByteCodeGen.lookupIE" (ppr con_nm)
1302
1303 -- HACK!!!  ToDo: cleaner
1304 nameToCLabel :: Name -> String{-suffix-} -> String
1305 nameToCLabel n suffix
1306    = _UNPK_(moduleNameFS (rdrNameModule rn)) 
1307      ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
1308      where rn = toRdrName n
1309
1310 \end{code}
1311
1312 %************************************************************************
1313 %*                                                                      *
1314 \subsection{Manufacturing of info tables for DataCons}
1315 %*                                                                      *
1316 %************************************************************************
1317
1318 \begin{code}
1319
1320 #if __GLASGOW_HASKELL__ <= 408
1321 type ItblPtr = Addr
1322 #else
1323 type ItblPtr = Ptr StgInfoTable
1324 #endif
1325
1326 -- Make info tables for the data decls in this module
1327 mkITbls :: [TyCon] -> IO ItblEnv
1328 mkITbls [] = return emptyFM
1329 mkITbls (tc:tcs) = do itbls  <- mkITbl tc
1330                       itbls2 <- mkITbls tcs
1331                       return (itbls `plusFM` itbls2)
1332
1333 mkITbl :: TyCon -> IO ItblEnv
1334 mkITbl tc
1335    | not (isDataTyCon tc) 
1336    = return emptyFM
1337    | n == length dcs  -- paranoia; this is an assertion.
1338    = make_constr_itbls dcs
1339      where
1340         dcs = tyConDataCons tc
1341         n   = tyConFamilySize tc
1342
1343 cONSTR :: Int
1344 cONSTR = 1  -- as defined in ghc/includes/ClosureTypes.h
1345
1346 -- Assumes constructors are numbered from zero, not one
1347 make_constr_itbls :: [DataCon] -> IO ItblEnv
1348 make_constr_itbls cons
1349    | length cons <= 8
1350    = do is <- mapM mk_vecret_itbl (zip cons [0..])
1351         return (listToFM is)
1352    | otherwise
1353    = do is <- mapM mk_dirret_itbl (zip cons [0..])
1354         return (listToFM is)
1355      where
1356         mk_vecret_itbl (dcon, conNo)
1357            = mk_itbl dcon conNo (vecret_entry conNo)
1358         mk_dirret_itbl (dcon, conNo)
1359            = mk_itbl dcon conNo stg_interp_constr_entry
1360
1361         mk_itbl :: DataCon -> Int -> Addr -> IO (Name,ItblPtr)
1362         mk_itbl dcon conNo entry_addr
1363            = let (tot_wds, ptr_wds, _) 
1364                     = mkVirtHeapOffsets typePrimRep (dataConRepArgTys dcon)
1365                  ptrs = ptr_wds
1366                  nptrs  = tot_wds - ptr_wds
1367                  itbl  = StgInfoTable {
1368                            ptrs = fromIntegral ptrs, nptrs = fromIntegral nptrs,
1369                            tipe = fromIntegral cONSTR,
1370                            srtlen = fromIntegral conNo,
1371                            code0 = fromIntegral code0, code1 = fromIntegral code1,
1372                            code2 = fromIntegral code2, code3 = fromIntegral code3,
1373                            code4 = fromIntegral code4, code5 = fromIntegral code5,
1374                            code6 = fromIntegral code6, code7 = fromIntegral code7 
1375                         }
1376                  -- Make a piece of code to jump to "entry_label".
1377                  -- This is the only arch-dependent bit.
1378                  -- On x86, if entry_label has an address 0xWWXXYYZZ,
1379                  -- emit   movl $0xWWXXYYZZ,%eax  ;  jmp *%eax
1380                  -- which is
1381                  -- B8 ZZ YY XX WW FF E0
1382                  (code0,code1,code2,code3,code4,code5,code6,code7)
1383                     = (0xB8, byte 0 entry_addr_w, byte 1 entry_addr_w, 
1384                              byte 2 entry_addr_w, byte 3 entry_addr_w, 
1385                        0xFF, 0xE0, 
1386                        0x90 {-nop-})
1387
1388                  entry_addr_w :: Word32
1389                  entry_addr_w = fromIntegral (addrToInt entry_addr)
1390              in
1391                  do addr <- malloc
1392                     --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl))
1393                     --putStrLn ("# ptrs  of itbl is " ++ show ptrs)
1394                     --putStrLn ("# nptrs of itbl is " ++ show nptrs)
1395                     poke addr itbl
1396                     return (getName dcon, addr `plusPtr` 8)
1397
1398
1399 byte :: Int -> Word32 -> Word32
1400 byte 0 w = w .&. 0xFF
1401 byte 1 w = (w `shiftR` 8) .&. 0xFF
1402 byte 2 w = (w `shiftR` 16) .&. 0xFF
1403 byte 3 w = (w `shiftR` 24) .&. 0xFF
1404
1405
1406 vecret_entry 0 = stg_interp_constr1_entry
1407 vecret_entry 1 = stg_interp_constr2_entry
1408 vecret_entry 2 = stg_interp_constr3_entry
1409 vecret_entry 3 = stg_interp_constr4_entry
1410 vecret_entry 4 = stg_interp_constr5_entry
1411 vecret_entry 5 = stg_interp_constr6_entry
1412 vecret_entry 6 = stg_interp_constr7_entry
1413 vecret_entry 7 = stg_interp_constr8_entry
1414
1415 -- entry point for direct returns for created constr itbls
1416 foreign label "stg_interp_constr_entry" stg_interp_constr_entry :: Addr
1417 -- and the 8 vectored ones
1418 foreign label "stg_interp_constr1_entry" stg_interp_constr1_entry :: Addr
1419 foreign label "stg_interp_constr2_entry" stg_interp_constr2_entry :: Addr
1420 foreign label "stg_interp_constr3_entry" stg_interp_constr3_entry :: Addr
1421 foreign label "stg_interp_constr4_entry" stg_interp_constr4_entry :: Addr
1422 foreign label "stg_interp_constr5_entry" stg_interp_constr5_entry :: Addr
1423 foreign label "stg_interp_constr6_entry" stg_interp_constr6_entry :: Addr
1424 foreign label "stg_interp_constr7_entry" stg_interp_constr7_entry :: Addr
1425 foreign label "stg_interp_constr8_entry" stg_interp_constr8_entry :: Addr
1426
1427
1428
1429
1430
1431 -- Ultra-minimalist version specially for constructors
1432 data StgInfoTable = StgInfoTable {
1433    ptrs :: Word16,
1434    nptrs :: Word16,
1435    srtlen :: Word16,
1436    tipe :: Word16,
1437    code0, code1, code2, code3, code4, code5, code6, code7 :: Word8
1438 }
1439
1440
1441 instance Storable StgInfoTable where
1442
1443    sizeOf itbl 
1444       = (sum . map (\f -> f itbl))
1445         [fieldSz ptrs, fieldSz nptrs, fieldSz srtlen, fieldSz tipe,
1446          fieldSz code0, fieldSz code1, fieldSz code2, fieldSz code3, 
1447          fieldSz code4, fieldSz code5, fieldSz code6, fieldSz code7]
1448
1449    alignment itbl 
1450       = (sum . map (\f -> f itbl))
1451         [fieldAl ptrs, fieldAl nptrs, fieldAl srtlen, fieldAl tipe,
1452          fieldAl code0, fieldAl code1, fieldAl code2, fieldAl code3, 
1453          fieldAl code4, fieldAl code5, fieldAl code6, fieldAl code7]
1454
1455    poke a0 itbl
1456       = do a1 <- store (ptrs   itbl) (castPtr a0)
1457            a2 <- store (nptrs  itbl) a1
1458            a3 <- store (tipe   itbl) a2
1459            a4 <- store (srtlen itbl) a3
1460            a5 <- store (code0  itbl) a4
1461            a6 <- store (code1  itbl) a5
1462            a7 <- store (code2  itbl) a6
1463            a8 <- store (code3  itbl) a7
1464            a9 <- store (code4  itbl) a8
1465            aA <- store (code5  itbl) a9
1466            aB <- store (code6  itbl) aA
1467            aC <- store (code7  itbl) aB
1468            return ()
1469
1470    peek a0
1471       = do (a1,ptrs)   <- load (castPtr a0)
1472            (a2,nptrs)  <- load a1
1473            (a3,tipe)   <- load a2
1474            (a4,srtlen) <- load a3
1475            (a5,code0)  <- load a4
1476            (a6,code1)  <- load a5
1477            (a7,code2)  <- load a6
1478            (a8,code3)  <- load a7
1479            (a9,code4)  <- load a8
1480            (aA,code5)  <- load a9
1481            (aB,code6)  <- load aA
1482            (aC,code7)  <- load aB
1483            return StgInfoTable { ptrs = ptrs, nptrs = nptrs, 
1484                                  srtlen = srtlen, tipe = tipe,
1485                                  code0 = code0, code1 = code1, code2 = code2,
1486                                  code3 = code3, code4 = code4, code5 = code5,
1487                                  code6 = code6, code7 = code7 }
1488
1489 fieldSz :: (Storable a, Storable b) => (a -> b) -> a -> Int
1490 fieldSz sel x = sizeOf (sel x)
1491
1492 fieldAl :: (Storable a, Storable b) => (a -> b) -> a -> Int
1493 fieldAl sel x = alignment (sel x)
1494
1495 store :: Storable a => a -> Ptr a -> IO (Ptr b)
1496 store x addr = do poke addr x
1497                   return (castPtr (addr `plusPtr` sizeOf x))
1498
1499 load :: Storable a => Ptr a -> IO (Ptr b, a)
1500 load addr = do x <- peek addr
1501                return (castPtr (addr `plusPtr` sizeOf x), x)
1502
1503 \end{code}
1504
1505 %************************************************************************
1506 %*                                                                      *
1507 \subsection{Connect to actual values for bytecode opcodes}
1508 %*                                                                      *
1509 %************************************************************************
1510
1511 \begin{code}
1512
1513 #include "Bytecodes.h"
1514
1515 i_ARGCHECK = (bci_ARGCHECK :: Int)
1516 i_PUSH_L   = (bci_PUSH_L :: Int)
1517 i_PUSH_LL  = (bci_PUSH_LL :: Int)
1518 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
1519 i_PUSH_G   = (bci_PUSH_G :: Int)
1520 i_PUSH_AS  = (bci_PUSH_AS :: Int)
1521 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
1522 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
1523 i_SLIDE    = (bci_SLIDE :: Int)
1524 i_ALLOC    = (bci_ALLOC :: Int)
1525 i_MKAP     = (bci_MKAP :: Int)
1526 i_UNPACK   = (bci_UNPACK :: Int)
1527 i_UPK_TAG  = (bci_UPK_TAG :: Int)
1528 i_PACK     = (bci_PACK :: Int)
1529 i_TESTLT_I = (bci_TESTLT_I :: Int)
1530 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
1531 i_TESTLT_F = (bci_TESTLT_F :: Int)
1532 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
1533 i_TESTLT_D = (bci_TESTLT_D :: Int)
1534 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
1535 i_TESTLT_P = (bci_TESTLT_P :: Int)
1536 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
1537 i_CASEFAIL = (bci_CASEFAIL :: Int)
1538 i_ENTER    = (bci_ENTER :: Int)
1539 i_RETURN   = (bci_RETURN :: Int)
1540
1541 \end{code}