[project @ 2000-10-12 15:23:21 by sewardj]
[ghc-hetmet.git] / ghc / compiler / main / HscMain.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
5
6 \begin{code}
7 module HscMain ( hscMain ) where
8
9 #include "HsVersions.h"
10
11 import IO               ( hPutStr, stderr )
12 import HsSyn
13
14 import RdrHsSyn         ( RdrNameHsModule )
15 import FastString       ( unpackFS )
16 import StringBuffer     ( hGetStringBuffer )
17 import Parser           ( parse )
18 import Lex              ( PState(..), ParseResult(..) )
19 import SrcLoc           ( mkSrcLoc )
20
21 import Rename           ( renameModule )
22
23 import MkIface          ( writeIface )
24 import TcModule         ( TcResults(..), typecheckModule )
25 import Desugar          ( deSugar )
26 import SimplCore        ( core2core )
27 import OccurAnal        ( occurAnalyseBinds )
28 import CoreUtils        ( coreBindsSize )
29 import CoreTidy         ( tidyCorePgm )
30 import CoreToStg        ( topCoreBindsToStg )
31 import StgSyn           ( collectFinalStgBinders )
32 import SimplStg         ( stg2stg )
33 import CodeGen          ( codeGen )
34 import CodeOutput       ( codeOutput )
35
36 import Module           ( ModuleName, moduleNameUserString )
37 import CmdLineOpts
38 import ErrUtils         ( ghcExit, doIfSet, dumpIfSet )
39 import UniqSupply       ( mkSplitUniqSupply )
40
41 import Outputable
42 import Char             ( isSpace )
43 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
44 import SocketPrim
45 import BSD
46 import IOExts           ( unsafePerformIO )
47 import NativeInfo       ( os, arch )
48 #endif
49 import StgInterp        ( runStgI )
50 \end{code}
51
52
53 %************************************************************************
54 %*                                                                      *
55 \subsection{The main compiler pipeline}
56 %*                                                                      *
57 %************************************************************************
58
59 \begin{code}
60 hscMain
61   :: DynFlags   
62   -> ModSummary       -- summary, including source filename
63   -> Maybe ModIFace   -- old interface, if available
64   -> String           -- file in which to put the output (.s, .hc, .java etc.)
65   -> HomeSymbolTable            -- for home module ModDetails
66   -> PersistentCompilerState    -- IN: persistent compiler state
67   -> IO HscResult
68
69 hscMain flags core_cmds stg_cmds summary maybe_old_iface
70         output_filename mod_details pcs1 =
71
72         --------------------------  Reader  ----------------
73     show_pass "Parser"  >>
74     _scc_     "Parser"
75
76     let src_filename -- name of the preprocessed source file
77        = case ms_ppsource summary of
78             Just (filename, fingerprint) -> filename
79             Nothing -> pprPanic "hscMain:summary is not of a source module"
80                                 (ppr summary)
81
82     buf <- hGetStringBuffer True{-expand tabs-} src_filename
83
84     let glaexts | opt_GlasgowExts = 1#
85                 | otherwise       = 0#
86
87     case parse buf PState{ bol = 0#, atbol = 1#,
88                            context = [], glasgow_exts = glaexts,
89                            loc = mkSrcLoc src_filename 1 } of {
90
91         PFailed err -> return (CompErrs pcs err)
92
93         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
94
95     dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
96
97     dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
98         (ppSourceStats False rdr_module)                >>
99
100     -- UniqueSupplies for later use (these are the only lower case uniques)
101     mkSplitUniqSupply 'r'       >>= \ rn_uniqs  -> -- renamer
102     mkSplitUniqSupply 'd'       >>= \ ds_uniqs  -> -- desugarer
103     mkSplitUniqSupply 'r'       >>= \ ru_uniqs  -> -- rules
104     mkSplitUniqSupply 'c'       >>= \ c2s_uniqs -> -- core-to-stg
105     mkSplitUniqSupply 'u'       >>= \ tidy_uniqs -> -- tidy up
106     mkSplitUniqSupply 'g'       >>= \ st_uniqs  -> -- stg-to-stg passes
107     mkSplitUniqSupply 'n'       >>= \ ncg_uniqs -> -- native-code generator
108
109         --------------------------  Rename  ----------------
110     show_pass "Renamer"                         >>
111     _scc_     "Renamer"
112
113     renameModule rn_uniqs rdr_module            >>= \ maybe_rn_stuff ->
114     case maybe_rn_stuff of {
115         Nothing ->      -- Hurrah!  Renamer reckons that there's no need to
116                         -- go any further
117                         reportCompile mod_name "Compilation NOT required!" >>
118                         return ();
119         
120         Just (this_mod, rn_mod, 
121               old_iface, new_iface,
122               rn_name_supply, fixity_env,
123               imported_modules) ->
124                         -- Oh well, we've got to recompile for real
125
126
127         --------------------------  Typechecking ----------------
128     show_pass "TypeCheck"                               >>
129     _scc_     "TypeCheck"
130     typecheckModule tc_uniqs rn_name_supply
131                     fixity_env rn_mod           >>= \ maybe_tc_stuff ->
132     case maybe_tc_stuff of {
133         Nothing -> ghcExit 1;   -- Type checker failed
134
135         Just (tc_results@(TcResults {tc_tycons  = local_tycons, 
136                                      tc_classes = local_classes, 
137                                      tc_insts   = inst_info })) ->
138
139
140         --------------------------  Desugaring ----------------
141     _scc_     "DeSugar"
142     deSugar this_mod ds_uniqs tc_results        >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
143
144
145         --------------------------  Main Core-language transformations ----------------
146     _scc_     "Core2Core"
147     core2core core_cmds desugared rules         >>= \ (simplified, orphan_rules) ->
148
149         -- Do the final tidy-up
150     tidyCorePgm tidy_uniqs this_mod
151                 simplified orphan_rules         >>= \ (tidy_binds, tidy_orphan_rules) -> 
152
153         -- Run the occurrence analyser one last time, so that
154         -- dead binders get dead-binder info.  This is exploited by
155         -- code generators to avoid spitting out redundant bindings.
156         -- The occurrence-zapping in Simplify.simplCaseBinder means
157         -- that the Simplifier nukes useful dead-var stuff especially
158         -- in case patterns.
159     let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
160
161     coreBindsSize occ_anal_tidy_binds `seq`
162 --      TEMP: the above call zaps some space usage allocated by the
163 --      simplifier, which for reasons I don't understand, persists
164 --      thoroughout code generation
165
166
167
168         --------------------------  Convert to STG code -------------------------------
169     show_pass "Core2Stg"                        >>
170     _scc_     "Core2Stg"
171     let
172         stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
173     in
174
175         --------------------------  Simplify STG code -------------------------------
176     show_pass "Stg2Stg"                          >>
177     _scc_     "Stg2Stg"
178     stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
179
180 #ifdef GHCI
181     runStgI local_tycons local_classes 
182                          (map fst stg_binds2)    >>= \ i_result ->
183     putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
184     >>
185
186 #else
187         --------------------------  Interface file -------------------------------
188         -- Dump instance decls and type signatures into the interface file
189     _scc_     "Interface"
190     let
191         final_ids = collectFinalStgBinders (map fst stg_binds2)
192     in
193     writeIface this_mod old_iface new_iface
194                local_tycons local_classes inst_info
195                final_ids occ_anal_tidy_binds tidy_orphan_rules          >>
196
197
198         --------------------------  Code generation -------------------------------
199     show_pass "CodeGen"                         >>
200     _scc_     "CodeGen"
201     codeGen this_mod imported_modules
202             cost_centre_info
203             fe_binders
204             local_tycons local_classes 
205             stg_binds2                          >>= \ abstractC ->
206
207
208         --------------------------  Code output -------------------------------
209     show_pass "CodeOutput"                              >>
210     _scc_     "CodeOutput"
211     codeOutput this_mod local_tycons local_classes
212                occ_anal_tidy_binds stg_binds2
213                c_code h_code abstractC 
214                ncg_uniqs                                >>
215
216
217         --------------------------  Final report -------------------------------
218     reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
219
220 #endif
221
222
223     ghcExit 0
224     } }
225   where
226     -------------------------------------------------------------
227     -- ****** help functions:
228
229     show_pass
230       = if opt_D_show_passes
231         then \ what -> hPutStr stderr ("*** "++what++":\n")
232         else \ what -> return ()
233 \end{code}
234
235
236 %************************************************************************
237 %*                                                                      *
238 \subsection{Initial persistent state}
239 %*                                                                      *
240 %************************************************************************
241
242 \begin{code}
243 initPersistentCompilerState :: PersistentCompilerState
244 initPersistentCompilerState 
245   = PCS { pcsPST   = initPackageDetails,
246           pcsInsts = emptyInstEnv,
247           pcsRules = emptyRuleEnv,
248           pcsPRS   = initPersistentRenamerState }
249
250 initPackageDetails :: PackageSymbolTable
251 initPackageDetails = extendTypeEnv emptyModuleEnv (map ATyCon wiredInTyCons)
252
253 initPersistentRenamerState :: PersistentRenamerState
254   = PRS { prsNS    = NS { nsNames  = initRenamerNames,
255                           nsIParam = emptyFM },
256           prsDecls = emptyNameEnv,
257           prsInsts = emptyBag,
258           prsRules = emptyBag
259     }
260
261 initRenamerNames :: FiniteMap (ModuleName,OccName) Name
262 initRenamerNames = grag wiredIn_in `plusFM` listToFM known_key
263          where
264            wired_in = [ ((moduleName (nameModule name), nameOccName name), name)
265                       | name <- wiredInNames ]
266
267            known_key = [ ((rdrNameModule rdr_name, rdrNameOcc rdr_name), mkKnownKeyGlobal rdr_name uniq) 
268                        | (rdr_name, uniq) <- knownKeyRdrNames ]
269
270 %************************************************************************
271 %*                                                                      *
272 \subsection{Statistics}
273 %*                                                                      *
274 %************************************************************************
275
276 \begin{code}
277 ppSourceStats short (HsModule name version exports imports decls _ src_loc)
278  = (if short then hcat else vcat)
279         (map pp_val
280                [("ExportAll        ", export_all), -- 1 if no export list
281                 ("ExportDecls      ", export_ds),
282                 ("ExportModules    ", export_ms),
283                 ("Imports          ", import_no),
284                 ("  ImpQual        ", import_qual),
285                 ("  ImpAs          ", import_as),
286                 ("  ImpAll         ", import_all),
287                 ("  ImpPartial     ", import_partial),
288                 ("  ImpHiding      ", import_hiding),
289                 ("FixityDecls      ", fixity_ds),
290                 ("DefaultDecls     ", default_ds),
291                 ("TypeDecls        ", type_ds),
292                 ("DataDecls        ", data_ds),
293                 ("NewTypeDecls     ", newt_ds),
294                 ("DataConstrs      ", data_constrs),
295                 ("DataDerivings    ", data_derivs),
296                 ("ClassDecls       ", class_ds),
297                 ("ClassMethods     ", class_method_ds),
298                 ("DefaultMethods   ", default_method_ds),
299                 ("InstDecls        ", inst_ds),
300                 ("InstMethods      ", inst_method_ds),
301                 ("TypeSigs         ", bind_tys),
302                 ("ValBinds         ", val_bind_ds),
303                 ("FunBinds         ", fn_bind_ds),
304                 ("InlineMeths      ", method_inlines),
305                 ("InlineBinds      ", bind_inlines),
306 --              ("SpecialisedData  ", data_specs),
307 --              ("SpecialisedInsts ", inst_specs),
308                 ("SpecialisedMeths ", method_specs),
309                 ("SpecialisedBinds ", bind_specs)
310                ])
311   where
312     pp_val (str, 0) = empty
313     pp_val (str, n) 
314       | not short   = hcat [text str, int n]
315       | otherwise   = hcat [text (trim str), equals, int n, semi]
316     
317     trim ls     = takeWhile (not.isSpace) (dropWhile isSpace ls)
318
319     fixity_ds   = length [() | FixD d <- decls]
320                 -- NB: this omits fixity decls on local bindings and
321                 -- in class decls.  ToDo
322
323     tycl_decls  = [d | TyClD d <- decls]
324     (class_ds, data_ds, newt_ds, type_ds) = countTyClDecls tycl_decls
325
326     inst_decls  = [d | InstD d <- decls]
327     inst_ds     = length inst_decls
328     default_ds  = length [() | DefD _ <- decls]
329     val_decls   = [d | ValD d <- decls]
330
331     real_exports = case exports of { Nothing -> []; Just es -> es }
332     n_exports    = length real_exports
333     export_ms    = length [() | IEModuleContents _ <- real_exports]
334     export_ds    = n_exports - export_ms
335     export_all   = case exports of { Nothing -> 1; other -> 0 }
336
337     (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
338         = count_binds (foldr ThenBinds EmptyBinds val_decls)
339
340     (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
341         = foldr add6 (0,0,0,0,0,0) (map import_info imports)
342     (data_constrs, data_derivs)
343         = foldr add2 (0,0) (map data_info tycl_decls)
344     (class_method_ds, default_method_ds)
345         = foldr add2 (0,0) (map class_info tycl_decls)
346     (inst_method_ds, method_specs, method_inlines)
347         = foldr add3 (0,0,0) (map inst_info inst_decls)
348
349
350     count_binds EmptyBinds        = (0,0,0,0,0)
351     count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
352     count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
353                                         ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
354
355     count_monobinds EmptyMonoBinds                 = (0,0)
356     count_monobinds (AndMonoBinds b1 b2)           = count_monobinds b1 `add2` count_monobinds b2
357     count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
358     count_monobinds (PatMonoBind p r _)            = (0,1)
359     count_monobinds (FunMonoBind f _ m _)          = (0,1)
360
361     count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
362
363     sig_info (Sig _ _ _)            = (1,0,0,0)
364     sig_info (ClassOpSig _ _ _ _)   = (0,1,0,0)
365     sig_info (SpecSig _ _ _)        = (0,0,1,0)
366     sig_info (InlineSig _ _ _)      = (0,0,0,1)
367     sig_info (NoInlineSig _ _ _)    = (0,0,0,1)
368     sig_info _                      = (0,0,0,0)
369
370     import_info (ImportDecl _ _ qual as spec _)
371         = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
372     qual_info False  = 0
373     qual_info True   = 1
374     as_info Nothing  = 0
375     as_info (Just _) = 1
376     spec_info Nothing           = (0,0,0,1,0,0)
377     spec_info (Just (False, _)) = (0,0,0,0,1,0)
378     spec_info (Just (True, _))  = (0,0,0,0,0,1)
379
380     data_info (TyData _ _ _ _ _ nconstrs derivs _ _ _ _)
381         = (nconstrs, case derivs of {Nothing -> 0; Just ds -> length ds})
382     data_info other = (0,0)
383
384     class_info (ClassDecl _ _ _ _ meth_sigs def_meths _ _ _ )
385         = case count_sigs meth_sigs of
386             (_,classops,_,_) ->
387                (classops, addpr (count_monobinds def_meths))
388     class_info other = (0,0)
389
390     inst_info (InstDecl _ inst_meths inst_sigs _ _)
391         = case count_sigs inst_sigs of
392             (_,_,ss,is) ->
393                (addpr (count_monobinds inst_meths), ss, is)
394
395     addpr :: (Int,Int) -> Int
396     add1  :: Int -> Int -> Int
397     add2  :: (Int,Int) -> (Int,Int) -> (Int, Int)
398     add3  :: (Int,Int,Int) -> (Int,Int,Int) -> (Int, Int, Int)
399     add4  :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> (Int, Int, Int, Int)
400     add5  :: (Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int)
401     add6  :: (Int,Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int, Int)
402
403     addpr (x,y) = x+y
404     add1 x1 y1  = x1+y1
405     add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
406     add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
407     add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
408     add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
409     add6 (x1,x2,x3,x4,x5,x6) (y1,y2,y3,y4,y5,y6) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5,x6+y6)
410 \end{code}
411
412 \begin{code}
413 \end{code}
414
415 \begin{code}
416 reportCompile :: ModuleName -> String -> IO ()
417 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
418 reportCompile mod_name info
419   | not opt_ReportCompile = return ()
420   | otherwise = (do 
421       sock <- udpSocket 0
422       addr <- motherShip
423       sendTo sock (moduleNameUserString mod_name ++ ';': compiler_version ++ 
424                    ';': os ++ ';':arch ++ '\n':' ':info ++ "\n") addr
425       return ()) `catch` (\ _ -> return ())
426
427 motherShip :: IO SockAddr
428 motherShip = do
429   he <- getHostByName "laysan.dcs.gla.ac.uk"
430   case (hostAddresses he) of
431     []    -> IOERROR (userError "No address!")
432     (x:_) -> return (SockAddrInet motherShipPort x)
433
434 --magick
435 motherShipPort :: PortNumber
436 motherShipPort = mkPortNumber 12345
437
438 -- creates a socket capable of sending datagrams,
439 -- binding it to a port
440 --  ( 0 => have the system pick next available port no.)
441 udpSocket :: Int -> IO Socket
442 udpSocket p = do
443   pr <- getProtocolNumber "udp"
444   s  <- socket AF_INET Datagram pr
445   bindSocket s (SockAddrInet (mkPortNumber p) iNADDR_ANY)
446   return s
447 #else
448 reportCompile _ _ = return ()
449 #endif
450
451 \end{code}