2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
7 module Main ( main ) where
9 #include "HsVersions.h"
11 import IO ( hPutStr, stderr )
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 )
21 import Rename ( renameModule )
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 )
36 import Module ( ModuleName, moduleNameUserString )
38 import ErrUtils ( ghcExit, doIfSet, dumpIfSet )
39 import UniqSupply ( mkSplitUniqSupply )
42 import Char ( isSpace )
43 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
46 import IOExts ( unsafePerformIO )
47 import NativeInfo ( os, arch )
49 import StgInterp ( runStgI )
54 main = stderr `seq` -- Bug fix. Sigh
60 parseModule :: IO (ModuleName, RdrNameHsModule)
62 buf <- hGetStringBuffer True{-expand tabs-} (unpackFS src_filename)
63 case parse buf PState{ bol = 0#, atbol = 1#,
64 context = [], glasgow_exts = glaexts,
65 loc = mkSrcLoc src_filename 1 } of
70 return (error "parseModule") -- just to get the types right
72 POk _ m@(HsModule mod _ _ _ _ _ _) ->
75 glaexts | opt_GlasgowExts = 1#
80 doIt :: ([CoreToDo], [StgToDo]) -> IO ()
82 doIt (core_cmds, stg_cmds)
84 (hPutStr stderr "Glasgow Haskell Compiler, Version " >>
85 hPutStr stderr compiler_version >>
86 hPutStr stderr ", for Haskell 98, compiled by GHC version " >>
87 hPutStr stderr booter_version >>
88 hPutStr stderr "\n") >>
90 -------------------------- Reader ----------------
93 parseModule >>= \ (mod_name, rdr_module) ->
95 dumpIfSet opt_D_dump_parsed "Parser" (ppr rdr_module) >>
97 dumpIfSet opt_D_source_stats "Source Statistics"
98 (ppSourceStats False rdr_module) >>
100 -- UniqueSupplies for later use (these are the only lower case uniques)
101 mkSplitUniqSupply 'r' >>= \ rn_uniqs -> -- renamer
102 mkSplitUniqSupply 'a' >>= \ tc_uniqs -> -- typechecker
103 mkSplitUniqSupply 'd' >>= \ ds_uniqs -> -- desugarer
104 mkSplitUniqSupply 'r' >>= \ ru_uniqs -> -- rules
105 mkSplitUniqSupply 'c' >>= \ c2s_uniqs -> -- core-to-stg
106 mkSplitUniqSupply 'u' >>= \ tidy_uniqs -> -- tidy up
107 mkSplitUniqSupply 'g' >>= \ st_uniqs -> -- stg-to-stg passes
108 mkSplitUniqSupply 'n' >>= \ ncg_uniqs -> -- native-code generator
110 -------------------------- Rename ----------------
111 show_pass "Renamer" >>
114 renameModule rn_uniqs rdr_module >>= \ maybe_rn_stuff ->
115 case maybe_rn_stuff of {
116 Nothing -> -- Hurrah! Renamer reckons that there's no need to
118 reportCompile mod_name "Compilation NOT required!" >>
121 Just (this_mod, rn_mod,
122 old_iface, new_iface,
123 rn_name_supply, fixity_env,
125 -- Oh well, we've got to recompile for real
128 -------------------------- Typechecking ----------------
129 show_pass "TypeCheck" >>
131 typecheckModule tc_uniqs rn_name_supply
132 fixity_env rn_mod >>= \ maybe_tc_stuff ->
133 case maybe_tc_stuff of {
134 Nothing -> ghcExit 1; -- Type checker failed
136 Just (tc_results@(TcResults {tc_tycons = local_tycons,
137 tc_classes = local_classes,
138 tc_insts = inst_info })) ->
141 -------------------------- Desugaring ----------------
143 deSugar this_mod ds_uniqs tc_results >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
146 -------------------------- Main Core-language transformations ----------------
148 core2core core_cmds desugared rules >>= \ (simplified, orphan_rules) ->
150 -- Do the final tidy-up
151 tidyCorePgm tidy_uniqs this_mod
152 simplified orphan_rules >>= \ (tidy_binds, tidy_orphan_rules) ->
154 -- Run the occurrence analyser one last time, so that
155 -- dead binders get dead-binder info. This is exploited by
156 -- code generators to avoid spitting out redundant bindings.
157 -- The occurrence-zapping in Simplify.simplCaseBinder means
158 -- that the Simplifier nukes useful dead-var stuff especially
160 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
162 coreBindsSize occ_anal_tidy_binds `seq`
163 -- TEMP: the above call zaps some space usage allocated by the
164 -- simplifier, which for reasons I don't understand, persists
165 -- thoroughout code generation
169 -------------------------- Convert to STG code -------------------------------
170 show_pass "Core2Stg" >>
173 stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
176 -------------------------- Simplify STG code -------------------------------
177 show_pass "Stg2Stg" >>
179 stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
182 runStgI local_tycons local_classes
183 (map fst stg_binds2) >>= \ i_result ->
184 putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
188 -------------------------- Interface file -------------------------------
189 -- Dump instance decls and type signatures into the interface file
192 final_ids = collectFinalStgBinders (map fst stg_binds2)
194 writeIface this_mod old_iface new_iface
195 local_tycons local_classes inst_info
196 final_ids occ_anal_tidy_binds tidy_orphan_rules >>
199 -------------------------- Code generation -------------------------------
200 show_pass "CodeGen" >>
202 codeGen this_mod imported_modules
205 local_tycons local_classes
206 stg_binds2 >>= \ abstractC ->
209 -------------------------- Code output -------------------------------
210 show_pass "CodeOutput" >>
212 codeOutput this_mod local_tycons local_classes
213 occ_anal_tidy_binds stg_binds2
214 c_code h_code abstractC
218 -------------------------- Final report -------------------------------
219 reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
227 -------------------------------------------------------------
228 -- ****** help functions:
231 = if opt_D_show_passes
232 then \ what -> hPutStr stderr ("*** "++what++":\n")
233 else \ what -> return ()
235 ppSourceStats short (HsModule name version exports imports decls _ src_loc)
236 = (if short then hcat else vcat)
238 [("ExportAll ", export_all), -- 1 if no export list
239 ("ExportDecls ", export_ds),
240 ("ExportModules ", export_ms),
241 ("Imports ", import_no),
242 (" ImpQual ", import_qual),
243 (" ImpAs ", import_as),
244 (" ImpAll ", import_all),
245 (" ImpPartial ", import_partial),
246 (" ImpHiding ", import_hiding),
247 ("FixityDecls ", fixity_ds),
248 ("DefaultDecls ", default_ds),
249 ("TypeDecls ", type_ds),
250 ("DataDecls ", data_ds),
251 ("NewTypeDecls ", newt_ds),
252 ("DataConstrs ", data_constrs),
253 ("DataDerivings ", data_derivs),
254 ("ClassDecls ", class_ds),
255 ("ClassMethods ", class_method_ds),
256 ("DefaultMethods ", default_method_ds),
257 ("InstDecls ", inst_ds),
258 ("InstMethods ", inst_method_ds),
259 ("TypeSigs ", bind_tys),
260 ("ValBinds ", val_bind_ds),
261 ("FunBinds ", fn_bind_ds),
262 ("InlineMeths ", method_inlines),
263 ("InlineBinds ", bind_inlines),
264 -- ("SpecialisedData ", data_specs),
265 -- ("SpecialisedInsts ", inst_specs),
266 ("SpecialisedMeths ", method_specs),
267 ("SpecialisedBinds ", bind_specs)
270 pp_val (str, 0) = empty
272 | not short = hcat [text str, int n]
273 | otherwise = hcat [text (trim str), equals, int n, semi]
275 trim ls = takeWhile (not.isSpace) (dropWhile isSpace ls)
277 fixity_ds = length [() | FixD d <- decls]
278 -- NB: this omits fixity decls on local bindings and
279 -- in class decls. ToDo
281 tycl_decls = [d | TyClD d <- decls]
282 (class_ds, data_ds, newt_ds, type_ds) = countTyClDecls tycl_decls
284 inst_decls = [d | InstD d <- decls]
285 inst_ds = length inst_decls
286 default_ds = length [() | DefD _ <- decls]
287 val_decls = [d | ValD d <- decls]
289 real_exports = case exports of { Nothing -> []; Just es -> es }
290 n_exports = length real_exports
291 export_ms = length [() | IEModuleContents _ <- real_exports]
292 export_ds = n_exports - export_ms
293 export_all = case exports of { Nothing -> 1; other -> 0 }
295 (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
296 = count_binds (foldr ThenBinds EmptyBinds val_decls)
298 (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
299 = foldr add6 (0,0,0,0,0,0) (map import_info imports)
300 (data_constrs, data_derivs)
301 = foldr add2 (0,0) (map data_info tycl_decls)
302 (class_method_ds, default_method_ds)
303 = foldr add2 (0,0) (map class_info tycl_decls)
304 (inst_method_ds, method_specs, method_inlines)
305 = foldr add3 (0,0,0) (map inst_info inst_decls)
308 count_binds EmptyBinds = (0,0,0,0,0)
309 count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
310 count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
311 ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
313 count_monobinds EmptyMonoBinds = (0,0)
314 count_monobinds (AndMonoBinds b1 b2) = count_monobinds b1 `add2` count_monobinds b2
315 count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
316 count_monobinds (PatMonoBind p r _) = (0,1)
317 count_monobinds (FunMonoBind f _ m _) = (0,1)
319 count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
321 sig_info (Sig _ _ _) = (1,0,0,0)
322 sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
323 sig_info (SpecSig _ _ _) = (0,0,1,0)
324 sig_info (InlineSig _ _ _) = (0,0,0,1)
325 sig_info (NoInlineSig _ _ _) = (0,0,0,1)
326 sig_info _ = (0,0,0,0)
328 import_info (ImportDecl _ _ qual as spec _)
329 = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
334 spec_info Nothing = (0,0,0,1,0,0)
335 spec_info (Just (False, _)) = (0,0,0,0,1,0)
336 spec_info (Just (True, _)) = (0,0,0,0,0,1)
338 data_info (TyData _ _ _ _ _ nconstrs derivs _ _ _ _)
339 = (nconstrs, case derivs of {Nothing -> 0; Just ds -> length ds})
340 data_info other = (0,0)
342 class_info (ClassDecl _ _ _ _ meth_sigs def_meths _ _ _ )
343 = case count_sigs meth_sigs of
345 (classops, addpr (count_monobinds def_meths))
346 class_info other = (0,0)
348 inst_info (InstDecl _ inst_meths inst_sigs _ _)
349 = case count_sigs inst_sigs of
351 (addpr (count_monobinds inst_meths), ss, is)
353 addpr :: (Int,Int) -> Int
354 add1 :: Int -> Int -> Int
355 add2 :: (Int,Int) -> (Int,Int) -> (Int, Int)
356 add3 :: (Int,Int,Int) -> (Int,Int,Int) -> (Int, Int, Int)
357 add4 :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> (Int, Int, Int, Int)
358 add5 :: (Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int)
359 add6 :: (Int,Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int, Int)
363 add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
364 add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
365 add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
366 add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
367 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)
371 compiler_version :: String
373 case (show opt_HiVersion) of
375 ls@[x,y] -> "0." ++ ls
378 -- 10232353 => 10232.53
384 \ __GLASGOW_HASKELL__" of
390 reportCompile :: ModuleName -> String -> IO ()
391 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
392 reportCompile mod_name info
393 | not opt_ReportCompile = return ()
397 sendTo sock (moduleNameUserString mod_name ++ ';': compiler_version ++
398 ';': os ++ ';':arch ++ '\n':' ':info ++ "\n") addr
399 return ()) `catch` (\ _ -> return ())
401 motherShip :: IO SockAddr
403 he <- getHostByName "laysan.dcs.gla.ac.uk"
404 case (hostAddresses he) of
405 [] -> IOERROR (userError "No address!")
406 (x:_) -> return (SockAddrInet motherShipPort x)
409 motherShipPort :: PortNumber
410 motherShipPort = mkPortNumber 12345
412 -- creates a socket capable of sending datagrams,
413 -- binding it to a port
414 -- ( 0 => have the system pick next available port no.)
415 udpSocket :: Int -> IO Socket
417 pr <- getProtocolNumber "udp"
418 s <- socket AF_INET Datagram pr
419 bindSocket s (SockAddrInet (mkPortNumber p) iNADDR_ANY)
422 reportCompile _ _ = return ()