[project @ 2002-11-11 10:59:07 by simonpj]
[ghc-hetmet.git] / ghc / compiler / ghci / ByteCodeGen.lhs
index 345a81b..0d21f2d 100644 (file)
@@ -4,22 +4,29 @@
 \section[ByteCodeGen]{Generate bytecode from Core}
 
 \begin{code}
-module ByteCodeGen ( UnlinkedBCO, UnlinkedBCOExpr, ItblEnv, ClosureEnv, HValue,
-                    filterNameMap,
-                     byteCodeGen, coreExprToBCOs
+module ByteCodeGen ( UnlinkedBCO, UnlinkedBCOExpr, 
+                    byteCodeGen, coreExprToBCOs
                   ) where
 
 #include "HsVersions.h"
 
+import ByteCodeInstr   ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO, bciStackUse )
+import ByteCodeFFI     ( taggedSizeW, untaggedSizeW, mkMarshalCode, moan64 )
+import ByteCodeAsm     ( CompiledByteCode(..), UnlinkedBCO, UnlinkedBCOExpr, 
+                         assembleBCO, assembleBCOs, iNTERP_STACK_CHECK_THRESH )
+import ByteCodeLink    ( lookupStaticPtr )
+
 import Outputable
-import Name            ( Name, getName )
+import Name            ( Name, getName, mkSystemName )
 import Id              ( Id, idType, isDataConId_maybe, isPrimOpId_maybe, isFCallId,
-                         idPrimRep, mkSysLocal, idName, isFCallId_maybe, isPrimOpId )
+                         idPrimRep, mkLocalId, isFCallId_maybe, isPrimOpId )
 import ForeignCall     ( ForeignCall(..), CCallTarget(..), CCallSpec(..) )
 import OrdList         ( OrdList, consOL, snocOL, appOL, unitOL, 
                          nilOL, toOL, concatOL, fromOL )
 import FiniteMap       ( FiniteMap, addListToFM, listToFM, elemFM,
                          addToFM, lookupFM, fmToList )
+import HscTypes                ( ModGuts(..), ModGuts, typeEnvTyCons, typeEnvClasses )
+import CoreUtils       ( exprType )
 import CoreSyn
 import PprCore         ( pprCoreExpr )
 import Literal         ( Literal(..), literalPrimRep )
@@ -29,7 +36,7 @@ import CoreFVs                ( freeVars )
 import Type            ( typePrimRep, isUnLiftedType, splitTyConApp_maybe, isTyVarTy )
 import DataCon         ( dataConTag, fIRST_TAG, dataConTyCon, 
                           dataConWrapId, isUnboxedTupleCon )
-import TyCon           ( TyCon(..), tyConFamilySize, isDataTyCon, tyConDataCons,
+import TyCon           ( tyConFamilySize, isDataTyCon, tyConDataCons,
                          isFunTyCon, isUnboxedTupleTyCon )
 import Class           ( Class, classTyCon )
 import Type            ( Type, repType, splitFunTys, dropForAlls )
@@ -38,6 +45,10 @@ import Util          ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem,
 import DataCon         ( dataConRepArity )
 import Var             ( isTyVar )
 import VarSet          ( VarSet, varSetElems )
+import TysPrim         ( foreignObjPrimTyCon, 
+                         arrayPrimTyCon, mutableArrayPrimTyCon,
+                         byteArrayPrimTyCon, mutableByteArrayPrimTyCon
+                       )
 import PrimRep         ( isFollowableRep )
 import CmdLineOpts     ( DynFlags, DynFlag(..) )
 import ErrUtils                ( showPass, dumpIfSet_dyn )
@@ -47,20 +58,13 @@ import Panic                ( GhcException(..) )
 import PprType         ( pprType )
 import SMRep           ( arrWordsHdrSize, arrPtrsHdrSize )
 import Constants       ( wORD_SIZE )
-import ByteCodeInstr   ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO, bciStackUse )
-import ByteCodeItbls   ( ItblEnv, mkITbls )
-import ByteCodeLink    ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
-                         ClosureEnv, HValue, filterNameMap, linkFail,
-                         iNTERP_STACK_CHECK_THRESH )
-import ByteCodeFFI     ( taggedSizeW, untaggedSizeW, mkMarshalCode, moan64 )
-import Linker          ( lookupSymbol )
 
 import List            ( intersperse, sortBy, zip4 )
 import Foreign         ( Ptr, castPtr, mallocBytes, pokeByteOff, Word8 )
