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