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