-import CTypes          ( CInt )
-import Exception       ( throwDyn )
+import Foreign.C       ( CInt )
+import Control.Exception       ( throwDyn )
 
-import GlaExts         ( Int(..), ByteArray# )
+import GHC.Exts                ( Int(..), ByteArray# )
 
 import Monad           ( when )
 import Maybe           ( isJust )
@@ -76,13 +80,13 @@ import Char         ( ord )
 \begin{code}
 
 byteCodeGen :: DynFlags
-            -> [CoreBind] 
-            -> [TyCon] -> [Class]
-            -> IO ([UnlinkedBCO], ItblEnv)
-byteCodeGen dflags binds local_tycons local_classes
+            -> ModGuts
+            -> IO CompiledByteCode
+byteCodeGen dflags (ModGuts { mg_binds = binds, mg_types = type_env })
    = do showPass dflags "ByteCodeGen"
-        let tycs = local_tycons ++ map classTyCon local_classes
-        itblenv <- mkITbls tycs
+        let  local_tycons  = typeEnvTyCons  type_env
+            local_classes = typeEnvClasses type_env
+            tycs = local_tycons ++ map classTyCon local_classes
 
         let flatBinds = concatMap getBind binds
             getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
@@ -100,9 +104,7 @@ byteCodeGen dflags binds local_tycons local_classes
         dumpIfSet_dyn dflags Opt_D_dump_BCOs
            "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
 
-        bcos <- mapM assembleBCO proto_bcos
-
-        return (bcos, itblenv)
+        assembleBCOs proto_bcos tycs
         
 
 -- Returns: (the root BCO for this expression, 
@@ -115,13 +117,10 @@ coreExprToBCOs dflags expr
 
       -- create a totally bogus name for the top-level BCO; this
       -- should be harmless, since it's never used for anything
-      let invented_id   = mkSysLocal FSLIT("ExprTopLevel") 
-                               (mkPseudoUnique3 0) 
-                               (panic "invented_id's type")
-      let invented_name = idName invented_id
-
-         annexpr = freeVars expr
-         fvs = filter (not.isTyVar) (varSetElems (fst annexpr))
+      let invented_name = mkSystemName (mkPseudoUnique3 0) FSLIT("ExprTopLevel")
+          invented_id   = mkLocalId invented_name (panic "invented_id's type")
+         annexpr       = freeVars expr
+         fvs           = filter (not.isTyVar) (varSetElems (fst annexpr))
 
       (BcM_State all_proto_bcos final_ctr mallocd, ()) 
          <- runBc (BcM_State [] 0 []) 
@@ -649,18 +648,25 @@ schemeT d s p app
      )
 
    -- Case 2
-   | [arg1,arg2] <- args_r_to_l,
+   | is_con_call,
+     isUnboxedTupleCon con,                    -- (# ... #)
+     [(_,arg1),(_,arg2)] <- args_r_to_l,       -- Exactly two args
      let 
-        isVoidRepAtom (_, AnnVar v)    = typePrimRep (idType v) == VoidRep
-         isVoidRepAtom (_, AnnNote n e) = isVoidRepAtom e
-        isVoidRepAtom _ = False
+        isVoidRepAtom (AnnVar v)        = typePrimRep (idType v) == VoidRep
+         isVoidRepAtom (AnnNote n (_,e)) = isVoidRepAtom e
+        isVoidRepAtom _                 = False
      in  
-        isVoidRepAtom arg2
+     isVoidRepAtom arg2                        -- The first arg is void
    = --trace (if isSingleton args_r_to_l
      --       then "schemeT: unboxed singleton"
      --       else "schemeT: unboxed pair with Void first component") (
-     schemeT d s p arg1
-     --)
+     pushAtom True d p arg1    `thenBc` \ (push, szw) ->
+     returnBc (push                            -- value onto stack
+               `appOL`  mkSLIDE szw (d-s)      -- clear to sequel
+               `snocOL` RETURN (atomRep arg1)) -- go
+       -- We used to use "schemeT d s p arg1", but that is wrong.
+       -- We must use RETURN (because it's an unboxed tuple)
+       -- I think that this still does not work: SLPJ Oct 02
 
    -- Case 3
    | Just (CCall ccall_spec) <- isFCallId_maybe fn
@@ -779,14 +785,16 @@ generateCCall d0 s p ccall_spec@(CCallSpec target cconv safety) fn args_r_to_l
 
          pargs d [] = returnBc []
          pargs d ((_,a):az) 
-            = let rep_arg = atomRep a
-              in case rep_arg of
+            = let arg_ty = repType (exprType (deAnnotate' a))
+
+              in case splitTyConApp_maybe arg_ty of
                     -- Don't push the FO; instead push the Addr# it
                     -- contains.
-                    ForeignObjRep
+                   Just (t, _)
+                    | t == foreignObjPrimTyCon
                        -> pushAtom False{-irrelevant-} d p a
                                                        `thenBc` \ (push_fo, _) ->
-                          let foro_szW = taggedSizeW ForeignObjRep
+                          let foro_szW = taggedSizeW PtrRep
                               d_now    = d + addr_tsizeW
                               code     = push_fo `appOL` toOL [
                                             UPK_TAG addr_usizeW 0 0,
@@ -795,13 +803,13 @@ generateCCall d0 s p ccall_spec@(CCallSpec target cconv safety) fn args_r_to_l
                           in  pargs d_now az           `thenBc` \ rest ->
                               returnBc ((code, AddrRep) : rest)
 
-                    ArrayRep
+                    | t == arrayPrimTyCon || t == mutableArrayPrimTyCon
                        -> pargs (d + addr_tsizeW) az   `thenBc` \ rest ->
                           parg_ArrayishRep arrPtrsHdrSize d p a
                                                        `thenBc` \ code ->
                           returnBc ((code,AddrRep):rest)
 
-                    ByteArrayRep
+                    | t == byteArrayPrimTyCon || t == mutableByteArrayPrimTyCon
                        -> pargs (d + addr_tsizeW) az   `thenBc` \ rest ->
                           parg_ArrayishRep arrWordsHdrSize d p a
                                                        `thenBc` \ code ->
@@ -811,7 +819,7 @@ generateCCall d0 s p ccall_spec@(CCallSpec target cconv safety) fn args_r_to_l
                     other
                        -> pushAtom True d p a          `thenBc` \ (code_a, sz_a) ->
                           pargs (d+sz_a) az            `thenBc` \ rest ->
-                          returnBc ((code_a, rep_arg) : rest)
+                          returnBc ((code_a, atomRep a) : rest)
 
          -- Do magic for Ptr/Byte arrays.  Push a ptr to the array on
          -- the stack but then advance it over the headers, so as to
@@ -890,12 +898,8 @@ generateCCall d0 s p ccall_spec@(CCallSpec target cconv safety) fn args_r_to_l
                  DynamicTarget
                     -> returnBc (False, panic "ByteCodeGen.generateCCall(dyn)")
                  StaticTarget target
-                    -> let sym_to_find = unpackFS target in
-                       ioToBc (lookupSymbol sym_to_find) `thenBc` \res ->
-                       case res of
-                           Just aa -> returnBc (True, aa)
-                           Nothing -> ioToBc (linkFail "ByteCodeGen.generateCCall" 
-                                                       sym_to_find)
+                    -> ioToBc (lookupStaticPtr target) `thenBc` \res ->
+                       returnBc (True, res)
                  CasmTarget _
                     -> pprPanic "ByteCodeGen.generateCCall: casm" (ppr ccall_spec)
      in
@@ -1016,7 +1020,6 @@ atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
 
-
 -- Compile code which expects an unboxed Int on the top of stack,
 -- (call it i), and pushes the i'th closure in the supplied list 
 -- as a consequence.