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