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