[project @ 2001-02-06 12:00:17 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, mkSysLocalName )
17 import Id               ( Id, idType, isDataConId_maybe, mkVanillaId,
18                           isPrimOpId_maybe, idPrimRep )
19 import OrdList          ( OrdList, consOL, snocOL, appOL, unitOL, 
20                           nilOL, toOL, concatOL, fromOL )
21 import FiniteMap        ( FiniteMap, addListToFM, listToFM,
22                           addToFM, lookupFM, fmToList, plusFM )
23 import CoreSyn
24 import PprCore          ( pprCoreExpr )
25 import Literal          ( Literal(..), literalPrimRep )
26 import PrimRep          ( PrimRep(..) )
27 import PrimOp           ( PrimOp(..)  )
28 import CoreFVs          ( freeVars )
29 import Type             ( typePrimRep )
30 import DataCon          ( dataConTag, fIRST_TAG, dataConTyCon, dataConWrapId )
31 import TyCon            ( TyCon, tyConFamilySize )
32 import Class            ( Class, classTyCon )
33 import Util             ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem )
34 import Var              ( isTyVar )
35 import VarSet           ( VarSet, varSetElems )
36 import PrimRep          ( getPrimRepSize, isFollowableRep )
37 import CmdLineOpts      ( DynFlags, DynFlag(..) )
38 import ErrUtils         ( showPass, dumpIfSet_dyn )
39 import Unique           ( mkPseudoUnique3 )
40 import FastString       ( FastString(..) )
41 import PprType          ( pprType )
42 import ByteCodeInstr    ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO, bciStackUse )
43 import ByteCodeItbls    ( ItblEnv, mkITbls )
44 import ByteCodeLink     ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
45                           ClosureEnv, HValue, linkSomeBCOs, filterNameMap,
46                           iNTERP_STACK_CHECK_THRESH )
47
48 import List             ( intersperse, sortBy )
49 import Foreign          ( Ptr(..), mallocBytes )
50 import Addr             ( Addr(..), addrToInt, writeCharOffAddr )
51 import CTypes           ( CInt )
52
53 import PrelBase         ( Int(..) )
54 import PrelGHC          ( ByteArray# )
55 import IOExts           ( unsafePerformIO )
56 import PrelIOBase       ( IO(..) )
57
58 \end{code}
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{Functions visible from outside this module.}
63 %*                                                                      *
64 %************************************************************************
65
66 \begin{code}
67
68 byteCodeGen :: DynFlags
69             -> [CoreBind] 
70             -> [TyCon] -> [Class]
71             -> IO ([UnlinkedBCO], ItblEnv)
72 byteCodeGen dflags binds local_tycons local_classes
73    = do showPass dflags "ByteCodeGen"
74         let tycs = local_tycons ++ map classTyCon local_classes
75         itblenv <- mkITbls tycs
76
77         let flatBinds = concatMap getBind binds
78             getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
79             getBind (Rec binds)       = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
80             final_state = runBc (BcM_State [] 0) 
81                                 (mapBc (schemeR True) flatBinds
82                                         `thenBc_` returnBc ())
83             (BcM_State proto_bcos final_ctr) = final_state
84
85         dumpIfSet_dyn dflags Opt_D_dump_BCOs
86            "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
87
88         bcos <- mapM assembleBCO proto_bcos
89
90         return (bcos, itblenv)
91         
92
93 -- Returns: (the root BCO for this expression, 
94 --           a list of auxilary BCOs resulting from compiling closures)
95 coreExprToBCOs :: DynFlags
96                -> CoreExpr
97                -> IO UnlinkedBCOExpr
98 coreExprToBCOs dflags expr
99  = do showPass dflags "ByteCodeGen"
100
101       -- create a totally bogus name for the top-level BCO; this
102       -- should be harmless, since it's never used for anything
103       let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
104       let invented_id   = mkVanillaId invented_name (panic "invented_id's type")
105
106       let (BcM_State all_proto_bcos final_ctr) 
107              = runBc (BcM_State [] 0) 
108                      (schemeR True (invented_id, freeVars expr))
109       dumpIfSet_dyn dflags Opt_D_dump_BCOs
110          "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
111
112       let root_proto_bco 
113              = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
114                   [root_bco] -> root_bco
115           auxiliary_proto_bcos
116              = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
117
118       auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
119       root_bco <- assembleBCO root_proto_bco
120
121       return (root_bco, auxiliary_bcos)
122
123
124 -- Linking stuff
125 linkIModules :: ItblEnv    -- incoming global itbl env; returned updated
126              -> ClosureEnv -- incoming global closure env; returned updated
127              -> [([UnlinkedBCO], ItblEnv)]
128              -> IO ([HValue], ItblEnv, ClosureEnv)
129 linkIModules gie gce mods 
130    = do let (bcoss, ies) = unzip mods
131             bcos = concat bcoss
132             final_gie = foldr plusFM gie ies
133         (final_gce, linked_bcos) <- linkSomeBCOs True final_gie gce bcos
134         return (linked_bcos, final_gie, final_gce)
135
136
137 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
138           -> IO HValue    -- IO BCO# really
139 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
140    = do (aux_ce, _) <- linkSomeBCOs False ie ce aux_ul_bcos
141         (_, [root_bco]) <- linkSomeBCOs False ie aux_ce [root_ul_bco]
142         return root_bco
143 \end{code}
144
145 %************************************************************************
146 %*                                                                      *
147 \subsection{Compilation schema for the bytecode generator.}
148 %*                                                                      *
149 %************************************************************************
150
151 \begin{code}
152
153 type BCInstrList = OrdList BCInstr
154
155 type Sequel = Int       -- back off to this depth before ENTER
156
157 -- Maps Ids to the offset from the stack _base_ so we don't have
158 -- to mess with it after each push/pop.
159 type BCEnv = FiniteMap Id Int   -- To find vars on the stack
160
161 ppBCEnv :: BCEnv -> SDoc
162 ppBCEnv p
163    = text "begin-env"
164      $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
165      $$ text "end-env"
166      where
167         pp_one (var, offset) = int offset <> colon <+> ppr var
168         cmp_snd x y = compare (snd x) (snd y)
169
170 -- Create a BCO and do a spot of peephole optimisation on the insns
171 -- at the same time.
172 mkProtoBCO nm instrs_ordlist origin
173    = ProtoBCO nm maybe_with_stack_check origin
174      where
175         -- Overestimate the stack usage (in words) of this BCO,
176         -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
177         -- stack check.  (The interpreter always does a stack check
178         -- for iNTERP_STACK_CHECK_THRESH words at the start of each
179         -- BCO anyway, so we only need to add an explicit on in the
180         -- (hopefully rare) cases when the (overestimated) stack use
181         -- exceeds iNTERP_STACK_CHECK_THRESH.
182         maybe_with_stack_check
183            | stack_overest >= 65535
184            = pprPanic "mkProtoBCO: stack use won't fit in 16 bits" 
185                       (int stack_overest)
186            | stack_overest >= iNTERP_STACK_CHECK_THRESH
187            = (STKCHECK stack_overest) : peep_d
188            | otherwise
189            = peep_d     -- the supposedly common case
190              
191         stack_overest = sum (map bciStackUse peep_d)
192                         + 10 {- just to be really really sure -}
193
194
195         -- Merge local pushes
196         peep_d = peep (fromOL instrs_ordlist)
197
198         peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
199            = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
200         peep (PUSH_L off1 : PUSH_L off2 : rest)
201            = PUSH_LL off1 (off2-1) : peep rest
202         peep (i:rest)
203            = i : peep rest
204         peep []
205            = []
206
207
208 -- Compile code for the right hand side of a let binding.
209 -- Park the resulting BCO in the monad.  Also requires the
210 -- variable to which this value was bound, so as to give the
211 -- resulting BCO a name.  Bool indicates top-levelness.
212
213 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
214 schemeR is_top (nm, rhs) 
215 {-
216    | trace (showSDoc (
217               (char ' '
218                $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
219                $$ pprCoreExpr (deAnnotate rhs)
220                $$ char ' '
221               ))) False
222    = undefined
223 -}
224    | otherwise
225    = schemeR_wrk is_top rhs nm (collect [] rhs)
226
227
228 collect xs (_, AnnNote note e)
229    = collect xs e
230 collect xs (_, AnnLam x e) 
231    = collect (if isTyVar x then xs else (x:xs)) e
232 collect xs not_lambda
233    = (reverse xs, not_lambda)
234
235 schemeR_wrk is_top original_body nm (args, body)
236    | Just dcon <- maybe_toplevel_null_con_rhs
237    = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
238      emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
239                                      (Right original_body))
240      --)
241
242    | otherwise
243    = let fvs       = filter (not.isTyVar) (varSetElems (fst original_body))
244          all_args  = reverse args ++ fvs
245          szsw_args = map taggedIdSizeW all_args
246          szw_args  = sum szsw_args
247          p_init    = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
248          argcheck  = unitOL (ARGCHECK szw_args)
249      in
250      schemeE szw_args 0 p_init body             `thenBc` \ body_code ->
251      emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) 
252                                      (Right original_body))
253
254      where
255         maybe_toplevel_null_con_rhs
256            | is_top && null args
257            = case snd body of
258                 AnnVar v_wrk 
259                    -> case isDataConId_maybe v_wrk of
260                          Nothing -> Nothing
261                          Just dc_wrk |  nm == dataConWrapId dc_wrk
262                                      -> Just dc_wrk
263                                      |  otherwise 
264                                      -> Nothing
265                 other -> Nothing
266            | otherwise
267            = Nothing
268
269 -- Let szsw be the sizes in words of some items pushed onto the stack,
270 -- which has initial depth d'.  Return the values which the stack environment
271 -- should map these items to.
272 mkStackOffsets :: Int -> [Int] -> [Int]
273 mkStackOffsets original_depth szsw
274    = map (subtract 1) (tail (scanl (+) original_depth szsw))
275
276 -- Compile code to apply the given expression to the remaining args
277 -- on the stack, returning a HNF.
278 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
279
280 -- Delegate tail-calls to schemeT.
281 schemeE d s p e@(fvs, AnnApp f a) 
282    = returnBc (schemeT d s p (fvs, AnnApp f a))
283 schemeE d s p e@(fvs, AnnVar v)
284    | isFollowableRep v_rep
285    = returnBc (schemeT d s p (fvs, AnnVar v))
286
287    | otherwise
288    = -- returning an unboxed value.  Heave it on the stack, SLIDE, and RETURN.
289      let (push, szw) = pushAtom True d p (AnnVar v)
290      in  returnBc (push                         -- value onto stack
291                    `appOL`  mkSLIDE szw (d-s)   -- clear to sequel
292                    `snocOL` RETURN v_rep)       -- go
293    where
294       v_rep = typePrimRep (idType v)
295
296 schemeE d s p (fvs, AnnLit literal)
297    = let (push, szw) = pushAtom True d p (AnnLit literal)
298          l_rep = literalPrimRep literal
299      in  returnBc (push                         -- value onto stack
300                    `appOL`  mkSLIDE szw (d-s)   -- clear to sequel
301                    `snocOL` RETURN l_rep)       -- go
302
303 schemeE d s p (fvs, AnnLet binds b)
304    = let (xs,rhss) = case binds of AnnNonRec x rhs  -> ([x],[rhs])
305                                    AnnRec xs_n_rhss -> unzip xs_n_rhss
306          n     = length xs
307          fvss  = map (filter (not.isTyVar).varSetElems.fst) rhss
308
309          -- Sizes of tagged free vars, + 1 for the fn
310          sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
311
312          -- This p', d' defn is safe because all the items being pushed
313          -- are ptrs, so all have size 1.  d' and p' reflect the stack
314          -- after the closures have been allocated in the heap (but not
315          -- filled in), and pointers to them parked on the stack.
316          p'    = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
317          d'    = d + n
318
319          infos = zipE4 fvss sizes xs [n, n-1 .. 1]
320          zipE  = zipEqual "schemeE"
321          zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
322
323          -- ToDo: don't build thunks for things with no free variables
324          buildThunk dd ([], size, id, off)
325             = PUSH_G (Left (getName id))
326               `consOL` unitOL (MKAP (off+size-1) size)
327          buildThunk dd ((fv:fvs), size, id, off)
328             = case pushAtom True dd p' (AnnVar fv) of
329                  (push_code, pushed_szw)
330                     -> push_code `appOL`
331                        buildThunk (dd+pushed_szw) (fvs, size, id, off)
332
333          thunkCode = concatOL (map (buildThunk d') infos)
334          allocCode = toOL (map ALLOC sizes)
335      in
336      schemeE d' s p' b                                  `thenBc`  \ bodyCode ->
337      mapBc (schemeR False) (zip xs rhss)                `thenBc_`
338      returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
339
340
341 schemeE d s p (fvs, AnnCase scrut bndr alts)
342    = let
343         -- Top of stack is the return itbl, as usual.
344         -- underneath it is the pointer to the alt_code BCO.
345         -- When an alt is entered, it assumes the returned value is
346         -- on top of the itbl.
347         ret_frame_sizeW = 2
348
349         -- Env and depth in which to compile the alts, not including
350         -- any vars bound by the alts themselves
351         d' = d + ret_frame_sizeW + taggedIdSizeW bndr
352         p' = addToFM p bndr (d' - 1)
353
354         scrut_primrep = typePrimRep (idType bndr)
355         isAlgCase
356            = case scrut_primrep of
357                 CharRep -> False ; AddrRep -> False ; WordRep -> False
358                 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
359                 PtrRep -> True
360                 other  -> pprPanic "ByteCodeGen.schemeE" (ppr other)
361
362         -- given an alt, return a discr and code for it.
363         codeAlt alt@(discr, binds_f, rhs)
364            | isAlgCase 
365            = let (unpack_code, d_after_unpack, p_after_unpack)
366                     = mkUnpackCode binds_f d' p'
367              in  schemeE d_after_unpack s p_after_unpack rhs
368                                         `thenBc` \ rhs_code -> 
369                  returnBc (my_discr alt, unpack_code `appOL` rhs_code)
370            | otherwise 
371            = ASSERT(null binds_f) 
372              schemeE d' s p' rhs        `thenBc` \ rhs_code ->
373              returnBc (my_discr alt, rhs_code)
374
375         my_discr (DEFAULT, binds, rhs)  = NoDiscr
376         my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc - fIRST_TAG)
377         my_discr (LitAlt l, binds, rhs)
378            = case l of MachInt i     -> DiscrI (fromInteger i)
379                        MachFloat r   -> DiscrF (fromRational r)
380                        MachDouble r  -> DiscrD (fromRational r)
381                        MachChar i    -> DiscrI i
382                        _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
383
384         maybe_ncons 
385            | not isAlgCase = Nothing
386            | otherwise 
387            = case [dc | (DataAlt dc, _, _) <- alts] of
388                 []     -> Nothing
389                 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
390
391      in 
392      mapBc codeAlt alts                                 `thenBc` \ alt_stuff ->
393      mkMultiBranch maybe_ncons alt_stuff                `thenBc` \ alt_final ->
394      let 
395          alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
396          alt_bco_name = getName bndr
397          alt_bco      = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
398      in
399      schemeE (d + ret_frame_sizeW) 
400              (d + ret_frame_sizeW) p scrut              `thenBc` \ scrut_code ->
401
402      emitBc alt_bco                                     `thenBc_`
403      returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
404
405
406 schemeE d s p (fvs, AnnNote note body)
407    = schemeE d s p body
408
409 schemeE d s p other
410    = pprPanic "ByteCodeGen.schemeE: unhandled case" 
411                (pprCoreExpr (deAnnotate other))
412
413
414 -- Compile code to do a tail call.  Three cases:
415 --
416 -- 1.  A nullary constructor.  Push its closure on the stack 
417 --     and SLIDE and RETURN.
418 --
419 -- 2.  Application of a non-nullary constructor, by defn saturated.
420 --     Split the args into ptrs and non-ptrs, and push the nonptrs, 
421 --     then the ptrs, and then do PACK and RETURN.
422 --
423 -- 3.  Otherwise, it must be a function call.  Push the args
424 --     right to left, SLIDE and ENTER.
425
426 schemeT :: Int          -- Stack depth
427         -> Sequel       -- Sequel depth
428         -> BCEnv        -- stack env
429         -> AnnExpr Id VarSet 
430         -> BCInstrList
431
432 schemeT d s p app
433 --   | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
434 --   = panic "schemeT ?!?!"
435
436    -- Handle case 1
437    | is_con_call && null args_r_to_l
438    = (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
439      `snocOL` ENTER
440
441    -- Cases 2 and 3
442    | otherwise
443    = code
444
445      where
446          -- Extract the args (R->L) and fn
447          (args_r_to_l_raw, fn) = chomp app
448          chomp expr
449             = case snd expr of
450                  AnnVar v    -> ([], v)
451                  AnnApp f a  -> case chomp f of (az, f) -> (snd a:az, f)
452                  AnnNote n e -> chomp e
453                  other       -> pprPanic "schemeT" 
454                                    (ppr (deAnnotate (panic "schemeT.chomp", other)))
455          
456          args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
457          isTypeAtom (AnnType _) = True
458          isTypeAtom _           = False
459
460          -- decide if this is a constructor call, and rearrange
461          -- args appropriately.
462          maybe_dcon  = isDataConId_maybe fn
463          is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
464          (Just con)  = maybe_dcon
465
466          args_final_r_to_l
467             | not is_con_call
468             = args_r_to_l
469             | otherwise
470             = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
471               where isPtr = isFollowableRep . atomRep
472
473          -- make code to push the args and then do the SLIDE-ENTER thing
474          code = do_pushery d args_final_r_to_l
475
476          tag_when_push = not is_con_call
477          narg_words    = sum (map (get_arg_szw . atomRep) args_r_to_l)
478          get_arg_szw   = if tag_when_push then taggedSizeW else untaggedSizeW
479
480          do_pushery d (arg:args)
481             = let (push, arg_words) = pushAtom tag_when_push d p arg
482               in  push `appOL` do_pushery (d+arg_words) args
483          do_pushery d []
484             = case maybe_dcon of
485                  Just con -> PACK con narg_words `consOL` (
486                              mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
487                  Nothing
488                     -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
489                        in  push 
490                            `appOL` mkSLIDE (narg_words+arg_words) 
491                                            (d - s - narg_words)
492                            `snocOL` ENTER
493
494 mkSLIDE n d 
495    = if d == 0 then nilOL else unitOL (SLIDE n d)
496
497 atomRep (AnnVar v)    = typePrimRep (idType v)
498 atomRep (AnnLit l)    = literalPrimRep l
499 atomRep (AnnNote n b) = atomRep (snd b)
500 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
501 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
502 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
503
504
505 -- Make code to unpack the top-of-stack constructor onto the stack, 
506 -- adding tags for the unboxed bits.  Takes the PrimReps of the 
507 -- constructor's arguments.  off_h and off_s are travelling offsets
508 -- along the constructor and the stack.
509 --
510 -- Supposing a constructor in the heap has layout
511 --
512 --      Itbl p_1 ... p_i np_1 ... np_j
513 --
514 -- then we add to the stack, shown growing down, the following:
515 --
516 --    (previous stack)
517 --         p_i
518 --         ...
519 --         p_1
520 --         np_j
521 --         tag_for(np_j)
522 --         ..
523 --         np_1
524 --         tag_for(np_1)
525 --
526 -- so that in the common case (ptrs only) a single UNPACK instr can
527 -- copy all the payload of the constr onto the stack with no further ado.
528
529 mkUnpackCode :: [Id]    -- constr args
530              -> Int     -- depth before unpack
531              -> BCEnv   -- env before unpack
532              -> (BCInstrList, Int, BCEnv)
533 mkUnpackCode vars d p
534    = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
535      --       ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
536      --       ++ "\n") (
537      (code_p `appOL` code_np, d', p')
538      --)
539      where
540         -- vars with reps
541         vreps = [(var, typePrimRep (idType var)) | var <- vars]
542
543         -- ptrs and nonptrs, forward
544         vreps_p  = filter (isFollowableRep.snd) vreps
545         vreps_np = filter (not.isFollowableRep.snd) vreps
546
547         -- the order in which we will augment the environment
548         vreps_env = reverse vreps_p ++ reverse vreps_np
549
550         -- new env and depth
551         vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
552         p' = addListToFM p (zip (map fst vreps_env) 
553                                 (mkStackOffsets d vreps_env_tszsw))
554         d' = d + sum vreps_env_tszsw
555
556         -- code to unpack the ptrs
557         ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
558         code_p | null vreps_p = nilOL
559                | otherwise    = unitOL (UNPACK ptrs_szw)
560
561         -- code to unpack the nonptrs
562         vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
563         code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
564         do_nptrs off_h off_s [] = nilOL
565         do_nptrs off_h off_s (npr:nprs)
566            = case npr of
567                 IntRep -> approved ; FloatRep -> approved
568                 DoubleRep -> approved ; AddrRep -> approved
569                 CharRep -> approved
570                 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
571              where
572                 approved = UPK_TAG usizeW (off_h-usizeW) off_s   `consOL` theRest
573                 theRest  = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
574                 usizeW   = untaggedSizeW npr
575                 tsizeW   = taggedSizeW npr
576
577
578 -- Push an atom onto the stack, returning suitable code & number of
579 -- stack words used.  Pushes it either tagged or untagged, since 
580 -- pushAtom is used to set up the stack prior to copying into the
581 -- heap for both APs (requiring tags) and constructors (which don't).
582 --
583 -- NB this means NO GC between pushing atoms for a constructor and
584 -- copying them into the heap.  It probably also means that 
585 -- tail calls MUST be of the form atom{atom ... atom} since if the
586 -- expression head was allowed to be arbitrary, there could be GC
587 -- in between pushing the arg atoms and completing the head.
588 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
589 -- isn't a problem; but only if arbitrary graph construction for the
590 -- head doesn't leave this BCO, since GC might happen at the start of
591 -- each BCO (we consult doYouWantToGC there).
592 --
593 -- Blargh.  JRS 001206
594 --
595 -- NB (further) that the env p must map each variable to the highest-
596 -- numbered stack slot for it.  For example, if the stack has depth 4 
597 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
598 -- the tag in stack[5], the stack will have depth 6, and p must map v to
599 -- 5 and not to 4.  Stack locations are numbered from zero, so a depth
600 -- 6 stack has valid words 0 .. 5.
601
602 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
603 pushAtom tagged d p (AnnVar v)
604
605    | idPrimRep v == VoidRep
606    = ASSERT(tagged)
607      (unitOL (PUSH_TAG 0), 1)
608
609    | Just primop <- isPrimOpId_maybe v
610    = case primop of
611         CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
612         other     -> (unitOL (PUSH_G (Right primop)), 1)
613
614    | otherwise
615    = let str = "\npushAtom " ++ showSDocDebug (ppr v) 
616                ++ " :: " ++ showSDocDebug (pprType (idType v))
617                ++ ", depth = " ++ show d
618                ++ ", tagged = " ++ show tagged ++ ", env =\n" ++ 
619                showSDocDebug (ppBCEnv p)
620                ++ " --> words: " ++ show (snd result) ++ "\n" ++
621                showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
622                ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
623                   where
624                      cmp_snd x y = compare (snd x) (snd y)
625          str' = if str == str then str else str
626
627          result
628             = case lookupBCEnv_maybe p v of
629                  Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
630                  Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
631
632          nm = case isDataConId_maybe v of
633                  Just c  -> getName c
634                  Nothing -> getName v
635
636          sz_t   = taggedIdSizeW v
637          sz_u   = untaggedIdSizeW v
638          nwords = if tagged then sz_t else sz_u
639      in
640          --trace str'
641          result
642
643 pushAtom True d p (AnnLit lit)
644    = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
645      in  (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
646
647 pushAtom False d p (AnnLit lit)
648    = case lit of
649         MachWord w   -> code WordRep
650         MachInt i    -> code IntRep
651         MachFloat r  -> code FloatRep
652         MachDouble r -> code DoubleRep
653         MachChar c   -> code CharRep
654         MachStr s    -> pushStr s
655      where
656         code rep
657            = let size_host_words = untaggedSizeW rep
658              in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
659
660         pushStr s 
661            = let mallocvilleAddr
662                     = case s of
663                          CharStr s i -> A# s
664
665                          FastString _ l ba -> 
666                             -- sigh, a string in the heap is no good to us.
667                             -- We need a static C pointer, since the type of 
668                             -- a string literal is Addr#.  So, copy the string 
669                             -- into C land and introduce a memory leak 
670                             -- at the same time.
671                             let n = I# l
672                             -- CAREFUL!  Chars are 32 bits in ghc 4.09+
673                             in  unsafePerformIO (
674                                    do (Ptr a#) <- mallocBytes (n+1)
675                                       strncpy (Ptr a#) ba (fromIntegral n)
676                                       writeCharOffAddr (A# a#) n '\0'
677                                       return (A# a#)
678                                    )
679                          _ -> panic "StgInterp.lit2expr: unhandled string constant type"
680
681                  addrLit 
682                     = MachInt (toInteger (addrToInt mallocvilleAddr))
683              in
684                 -- Get the addr on the stack, untaggedly
685                 (unitOL (PUSH_UBX addrLit 1), 1)
686
687
688
689
690
691 pushAtom tagged d p (AnnApp f (_, AnnType _))
692    = pushAtom tagged d p (snd f)
693
694 pushAtom tagged d p (AnnNote note e)
695    = pushAtom tagged d p (snd e)
696
697 pushAtom tagged d p (AnnLam x e) 
698    | isTyVar x 
699    = pushAtom tagged d p (snd e)
700
701 pushAtom tagged d p other
702    = pprPanic "ByteCodeGen.pushAtom" 
703               (pprCoreExpr (deAnnotate (undefined, other)))
704
705 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
706
707
708 -- Given a bunch of alts code and their discrs, do the donkey work
709 -- of making a multiway branch using a switch tree.
710 -- What a load of hassle!
711 mkMultiBranch :: Maybe Int      -- # datacons in tycon, if alg alt
712                                 -- a hint; generates better code
713                                 -- Nothing is always safe
714               -> [(Discr, BCInstrList)] 
715               -> BcM BCInstrList
716 mkMultiBranch maybe_ncons raw_ways
717    = let d_way     = filter (isNoDiscr.fst) raw_ways
718          notd_ways = naturalMergeSortLe 
719                         (\w1 w2 -> leAlt (fst w1) (fst w2))
720                         (filter (not.isNoDiscr.fst) raw_ways)
721
722          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
723          mkTree [] range_lo range_hi = returnBc the_default
724
725          mkTree [val] range_lo range_hi
726             | range_lo `eqAlt` range_hi 
727             = returnBc (snd val)
728             | otherwise
729             = getLabelBc                                `thenBc` \ label_neq ->
730               returnBc (mkTestEQ (fst val) label_neq 
731                         `consOL` (snd val
732                         `appOL`   unitOL (LABEL label_neq)
733                         `appOL`   the_default))
734
735          mkTree vals range_lo range_hi
736             = let n = length vals `div` 2
737                   vals_lo = take n vals
738                   vals_hi = drop n vals
739                   v_mid = fst (head vals_hi)
740               in
741               getLabelBc                                `thenBc` \ label_geq ->
742               mkTree vals_lo range_lo (dec v_mid)       `thenBc` \ code_lo ->
743               mkTree vals_hi v_mid range_hi             `thenBc` \ code_hi ->
744               returnBc (mkTestLT v_mid label_geq
745                         `consOL` (code_lo
746                         `appOL`   unitOL (LABEL label_geq)
747                         `appOL`   code_hi))
748  
749          the_default 
750             = case d_way of [] -> unitOL CASEFAIL
751                             [(_, def)] -> def
752
753          -- None of these will be needed if there are no non-default alts
754          (mkTestLT, mkTestEQ, init_lo, init_hi)
755             | null notd_ways
756             = panic "mkMultiBranch: awesome foursome"
757             | otherwise
758             = case fst (head notd_ways) of {
759               DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
760                             \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
761                             DiscrI minBound,
762                             DiscrI maxBound );
763               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
764                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
765                             DiscrF minF,
766                             DiscrF maxF );
767               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
768                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
769                             DiscrD minD,
770                             DiscrD maxD );
771               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
772                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
773                             DiscrP algMinBound,
774                             DiscrP algMaxBound )
775               }
776
777          (algMinBound, algMaxBound)
778             = case maybe_ncons of
779                  Just n  -> (0, n - 1)
780                  Nothing -> (minBound, maxBound)
781
782          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
783          (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
784          (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
785          (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
786          NoDiscr     `eqAlt` NoDiscr     = True
787          _           `eqAlt` _           = False
788
789          (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
790          (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
791          (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
792          (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
793          NoDiscr     `leAlt` NoDiscr     = True
794          _           `leAlt` _           = False
795
796          isNoDiscr NoDiscr = True
797          isNoDiscr _       = False
798
799          dec (DiscrI i) = DiscrI (i-1)
800          dec (DiscrP i) = DiscrP (i-1)
801          dec other      = other         -- not really right, but if you
802                 -- do cases on floating values, you'll get what you deserve
803
804          -- same snotty comment applies to the following
805          minF, maxF :: Float
806          minD, maxD :: Double
807          minF = -1.0e37
808          maxF =  1.0e37
809          minD = -1.0e308
810          maxD =  1.0e308
811      in
812          mkTree notd_ways init_lo init_hi
813
814 \end{code}
815
816 %************************************************************************
817 %*                                                                      *
818 \subsection{Supporting junk for the compilation schemes}
819 %*                                                                      *
820 %************************************************************************
821
822 \begin{code}
823
824 -- Describes case alts
825 data Discr 
826    = DiscrI Int
827    | DiscrF Float
828    | DiscrD Double
829    | DiscrP Int
830    | NoDiscr
831
832 instance Outputable Discr where
833    ppr (DiscrI i) = int i
834    ppr (DiscrF f) = text (show f)
835    ppr (DiscrD d) = text (show d)
836    ppr (DiscrP i) = int i
837    ppr NoDiscr    = text "DEF"
838
839
840 -- Find things in the BCEnv (the what's-on-the-stack-env)
841 -- See comment preceding pushAtom for precise meaning of env contents
842 --lookupBCEnv :: BCEnv -> Id -> Int
843 --lookupBCEnv env nm
844 --   = case lookupFM env nm of
845 --        Nothing -> pprPanic "lookupBCEnv" 
846 --                            (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
847 --        Just xx -> xx
848
849 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
850 lookupBCEnv_maybe = lookupFM
851
852
853 -- When I push one of these on the stack, how much does Sp move by?
854 taggedSizeW :: PrimRep -> Int
855 taggedSizeW pr
856    | isFollowableRep pr = 1
857    | otherwise          = 1{-the tag-} + getPrimRepSize pr
858
859
860 -- The plain size of something, without tag.
861 untaggedSizeW :: PrimRep -> Int
862 untaggedSizeW pr
863    | isFollowableRep pr = 1
864    | otherwise          = getPrimRepSize pr
865
866
867 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
868 taggedIdSizeW   = taggedSizeW   . typePrimRep . idType
869 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
870
871 \end{code}
872
873 %************************************************************************
874 %*                                                                      *
875 \subsection{The bytecode generator's monad}
876 %*                                                                      *
877 %************************************************************************
878
879 \begin{code}
880 data BcM_State 
881    = BcM_State { bcos      :: [ProtoBCO Name],  -- accumulates completed BCOs
882                  nextlabel :: Int }             -- for generating local labels
883
884 type BcM result = BcM_State -> (result, BcM_State)
885
886 runBc :: BcM_State -> BcM () -> BcM_State
887 runBc init_st m = case m init_st of { (r,st) -> st }
888
889 thenBc :: BcM a -> (a -> BcM b) -> BcM b
890 thenBc expr cont st
891   = case expr st of { (result, st') -> cont result st' }
892
893 thenBc_ :: BcM a -> BcM b -> BcM b
894 thenBc_ expr cont st
895   = case expr st of { (result, st') -> cont st' }
896
897 returnBc :: a -> BcM a
898 returnBc result st = (result, st)
899
900 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
901 mapBc f []     = returnBc []
902 mapBc f (x:xs)
903   = f x          `thenBc` \ r  ->
904     mapBc f xs   `thenBc` \ rs ->
905     returnBc (r:rs)
906
907 emitBc :: ProtoBCO Name -> BcM ()
908 emitBc bco st
909    = ((), st{bcos = bco : bcos st})
910
911 getLabelBc :: BcM Int
912 getLabelBc st
913    = (nextlabel st, st{nextlabel = 1 + nextlabel st})
914
915 \end{code}