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