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