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