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