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