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