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