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