[project @ 2001-05-22 13:43:14 by simonpj]
[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, isFCallId,
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 )
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                        Just TagToEnumOp -> Just (snd arg, extract_constr_Names t)
500                        other            -> Nothing
501               other -> Nothing
502
503       -- Extract the args (R->L) and fn
504       (args_r_to_l_raw, fn) = chomp app
505       chomp expr
506          = case snd expr of
507               AnnVar v    -> ([], v)
508               AnnApp f a  -> case chomp f of (az, f) -> (snd a:az, f)
509               AnnNote n e -> chomp e
510               other       -> pprPanic "schemeT" 
511                                 (ppr (deAnnotate (panic "schemeT.chomp", other)))
512          
513       args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
514       isTypeAtom (AnnType _) = True
515       isTypeAtom _           = False
516
517       -- decide if this is a constructor call, and rearrange
518       -- args appropriately.
519       maybe_dcon  = isDataConId_maybe fn
520       is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
521       (Just con)  = maybe_dcon
522
523       args_final_r_to_l
524          | not is_con_call
525          = args_r_to_l
526          | otherwise
527          = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
528            where isPtr = isFollowableRep . atomRep
529
530       -- make code to push the args and then do the SLIDE-ENTER thing
531       code = do_pushery d args_final_r_to_l
532
533       tag_when_push = not is_con_call
534       narg_words    = sum (map (get_arg_szw . atomRep) args_r_to_l)
535       get_arg_szw   = if tag_when_push then taggedSizeW else untaggedSizeW
536
537       do_pushery d (arg:args)
538          = let (push, arg_words) = pushAtom tag_when_push d p arg
539            in  push `appOL` do_pushery (d+arg_words) args
540       do_pushery d []
541          = case maybe_dcon of
542               Just con -> PACK con narg_words `consOL` (
543                           mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
544               Nothing
545                  -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
546                     in  push 
547                         `appOL` mkSLIDE (narg_words+arg_words) 
548                                         (d - s - narg_words)
549                         `snocOL` ENTER
550
551 mkSLIDE n d 
552    = if d == 0 then nilOL else unitOL (SLIDE n d)
553 bind x f 
554    = f x
555
556
557 atomRep (AnnVar v)    = typePrimRep (idType v)
558 atomRep (AnnLit l)    = literalPrimRep l
559 atomRep (AnnNote n b) = atomRep (snd b)
560 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
561 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
562 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
563
564
565 -- Compile code which expects an unboxed Int on the top of stack,
566 -- (call it i), and pushes the i'th closure in the supplied list 
567 -- as a consequence.
568 implement_tagToId :: [Name] -> BcM BCInstrList
569 implement_tagToId names
570    = ASSERT(not (null names))
571      getLabelsBc (length names)                 `thenBc` \ labels ->
572      getLabelBc                                 `thenBc` \ label_fail ->
573      getLabelBc                                 `thenBc` \ label_exit ->
574      zip4 labels (tail labels ++ [label_fail])
575                  [0 ..] names                   `bind`   \ infos ->
576      map (mkStep label_exit) infos              `bind`   \ steps ->
577      returnBc (concatOL steps
578                `appOL` 
579                toOL [LABEL label_fail, CASEFAIL, LABEL label_exit])
580      where
581         mkStep l_exit (my_label, next_label, n, name_for_n)
582            = toOL [LABEL my_label, 
583                    TESTEQ_I n next_label, 
584                    PUSH_G (Left name_for_n), 
585                    JMP l_exit]
586
587
588 -- Make code to unpack the top-of-stack constructor onto the stack, 
589 -- adding tags for the unboxed bits.  Takes the PrimReps of the 
590 -- constructor's arguments.  off_h and off_s are travelling offsets
591 -- along the constructor and the stack.
592 --
593 -- Supposing a constructor in the heap has layout
594 --
595 --      Itbl p_1 ... p_i np_1 ... np_j
596 --
597 -- then we add to the stack, shown growing down, the following:
598 --
599 --    (previous stack)
600 --         p_i
601 --         ...
602 --         p_1
603 --         np_j
604 --         tag_for(np_j)
605 --         ..
606 --         np_1
607 --         tag_for(np_1)
608 --
609 -- so that in the common case (ptrs only) a single UNPACK instr can
610 -- copy all the payload of the constr onto the stack with no further ado.
611
612 mkUnpackCode :: [Id]    -- constr args
613              -> Int     -- depth before unpack
614              -> BCEnv   -- env before unpack
615              -> (BCInstrList, Int, BCEnv)
616 mkUnpackCode vars d p
617    = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
618      --       ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
619      --       ++ "\n") (
620      (code_p `appOL` code_np, d', p')
621      --)
622      where
623         -- vars with reps
624         vreps = [(var, typePrimRep (idType var)) | var <- vars]
625
626         -- ptrs and nonptrs, forward
627         vreps_p  = filter (isFollowableRep.snd) vreps
628         vreps_np = filter (not.isFollowableRep.snd) vreps
629
630         -- the order in which we will augment the environment
631         vreps_env = reverse vreps_p ++ reverse vreps_np
632
633         -- new env and depth
634         vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
635         p' = addListToFM p (zip (map fst vreps_env) 
636                                 (mkStackOffsets d vreps_env_tszsw))
637         d' = d + sum vreps_env_tszsw
638
639         -- code to unpack the ptrs
640         ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
641         code_p | null vreps_p = nilOL
642                | otherwise    = unitOL (UNPACK ptrs_szw)
643
644         -- code to unpack the nonptrs
645         vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
646         code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
647         do_nptrs off_h off_s [] = nilOL
648         do_nptrs off_h off_s (npr:nprs)
649            = case npr of
650                 IntRep -> approved ; FloatRep -> approved
651                 DoubleRep -> approved ; AddrRep -> approved
652                 CharRep -> approved
653                 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
654              where
655                 approved = UPK_TAG usizeW (off_h-usizeW) off_s   `consOL` theRest
656                 theRest  = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
657                 usizeW   = untaggedSizeW npr
658                 tsizeW   = taggedSizeW npr
659
660
661 -- Push an atom onto the stack, returning suitable code & number of
662 -- stack words used.  Pushes it either tagged or untagged, since 
663 -- pushAtom is used to set up the stack prior to copying into the
664 -- heap for both APs (requiring tags) and constructors (which don't).
665 --
666 -- NB this means NO GC between pushing atoms for a constructor and
667 -- copying them into the heap.  It probably also means that 
668 -- tail calls MUST be of the form atom{atom ... atom} since if the
669 -- expression head was allowed to be arbitrary, there could be GC
670 -- in between pushing the arg atoms and completing the head.
671 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
672 -- isn't a problem; but only if arbitrary graph construction for the
673 -- head doesn't leave this BCO, since GC might happen at the start of
674 -- each BCO (we consult doYouWantToGC there).
675 --
676 -- Blargh.  JRS 001206
677 --
678 -- NB (further) that the env p must map each variable to the highest-
679 -- numbered stack slot for it.  For example, if the stack has depth 4 
680 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
681 -- the tag in stack[5], the stack will have depth 6, and p must map v to
682 -- 5 and not to 4.  Stack locations are numbered from zero, so a depth
683 -- 6 stack has valid words 0 .. 5.
684
685 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
686 pushAtom tagged d p (AnnVar v)
687
688    | idPrimRep v == VoidRep
689    = ASSERT(tagged)
690      (unitOL (PUSH_TAG 0), 1)
691
692    | isFCallId v
693    = pprPanic "pushAtom: byte code generator can't handle CCalls" (ppr v)
694
695    | Just primop <- isPrimOpId_maybe v
696    = (unitOL (PUSH_G (Right primop)), 1)
697
698    | otherwise
699    = let  {-
700           str = "\npushAtom " ++ showSDocDebug (ppr v) 
701                ++ " :: " ++ showSDocDebug (pprType (idType v))
702                ++ ", depth = " ++ show d
703                ++ ", tagged = " ++ show tagged ++ ", env =\n" ++ 
704                showSDocDebug (ppBCEnv p)
705                ++ " --> words: " ++ show (snd result) ++ "\n" ++
706                showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
707                ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
708          -}
709
710          result
711             = case lookupBCEnv_maybe p v of
712                  Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
713                  Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
714
715          nm = case isDataConId_maybe v of
716                  Just c  -> getName c
717                  Nothing -> getName v
718
719          sz_t   = taggedIdSizeW v
720          sz_u   = untaggedIdSizeW v
721          nwords = if tagged then sz_t else sz_u
722      in
723          result
724
725 pushAtom True d p (AnnLit lit)
726    = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
727      in  (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
728
729 pushAtom False d p (AnnLit lit)
730    = case lit of
731         MachWord w   -> code WordRep
732         MachInt i    -> code IntRep
733         MachFloat r  -> code FloatRep
734         MachDouble r -> code DoubleRep
735         MachChar c   -> code CharRep
736         MachStr s    -> pushStr s
737      where
738         code rep
739            = let size_host_words = untaggedSizeW rep
740              in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
741
742         pushStr s 
743            = let mallocvilleAddr
744                     = case s of
745                          CharStr s i -> A# s
746
747                          FastString _ l ba -> 
748                             -- sigh, a string in the heap is no good to us.
749                             -- We need a static C pointer, since the type of 
750                             -- a string literal is Addr#.  So, copy the string 
751                             -- into C land and introduce a memory leak 
752                             -- at the same time.
753                             let n = I# l
754                             -- CAREFUL!  Chars are 32 bits in ghc 4.09+
755                             in  unsafePerformIO (
756                                    do (Ptr a#) <- mallocBytes (n+1)
757                                       strncpy (Ptr a#) ba (fromIntegral n)
758                                       writeCharOffAddr (A# a#) n '\0'
759                                       return (A# a#)
760                                    )
761                          _ -> panic "StgInterp.lit2expr: unhandled string constant type"
762
763                  addrLit 
764                     = MachInt (toInteger (addrToInt mallocvilleAddr))
765              in
766                 -- Get the addr on the stack, untaggedly
767                 (unitOL (PUSH_UBX addrLit 1), 1)
768
769
770
771
772
773 pushAtom tagged d p (AnnApp f (_, AnnType _))
774    = pushAtom tagged d p (snd f)
775
776 pushAtom tagged d p (AnnNote note e)
777    = pushAtom tagged d p (snd e)
778
779 pushAtom tagged d p (AnnLam x e) 
780    | isTyVar x 
781    = pushAtom tagged d p (snd e)
782
783 pushAtom tagged d p other
784    = pprPanic "ByteCodeGen.pushAtom" 
785               (pprCoreExpr (deAnnotate (undefined, other)))
786
787 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
788
789
790 -- Given a bunch of alts code and their discrs, do the donkey work
791 -- of making a multiway branch using a switch tree.
792 -- What a load of hassle!
793 mkMultiBranch :: Maybe Int      -- # datacons in tycon, if alg alt
794                                 -- a hint; generates better code
795                                 -- Nothing is always safe
796               -> [(Discr, BCInstrList)] 
797               -> BcM BCInstrList
798 mkMultiBranch maybe_ncons raw_ways
799    = let d_way     = filter (isNoDiscr.fst) raw_ways
800          notd_ways = naturalMergeSortLe 
801                         (\w1 w2 -> leAlt (fst w1) (fst w2))
802                         (filter (not.isNoDiscr.fst) raw_ways)
803
804          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
805          mkTree [] range_lo range_hi = returnBc the_default
806
807          mkTree [val] range_lo range_hi
808             | range_lo `eqAlt` range_hi 
809             = returnBc (snd val)
810             | otherwise
811             = getLabelBc                                `thenBc` \ label_neq ->
812               returnBc (mkTestEQ (fst val) label_neq 
813                         `consOL` (snd val
814                         `appOL`   unitOL (LABEL label_neq)
815                         `appOL`   the_default))
816
817          mkTree vals range_lo range_hi
818             = let n = length vals `div` 2
819                   vals_lo = take n vals
820                   vals_hi = drop n vals
821                   v_mid = fst (head vals_hi)
822               in
823               getLabelBc                                `thenBc` \ label_geq ->
824               mkTree vals_lo range_lo (dec v_mid)       `thenBc` \ code_lo ->
825               mkTree vals_hi v_mid range_hi             `thenBc` \ code_hi ->
826               returnBc (mkTestLT v_mid label_geq
827                         `consOL` (code_lo
828                         `appOL`   unitOL (LABEL label_geq)
829                         `appOL`   code_hi))
830  
831          the_default 
832             = case d_way of [] -> unitOL CASEFAIL
833                             [(_, def)] -> def
834
835          -- None of these will be needed if there are no non-default alts
836          (mkTestLT, mkTestEQ, init_lo, init_hi)
837             | null notd_ways
838             = panic "mkMultiBranch: awesome foursome"
839             | otherwise
840             = case fst (head notd_ways) of {
841               DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
842                             \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
843                             DiscrI minBound,
844                             DiscrI maxBound );
845               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
846                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
847                             DiscrF minF,
848                             DiscrF maxF );
849               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
850                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
851                             DiscrD minD,
852                             DiscrD maxD );
853               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
854                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
855                             DiscrP algMinBound,
856                             DiscrP algMaxBound )
857               }
858
859          (algMinBound, algMaxBound)
860             = case maybe_ncons of
861                  Just n  -> (0, n - 1)
862                  Nothing -> (minBound, maxBound)
863
864          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
865          (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
866          (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
867          (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
868          NoDiscr     `eqAlt` NoDiscr     = True
869          _           `eqAlt` _           = False
870
871          (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
872          (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
873          (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
874          (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
875          NoDiscr     `leAlt` NoDiscr     = True
876          _           `leAlt` _           = False
877
878          isNoDiscr NoDiscr = True
879          isNoDiscr _       = False
880
881          dec (DiscrI i) = DiscrI (i-1)
882          dec (DiscrP i) = DiscrP (i-1)
883          dec other      = other         -- not really right, but if you
884                 -- do cases on floating values, you'll get what you deserve
885
886          -- same snotty comment applies to the following
887          minF, maxF :: Float
888          minD, maxD :: Double
889          minF = -1.0e37
890          maxF =  1.0e37
891          minD = -1.0e308
892          maxD =  1.0e308
893      in
894          mkTree notd_ways init_lo init_hi
895
896 \end{code}
897
898 %************************************************************************
899 %*                                                                      *
900 \subsection{Supporting junk for the compilation schemes}
901 %*                                                                      *
902 %************************************************************************
903
904 \begin{code}
905
906 -- Describes case alts
907 data Discr 
908    = DiscrI Int
909    | DiscrF Float
910    | DiscrD Double
911    | DiscrP Int
912    | NoDiscr
913
914 instance Outputable Discr where
915    ppr (DiscrI i) = int i
916    ppr (DiscrF f) = text (show f)
917    ppr (DiscrD d) = text (show d)
918    ppr (DiscrP i) = int i
919    ppr NoDiscr    = text "DEF"
920
921
922 -- Find things in the BCEnv (the what's-on-the-stack-env)
923 -- See comment preceding pushAtom for precise meaning of env contents
924 --lookupBCEnv :: BCEnv -> Id -> Int
925 --lookupBCEnv env nm
926 --   = case lookupFM env nm of
927 --        Nothing -> pprPanic "lookupBCEnv" 
928 --                            (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
929 --        Just xx -> xx
930
931 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
932 lookupBCEnv_maybe = lookupFM
933
934
935 -- When I push one of these on the stack, how much does Sp move by?
936 taggedSizeW :: PrimRep -> Int
937 taggedSizeW pr
938    | isFollowableRep pr = 1
939    | otherwise          = 1{-the tag-} + getPrimRepSize pr
940
941
942 -- The plain size of something, without tag.
943 untaggedSizeW :: PrimRep -> Int
944 untaggedSizeW pr
945    | isFollowableRep pr = 1
946    | otherwise          = getPrimRepSize pr
947
948
949 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
950 taggedIdSizeW   = taggedSizeW   . typePrimRep . idType
951 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
952
953 unboxedTupleException :: a
954 unboxedTupleException 
955    = throwDyn 
956         (Panic 
957            ("Bytecode generator can't handle unboxed tuples.  Possibly due\n" ++
958             "\tto foreign import/export decls in source.  Workaround:\n" ++
959             "\tcompile this module to a .o file, then restart session."))
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}