d395aa06c1b550cc809cf4acaf62288425d4afe7
[ghc-hetmet.git] / compiler / ghci / ByteCodeGen.lhs
1 %
2 % (c) The University of Glasgow 2002-2006
3 %
4
5 ByteCodeGen: Generate bytecode from Core
6
7 \begin{code}
8 module ByteCodeGen ( UnlinkedBCO, byteCodeGen, coreExprToBCOs ) where
9
10 #include "HsVersions.h"
11
12 import ByteCodeInstr
13 import ByteCodeItbls
14 import ByteCodeAsm
15 import ByteCodeLink
16 import LibFFI
17
18 import Outputable
19 import Name
20 import Id
21 import FiniteMap
22 import ForeignCall
23 import HscTypes
24 import CoreUtils
25 import CoreSyn
26 import PprCore
27 import Literal
28 import PrimOp
29 import CoreFVs
30 import Type
31 import DataCon
32 import TyCon
33 import Type
34 import Util
35 import DataCon
36 import Var
37 import VarSet
38 import TysPrim
39 import DynFlags
40 import ErrUtils
41 import Unique
42 import FastString
43 import Panic
44 import SMRep
45 import Bitmap
46 import OrdList
47 import Constants
48
49 import Data.List
50 import Foreign
51 import Foreign.C
52 import Control.Exception        ( throwDyn )
53
54 import GHC.Exts         ( Int(..), ByteArray# )
55
56 import Control.Monad    ( when )
57 import Data.Char
58
59 import UniqSupply
60 import BreakArray
61 import Data.Maybe
62 import Module 
63 import IdInfo 
64
65 -- -----------------------------------------------------------------------------
66 -- Generating byte code for a complete module 
67
68 byteCodeGen :: DynFlags
69             -> [CoreBind]
70             -> [TyCon]
71             -> ModBreaks 
72             -> IO CompiledByteCode
73 byteCodeGen dflags binds tycs modBreaks 
74    = do showPass dflags "ByteCodeGen"
75
76         let flatBinds = [ (bndr, freeVars rhs) 
77                         | (bndr, rhs) <- flattenBinds binds]
78
79         us <- mkSplitUniqSupply 'y'  
80         (BcM_State _us _final_ctr mallocd _, proto_bcos) 
81            <- runBc us modBreaks (mapM schemeTopBind flatBinds)  
82
83         when (notNull mallocd)
84              (panic "ByteCodeGen.byteCodeGen: missing final emitBc?")
85
86         dumpIfSet_dyn dflags Opt_D_dump_BCOs
87            "Proto-BCOs" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
88
89         assembleBCOs proto_bcos tycs
90         
91 -- -----------------------------------------------------------------------------
92 -- Generating byte code for an expression
93
94 -- Returns: (the root BCO for this expression, 
95 --           a list of auxilary BCOs resulting from compiling closures)
96 coreExprToBCOs :: DynFlags
97                -> CoreExpr
98                -> IO UnlinkedBCO
99 coreExprToBCOs dflags expr
100  = do showPass dflags "ByteCodeGen"
101
102       -- create a totally bogus name for the top-level BCO; this
103       -- should be harmless, since it's never used for anything
104       let invented_name  = mkSystemVarName (mkPseudoUniqueE 0) (fsLit "ExprTopLevel")
105           invented_id    = Id.mkLocalId invented_name (panic "invented_id's type")
106           
107       -- the uniques are needed to generate fresh variables when we introduce new
108       -- let bindings for ticked expressions
109       us <- mkSplitUniqSupply 'y'
110       (BcM_State _us _final_ctr mallocd _ , proto_bco)  
111          <- runBc us emptyModBreaks (schemeTopBind (invented_id, freeVars expr))
112
113       when (notNull mallocd)
114            (panic "ByteCodeGen.coreExprToBCOs: missing final emitBc?")
115
116       dumpIfSet_dyn dflags Opt_D_dump_BCOs "Proto-BCOs" (ppr proto_bco)
117
118       assembleBCO proto_bco
119
120
121 -- -----------------------------------------------------------------------------
122 -- Compilation schema for the bytecode generator
123
124 type BCInstrList = OrdList BCInstr
125
126 type Sequel = Int       -- back off to this depth before ENTER
127
128 -- Maps Ids to the offset from the stack _base_ so we don't have
129 -- to mess with it after each push/pop.
130 type BCEnv = FiniteMap Id Int   -- To find vars on the stack
131
132 {-
133 ppBCEnv :: BCEnv -> SDoc
134 ppBCEnv p
135    = text "begin-env"
136      $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
137      $$ text "end-env"
138      where
139         pp_one (var, offset) = int offset <> colon <+> ppr var <+> ppr (idCgRep var)
140         cmp_snd x y = compare (snd x) (snd y)
141 -}
142
143 -- Create a BCO and do a spot of peephole optimisation on the insns
144 -- at the same time.
145 mkProtoBCO
146    :: name
147    -> BCInstrList
148    -> Either  [AnnAlt Id VarSet] (AnnExpr Id VarSet)
149    -> Int
150    -> Int
151    -> [StgWord]
152    -> Bool      -- True <=> is a return point, rather than a function
153    -> [BcPtr]
154    -> ProtoBCO name
155 mkProtoBCO nm instrs_ordlist origin arity bitmap_size bitmap is_ret mallocd_blocks 
156    = ProtoBCO {
157         protoBCOName = nm,
158         protoBCOInstrs = maybe_with_stack_check,
159         protoBCOBitmap = bitmap,
160         protoBCOBitmapSize = bitmap_size,
161         protoBCOArity = arity,
162         protoBCOExpr = origin,
163         protoBCOPtrs = mallocd_blocks
164       }
165      where
166         -- Overestimate the stack usage (in words) of this BCO,
167         -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
168         -- stack check.  (The interpreter always does a stack check
169         -- for iNTERP_STACK_CHECK_THRESH words at the start of each
170         -- BCO anyway, so we only need to add an explicit on in the
171         -- (hopefully rare) cases when the (overestimated) stack use
172         -- exceeds iNTERP_STACK_CHECK_THRESH.
173         maybe_with_stack_check
174            | is_ret && stack_usage < aP_STACK_SPLIM = peep_d
175                 -- don't do stack checks at return points,
176                 -- everything is aggregated up to the top BCO
177                 -- (which must be a function).
178                 -- That is, unless the stack usage is >= AP_STACK_SPLIM,
179                 -- see bug #1466.
180            | stack_usage >= iNTERP_STACK_CHECK_THRESH
181            = STKCHECK stack_usage : peep_d
182            | otherwise
183            = peep_d     -- the supposedly common case
184              
185         -- We assume that this sum doesn't wrap
186         stack_usage = sum (map bciStackUse peep_d)
187
188         -- Merge local pushes
189         peep_d = peep (fromOL instrs_ordlist)
190
191         peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
192            = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
193         peep (PUSH_L off1 : PUSH_L off2 : rest)
194            = PUSH_LL off1 (off2-1) : peep rest
195         peep (i:rest)
196            = i : peep rest
197         peep []
198            = []
199
200 argBits :: [CgRep] -> [Bool]
201 argBits [] = []
202 argBits (rep : args)
203   | isFollowableArg rep = False : argBits args
204   | otherwise = take (cgRepSizeW rep) (repeat True) ++ argBits args
205
206 -- -----------------------------------------------------------------------------
207 -- schemeTopBind
208
209 -- Compile code for the right-hand side of a top-level binding
210
211 schemeTopBind :: (Id, AnnExpr Id VarSet) -> BcM (ProtoBCO Name)
212
213
214 schemeTopBind (id, rhs) 
215   | Just data_con <- isDataConWorkId_maybe id,
216     isNullaryRepDataCon data_con = do
217         -- Special case for the worker of a nullary data con.
218         -- It'll look like this:        Nil = /\a -> Nil a
219         -- If we feed it into schemeR, we'll get 
220         --      Nil = Nil
221         -- because mkConAppCode treats nullary constructor applications
222         -- by just re-using the single top-level definition.  So
223         -- for the worker itself, we must allocate it directly.
224     -- ioToBc (putStrLn $ "top level BCO")
225     emitBc (mkProtoBCO (getName id) (toOL [PACK data_con 0, ENTER])
226                        (Right rhs) 0 0 [{-no bitmap-}] False{-not alts-}) 
227
228   | otherwise
229   = schemeR [{- No free variables -}] (id, rhs)
230
231
232 -- -----------------------------------------------------------------------------
233 -- schemeR
234
235 -- Compile code for a right-hand side, to give a BCO that,
236 -- when executed with the free variables and arguments on top of the stack,
237 -- will return with a pointer to the result on top of the stack, after
238 -- removing the free variables and arguments.
239 --
240 -- Park the resulting BCO in the monad.  Also requires the
241 -- variable to which this value was bound, so as to give the
242 -- resulting BCO a name. 
243
244 schemeR :: [Id]                 -- Free vars of the RHS, ordered as they
245                                 -- will appear in the thunk.  Empty for
246                                 -- top-level things, which have no free vars.
247         -> (Id, AnnExpr Id VarSet)
248         -> BcM (ProtoBCO Name)
249 schemeR fvs (nm, rhs)
250 {-
251    | trace (showSDoc (
252               (char ' '
253                $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
254                $$ pprCoreExpr (deAnnotate rhs)
255                $$ char ' '
256               ))) False
257    = undefined
258    | otherwise
259 -}
260    = schemeR_wrk fvs nm rhs (collect [] rhs)
261
262 collect :: [Var] -> AnnExpr Id VarSet -> ([Var], AnnExpr' Id VarSet)
263 collect xs (_, AnnNote _ e) = collect xs e
264 collect xs (_, AnnCast e _) = collect xs e
265 collect xs (_, AnnLam x e)  = collect (if isTyVar x then xs else (x:xs)) e
266 collect xs (_, not_lambda)  = (reverse xs, not_lambda)
267
268 schemeR_wrk :: [Id] -> Id -> AnnExpr Id VarSet -> ([Var], AnnExpr' Var VarSet) -> BcM (ProtoBCO Name) 
269 schemeR_wrk fvs nm original_body (args, body)
270    = let 
271          all_args  = reverse args ++ fvs
272          arity     = length all_args
273          -- all_args are the args in reverse order.  We're compiling a function
274          -- \fv1..fvn x1..xn -> e 
275          -- i.e. the fvs come first
276
277          szsw_args = map idSizeW all_args
278          szw_args  = sum szsw_args
279          p_init    = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
280
281          -- make the arg bitmap
282          bits = argBits (reverse (map idCgRep all_args))
283          bitmap_size = length bits
284          bitmap = mkBitmap bits
285      in do
286      body_code <- schemeER_wrk szw_args p_init body   
287  
288      emitBc (mkProtoBCO (getName nm) body_code (Right original_body)
289                 arity bitmap_size bitmap False{-not alts-})
290
291 -- introduce break instructions for ticked expressions
292 schemeER_wrk :: Int -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList
293 schemeER_wrk d p rhs
294    | Just (tickInfo, (_annot, newRhs)) <- isTickedExp' rhs = do 
295         code <- schemeE d 0 p newRhs 
296         arr <- getBreakArray 
297         let idOffSets = getVarOffSets d p tickInfo 
298         let tickNumber = tickInfo_number tickInfo
299         let breakInfo = BreakInfo 
300                         { breakInfo_module = tickInfo_module tickInfo
301                         , breakInfo_number = tickNumber 
302                         , breakInfo_vars = idOffSets
303                         , breakInfo_resty = exprType (deAnnotate' newRhs)
304                         }
305         let breakInstr = case arr of (BA arr#) -> BRK_FUN arr# tickNumber breakInfo 
306         return $ breakInstr `consOL` code
307    | otherwise = schemeE d 0 p rhs 
308
309 getVarOffSets :: Int -> BCEnv -> TickInfo -> [(Id, Int)]
310 getVarOffSets d p = catMaybes . map (getOffSet d p) . tickInfo_locals 
311
312 getOffSet :: Int -> BCEnv -> Id -> Maybe (Id, Int)
313 getOffSet d env id 
314    = case lookupBCEnv_maybe env id of
315         Nothing     -> Nothing 
316         Just offset -> Just (id, d - offset)
317
318 fvsToEnv :: BCEnv -> VarSet -> [Id]
319 -- Takes the free variables of a right-hand side, and
320 -- delivers an ordered list of the local variables that will
321 -- be captured in the thunk for the RHS
322 -- The BCEnv argument tells which variables are in the local
323 -- environment: these are the ones that should be captured
324 --
325 -- The code that constructs the thunk, and the code that executes
326 -- it, have to agree about this layout
327 fvsToEnv p fvs = [v | v <- varSetElems fvs, 
328                       isId v,           -- Could be a type variable
329                       v `elemFM` p]
330
331 -- -----------------------------------------------------------------------------
332 -- schemeE
333
334 data TickInfo 
335    = TickInfo   
336      { tickInfo_number :: Int     -- the (module) unique number of the tick
337      , tickInfo_module :: Module  -- the origin of the ticked expression 
338      , tickInfo_locals :: [Id]    -- the local vars in scope at the ticked expression
339      } 
340
341 instance Outputable TickInfo where
342    ppr info = text "TickInfo" <+> 
343               parens (int (tickInfo_number info) <+> ppr (tickInfo_module info) <+>
344                       ppr (tickInfo_locals info))
345
346 -- Compile code to apply the given expression to the remaining args
347 -- on the stack, returning a HNF.
348 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList
349
350 -- Delegate tail-calls to schemeT.
351 schemeE d s p e@(AnnApp _ _) 
352    = schemeT d s p e
353
354 schemeE d s p e@(AnnVar v)
355    | not (isUnLiftedType v_type)
356    =  -- Lifted-type thing; push it in the normal way
357      schemeT d s p e
358
359    | otherwise
360    = do -- Returning an unlifted value.  
361         -- Heave it on the stack, SLIDE, and RETURN.
362         (push, szw) <- pushAtom d p (AnnVar v)
363         return (push                    -- value onto stack
364                   `appOL`  mkSLIDE szw (d-s)    -- clear to sequel
365                   `snocOL` RETURN_UBX v_rep)    -- go
366    where
367       v_type = idType v
368       v_rep = typeCgRep v_type
369
370 schemeE d s p (AnnLit literal)
371    = do (push, szw) <- pushAtom d p (AnnLit literal)
372         let l_rep = typeCgRep (literalType literal)
373         return (push                    -- value onto stack
374                `appOL`  mkSLIDE szw (d-s)       -- clear to sequel
375                `snocOL` RETURN_UBX l_rep)       -- go
376
377 schemeE d s p (AnnLet (AnnNonRec x (_,rhs)) (_,body))
378    | (AnnVar v, args_r_to_l) <- splitApp rhs,
379      Just data_con <- isDataConWorkId_maybe v,
380      dataConRepArity data_con == length args_r_to_l
381    = do -- Special case for a non-recursive let whose RHS is a 
382         -- saturatred constructor application.
383         -- Just allocate the constructor and carry on
384         alloc_code <- mkConAppCode d s p data_con args_r_to_l
385         body_code <- schemeE (d+1) s (addToFM p x d) body
386         return (alloc_code `appOL` body_code)
387
388 -- General case for let.  Generates correct, if inefficient, code in
389 -- all situations.
390 schemeE d s p (AnnLet binds (_,body))
391    = let (xs,rhss) = case binds of AnnNonRec x rhs  -> ([x],[rhs])
392                                    AnnRec xs_n_rhss -> unzip xs_n_rhss
393          n_binds = length xs
394
395          fvss  = map (fvsToEnv p' . fst) rhss
396
397          -- Sizes of free vars
398          sizes = map (\rhs_fvs -> sum (map idSizeW rhs_fvs)) fvss
399
400          -- the arity of each rhs
401          arities = map (length . fst . collect []) rhss
402
403          -- This p', d' defn is safe because all the items being pushed
404          -- are ptrs, so all have size 1.  d' and p' reflect the stack
405          -- after the closures have been allocated in the heap (but not
406          -- filled in), and pointers to them parked on the stack.
407          p'    = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n_binds 1)))
408          d'    = d + n_binds
409          zipE  = zipEqual "schemeE"
410
411          -- ToDo: don't build thunks for things with no free variables
412          build_thunk _ [] size bco off arity
413             = return (PUSH_BCO bco `consOL` unitOL (mkap (off+size) size))
414            where 
415                 mkap | arity == 0 = MKAP
416                      | otherwise  = MKPAP
417          build_thunk dd (fv:fvs) size bco off arity = do
418               (push_code, pushed_szw) <- pushAtom dd p' (AnnVar fv) 
419               more_push_code <- build_thunk (dd+pushed_szw) fvs size bco off arity
420               return (push_code `appOL` more_push_code)
421
422          alloc_code = toOL (zipWith mkAlloc sizes arities)
423            where mkAlloc sz 0
424                     | is_tick     = ALLOC_AP_NOUPD sz
425                     | otherwise   = ALLOC_AP sz
426                  mkAlloc sz arity = ALLOC_PAP arity sz
427
428          is_tick = case binds of 
429                      AnnNonRec id _ -> occNameFS (getOccName id) == tickFS
430                      _other -> False
431
432          compile_bind d' fvs x rhs size arity off = do
433                 bco <- schemeR fvs (x,rhs)
434                 build_thunk d' fvs size bco off arity
435
436          compile_binds = 
437             [ compile_bind d' fvs x rhs size arity n
438             | (fvs, x, rhs, size, arity, n) <- 
439                 zip6 fvss xs rhss sizes arities [n_binds, n_binds-1 .. 1]
440             ]
441      in do
442      body_code <- schemeE d' s p' body
443      thunk_codes <- sequence compile_binds
444      return (alloc_code `appOL` concatOL thunk_codes `appOL` body_code)
445
446 -- introduce a let binding for a ticked case expression. This rule
447 -- *should* only fire when the expression was not already let-bound
448 -- (the code gen for let bindings should take care of that).  Todo: we
449 -- call exprFreeVars on a deAnnotated expression, this may not be the
450 -- best way to calculate the free vars but it seemed like the least
451 -- intrusive thing to do
452 schemeE d s p exp@(AnnCase {})
453    | Just (_tickInfo, rhs) <- isTickedExp' exp
454    = if isUnLiftedType ty
455         then schemeE d s p (snd rhs)
456         else do
457           id <- newId ty
458           -- Todo: is emptyVarSet correct on the next line?
459           let letExp = AnnLet (AnnNonRec id (fvs, exp)) (emptyVarSet, AnnVar id)
460           schemeE d s p letExp
461    where exp' = deAnnotate' exp
462          fvs  = exprFreeVars exp'
463          ty   = exprType exp'
464
465 schemeE d s p (AnnCase scrut _ _ [(DataAlt dc, [bind1, bind2], rhs)])
466    | isUnboxedTupleCon dc, VoidArg <- typeCgRep (idType bind1)
467         -- Convert 
468         --      case .... of x { (# VoidArg'd-thing, a #) -> ... }
469         -- to
470         --      case .... of a { DEFAULT -> ... }
471         -- becuse the return convention for both are identical.
472         --
473         -- Note that it does not matter losing the void-rep thing from the
474         -- envt (it won't be bound now) because we never look such things up.
475
476    = --trace "automagic mashing of case alts (# VoidArg, a #)" $
477      doCase d s p scrut bind2 [(DEFAULT, [], rhs)] True{-unboxed tuple-} 
478
479    | isUnboxedTupleCon dc, VoidArg <- typeCgRep (idType bind2)
480    = --trace "automagic mashing of case alts (# a, VoidArg #)" $
481      doCase d s p scrut bind1 [(DEFAULT, [], rhs)] True{-unboxed tuple-} 
482
483 schemeE d s p (AnnCase scrut _ _ [(DataAlt dc, [bind1], rhs)])
484    | isUnboxedTupleCon dc
485         -- Similarly, convert
486         --      case .... of x { (# a #) -> ... }
487         -- to
488         --      case .... of a { DEFAULT -> ... }
489    = --trace "automagic mashing of case alts (# a #)"  $
490      doCase d s p scrut bind1 [(DEFAULT, [], rhs)] True{-unboxed tuple-} 
491
492 schemeE d s p (AnnCase scrut bndr _ alts)
493    = doCase d s p scrut bndr alts False{-not an unboxed tuple-} 
494
495 schemeE d s p (AnnNote _ (_, body))
496    = schemeE d s p body
497
498 schemeE d s p (AnnCast (_, body) _)
499    = schemeE d s p body
500
501 schemeE _ _ _ expr
502    = pprPanic "ByteCodeGen.schemeE: unhandled case" 
503                (pprCoreExpr (deAnnotate' expr))
504
505 {- 
506    Ticked Expressions
507    ------------------
508   
509    A ticked expression looks like this:
510
511       case tick<n> var1 ... varN of DEFAULT -> e
512
513    (*) <n> is the number of the tick, which is unique within a module
514    (*) var1 ... varN are the local variables in scope at the tick site
515
516    If we find a ticked expression we return:
517
518       Just ((n, [var1 ... varN]), e)
519
520   otherwise we return Nothing.
521
522   The idea is that the "case tick<n> ..." is really just an annotation on 
523   the code. When we find such a thing, we pull out the useful information,
524   and then compile the code as if it was just the expression "e".
525
526 -}
527
528 isTickedExp' :: AnnExpr' Id a -> Maybe (TickInfo, AnnExpr Id a)
529 isTickedExp' (AnnCase scrut _bndr _type alts)
530    | Just tickInfo <- isTickedScrut scrut,
531      [(DEFAULT, _bndr, rhs)] <- alts 
532      = Just (tickInfo, rhs)
533    where
534    isTickedScrut :: (AnnExpr Id a) -> Maybe TickInfo 
535    isTickedScrut expr
536       | Var id <- f,
537         Just (TickBox modName tickNumber) <- isTickBoxOp_maybe id
538            = Just $ TickInfo { tickInfo_number = tickNumber
539                              , tickInfo_module = modName
540                              , tickInfo_locals = idsOfArgs args
541                              }
542       | otherwise = Nothing
543       where
544       (f, args) = collectArgs $ deAnnotate expr
545       idsOfArgs :: [Expr Id] -> [Id]
546       idsOfArgs = catMaybes . map exprId 
547       exprId :: Expr Id -> Maybe Id
548       exprId (Var id) = Just id
549       exprId _        = Nothing
550
551 isTickedExp' _ = Nothing
552
553 -- Compile code to do a tail call.  Specifically, push the fn,
554 -- slide the on-stack app back down to the sequel depth,
555 -- and enter.  Four cases:
556 --
557 -- 0.  (Nasty hack).
558 --     An application "GHC.Prim.tagToEnum# <type> unboxed-int".
559 --     The int will be on the stack.  Generate a code sequence
560 --     to convert it to the relevant constructor, SLIDE and ENTER.
561 --
562 -- 1.  The fn denotes a ccall.  Defer to generateCCall.
563 --
564 -- 2.  (Another nasty hack).  Spot (# a::VoidArg, b #) and treat
565 --     it simply as  b  -- since the representations are identical
566 --     (the VoidArg takes up zero stack space).  Also, spot
567 --     (# b #) and treat it as  b.
568 --
569 -- 3.  Application of a constructor, by defn saturated.
570 --     Split the args into ptrs and non-ptrs, and push the nonptrs, 
571 --     then the ptrs, and then do PACK and RETURN.
572 --
573 -- 4.  Otherwise, it must be a function call.  Push the args
574 --     right to left, SLIDE and ENTER.
575
576 schemeT :: Int          -- Stack depth
577         -> Sequel       -- Sequel depth
578         -> BCEnv        -- stack env
579         -> AnnExpr' Id VarSet 
580         -> BcM BCInstrList
581
582 schemeT d s p app
583
584 --   | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
585 --   = panic "schemeT ?!?!"
586
587 --   | trace ("\nschemeT\n" ++ showSDoc (pprCoreExpr (deAnnotate' app)) ++ "\n") False
588 --   = error "?!?!" 
589
590    -- Case 0
591    | Just (arg, constr_names) <- maybe_is_tagToEnum_call
592    = do (push, arg_words) <- pushAtom d p arg
593         tagToId_sequence <- implement_tagToId constr_names
594         return (push `appOL`  tagToId_sequence            
595                        `appOL`  mkSLIDE 1 (d+arg_words-s)
596                        `snocOL` ENTER)
597
598    -- Case 1
599    | Just (CCall ccall_spec) <- isFCallId_maybe fn
600    = generateCCall d s p ccall_spec fn args_r_to_l
601
602    -- Case 2: Constructor application
603    | Just con <- maybe_saturated_dcon,
604      isUnboxedTupleCon con
605    = case args_r_to_l of
606         [arg1,arg2] | isVoidArgAtom arg1 -> 
607                   unboxedTupleReturn d s p arg2
608         [arg1,arg2] | isVoidArgAtom arg2 -> 
609                   unboxedTupleReturn d s p arg1
610         _other -> unboxedTupleException
611
612    -- Case 3: Ordinary data constructor
613    | Just con <- maybe_saturated_dcon
614    = do alloc_con <- mkConAppCode d s p con args_r_to_l
615         return (alloc_con        `appOL` 
616                   mkSLIDE 1 (d - s) `snocOL`
617                   ENTER)
618
619    -- Case 4: Tail call of function 
620    | otherwise
621    = doTailCall d s p fn args_r_to_l
622
623    where
624       -- Detect and extract relevant info for the tagToEnum kludge.
625       maybe_is_tagToEnum_call
626          = let extract_constr_Names ty
627                  | Just (tyc, []) <- splitTyConApp_maybe (repType ty),
628                    isDataTyCon tyc
629                    = map (getName . dataConWorkId) (tyConDataCons tyc)
630                    -- NOTE: use the worker name, not the source name of
631                    -- the DataCon.  See DataCon.lhs for details.
632                  | otherwise
633                    = panic "maybe_is_tagToEnum_call.extract_constr_Ids"
634            in
635            case app of
636               (AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg)
637                  -> case isPrimOpId_maybe v of
638                        Just TagToEnumOp -> Just (snd arg, extract_constr_Names t)
639                        _                -> Nothing
640               _ -> Nothing
641
642         -- Extract the args (R->L) and fn
643         -- The function will necessarily be a variable, 
644         -- because we are compiling a tail call
645       (AnnVar fn, args_r_to_l) = splitApp app
646
647       -- Only consider this to be a constructor application iff it is
648       -- saturated.  Otherwise, we'll call the constructor wrapper.
649       n_args = length args_r_to_l
650       maybe_saturated_dcon  
651         = case isDataConWorkId_maybe fn of
652                 Just con | dataConRepArity con == n_args -> Just con
653                 _ -> Nothing
654
655 -- -----------------------------------------------------------------------------
656 -- Generate code to build a constructor application, 
657 -- leaving it on top of the stack
658
659 mkConAppCode :: Int -> Sequel -> BCEnv
660              -> DataCon                 -- The data constructor
661              -> [AnnExpr' Id VarSet]    -- Args, in *reverse* order
662              -> BcM BCInstrList
663
664 mkConAppCode _ _ _ con []       -- Nullary constructor
665   = ASSERT( isNullaryRepDataCon con )
666     return (unitOL (PUSH_G (getName (dataConWorkId con))))
667         -- Instead of doing a PACK, which would allocate a fresh
668         -- copy of this constructor, use the single shared version.
669
670 mkConAppCode orig_d _ p con args_r_to_l 
671   = ASSERT( dataConRepArity con == length args_r_to_l )
672     do_pushery orig_d (non_ptr_args ++ ptr_args)
673  where
674         -- The args are already in reverse order, which is the way PACK
675         -- expects them to be.  We must push the non-ptrs after the ptrs.
676       (ptr_args, non_ptr_args) = partition isPtrAtom args_r_to_l
677
678       do_pushery d (arg:args)
679          = do (push, arg_words) <- pushAtom d p arg
680               more_push_code <- do_pushery (d+arg_words) args
681               return (push `appOL` more_push_code)
682       do_pushery d []
683          = return (unitOL (PACK con n_arg_words))
684          where
685            n_arg_words = d - orig_d
686
687
688 -- -----------------------------------------------------------------------------
689 -- Returning an unboxed tuple with one non-void component (the only
690 -- case we can handle).
691 --
692 -- Remember, we don't want to *evaluate* the component that is being
693 -- returned, even if it is a pointed type.  We always just return.
694
695 unboxedTupleReturn
696         :: Int -> Sequel -> BCEnv
697         -> AnnExpr' Id VarSet -> BcM BCInstrList
698 unboxedTupleReturn d s p arg = do
699   (push, sz) <- pushAtom d p arg
700   return (push `appOL`
701             mkSLIDE sz (d-s) `snocOL`
702             RETURN_UBX (atomRep arg))
703
704 -- -----------------------------------------------------------------------------
705 -- Generate code for a tail-call
706
707 doTailCall
708         :: Int -> Sequel -> BCEnv
709         -> Id -> [AnnExpr' Id VarSet]
710         -> BcM BCInstrList
711 doTailCall init_d s p fn args
712   = do_pushes init_d args (map atomRep args)
713   where
714   do_pushes d [] reps = do
715         ASSERT( null reps ) return ()
716         (push_fn, sz) <- pushAtom d p (AnnVar fn)
717         ASSERT( sz == 1 ) return ()
718         return (push_fn `appOL` (
719                   mkSLIDE ((d-init_d) + 1) (init_d - s) `appOL`
720                   unitOL ENTER))
721   do_pushes d args reps = do
722       let (push_apply, n, rest_of_reps) = findPushSeq reps
723           (these_args, rest_of_args) = splitAt n args
724       (next_d, push_code) <- push_seq d these_args
725       instrs <- do_pushes (next_d + 1) rest_of_args rest_of_reps 
726                 --                ^^^ for the PUSH_APPLY_ instruction
727       return (push_code `appOL` (push_apply `consOL` instrs))
728
729   push_seq d [] = return (d, nilOL)
730   push_seq d (arg:args) = do
731     (push_code, sz) <- pushAtom d p arg 
732     (final_d, more_push_code) <- push_seq (d+sz) args
733     return (final_d, push_code `appOL` more_push_code)
734
735 -- v. similar to CgStackery.findMatch, ToDo: merge
736 findPushSeq :: [CgRep] -> (BCInstr, Int, [CgRep])
737 findPushSeq (PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: rest)
738   = (PUSH_APPLY_PPPPPP, 6, rest)
739 findPushSeq (PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: rest)
740   = (PUSH_APPLY_PPPPP, 5, rest)
741 findPushSeq (PtrArg: PtrArg: PtrArg: PtrArg: rest)
742   = (PUSH_APPLY_PPPP, 4, rest)
743 findPushSeq (PtrArg: PtrArg: PtrArg: rest)
744   = (PUSH_APPLY_PPP, 3, rest)
745 findPushSeq (PtrArg: PtrArg: rest)
746   = (PUSH_APPLY_PP, 2, rest)
747 findPushSeq (PtrArg: rest)
748   = (PUSH_APPLY_P, 1, rest)
749 findPushSeq (VoidArg: rest)
750   = (PUSH_APPLY_V, 1, rest)
751 findPushSeq (NonPtrArg: rest)
752   = (PUSH_APPLY_N, 1, rest)
753 findPushSeq (FloatArg: rest)
754   = (PUSH_APPLY_F, 1, rest)
755 findPushSeq (DoubleArg: rest)
756   = (PUSH_APPLY_D, 1, rest)
757 findPushSeq (LongArg: rest)
758   = (PUSH_APPLY_L, 1, rest)
759 findPushSeq _
760   = panic "ByteCodeGen.findPushSeq"
761
762 -- -----------------------------------------------------------------------------
763 -- Case expressions
764
765 doCase  :: Int -> Sequel -> BCEnv
766         -> AnnExpr Id VarSet -> Id -> [AnnAlt Id VarSet]
767         -> Bool  -- True <=> is an unboxed tuple case, don't enter the result
768         -> BcM BCInstrList
769 doCase d s p (_,scrut) bndr alts is_unboxed_tuple 
770   = let
771         -- Top of stack is the return itbl, as usual.
772         -- underneath it is the pointer to the alt_code BCO.
773         -- When an alt is entered, it assumes the returned value is
774         -- on top of the itbl.
775         ret_frame_sizeW = 2
776
777         -- An unlifted value gets an extra info table pushed on top
778         -- when it is returned.
779         unlifted_itbl_sizeW | isAlgCase = 0
780                             | otherwise = 1
781
782         -- depth of stack after the return value has been pushed
783         d_bndr = d + ret_frame_sizeW + idSizeW bndr
784
785         -- depth of stack after the extra info table for an unboxed return
786         -- has been pushed, if any.  This is the stack depth at the
787         -- continuation.
788         d_alts = d_bndr + unlifted_itbl_sizeW
789
790         -- Env in which to compile the alts, not including
791         -- any vars bound by the alts themselves
792         p_alts = addToFM p bndr (d_bndr - 1)
793
794         bndr_ty = idType bndr
795         isAlgCase = not (isUnLiftedType bndr_ty) && not is_unboxed_tuple
796
797         -- given an alt, return a discr and code for it.
798         codeAlt (DEFAULT, _, (_,rhs))
799            = do rhs_code <- schemeE d_alts s p_alts rhs
800                 return (NoDiscr, rhs_code)
801
802         codeAlt alt@(_, bndrs, (_,rhs))
803            -- primitive or nullary constructor alt: no need to UNPACK
804            | null real_bndrs = do
805                 rhs_code <- schemeE d_alts s p_alts rhs
806                 return (my_discr alt, rhs_code)
807            -- algebraic alt with some binders
808            | otherwise =
809              let
810                  (ptrs,nptrs) = partition (isFollowableArg.idCgRep) real_bndrs
811                  ptr_sizes    = map idSizeW ptrs
812                  nptrs_sizes  = map idSizeW nptrs
813                  bind_sizes   = ptr_sizes ++ nptrs_sizes
814                  size         = sum ptr_sizes + sum nptrs_sizes
815                  -- the UNPACK instruction unpacks in reverse order...
816                  p' = addListToFM p_alts 
817                         (zip (reverse (ptrs ++ nptrs))
818                           (mkStackOffsets d_alts (reverse bind_sizes)))
819              in do
820              MASSERT(isAlgCase)
821              rhs_code <- schemeE (d_alts+size) s p' rhs
822              return (my_discr alt, unitOL (UNPACK size) `appOL` rhs_code)
823            where
824              real_bndrs = filter (not.isTyVar) bndrs
825
826         my_discr (DEFAULT, _, _) = NoDiscr {-shouldn't really happen-}
827         my_discr (DataAlt dc, _, _) 
828            | isUnboxedTupleCon dc
829            = unboxedTupleException
830            | otherwise
831            = DiscrP (dataConTag dc - fIRST_TAG)
832         my_discr (LitAlt l, _, _)
833            = case l of MachInt i     -> DiscrI (fromInteger i)
834                        MachFloat r   -> DiscrF (fromRational r)
835                        MachDouble r  -> DiscrD (fromRational r)
836                        MachChar i    -> DiscrI (ord i)
837                        _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
838
839         maybe_ncons 
840            | not isAlgCase = Nothing
841            | otherwise 
842            = case [dc | (DataAlt dc, _, _) <- alts] of
843                 []     -> Nothing
844                 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
845
846         -- the bitmap is relative to stack depth d, i.e. before the
847         -- BCO, info table and return value are pushed on.
848         -- This bit of code is v. similar to buildLivenessMask in CgBindery,
849         -- except that here we build the bitmap from the known bindings of
850         -- things that are pointers, whereas in CgBindery the code builds the
851         -- bitmap from the free slots and unboxed bindings.
852         -- (ToDo: merge?)
853         --
854         -- NOTE [7/12/2006] bug #1013, testcase ghci/should_run/ghci002.
855         -- The bitmap must cover the portion of the stack up to the sequel only.
856         -- Previously we were building a bitmap for the whole depth (d), but we
857         -- really want a bitmap up to depth (d-s).  This affects compilation of
858         -- case-of-case expressions, which is the only time we can be compiling a
859         -- case expression with s /= 0.
860         bitmap_size = d-s
861         bitmap = intsToReverseBitmap bitmap_size{-size-} 
862                         (sortLe (<=) (filter (< bitmap_size) rel_slots))
863           where
864           binds = fmToList p
865           rel_slots = concat (map spread binds)
866           spread (id, offset)
867                 | isFollowableArg (idCgRep id) = [ rel_offset ]
868                 | otherwise = []
869                 where rel_offset = d - offset - 1
870
871      in do
872      alt_stuff <- mapM codeAlt alts
873      alt_final <- mkMultiBranch maybe_ncons alt_stuff
874
875      let 
876          alt_bco_name = getName bndr
877          alt_bco = mkProtoBCO alt_bco_name alt_final (Left alts)
878                         0{-no arity-} bitmap_size bitmap True{-is alts-}
879      -- in
880 --     trace ("case: bndr = " ++ showSDocDebug (ppr bndr) ++ "\ndepth = " ++ show d ++ "\nenv = \n" ++ showSDocDebug (ppBCEnv p) ++
881 --           "\n      bitmap = " ++ show bitmap) $ do
882      scrut_code <- schemeE (d + ret_frame_sizeW) (d + ret_frame_sizeW) p scrut
883      alt_bco' <- emitBc alt_bco
884      let push_alts
885             | isAlgCase = PUSH_ALTS alt_bco'
886             | otherwise = PUSH_ALTS_UNLIFTED alt_bco' (typeCgRep bndr_ty)
887      return (push_alts `consOL` scrut_code)
888
889
890 -- -----------------------------------------------------------------------------
891 -- Deal with a CCall.
892
893 -- Taggedly push the args onto the stack R->L,
894 -- deferencing ForeignObj#s and adjusting addrs to point to
895 -- payloads in Ptr/Byte arrays.  Then, generate the marshalling
896 -- (machine) code for the ccall, and create bytecodes to call that and
897 -- then return in the right way.  
898
899 generateCCall :: Int -> Sequel          -- stack and sequel depths
900               -> BCEnv
901               -> CCallSpec              -- where to call
902               -> Id                     -- of target, for type info
903               -> [AnnExpr' Id VarSet]   -- args (atoms)
904               -> BcM BCInstrList
905
906 generateCCall d0 s p (CCallSpec target cconv _) fn args_r_to_l
907    = let 
908          -- useful constants
909          addr_sizeW = cgRepSizeW NonPtrArg
910
911          -- Get the args on the stack, with tags and suitably
912          -- dereferenced for the CCall.  For each arg, return the
913          -- depth to the first word of the bits for that arg, and the
914          -- CgRep of what was actually pushed.
915
916          pargs _ [] = return []
917          pargs d (a:az) 
918             = let arg_ty = repType (exprType (deAnnotate' a))
919
920               in case splitTyConApp_maybe arg_ty of
921                     -- Don't push the FO; instead push the Addr# it
922                     -- contains.
923                     Just (t, _)
924                      | t == arrayPrimTyCon || t == mutableArrayPrimTyCon
925                        -> do rest <- pargs (d + addr_sizeW) az
926                              code <- parg_ArrayishRep arrPtrsHdrSize d p a
927                              return ((code,AddrRep):rest)
928
929                      | t == byteArrayPrimTyCon || t == mutableByteArrayPrimTyCon
930                        -> do rest <- pargs (d + addr_sizeW) az
931                              code <- parg_ArrayishRep arrWordsHdrSize d p a
932                              return ((code,AddrRep):rest)
933
934                     -- Default case: push taggedly, but otherwise intact.
935                     _
936                        -> do (code_a, sz_a) <- pushAtom d p a
937                              rest <- pargs (d+sz_a) az
938                              return ((code_a, atomPrimRep a) : rest)
939
940          -- Do magic for Ptr/Byte arrays.  Push a ptr to the array on
941          -- the stack but then advance it over the headers, so as to
942          -- point to the payload.
943          parg_ArrayishRep hdrSize d p a
944             = do (push_fo, _) <- pushAtom d p a
945                  -- The ptr points at the header.  Advance it over the
946                  -- header and then pretend this is an Addr#.
947                  return (push_fo `snocOL` SWIZZLE 0 hdrSize)
948
949      in do
950      code_n_reps <- pargs d0 args_r_to_l
951      let
952          (pushs_arg, a_reps_pushed_r_to_l) = unzip code_n_reps
953
954          push_args    = concatOL pushs_arg
955          d_after_args = d0 + sum (map primRepSizeW a_reps_pushed_r_to_l)
956          a_reps_pushed_RAW
957             | null a_reps_pushed_r_to_l || head a_reps_pushed_r_to_l /= VoidRep
958             = panic "ByteCodeGen.generateCCall: missing or invalid World token?"
959             | otherwise
960             = reverse (tail a_reps_pushed_r_to_l)
961
962          -- Now: a_reps_pushed_RAW are the reps which are actually on the stack.
963          -- push_args is the code to do that.
964          -- d_after_args is the stack depth once the args are on.
965
966          -- Get the result rep.
967          (returns_void, r_rep)
968             = case maybe_getCCallReturnRep (idType fn) of
969                  Nothing -> (True,  VoidRep)
970                  Just rr -> (False, rr) 
971          {-
972          Because the Haskell stack grows down, the a_reps refer to 
973          lowest to highest addresses in that order.  The args for the call
974          are on the stack.  Now push an unboxed Addr# indicating
975          the C function to call.  Then push a dummy placeholder for the 
976          result.  Finally, emit a CCALL insn with an offset pointing to the 
977          Addr# just pushed, and a literal field holding the mallocville
978          address of the piece of marshalling code we generate.
979          So, just prior to the CCALL insn, the stack looks like this 
980          (growing down, as usual):
981                  
982             <arg_n>
983             ...
984             <arg_1>
985             Addr# address_of_C_fn
986             <placeholder-for-result#> (must be an unboxed type)
987
988          The interpreter then calls the marshall code mentioned
989          in the CCALL insn, passing it (& <placeholder-for-result#>), 
990          that is, the addr of the topmost word in the stack.
991          When this returns, the placeholder will have been
992          filled in.  The placeholder is slid down to the sequel
993          depth, and we RETURN.
994
995          This arrangement makes it simple to do f-i-dynamic since the Addr#
996          value is the first arg anyway.
997
998          The marshalling code is generated specifically for this
999          call site, and so knows exactly the (Haskell) stack
1000          offsets of the args, fn address and placeholder.  It
1001          copies the args to the C stack, calls the stacked addr,
1002          and parks the result back in the placeholder.  The interpreter
1003          calls it as a normal C call, assuming it has a signature
1004             void marshall_code ( StgWord* ptr_to_top_of_stack )
1005          -}
1006          -- resolve static address
1007          get_target_info
1008             = case target of
1009                  DynamicTarget
1010                     -> return (False, panic "ByteCodeGen.generateCCall(dyn)")
1011                  StaticTarget target
1012                     -> do res <- ioToBc (lookupStaticPtr target)
1013                           return (True, res)
1014      -- in
1015      (is_static, static_target_addr) <- get_target_info
1016      let
1017
1018          -- Get the arg reps, zapping the leading Addr# in the dynamic case
1019          a_reps --  | trace (showSDoc (ppr a_reps_pushed_RAW)) False = error "???"
1020                 | is_static = a_reps_pushed_RAW
1021                 | otherwise = if null a_reps_pushed_RAW 
1022                               then panic "ByteCodeGen.generateCCall: dyn with no args"
1023                               else tail a_reps_pushed_RAW
1024
1025          -- push the Addr#
1026          (push_Addr, d_after_Addr)
1027             | is_static
1028             = (toOL [PUSH_UBX (Right static_target_addr) addr_sizeW],
1029                d_after_args + addr_sizeW)
1030             | otherwise -- is already on the stack
1031             = (nilOL, d_after_args)
1032
1033          -- Push the return placeholder.  For a call returning nothing,
1034          -- this is a VoidArg (tag).
1035          r_sizeW   = primRepSizeW r_rep
1036          d_after_r = d_after_Addr + r_sizeW
1037          r_lit     = mkDummyLiteral r_rep
1038          push_r    = (if   returns_void 
1039                       then nilOL 
1040                       else unitOL (PUSH_UBX (Left r_lit) r_sizeW))
1041
1042          -- generate the marshalling code we're going to call
1043
1044          -- Offset of the next stack frame down the stack.  The CCALL
1045          -- instruction needs to describe the chunk of stack containing
1046          -- the ccall args to the GC, so it needs to know how large it
1047          -- is.  See comment in Interpreter.c with the CCALL instruction.
1048          stk_offset   = d_after_r - s
1049
1050      -- in
1051      -- the only difference in libffi mode is that we prepare a cif
1052      -- describing the call type by calling libffi, and we attach the
1053      -- address of this to the CCALL instruction.
1054      token <- ioToBc $ prepForeignCall cconv a_reps r_rep
1055      let addr_of_marshaller = castPtrToFunPtr token
1056
1057      recordItblMallocBc (ItblPtr (castFunPtrToPtr addr_of_marshaller))
1058      let
1059          -- do the call
1060          do_call      = unitOL (CCALL stk_offset (castFunPtrToPtr addr_of_marshaller))
1061          -- slide and return
1062          wrapup       = mkSLIDE r_sizeW (d_after_r - r_sizeW - s)
1063                         `snocOL` RETURN_UBX (primRepToCgRep r_rep)
1064      --in
1065          --trace (show (arg1_offW, args_offW  ,  (map cgRepSizeW a_reps) )) $
1066      return (
1067          push_args `appOL`
1068          push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup
1069          )
1070
1071 -- Make a dummy literal, to be used as a placeholder for FFI return
1072 -- values on the stack.
1073 mkDummyLiteral :: PrimRep -> Literal
1074 mkDummyLiteral pr
1075    = case pr of
1076         IntRep    -> MachInt 0
1077         WordRep   -> MachWord 0
1078         AddrRep   -> MachNullAddr
1079         DoubleRep -> MachDouble 0
1080         FloatRep  -> MachFloat 0
1081         Int64Rep  -> MachInt64 0
1082         Word64Rep -> MachWord64 0
1083         _         -> panic "mkDummyLiteral"
1084
1085
1086 -- Convert (eg) 
1087 --     GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld
1088 --                   -> (# GHC.Prim.State# GHC.Prim.RealWorld, GHC.Prim.Int# #)
1089 --
1090 -- to  Just IntRep
1091 -- and check that an unboxed pair is returned wherein the first arg is VoidArg'd.
1092 --
1093 -- Alternatively, for call-targets returning nothing, convert
1094 --
1095 --     GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld
1096 --                   -> (# GHC.Prim.State# GHC.Prim.RealWorld #)
1097 --
1098 -- to  Nothing
1099
1100 maybe_getCCallReturnRep :: Type -> Maybe PrimRep
1101 maybe_getCCallReturnRep fn_ty
1102    = let (_a_tys, r_ty) = splitFunTys (dropForAlls fn_ty)
1103          maybe_r_rep_to_go  
1104             = if isSingleton r_reps then Nothing else Just (r_reps !! 1)
1105          (r_tycon, r_reps) 
1106             = case splitTyConApp_maybe (repType r_ty) of
1107                       (Just (tyc, tys)) -> (tyc, map typePrimRep tys)
1108                       Nothing -> blargh
1109          ok = ( ( r_reps `lengthIs` 2 && VoidRep == head r_reps)
1110                 || r_reps == [VoidRep] )
1111               && isUnboxedTupleTyCon r_tycon
1112               && case maybe_r_rep_to_go of
1113                     Nothing    -> True
1114                     Just r_rep -> r_rep /= PtrRep
1115                                   -- if it was, it would be impossible 
1116                                   -- to create a valid return value 
1117                                   -- placeholder on the stack
1118          blargh = pprPanic "maybe_getCCallReturn: can't handle:" 
1119                            (pprType fn_ty)
1120      in 
1121      --trace (showSDoc (ppr (a_reps, r_reps))) $
1122      if ok then maybe_r_rep_to_go else blargh
1123
1124 -- Compile code which expects an unboxed Int on the top of stack,
1125 -- (call it i), and pushes the i'th closure in the supplied list 
1126 -- as a consequence.
1127 implement_tagToId :: [Name] -> BcM BCInstrList
1128 implement_tagToId names
1129    = ASSERT( notNull names )
1130      do labels <- getLabelsBc (length names)
1131         label_fail <- getLabelBc
1132         label_exit <- getLabelBc
1133         let infos = zip4 labels (tail labels ++ [label_fail])
1134                                 [0 ..] names
1135             steps = map (mkStep label_exit) infos
1136         return (concatOL steps
1137                   `appOL` 
1138                   toOL [LABEL label_fail, CASEFAIL, LABEL label_exit])
1139      where
1140         mkStep l_exit (my_label, next_label, n, name_for_n)
1141            = toOL [LABEL my_label, 
1142                    TESTEQ_I n next_label, 
1143                    PUSH_G name_for_n, 
1144                    JMP l_exit]
1145
1146
1147 -- -----------------------------------------------------------------------------
1148 -- pushAtom
1149
1150 -- Push an atom onto the stack, returning suitable code & number of
1151 -- stack words used.
1152 --
1153 -- The env p must map each variable to the highest- numbered stack
1154 -- slot for it.  For example, if the stack has depth 4 and we
1155 -- tagged-ly push (v :: Int#) on it, the value will be in stack[4],
1156 -- the tag in stack[5], the stack will have depth 6, and p must map v
1157 -- to 5 and not to 4.  Stack locations are numbered from zero, so a
1158 -- depth 6 stack has valid words 0 .. 5.
1159
1160 pushAtom :: Int -> BCEnv -> AnnExpr' Id VarSet -> BcM (BCInstrList, Int)
1161
1162 pushAtom d p (AnnApp f (_, AnnType _))
1163    = pushAtom d p (snd f)
1164
1165 pushAtom d p (AnnNote _ e)
1166    = pushAtom d p (snd e)
1167
1168 pushAtom d p (AnnLam x e) 
1169    | isTyVar x 
1170    = pushAtom d p (snd e)
1171
1172 pushAtom d p (AnnVar v)
1173
1174    | idCgRep v == VoidArg
1175    = return (nilOL, 0)
1176
1177    | isFCallId v
1178    = pprPanic "pushAtom: shouldn't get an FCallId here" (ppr v)
1179
1180    | Just primop <- isPrimOpId_maybe v
1181    = return (unitOL (PUSH_PRIMOP primop), 1)
1182
1183    | Just d_v <- lookupBCEnv_maybe p v  -- v is a local variable
1184    = return (toOL (nOfThem sz (PUSH_L (d-d_v+sz-2))), sz)
1185          -- d - d_v                 the number of words between the TOS 
1186          --                         and the 1st slot of the object
1187          --
1188          -- d - d_v - 1             the offset from the TOS of the 1st slot
1189          --
1190          -- d - d_v - 1 + sz - 1    the offset from the TOS of the last slot
1191          --                         of the object.
1192          --
1193          -- Having found the last slot, we proceed to copy the right number of
1194          -- slots on to the top of the stack.
1195
1196     | otherwise  -- v must be a global variable
1197     = ASSERT(sz == 1) 
1198       return (unitOL (PUSH_G (getName v)), sz)
1199
1200     where
1201          sz = idSizeW v
1202
1203
1204 pushAtom _ _ (AnnLit lit)
1205    = case lit of
1206         MachLabel _ _ -> code NonPtrArg
1207         MachWord _    -> code NonPtrArg
1208         MachInt _     -> code PtrArg
1209         MachFloat _   -> code FloatArg
1210         MachDouble _  -> code DoubleArg
1211         MachChar _    -> code NonPtrArg
1212         MachStr s     -> pushStr s
1213         l             -> pprPanic "pushAtom" (ppr l)
1214      where
1215         code rep
1216            = let size_host_words = cgRepSizeW rep
1217              in  return (unitOL (PUSH_UBX (Left lit) size_host_words), 
1218                            size_host_words)
1219
1220         pushStr s 
1221            = let getMallocvilleAddr
1222                     = case s of
1223                          FastString _ n _ fp _ -> 
1224                             -- we could grab the Ptr from the ForeignPtr,
1225                             -- but then we have no way to control its lifetime.
1226                             -- In reality it'll probably stay alive long enoungh
1227                             -- by virtue of the global FastString table, but
1228                             -- to be on the safe side we copy the string into
1229                             -- a malloc'd area of memory.
1230                                 do ptr <- ioToBc (mallocBytes (n+1))
1231                                    recordMallocBc ptr
1232                                    ioToBc (
1233                                       withForeignPtr fp $ \p -> do
1234                                          memcpy ptr p (fromIntegral n)
1235                                          pokeByteOff ptr n (fromIntegral (ord '\0') :: Word8)
1236                                          return ptr
1237                                       )
1238              in do
1239                 addr <- getMallocvilleAddr
1240                 -- Get the addr on the stack, untaggedly
1241                 return (unitOL (PUSH_UBX (Right addr) 1), 1)
1242
1243 pushAtom d p (AnnCast e _)
1244    = pushAtom d p (snd e)
1245
1246 pushAtom _ _ expr
1247    = pprPanic "ByteCodeGen.pushAtom" 
1248               (pprCoreExpr (deAnnotate (undefined, expr)))
1249
1250 foreign import ccall unsafe "memcpy"
1251  memcpy :: Ptr a -> Ptr b -> CSize -> IO ()
1252
1253
1254 -- -----------------------------------------------------------------------------
1255 -- Given a bunch of alts code and their discrs, do the donkey work
1256 -- of making a multiway branch using a switch tree.
1257 -- What a load of hassle!
1258
1259 mkMultiBranch :: Maybe Int      --  # datacons in tycon, if alg alt
1260                                 -- a hint; generates better code
1261                                 -- Nothing is always safe
1262               -> [(Discr, BCInstrList)] 
1263               -> BcM BCInstrList
1264 mkMultiBranch maybe_ncons raw_ways
1265    = let d_way     = filter (isNoDiscr.fst) raw_ways
1266          notd_ways = sortLe 
1267                         (\w1 w2 -> leAlt (fst w1) (fst w2))
1268                         (filter (not.isNoDiscr.fst) raw_ways)
1269
1270          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
1271          mkTree [] _range_lo _range_hi = return the_default
1272
1273          mkTree [val] range_lo range_hi
1274             | range_lo `eqAlt` range_hi 
1275             = return (snd val)
1276             | otherwise
1277             = do label_neq <- getLabelBc
1278                  return (mkTestEQ (fst val) label_neq 
1279                           `consOL` (snd val
1280                           `appOL`   unitOL (LABEL label_neq)
1281                           `appOL`   the_default))
1282
1283          mkTree vals range_lo range_hi
1284             = let n = length vals `div` 2
1285                   vals_lo = take n vals
1286                   vals_hi = drop n vals
1287                   v_mid = fst (head vals_hi)
1288               in do
1289               label_geq <- getLabelBc
1290               code_lo <- mkTree vals_lo range_lo (dec v_mid)
1291               code_hi <- mkTree vals_hi v_mid range_hi
1292               return (mkTestLT v_mid label_geq
1293                         `consOL` (code_lo
1294                         `appOL`   unitOL (LABEL label_geq)
1295                         `appOL`   code_hi))
1296  
1297          the_default 
1298             = case d_way of [] -> unitOL CASEFAIL
1299                             [(_, def)] -> def
1300                             _ -> panic "mkMultiBranch/the_default"
1301
1302          -- None of these will be needed if there are no non-default alts
1303          (mkTestLT, mkTestEQ, init_lo, init_hi)
1304             | null notd_ways
1305             = panic "mkMultiBranch: awesome foursome"
1306             | otherwise
1307             = case fst (head notd_ways) of {
1308               DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
1309                             \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
1310                             DiscrI minBound,
1311                             DiscrI maxBound );
1312               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
1313                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
1314                             DiscrF minF,
1315                             DiscrF maxF );
1316               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
1317                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
1318                             DiscrD minD,
1319                             DiscrD maxD );
1320               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
1321                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
1322                             DiscrP algMinBound,
1323                             DiscrP algMaxBound );
1324               NoDiscr -> panic "mkMultiBranch NoDiscr"
1325               }
1326
1327          (algMinBound, algMaxBound)
1328             = case maybe_ncons of
1329                  Just n  -> (0, n - 1)
1330                  Nothing -> (minBound, maxBound)
1331
1332          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
1333          (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
1334          (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
1335          (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
1336          NoDiscr     `eqAlt` NoDiscr     = True
1337          _           `eqAlt` _           = False
1338
1339          (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
1340          (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
1341          (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
1342          (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
1343          NoDiscr     `leAlt` NoDiscr     = True
1344          _           `leAlt` _           = False
1345
1346          isNoDiscr NoDiscr = True
1347          isNoDiscr _       = False
1348
1349          dec (DiscrI i) = DiscrI (i-1)
1350          dec (DiscrP i) = DiscrP (i-1)
1351          dec other      = other         -- not really right, but if you
1352                 -- do cases on floating values, you'll get what you deserve
1353
1354          -- same snotty comment applies to the following
1355          minF, maxF :: Float
1356          minD, maxD :: Double
1357          minF = -1.0e37
1358          maxF =  1.0e37
1359          minD = -1.0e308
1360          maxD =  1.0e308
1361      in
1362          mkTree notd_ways init_lo init_hi
1363
1364
1365 -- -----------------------------------------------------------------------------
1366 -- Supporting junk for the compilation schemes
1367
1368 -- Describes case alts
1369 data Discr 
1370    = DiscrI Int
1371    | DiscrF Float
1372    | DiscrD Double
1373    | DiscrP Int
1374    | NoDiscr
1375
1376 instance Outputable Discr where
1377    ppr (DiscrI i) = int i
1378    ppr (DiscrF f) = text (show f)
1379    ppr (DiscrD d) = text (show d)
1380    ppr (DiscrP i) = int i
1381    ppr NoDiscr    = text "DEF"
1382
1383
1384 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
1385 lookupBCEnv_maybe = lookupFM
1386
1387 idSizeW :: Id -> Int
1388 idSizeW id = cgRepSizeW (typeCgRep (idType id))
1389
1390 -- See bug #1257
1391 unboxedTupleException :: a
1392 unboxedTupleException 
1393    = throwDyn 
1394         (ProgramError 
1395            ("Error: bytecode compiler can't handle unboxed tuples.\n"++
1396             "  Possibly due to foreign import/export decls in source.\n"++
1397             "  Workaround: use -fobject-code, or compile this module to .o separately."))
1398
1399
1400 mkSLIDE :: Int -> Int -> OrdList BCInstr
1401 mkSLIDE n d = if d == 0 then nilOL else unitOL (SLIDE n d)
1402
1403 splitApp :: AnnExpr' id ann -> (AnnExpr' id ann, [AnnExpr' id ann])
1404         -- The arguments are returned in *right-to-left* order
1405 splitApp (AnnApp (_,f) (_,a))
1406                | isTypeAtom a = splitApp f
1407                | otherwise    = case splitApp f of 
1408                                      (f', as) -> (f', a:as)
1409 splitApp (AnnNote _ (_,e))    = splitApp e
1410 splitApp (AnnCast (_,e) _)    = splitApp e
1411 splitApp e                    = (e, [])
1412
1413
1414 isTypeAtom :: AnnExpr' id ann -> Bool
1415 isTypeAtom (AnnType _) = True
1416 isTypeAtom _           = False
1417
1418 isVoidArgAtom :: AnnExpr' id ann -> Bool
1419 isVoidArgAtom (AnnVar v)        = typePrimRep (idType v) == VoidRep
1420 isVoidArgAtom (AnnNote _ (_,e)) = isVoidArgAtom e
1421 isVoidArgAtom (AnnCast (_,e) _) = isVoidArgAtom e
1422 isVoidArgAtom _                 = False
1423
1424 atomPrimRep :: AnnExpr' Id ann -> PrimRep
1425 atomPrimRep (AnnVar v)    = typePrimRep (idType v)
1426 atomPrimRep (AnnLit l)    = typePrimRep (literalType l)
1427 atomPrimRep (AnnNote _ b) = atomPrimRep (snd b)
1428 atomPrimRep (AnnApp f (_, AnnType _)) = atomPrimRep (snd f)
1429 atomPrimRep (AnnLam x e) | isTyVar x = atomPrimRep (snd e)
1430 atomPrimRep (AnnCast b _) = atomPrimRep (snd b)
1431 atomPrimRep other = pprPanic "atomPrimRep" (ppr (deAnnotate (undefined,other)))
1432
1433 atomRep :: AnnExpr' Id ann -> CgRep
1434 atomRep e = primRepToCgRep (atomPrimRep e)
1435
1436 isPtrAtom :: AnnExpr' Id ann -> Bool
1437 isPtrAtom e = atomRep e == PtrArg
1438
1439 -- Let szsw be the sizes in words of some items pushed onto the stack,
1440 -- which has initial depth d'.  Return the values which the stack environment
1441 -- should map these items to.
1442 mkStackOffsets :: Int -> [Int] -> [Int]
1443 mkStackOffsets original_depth szsw
1444    = map (subtract 1) (tail (scanl (+) original_depth szsw))
1445
1446 -- -----------------------------------------------------------------------------
1447 -- The bytecode generator's monad
1448
1449 type BcPtr = Either ItblPtr (Ptr ())
1450
1451 data BcM_State 
1452    = BcM_State { 
1453         uniqSupply :: UniqSupply,       -- for generating fresh variable names
1454         nextlabel :: Int,               -- for generating local labels
1455         malloced  :: [BcPtr],           -- thunks malloced for current BCO
1456                                         -- Should be free()d when it is GCd
1457         breakArray :: BreakArray        -- array of breakpoint flags 
1458         }
1459
1460 newtype BcM r = BcM (BcM_State -> IO (BcM_State, r))
1461
1462 ioToBc :: IO a -> BcM a
1463 ioToBc io = BcM $ \st -> do 
1464   x <- io 
1465   return (st, x)
1466
1467 runBc :: UniqSupply -> ModBreaks -> BcM r -> IO (BcM_State, r)
1468 runBc us modBreaks (BcM m) 
1469    = m (BcM_State us 0 [] breakArray)   
1470    where
1471    breakArray = modBreaks_flags modBreaks
1472
1473 thenBc :: BcM a -> (a -> BcM b) -> BcM b
1474 thenBc (BcM expr) cont = BcM $ \st0 -> do
1475   (st1, q) <- expr st0
1476   let BcM k = cont q 
1477   (st2, r) <- k st1
1478   return (st2, r)
1479
1480 thenBc_ :: BcM a -> BcM b -> BcM b
1481 thenBc_ (BcM expr) (BcM cont) = BcM $ \st0 -> do
1482   (st1, _) <- expr st0
1483   (st2, r) <- cont st1
1484   return (st2, r)
1485
1486 returnBc :: a -> BcM a
1487 returnBc result = BcM $ \st -> (return (st, result))
1488
1489 instance Monad BcM where
1490   (>>=) = thenBc
1491   (>>)  = thenBc_
1492   return = returnBc
1493
1494 emitBc :: ([BcPtr] -> ProtoBCO Name) -> BcM (ProtoBCO Name)
1495 emitBc bco
1496   = BcM $ \st -> return (st{malloced=[]}, bco (malloced st))
1497
1498 recordMallocBc :: Ptr a -> BcM ()
1499 recordMallocBc a
1500   = BcM $ \st -> return (st{malloced = Right (castPtr a) : malloced st}, ())
1501
1502 recordItblMallocBc :: ItblPtr -> BcM ()
1503 recordItblMallocBc a
1504   = BcM $ \st -> return (st{malloced = Left a : malloced st}, ())
1505
1506 getLabelBc :: BcM Int
1507 getLabelBc
1508   = BcM $ \st -> return (st{nextlabel = 1 + nextlabel st}, nextlabel st)
1509
1510 getLabelsBc :: Int -> BcM [Int]
1511 getLabelsBc n
1512   = BcM $ \st -> let ctr = nextlabel st 
1513                  in return (st{nextlabel = ctr+n}, [ctr .. ctr+n-1])
1514
1515 getBreakArray :: BcM BreakArray 
1516 getBreakArray = BcM $ \st -> return (st, breakArray st)
1517
1518 newUnique :: BcM Unique
1519 newUnique = BcM $
1520    \st -> case splitUniqSupply (uniqSupply st) of
1521              (us1, us2) -> let newState = st { uniqSupply = us2 } 
1522                            in  return (newState, uniqFromSupply us1) 
1523
1524 newId :: Type -> BcM Id
1525 newId ty = do 
1526     uniq <- newUnique
1527     return $ mkSysLocal tickFS uniq ty
1528
1529 tickFS :: FastString
1530 tickFS = fsLit "ticked"
1531 \end{code}