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