[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / compiler / main / Main.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 Main ( main ) where
8
9 #include "HsVersions.h"
10
11 import IO       ( IOMode(..), hPutStr, hClose, openFile, stderr )
12 import HsSyn
13 import BasicTypes       ( NewOrData(..) )
14
15 import ReadPrefix       ( rdModule )
16 import Rename           ( renameModule )
17
18 import MkIface          -- several functions
19 import TcModule         ( typecheckModule )
20 import Desugar          ( deSugar )
21 import SimplCore        ( core2core )
22 import CoreToStg        ( topCoreBindsToStg )
23 import StgSyn           ( collectFinalStgBinders, pprStgBindingsWithSRTs )
24 import SimplStg         ( stg2stg )
25 import CodeGen          ( codeGen )
26 #if ! OMIT_NATIVE_CODEGEN
27 import AsmCodeGen       ( dumpRealAsm, writeRealAsm )
28 #endif
29
30 import AbsCSyn          ( absCNop )
31 import AbsCUtils        ( flattenAbsC )
32 import CmdLineOpts
33 import ErrUtils         ( ghcExit, doIfSet, dumpIfSet )
34 import Maybes           ( maybeToBool, MaybeErr(..) )
35 import TyCon            ( isDataTyCon )
36 import Class            ( classTyCon )
37 import UniqSupply       ( mkSplitUniqSupply )
38
39 import PprAbsC          ( dumpRealC, writeRealC )
40 import FiniteMap        ( emptyFM )
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
50 \end{code}
51
52 \begin{code}
53 main =
54  --  _scc_ "main" 
55  doIt classifyOpts
56 \end{code}
57
58 \begin{code}
59 doIt :: ([CoreToDo], [StgToDo]) -> IO ()
60
61 doIt (core_cmds, stg_cmds)
62   = doIfSet opt_Verbose 
63         (hPutStr stderr "Glasgow Haskell Compiler, version "    >>
64          hPutStr stderr compiler_version                        >>
65          hPutStr stderr ", for Haskell 1.4\n")                  >>
66
67     -- ******* READER
68     show_pass "Reader"  >>
69     _scc_     "Reader"
70     rdModule            >>= \ (mod_name, rdr_module) ->
71
72     dumpIfSet opt_D_dump_rdr "Reader" (ppr rdr_module)          >>
73
74     dumpIfSet opt_D_source_stats "Source Statistics"
75         (ppSourceStats False rdr_module)                >>
76
77     -- UniqueSupplies for later use (these are the only lower case uniques)
78 --    _scc_     "spl-rn"
79     mkSplitUniqSupply 'r'       >>= \ rn_uniqs  -> -- renamer
80 --    _scc_     "spl-tc"
81     mkSplitUniqSupply 'a'       >>= \ tc_uniqs  -> -- typechecker
82 --    _scc_     "spl-ds"
83     mkSplitUniqSupply 'd'       >>= \ ds_uniqs  -> -- desugarer
84 --    _scc_     "spl-sm"
85     mkSplitUniqSupply 's'       >>= \ sm_uniqs  -> -- core-to-core simplifier
86 --    _scc_     "spl-c2s"
87     mkSplitUniqSupply 'c'       >>= \ c2s_uniqs -> -- core-to-stg
88 --    _scc_     "spl-st"
89     mkSplitUniqSupply 'g'       >>= \ st_uniqs  -> -- stg-to-stg passes
90 --    _scc_     "spl-absc"
91     mkSplitUniqSupply 'f'       >>= \ fl_uniqs  -> -- absC flattener
92 --    _scc_     "spl-ncg"
93     mkSplitUniqSupply 'n'       >>= \ ncg_uniqs -> -- native-code generator
94
95     -- ******* RENAMER
96     show_pass "Renamer"                         >>
97     _scc_     "Renamer"
98
99     renameModule rn_uniqs rdr_module            >>=
100         \ maybe_rn_stuff ->
101     case maybe_rn_stuff of {
102         Nothing ->      -- Hurrah!  Renamer reckons that there's no need to
103                         -- go any further
104                         reportCompile (_UNPK_ mod_name) "Compilation NOT required!" >>
105                         return ();
106         
107         Just (rn_mod, iface_file_stuff, rn_name_supply, imported_modules) ->
108                         -- Oh well, we've got to recompile for real
109
110
111     -- Safely past renaming: we can start the interface file:
112     -- (the iface file is produced incrementally, as we have
113     -- the information that we need...; we use "iface<blah>")
114     -- "endIface" finishes the job.
115     startIface mod_name                                 >>= \ if_handle ->
116     ifaceMain if_handle iface_file_stuff                >>
117
118
119     -- ******* TYPECHECKER
120     show_pass "TypeCheck"                               >>
121     _scc_     "TypeCheck"
122     typecheckModule tc_uniqs rn_name_supply rn_mod      >>= \ maybe_tc_stuff ->
123     case maybe_tc_stuff of {
124         Nothing -> ghcExit 1;   -- Type checker failed
125
126         Just (all_binds,
127               local_tycons, local_classes, inst_info, 
128               fo_decls,
129               ddump_deriv,
130               global_env,
131               global_ids) ->
132
133
134     -- ******* DESUGARER
135     show_pass "DeSugar"                                     >>
136     _scc_     "DeSugar"
137     deSugar ds_uniqs global_env mod_name all_binds fo_decls >>= \ (desugared, h_code, c_code) ->
138
139
140     -- ******* CORE-TO-CORE SIMPLIFICATION
141     show_pass "Core2Core"                       >>
142     _scc_     "Core2Core"
143     let
144         local_data_tycons = filter isDataTyCon local_tycons
145     in
146     core2core core_cmds mod_name
147               sm_uniqs desugared
148                                                 >>=
149          \ simplified ->
150
151
152     -- ******* STG-TO-STG SIMPLIFICATION
153     show_pass "Core2Stg"                        >>
154     _scc_     "Core2Stg"
155     let
156         stg_binds   = topCoreBindsToStg c2s_uniqs simplified
157     in
158
159     show_pass "Stg2Stg"                         >>
160     _scc_     "Stg2Stg"
161     stg2stg stg_cmds mod_name st_uniqs stg_binds
162                                                 >>=
163         \ (stg_binds2, cost_centre_info) ->
164
165     dumpIfSet opt_D_dump_stg "STG syntax:" 
166         (pprStgBindingsWithSRTs stg_binds2)     >>
167
168         -- Dump instance decls and type signatures into the interface file
169     let
170         final_ids = collectFinalStgBinders (map fst stg_binds2)
171     in
172     _scc_     "Interface"
173     ifaceDecls if_handle local_tycons local_classes inst_info final_ids simplified      >>
174     endIface if_handle                                          >>
175     -- We are definitely done w/ interface-file stuff at this point:
176     -- (See comments near call to "startIface".)
177
178     -- ******* "ABSTRACT", THEN "FLAT", THEN *REAL* C!
179     show_pass "CodeGen"                         >>
180     _scc_     "CodeGen"
181     let
182         all_local_data_tycons = filter isDataTyCon (map classTyCon local_classes)
183                                 ++ local_data_tycons
184                                         -- Generate info tables  for the data constrs arising
185                                         -- from class decls as well
186
187         all_tycon_specs       = emptyFM -- Not specialising tycons any more
188
189         abstractC      = codeGen mod_name               -- module name for CC labelling
190                                  cost_centre_info
191                                  imported_modules       -- import names for CC registering
192                                  all_local_data_tycons  -- type constructors generated locally
193                                  all_tycon_specs        -- tycon specialisations
194                                  stg_binds2
195
196         flat_abstractC = flattenAbsC fl_uniqs abstractC
197     in
198     show_pass "CodeOutput"                      >>
199     _scc_     "CodeOutput"
200     -- You can have C (c_output) or assembly-language (ncg_output),
201     -- but not both.  [Allowing for both gives a space leak on
202     -- flat_abstractC.  WDP 94/10]
203     let
204         (flat_absC_c, flat_absC_ncg) =
205            case (maybeToBool opt_ProduceC || opt_D_dump_realC,
206                  maybeToBool opt_ProduceS || opt_D_dump_asm) of
207              (True,  False) -> (flat_abstractC, absCNop)
208              (False, True)  -> (absCNop, flat_abstractC)
209              (False, False) -> (absCNop, absCNop)
210              (True,  True)  -> error "ERROR: Can't do both .hc and .s at the same time"
211
212         -- C stubs for "foreign export"ed functions.
213         stub_c_output_d = pprCode CStyle c_code
214         stub_c_output_w = showSDoc stub_c_output_d
215
216         -- Header file protos for "foreign export"ed functions.
217         stub_h_output_d = pprCode CStyle h_code
218         stub_h_output_w = showSDoc stub_h_output_d
219
220         c_output_d = dumpRealC flat_absC_c
221         c_output_w = (\ f -> writeRealC f flat_absC_c)
222
223 #if OMIT_NATIVE_CODEGEN
224         ncg_output_d = error "*** GHC not built with a native-code generator ***"
225         ncg_output_w = ncg_output_d
226 #else
227         ncg_output_d = dumpRealAsm flat_absC_ncg ncg_uniqs
228         ncg_output_w = (\ f -> writeRealAsm f flat_absC_ncg ncg_uniqs)
229 #endif
230     in
231
232     dumpIfSet opt_D_dump_asm "Asm code" ncg_output_d    >>
233     doOutput opt_ProduceS ncg_output_w                  >>
234
235     dumpIfSet opt_D_dump_foreign "Foreign export header file" stub_h_output_d >>
236     outputHStub opt_ProduceExportHStubs stub_h_output_w >>
237
238     dumpIfSet opt_D_dump_foreign "Foreign export stubs" stub_c_output_d >>
239     outputCStub mod_name opt_ProduceExportCStubs stub_c_output_w        >>
240
241     dumpIfSet opt_D_dump_realC "Real C" c_output_d      >>
242     doOutput opt_ProduceC c_output_w                    >>
243
244     reportCompile (_UNPK_ mod_name) (showSDoc (ppSourceStats True rdr_module)) >>
245
246     ghcExit 0
247     } }
248   where
249     -------------------------------------------------------------
250     -- ****** help functions:
251
252     show_pass
253       = if opt_D_show_passes
254         then \ what -> hPutStr stderr ("*** "++what++":\n")
255         else \ what -> return ()
256
257     doOutput switch io_action
258       = case switch of
259           Nothing    -> return ()
260           Just fname ->
261             openFile fname WriteMode    >>= \ handle ->
262             io_action handle            >>
263             hClose handle
264
265     -- don't use doOutput for dumping the f. export stubs
266     -- since it is more than likely that the stubs file will
267     -- turn out to be empty, in which case no file should be created.
268     outputCStub mod_name switch "" = return ()
269     outputCStub mod_name switch doc_str
270       = case switch of
271           Nothing    -> return ()
272           Just fname -> writeFile fname ("#include \"Rts.h\"\n#include \"RtsAPI.h\"\n"++rest)
273             where
274              rest = "#include "++show ((_UNPK_ mod_name) ++ "_stub.h") ++ '\n':doc_str
275               
276     outputHStub switch "" = return ()
277     outputHStub switch doc_str
278       = case switch of
279           Nothing    -> return ()
280           Just fname -> writeFile fname ("#include \"Rts.h\"\n"++doc_str)
281
282 ppSourceStats short (HsModule name version exports imports fixities decls src_loc)
283  = (if short then hcat else vcat)
284         (map pp_val
285                [("ExportAll        ", export_all), -- 1 if no export list
286                 ("ExportDecls      ", export_ds),
287                 ("ExportModules    ", export_ms),
288                 ("Imports          ", import_no),
289                 ("  ImpQual        ", import_qual),
290                 ("  ImpAs          ", import_as),
291                 ("  ImpAll         ", import_all),
292                 ("  ImpPartial     ", import_partial),
293                 ("  ImpHiding      ", import_hiding),
294                 ("FixityDecls      ", fixity_ds),
295                 ("DefaultDecls     ", default_ds),
296                 ("TypeDecls        ", type_ds),
297                 ("DataDecls        ", data_ds),
298                 ("NewTypeDecls     ", newt_ds),
299                 ("DataConstrs      ", data_constrs),
300                 ("DataDerivings    ", data_derivs),
301                 ("ClassDecls       ", class_ds),
302                 ("ClassMethods     ", class_method_ds),
303                 ("DefaultMethods   ", default_method_ds),
304                 ("InstDecls        ", inst_ds),
305                 ("InstMethods      ", inst_method_ds),
306                 ("TypeSigs         ", bind_tys),
307                 ("ValBinds         ", val_bind_ds),
308                 ("FunBinds         ", fn_bind_ds),
309                 ("InlineMeths      ", method_inlines),
310                 ("InlineBinds      ", bind_inlines),
311 --              ("SpecialisedData  ", data_specs),
312 --              ("SpecialisedInsts ", inst_specs),
313                 ("SpecialisedMeths ", method_specs),
314                 ("SpecialisedBinds ", bind_specs)
315                ])
316   where
317     pp_val (str, 0) = empty
318     pp_val (str, n) 
319       | not short   = hcat [text str, int n]
320       | otherwise   = hcat [text (trim str), equals, int n, semi]
321     
322     trim ls     = takeWhile (not.isSpace) (dropWhile isSpace ls)
323
324     fixity_ds   = length fixities
325     type_decls  = [d | TyD d@(TySynonym _ _ _ _)    <- decls]
326     data_decls  = [d | TyD d@(TyData DataType _ _ _ _ _ _ _) <- decls]
327     newt_decls  = [d | TyD d@(TyData NewType  _ _ _ _ _ _ _) <- decls]
328     type_ds     = length type_decls
329     data_ds     = length data_decls
330     newt_ds     = length newt_decls
331     class_decls = [d | ClD d <- decls]
332     class_ds    = length class_decls
333     inst_decls  = [d | InstD d <- decls]
334     inst_ds     = length inst_decls
335     default_ds  = length [() | DefD _ <- decls]
336     val_decls   = [d | ValD d <- decls]
337
338     real_exports = case exports of { Nothing -> []; Just es -> es }
339     n_exports    = length real_exports
340     export_ms    = length [() | IEModuleContents _ <- real_exports]
341     export_ds    = n_exports - export_ms
342     export_all   = case exports of { Nothing -> 1; other -> 0 }
343
344     (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
345         = count_binds (foldr ThenBinds EmptyBinds val_decls)
346
347     (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
348         = foldr add6 (0,0,0,0,0,0) (map import_info imports)
349     (data_constrs, data_derivs)
350         = foldr add2 (0,0) (map data_info (newt_decls ++ data_decls))
351     (class_method_ds, default_method_ds)
352         = foldr add2 (0,0) (map class_info class_decls)
353     (inst_method_ds, method_specs, method_inlines)
354         = foldr add3 (0,0,0) (map inst_info inst_decls)
355
356
357     count_binds EmptyBinds        = (0,0,0,0,0)
358     count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
359     count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
360                                         ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
361
362     count_monobinds EmptyMonoBinds        = (0,0)
363     count_monobinds (AndMonoBinds b1 b2)  = count_monobinds b1 `add2` count_monobinds b2
364     count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
365     count_monobinds (PatMonoBind p r _)   = (0,1)
366     count_monobinds (FunMonoBind f _ m _) = (0,1)
367
368     count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
369
370     sig_info (Sig _ _ _)          = (1,0,0,0)
371     sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
372     sig_info (SpecSig _ _ _ _)    = (0,0,1,0)
373     sig_info (InlineSig _ _)      = (0,0,0,1)
374     sig_info _                    = (0,0,0,0)
375
376     import_info (ImportDecl _ qual _ as spec _)
377         = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
378     qual_info False  = 0
379     qual_info True   = 1
380     as_info Nothing  = 0
381     as_info (Just _) = 1
382     spec_info Nothing           = (0,0,0,1,0,0)
383     spec_info (Just (False, _)) = (0,0,0,0,1,0)
384     spec_info (Just (True, _))  = (0,0,0,0,0,1)
385
386     data_info (TyData _ _ _ _ constrs derivs _ _)
387         = (length constrs, case derivs of {Nothing -> 0; Just ds -> length ds})
388
389     class_info (ClassDecl _ _ _ meth_sigs def_meths _ _ _ _)
390         = case count_sigs meth_sigs of
391             (_,classops,_,_) ->
392                (classops, addpr (count_monobinds def_meths))
393
394     inst_info (InstDecl _ inst_meths inst_sigs _ _)
395         = case count_sigs inst_sigs of
396             (_,_,ss,is) ->
397                (addpr (count_monobinds inst_meths), ss, is)
398
399     addpr (x,y) = x+y
400     add1 x1 y1  = x1+y1
401     add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
402     add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
403     add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
404     add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
405     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)
406 \end{code}
407
408 \begin{code}
409 compiler_version :: String
410 compiler_version =
411      case (show opt_HiVersion) of
412         [x]      -> ['0','.',x]
413         ls@[x,y] -> "0." ++ ls
414         ls       -> go ls
415  where
416   -- 10232353 => 10232.53
417   go ls@[x,y] = '.':ls
418   go (x:xs)   = x:go xs
419
420 \end{code}
421
422 \begin{code}
423 reportCompile :: String -> String -> IO ()
424 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
425 reportCompile mod_name info
426   | not opt_ReportCompile = return ()
427   | otherwise = (do 
428       sock <- udpSocket 0
429       addr <- motherShip
430       sendTo sock (mod_name++ ';': compiler_version ++ ';': os ++ ';':arch ++ '\n':' ':info ++ "\n") addr
431       return ()) `catch` (\ _ -> return ())
432
433 motherShip :: IO SockAddr
434 motherShip = do
435   he <- getHostByName "laysan.dcs.gla.ac.uk"
436   case (hostAddresses he) of
437     []    -> fail (userError "No address!")
438     (x:_) -> return (SockAddrInet motherShipPort x)
439
440 --magick
441 motherShipPort :: PortNumber
442 motherShipPort = mkPortNumber 12345
443
444 -- creates a socket capable of sending datagrams,
445 -- binding it to a port
446 --  ( 0 => have the system pick next available port no.)
447 udpSocket :: Int -> IO Socket
448 udpSocket p = do
449   pr <- getProtocolNumber "udp"
450   s  <- socket AF_INET Datagram pr
451   bindSocket s (SockAddrInet (mkPortNumber p) iNADDR_ANY)
452   return s
453 #else
454 reportCompile _ _ = return ()
455 #endif
456
457 \end{code}