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