CodeOutput.lhs 8.7 KB
Newer Older
1 2 3 4 5 6
%
% (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
%
\section{Code output phase}

\begin{code}
7
module CodeOutput( codeOutput, outputForeignStubs ) where
8 9 10

#include "HsVersions.h"

11
#ifndef OMIT_NATIVE_CODEGEN
12
import UniqSupply	( mkSplitUniqSupply )
13 14
import AsmCodeGen	( nativeCodeGen )
#endif
15

16 17 18
#ifdef ILX
import IlxGen		( ilxGen )
#endif
19

20
#ifdef JAVA
21
import JavaGen		( javaGen )
22
import OccurAnal	( occurAnalyseBinds )
23
import qualified PrintJava
24
import OccurAnal	( occurAnalyseBinds )
25
#endif
26

27
import Packages
28
import DriverState	( getExplicitPackagesAnd, getPackageCIncludes )
29
import FastString	( unpackFS )
30
import AbsCSyn		( AbstractC )
31
import PprAbsC		( dumpRealC, writeRealC )
32
import HscTypes
33
import CmdLineOpts
34
import ErrUtils		( dumpIfSet_dyn, showPass )
35
import Outputable
36
import Pretty		( Mode(..), printDoc )
37
import Module		( Module )
38
import ListSetOps	( removeDupsEq )
39

krc's avatar
krc committed
40
import Directory ( doesFileExist )
41
import Monad		( when )
42
import IO
43 44 45
\end{code}


46 47 48 49 50 51
%************************************************************************
%*									*
\subsection{Steering}
%*									*
%************************************************************************

52
\begin{code}
53
codeOutput :: DynFlags
54 55 56
	   -> Module
	   -> ForeignStubs
	   -> Dependencies
57
	   -> AbstractC			-- Compiled abstract C
58
	   -> IO (Bool{-stub_h_exists-}, Bool{-stub_c_exists-})
59

60
codeOutput dflags this_mod foreign_stubs deps flat_abstractC
61
  = 
62
    -- You can have C (c_output) or assembly-language (ncg_output),
63 64 65
    -- but not both.  [Allowing for both gives a space leak on
    -- flat_abstractC.  WDP 94/10]

66
    -- Dunno if the above comment is still meaningful now.  JRS 001024.
67

68 69
    do	{ showPass dflags "CodeOutput"
	; let filenm = dopt_OutName dflags 
70 71 72 73 74 75
	; stubs_exist <- outputForeignStubs dflags foreign_stubs
	; case dopt_HscLang dflags of {
             HscInterpreted -> return ();
             HscAsm         -> outputAsm dflags filenm flat_abstractC;
             HscC           -> outputC dflags filenm flat_abstractC stubs_exist
					deps foreign_stubs;
76 77
             HscJava        -> 
#ifdef JAVA
78
			       outputJava dflags filenm mod_name tycons core_binds;
79
#else
80
                               panic "Java support not compiled into this ghc";
81
#endif
82
	     HscILX         -> 
rrt's avatar
rrt committed
83
#ifdef ILX
84
			       let tycons = typeEnvTyCons type_env in
85
	                       outputIlx dflags filenm mod_name tycons stg_binds;
86
#else
87
                               panic "ILX support not compiled into this ghc";
rrt's avatar
rrt committed
88
#endif
89 90
	  }
	; return stubs_exist
91
	}
92

93
doOutput :: String -> (Handle -> IO ()) -> IO ()
94
doOutput filenm io_action = bracket (openFile filenm WriteMode) hClose io_action
95 96 97 98 99 100 101 102 103 104
\end{code}


%************************************************************************
%*									*
\subsection{C}
%*									*
%************************************************************************

\begin{code}
105
outputC dflags filenm flat_absC 
106
	(stub_h_exists, _) dependencies foreign_stubs
107
  = do dumpIfSet_dyn dflags Opt_D_dump_realC "Real C" (dumpRealC flat_absC)
108 109 110 111 112 113 114 115 116 117 118 119 120 121

       -- figure out which header files to #include in the generated .hc file:
       --
       --   * extra_includes from packages
       --   * -#include options from the cmdline and OPTIONS pragmas
       --   * the _stub.h file, if there is one.
       --
       let packages = dep_pkgs dependencies
       pkg_configs <- getExplicitPackagesAnd packages
       let pkg_names = map name pkg_configs

       c_includes <- getPackageCIncludes pkg_configs
       let cmdline_includes = cmdlineHcIncludes dflags -- -#include options
       
122 123 124 125 126 127
	   ffi_decl_headers 
	      = case foreign_stubs of
		  NoStubs 		  -> []
		  ForeignStubs _ _ fdhs _ -> map unpackFS (fst (removeDupsEq fdhs))
			-- Remove duplicates, because distinct foreign import decls
			-- may cite the same #include.  Order doesn't matter.
128

129 130
           all_headers =  c_includes
		       ++ reverse cmdline_includes
131
		       ++ ffi_decl_headers
132 133 134 135 136 137 138 139

       let cc_injects = unlines (map mk_include all_headers)
       	   mk_include h_file = 
       	    case h_file of 
       	       '"':_{-"-} -> "#include "++h_file
       	       '<':_      -> "#include "++h_file
       	       _          -> "#include \""++h_file++"\""

140
       doOutput filenm $ \ h -> do
141 142
	  hPutStr h ("/* GHC_PACKAGES " ++ unwords pkg_names ++ "\n*/\n")
	  hPutStr h cc_injects
143 144
	  when stub_h_exists $ 
	     hPutStrLn h ("#include \"" ++ (hscStubHOutName dflags) ++ "\"")
145
	  writeRealC h flat_absC
146 147 148 149 150 151 152 153 154 155
\end{code}


%************************************************************************
%*									*
\subsection{Assembler}
%*									*
%************************************************************************

\begin{code}
156
outputAsm dflags filenm flat_absC
157

158
#ifndef OMIT_NATIVE_CODEGEN
159

160
  = do ncg_uniqs <- mkSplitUniqSupply 'n'
161 162
       let (stix_final, ncg_output_d) = _scc_ "NativeCodeGen" 
				        nativeCodeGen flat_absC ncg_uniqs
163
       dumpIfSet_dyn dflags Opt_D_dump_stix "Final stix code" stix_final
164 165 166
       dumpIfSet_dyn dflags Opt_D_dump_asm "Asm code" (docToSDoc ncg_output_d)
       _scc_ "OutputAsm" doOutput filenm $
	   \f -> printDoc LeftMode f ncg_output_d
167 168 169 170
  where

#else /* OMIT_NATIVE_CODEGEN */

171 172
  = pprPanic "This compiler was built without a native code generator"
	     (text "Use -fvia-C instead")
173 174 175

#endif
\end{code}
176 177


178 179 180 181 182
%************************************************************************
%*									*
\subsection{Java}
%*									*
%************************************************************************
183

184
\begin{code}
185
#ifdef JAVA
186
outputJava dflags filenm mod tycons core_binds
187
  = doOutput filenm (\ f -> printForUser f alwaysQualify pp_java)
188
	-- User style printing for now to keep indentation
189
  where
190 191 192
    occ_anal_binds = occurAnalyseBinds core_binds
	-- Make sure we have up to date dead-var information
    java_code = javaGen mod [{- Should be imports-}] tycons occ_anal_binds
193
    pp_java   = PrintJava.compilationUnit java_code
194
#endif
195
\end{code}
196

197

rrt's avatar
rrt committed
198 199 200 201 202 203 204 205
%************************************************************************
%*									*
\subsection{Ilx}
%*									*
%************************************************************************

\begin{code}
#ifdef ILX
206 207
outputIlx dflags filename mod tycons stg_binds
  =  doOutput filename (\ f -> printForC f pp_ilx)
rrt's avatar
rrt committed
208 209 210 211 212 213
  where
    pp_ilx = ilxGen mod tycons stg_binds
#endif
\end{code}


214 215 216 217 218 219 220
%************************************************************************
%*									*
\subsection{Foreign import/export}
%*									*
%************************************************************************

\begin{code}
221 222 223
outputForeignStubs :: DynFlags -> ForeignStubs
		   -> IO (Bool, 	-- Header file created
			  Bool)		-- C file created
krc's avatar
krc committed
224 225 226 227 228 229
outputForeignStubs dflags NoStubs = do
-- When compiling External Core files, may need to use stub files from a 
-- previous compilation
   hFileExists <- doesFileExist (hscStubHOutName dflags)
   cFileExists <- doesFileExist (hscStubCOutName dflags)
   return (hFileExists, cFileExists)
230
outputForeignStubs dflags (ForeignStubs h_code c_code _ _)
231
  = do
232
	dumpIfSet_dyn dflags Opt_D_dump_foreign
233 234
                      "Foreign export header file" stub_h_output_d

235 236 237 238 239
	-- we need the #includes from the rts package for the stub files
	rts_pkgs <- getPackageDetails [rtsPackage]
 	let rts_includes = concatMap mk_include (concatMap c_includes rts_pkgs)
	    mk_include i = "#include \"" ++ i ++ "\"\n"

240 241
	stub_h_file_exists
           <- outputForeignStubs_help (hscStubHOutName dflags) stub_h_output_w
242
		("#include \"HsFFI.h\"\n" ++ cplusplus_hdr) cplusplus_ftr
243

244
	dumpIfSet_dyn dflags Opt_D_dump_foreign
245 246
                      "Foreign export stubs" stub_c_output_d

247 248
	stub_c_file_exists
           <- outputForeignStubs_help (hscStubCOutName dflags) stub_c_output_w
249
		("#define IN_STG_CODE 0\n" ++ 
250
		 "#include \"RtsAPI.h\"\n" ++
251
		 rts_includes ++
252 253
		 cplusplus_hdr)
		 cplusplus_ftr
254
	   -- We're adding the default hc_header to the stub file, but this
255 256
	   -- isn't really HC code, so we need to define IN_STG_CODE==0 to
	   -- avoid the register variables etc. being enabled.
257 258

        return (stub_h_file_exists, stub_c_file_exists)
259
  where
260 261 262 263 264 265 266 267
    -- C stubs for "foreign export"ed functions.
    stub_c_output_d = pprCode CStyle c_code
    stub_c_output_w = showSDoc stub_c_output_d

    -- Header file protos for "foreign export"ed functions.
    stub_h_output_d = pprCode CStyle h_code
    stub_h_output_w = showSDoc stub_h_output_d

268 269
cplusplus_hdr = "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"
cplusplus_ftr = "#ifdef __cplusplus\n}\n#endif\n"
270

271 272 273
-- Don't use doOutput for dumping the f. export stubs
-- since it is more than likely that the stubs file will
-- turn out to be empty, in which case no file should be created.
274 275 276
outputForeignStubs_help fname ""      header footer = return False
outputForeignStubs_help fname doc_str header footer
   = do writeFile fname (header ++ doc_str ++ '\n':footer ++ "\n")
277
        return True
278 279
\end{code}