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