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