ab070951b69f1a309b0b31e31e1cc6a654231026
[ghc-hetmet.git] / ghc / compiler / main / DriverState.hs
1 -----------------------------------------------------------------------------
2 -- $Id: DriverState.hs,v 1.26 2001/02/01 11:47:53 simonmar Exp $
3 --
4 -- Settings for the driver
5 --
6 -- (c) The University of Glasgow 2000
7 --
8 -----------------------------------------------------------------------------
9
10 module DriverState where
11
12 #include "HsVersions.h"
13
14 import CmStaticInfo
15 import CmdLineOpts
16 import DriverUtil
17 import Util
18 import Config
19 import Exception
20 import IOExts
21 #ifdef mingw32_TARGET_OS
22 import TmpFiles ( newTempName )
23 import Directory ( removeFile )
24 #endif
25 import Panic
26
27 import List
28 import Char  
29 import Monad
30
31 -----------------------------------------------------------------------------
32 -- non-configured things
33
34 cHaskell1Version = "5" -- i.e., Haskell 98
35
36 -----------------------------------------------------------------------------
37 -- Global compilation flags
38
39 -- location of compiler-related files
40 GLOBAL_VAR(v_TopDir,  clibdir, String)
41
42 -- Cpp-related flags
43 v_Hs_source_cpp_opts = global
44         [ "-D__HASKELL1__="++cHaskell1Version
45         , "-D__GLASGOW_HASKELL__="++cProjectVersionInt                          
46         , "-D__HASKELL98__"
47         , "-D__CONCURRENT_HASKELL__"
48         ]
49 {-# NOINLINE v_Hs_source_cpp_opts #-}
50
51 -- Keep output from intermediate phases
52 GLOBAL_VAR(v_Keep_hi_diffs,             False,          Bool)
53 GLOBAL_VAR(v_Keep_hc_files,             False,          Bool)
54 GLOBAL_VAR(v_Keep_s_files,              False,          Bool)
55 GLOBAL_VAR(v_Keep_raw_s_files,          False,          Bool)
56 GLOBAL_VAR(v_Keep_tmp_files,            False,          Bool)
57
58 -- Misc
59 GLOBAL_VAR(v_Scale_sizes_by,            1.0,            Double)
60 GLOBAL_VAR(v_Dry_run,                   False,          Bool)
61 GLOBAL_VAR(v_Static,                    True,           Bool)
62 GLOBAL_VAR(v_NoHsMain,                  False,          Bool)
63 GLOBAL_VAR(v_Recomp,                    True,           Bool)
64 GLOBAL_VAR(v_Collect_ghc_timing,        False,          Bool)
65 GLOBAL_VAR(v_Do_asm_mangling,           True,           Bool)
66 GLOBAL_VAR(v_Excess_precision,          False,          Bool)
67
68 -----------------------------------------------------------------------------
69 -- Splitting object files (for libraries)
70
71 GLOBAL_VAR(v_Split_object_files,        False,          Bool)
72 GLOBAL_VAR(v_Split_prefix,              "",             String)
73 GLOBAL_VAR(v_N_split_files,             0,              Int)
74         
75 can_split :: Bool
76 can_split =  prefixMatch "i386"    cTARGETPLATFORM
77           || prefixMatch "alpha"   cTARGETPLATFORM
78           || prefixMatch "hppa"    cTARGETPLATFORM
79           || prefixMatch "m68k"    cTARGETPLATFORM
80           || prefixMatch "mips"    cTARGETPLATFORM
81           || prefixMatch "powerpc" cTARGETPLATFORM
82           || prefixMatch "rs6000"  cTARGETPLATFORM
83           || prefixMatch "sparc"   cTARGETPLATFORM
84
85 -----------------------------------------------------------------------------
86 -- Compiler output options
87
88 defaultHscLang
89   | cGhcWithNativeCodeGen == "YES" && 
90         (prefixMatch "i386" cTARGETPLATFORM ||
91          prefixMatch "sparc" cTARGETPLATFORM)   =  HscAsm
92   | otherwise                                   =  HscC
93
94 GLOBAL_VAR(v_Output_dir,  Nothing, Maybe String)
95 GLOBAL_VAR(v_Object_suf,  Nothing, Maybe String)
96 GLOBAL_VAR(v_Output_file, Nothing, Maybe String)
97 GLOBAL_VAR(v_Output_hi,   Nothing, Maybe String)
98
99 GLOBAL_VAR(v_Ld_inputs, [],      [String])
100
101 odir_ify :: String -> IO String
102 odir_ify f = do
103   odir_opt <- readIORef v_Output_dir
104   case odir_opt of
105         Nothing -> return f
106         Just d  -> return (newdir d f)
107
108 osuf_ify :: String -> IO String
109 osuf_ify f = do
110   osuf_opt <- readIORef v_Object_suf
111   case osuf_opt of
112         Nothing -> return f
113         Just s  -> return (newsuf s f)
114
115 -----------------------------------------------------------------------------
116 -- Hi Files
117
118 GLOBAL_VAR(v_Hi_on_stdout,      False,  Bool)
119 GLOBAL_VAR(v_Hi_suf,            "hi",   String)
120
121 -----------------------------------------------------------------------------
122 -- Warnings & sanity checking
123
124 -- Warning packages that are controlled by -W and -Wall.  The 'standard'
125 -- warnings that you get all the time are
126 --         
127 --         -fwarn-overlapping-patterns
128 --         -fwarn-missing-methods
129 --         -fwarn-missing-fields
130 --         -fwarn-deprecations
131 --         -fwarn-duplicate-exports
132 -- 
133 -- these are turned off by -Wnot.
134
135
136 standardWarnings  = [ "-fwarn-overlapping-patterns"
137                     , "-fwarn-missing-methods"
138                     , "-fwarn-missing-fields"
139                     , "-fwarn-deprecations"
140                     , "-fwarn-duplicate-exports"
141                     ]
142 minusWOpts        = standardWarnings ++ 
143                     [ "-fwarn-unused-binds"
144                     , "-fwarn-unused-matches"
145                     , "-fwarn-incomplete-patterns"
146                     , "-fwarn-unused-imports"
147                     ]
148 minusWallOpts     = minusWOpts ++
149                     [ "-fwarn-type-defaults"
150                     , "-fwarn-name-shadowing"
151                     , "-fwarn-missing-signatures"
152                     , "-fwarn-hi-shadowing"
153                     ]
154
155 data WarningState = W_default | W_ | W_all | W_not
156 GLOBAL_VAR(v_Warning_opt, W_default, WarningState)
157
158 -----------------------------------------------------------------------------
159 -- Compiler optimisation options
160
161 GLOBAL_VAR(v_OptLevel, 0, Int)
162
163 setOptLevel :: String -> IO ()
164 setOptLevel ""              = do { writeIORef v_OptLevel 1 }
165 setOptLevel "not"           = writeIORef v_OptLevel 0
166 setOptLevel [c] | isDigit c = do
167    let level = ord c - ord '0'
168    writeIORef v_OptLevel level
169 setOptLevel s = unknownFlagErr ("-O"++s)
170
171 GLOBAL_VAR(v_minus_o2_for_C,            False, Bool)
172 GLOBAL_VAR(v_MaxSimplifierIterations,   4,     Int)
173 GLOBAL_VAR(v_StgStats,                  False, Bool)
174 GLOBAL_VAR(v_UsageSPInf,                False, Bool)  -- Off by default
175 GLOBAL_VAR(v_Strictness,                True,  Bool)
176 GLOBAL_VAR(v_CPR,                       True,  Bool)
177 GLOBAL_VAR(v_CSE,                       True,  Bool)
178
179 -- these are the static flags you get without -O.
180 hsc_minusNoO_flags =
181        [ 
182         "-fignore-interface-pragmas",
183         "-fomit-interface-pragmas",
184         "-flet-no-escape"
185         ]
186
187 -- these are the static flags you get when -O is on.
188 hsc_minusO_flags =
189   [ 
190         "-ffoldr-build-on",
191         "-fdo-eta-reduction",
192         "-fdo-lambda-eta-expansion",
193         "-fcase-of-case",
194         "-fcase-merge",
195         "-flet-to-case",
196         "-flet-no-escape"
197    ]
198
199 hsc_minusO2_flags = hsc_minusO_flags    -- for now
200
201 getStaticOptimisationFlags 0 = hsc_minusNoO_flags
202 getStaticOptimisationFlags 1 = hsc_minusO_flags
203 getStaticOptimisationFlags n = hsc_minusO2_flags
204
205 buildCoreToDo :: IO [CoreToDo]
206 buildCoreToDo = do
207    opt_level  <- readIORef v_OptLevel
208    max_iter   <- readIORef v_MaxSimplifierIterations
209    usageSP    <- readIORef v_UsageSPInf
210    strictness <- readIORef v_Strictness
211    cpr        <- readIORef v_CPR
212    cse        <- readIORef v_CSE
213
214    if opt_level == 0 then return
215       [
216         CoreDoSimplify (isAmongSimpl [
217             MaxSimplifierIterations max_iter
218         ])
219       ]
220
221     else {- opt_level >= 1 -} return [ 
222
223         -- initial simplify: mk specialiser happy: minimum effort please
224         CoreDoSimplify (isAmongSimpl [
225             SimplInlinePhase 0,
226                         -- Don't inline anything till full laziness has bitten
227                         -- In particular, inlining wrappers inhibits floating
228                         -- e.g. ...(case f x of ...)...
229                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
230                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
231                         -- and now the redex (f x) isn't floatable any more
232             DontApplyRules,
233                         -- Similarly, don't apply any rules until after full 
234                         -- laziness.  Notably, list fusion can prevent floating.
235             NoCaseOfCase,
236                         -- Don't do case-of-case transformations.
237                         -- This makes full laziness work better
238             MaxSimplifierIterations max_iter
239         ]),
240
241         -- Specialisation is best done before full laziness
242         -- so that overloaded functions have all their dictionary lambdas manifest
243         CoreDoSpecialising,
244
245         CoreDoFloatOutwards False{-not full-},
246         CoreDoFloatInwards,
247
248         CoreDoSimplify (isAmongSimpl [
249            SimplInlinePhase 1,
250                 -- Want to run with inline phase 1 after the specialiser to give
251                 -- maximum chance for fusion to work before we inline build/augment
252                 -- in phase 2.  This made a difference in 'ansi' where an 
253                 -- overloaded function wasn't inlined till too late.
254            MaxSimplifierIterations max_iter
255         ]),
256
257         -- infer usage information here in case we need it later.
258         -- (add more of these where you need them --KSW 1999-04)
259         if usageSP then CoreDoUSPInf else CoreDoNothing,
260
261         CoreDoSimplify (isAmongSimpl [
262                 -- Need inline-phase2 here so that build/augment get 
263                 -- inlined.  I found that spectral/hartel/genfft lost some useful
264                 -- strictness in the function sumcode' if augment is not inlined
265                 -- before strictness analysis runs
266            SimplInlinePhase 2,
267            MaxSimplifierIterations max_iter
268         ]),
269
270         CoreDoSimplify (isAmongSimpl [
271            MaxSimplifierIterations 2
272                 -- No -finline-phase: allow all Ids to be inlined now
273                 -- This gets foldr inlined before strictness analysis
274         ]),
275
276         if strictness then CoreDoStrictness else CoreDoNothing,
277         if cpr        then CoreDoCPResult   else CoreDoNothing,
278         CoreDoWorkerWrapper,
279         CoreDoGlomBinds,
280
281         CoreDoSimplify (isAmongSimpl [
282            MaxSimplifierIterations max_iter
283                 -- No -finline-phase: allow all Ids to be inlined now
284         ]),
285
286         CoreDoFloatOutwards False{-not full-},
287                 -- nofib/spectral/hartel/wang doubles in speed if you
288                 -- do full laziness late in the day.  It only happens
289                 -- after fusion and other stuff, so the early pass doesn't
290                 -- catch it.  For the record, the redex is 
291                 --        f_el22 (f_el21 r_midblock)
292
293
294 -- Leave out lambda lifting for now
295 --        "-fsimplify", -- Tidy up results of full laziness
296 --          "[", 
297 --                "-fmax-simplifier-iterations2",
298 --          "]",
299 --        "-ffloat-outwards-full",      
300
301         -- We want CSE to follow the final full-laziness pass, because it may
302         -- succeed in commoning up things floated out by full laziness.
303         -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
304
305         if cse then CoreCSE else CoreDoNothing,
306
307         CoreDoFloatInwards,
308
309 -- Case-liberation for -O2.  This should be after
310 -- strictness analysis and the simplification which follows it.
311
312         if opt_level >= 2 then
313            CoreLiberateCase
314         else
315            CoreDoNothing,
316
317         -- Final clean-up simplification:
318         CoreDoSimplify (isAmongSimpl [
319           MaxSimplifierIterations max_iter
320                 -- No -finline-phase: allow all Ids to be inlined now
321         ])
322      ]
323
324 buildStgToDo :: IO [ StgToDo ]
325 buildStgToDo = do
326   stg_stats <- readIORef v_StgStats
327   let flags1 | stg_stats = [ D_stg_stats ]
328              | otherwise = [ ]
329
330         -- STG passes
331   ways_ <- readIORef v_Ways
332   let flags2 | WayProf `elem` ways_ = StgDoMassageForProfiling : flags1
333              | otherwise            = flags1
334
335   return flags2
336
337 -----------------------------------------------------------------------------
338 -- Paths & Libraries
339
340 split_marker = ':'   -- not configurable (ToDo)
341
342 v_Import_paths, v_Include_paths, v_Library_paths :: IORef [String]
343 GLOBAL_VAR(v_Import_paths,  ["."], [String])
344 GLOBAL_VAR(v_Include_paths, ["."], [String])
345 GLOBAL_VAR(v_Library_paths, [],  [String])
346
347 GLOBAL_VAR(v_Cmdline_libraries,   [], [String])
348
349 addToDirList :: IORef [String] -> String -> IO ()
350 addToDirList ref path
351   = do paths <- readIORef ref
352        writeIORef ref (paths ++ split split_marker path)
353
354 -----------------------------------------------------------------------------
355 -- Packages
356
357 GLOBAL_VAR(v_Path_package_config, error "path_package_config", String)
358
359 -- package list is maintained in dependency order
360 GLOBAL_VAR(v_Packages, ("std":"rts":"gmp":[]), [String])
361
362 addPackage :: String -> IO ()
363 addPackage package
364   = do pkg_details <- readIORef v_Package_details
365        case lookupPkg package pkg_details of
366           Nothing -> throwDyn (OtherError ("unknown package name: " ++ package))
367           Just details -> do
368             ps <- readIORef v_Packages
369             unless (package `elem` ps) $ do
370                 mapM_ addPackage (package_deps details)
371                 ps <- readIORef v_Packages
372                 writeIORef v_Packages (package:ps)
373
374 getPackageImportPath   :: IO [String]
375 getPackageImportPath = do
376   ps <- getPackageInfo
377   return (nub (concat (map import_dirs ps)))
378
379 getPackageIncludePath   :: IO [String]
380 getPackageIncludePath = do
381   ps <- getPackageInfo
382   return (nub (filter (not.null) (concatMap include_dirs ps)))
383
384         -- includes are in reverse dependency order (i.e. rts first)
385 getPackageCIncludes   :: IO [String]
386 getPackageCIncludes = do
387   ps <- getPackageInfo
388   return (reverse (nub (filter (not.null) (concatMap c_includes ps))))
389
390 getPackageLibraryPath  :: IO [String]
391 getPackageLibraryPath = do
392   ps <- getPackageInfo
393   return (nub (concat (map library_dirs ps)))
394
395 getPackageLibraries    :: IO [String]
396 getPackageLibraries = do
397   ps <- getPackageInfo
398   tag <- readIORef v_Build_tag
399   let suffix = if null tag then "" else '_':tag
400   return (concat (
401         map (\p -> map (++suffix) (hs_libraries p) ++ extra_libraries p) ps
402      ))
403
404 getPackageExtraGhcOpts :: IO [String]
405 getPackageExtraGhcOpts = do
406   ps <- getPackageInfo
407   return (concatMap extra_ghc_opts ps)
408
409 getPackageExtraCcOpts  :: IO [String]
410 getPackageExtraCcOpts = do
411   ps <- getPackageInfo
412   return (concatMap extra_cc_opts ps)
413
414 getPackageExtraLdOpts  :: IO [String]
415 getPackageExtraLdOpts = do
416   ps <- getPackageInfo
417   return (concatMap extra_ld_opts ps)
418
419 getPackageInfo :: IO [Package]
420 getPackageInfo = do
421   ps <- readIORef v_Packages
422   getPackageDetails ps
423
424 getPackageDetails :: [String] -> IO [Package]
425 getPackageDetails ps = do
426   pkg_details <- readIORef v_Package_details
427   return [ pkg | p <- ps, Just pkg <- [ lookupPkg p pkg_details ] ]
428
429 GLOBAL_VAR(v_Package_details, (error "package_details"), [Package])
430
431 lookupPkg :: String -> [Package] -> Maybe Package
432 lookupPkg nm ps
433    = case [p | p <- ps, name p == nm] of
434         []    -> Nothing
435         (p:_) -> Just p
436 -----------------------------------------------------------------------------
437 -- Ways
438
439 -- The central concept of a "way" is that all objects in a given
440 -- program must be compiled in the same "way".  Certain options change
441 -- parameters of the virtual machine, eg. profiling adds an extra word
442 -- to the object header, so profiling objects cannot be linked with
443 -- non-profiling objects.
444
445 -- After parsing the command-line options, we determine which "way" we
446 -- are building - this might be a combination way, eg. profiling+ticky-ticky.
447
448 -- We then find the "build-tag" associated with this way, and this
449 -- becomes the suffix used to find .hi files and libraries used in
450 -- this compilation.
451
452 GLOBAL_VAR(v_Build_tag, "", String)
453
454 data WayName
455   = WayProf
456   | WayUnreg
457   | WayTicky
458   | WayPar
459   | WayGran
460   | WaySMP
461   | WayDebug
462   | WayUser_a
463   | WayUser_b
464   | WayUser_c
465   | WayUser_d
466   | WayUser_e
467   | WayUser_f
468   | WayUser_g
469   | WayUser_h
470   | WayUser_i
471   | WayUser_j
472   | WayUser_k
473   | WayUser_l
474   | WayUser_m
475   | WayUser_n
476   | WayUser_o
477   | WayUser_A
478   | WayUser_B
479   deriving (Eq,Ord)
480
481 GLOBAL_VAR(v_Ways, [] ,[WayName])
482
483 allowed_combination way = way `elem` combs
484   where  -- the sub-lists must be ordered according to WayName, 
485          -- because findBuildTag sorts them
486     combs                = [ [WayProf,WayUnreg], [WayProf,WaySMP] ]
487
488 findBuildTag :: IO [String]  -- new options
489 findBuildTag = do
490   way_names <- readIORef v_Ways
491   case sort way_names of
492      []  -> do  writeIORef v_Build_tag ""
493                 return []
494
495      [w] -> do let details = lkupWay w
496                writeIORef v_Build_tag (wayTag details)
497                return (wayOpts details)
498
499      ws  -> if not (allowed_combination ws)
500                 then throwDyn (OtherError $
501                                 "combination not supported: "  ++
502                                 foldr1 (\a b -> a ++ '/':b) 
503                                 (map (wayName . lkupWay) ws))
504                 else let stuff = map lkupWay ws
505                          tag   = concat (map wayTag stuff)
506                          flags = map wayOpts stuff
507                      in do
508                      writeIORef v_Build_tag tag
509                      return (concat flags)
510
511 lkupWay w = 
512    case lookup w way_details of
513         Nothing -> error "findBuildTag"
514         Just details -> details
515
516 data Way = Way {
517   wayTag   :: String,
518   wayName  :: String,
519   wayOpts  :: [String]
520   }
521
522 way_details :: [ (WayName, Way) ]
523 way_details =
524   [ (WayProf, Way  "p" "Profiling"  
525         [ "-fscc-profiling"
526         , "-DPROFILING"
527         , "-optc-DPROFILING"
528         , "-fvia-C" ]),
529
530     (WayTicky, Way  "t" "Ticky-ticky Profiling"  
531         [ "-fticky-ticky"
532         , "-DTICKY_TICKY"
533         , "-optc-DTICKY_TICKY"
534         , "-fvia-C" ]),
535
536     (WayUnreg, Way  "u" "Unregisterised" 
537         unregFlags ),
538
539     (WayPar, Way  "mp" "Parallel" 
540         [ "-fparallel"
541         , "-D__PARALLEL_HASKELL__"
542         , "-optc-DPAR"
543         , "-package concurrent"
544         , "-fvia-C" ]),
545
546     (WayGran, Way  "mg" "Gransim" 
547         [ "-fgransim"
548         , "-D__GRANSIM__"
549         , "-optc-DGRAN"
550         , "-package concurrent"
551         , "-fvia-C" ]),
552
553     (WaySMP, Way  "s" "SMP"
554         [ "-fsmp"
555         , "-optc-pthread"
556         , "-optl-pthread"
557         , "-optc-DSMP"
558         , "-fvia-C" ]),
559
560     (WayUser_a,  Way  "a"  "User way 'a'"  ["$WAY_a_REAL_OPTS"]),       
561     (WayUser_b,  Way  "b"  "User way 'b'"  ["$WAY_b_REAL_OPTS"]),       
562     (WayUser_c,  Way  "c"  "User way 'c'"  ["$WAY_c_REAL_OPTS"]),       
563     (WayUser_d,  Way  "d"  "User way 'd'"  ["$WAY_d_REAL_OPTS"]),       
564     (WayUser_e,  Way  "e"  "User way 'e'"  ["$WAY_e_REAL_OPTS"]),       
565     (WayUser_f,  Way  "f"  "User way 'f'"  ["$WAY_f_REAL_OPTS"]),       
566     (WayUser_g,  Way  "g"  "User way 'g'"  ["$WAY_g_REAL_OPTS"]),       
567     (WayUser_h,  Way  "h"  "User way 'h'"  ["$WAY_h_REAL_OPTS"]),       
568     (WayUser_i,  Way  "i"  "User way 'i'"  ["$WAY_i_REAL_OPTS"]),       
569     (WayUser_j,  Way  "j"  "User way 'j'"  ["$WAY_j_REAL_OPTS"]),       
570     (WayUser_k,  Way  "k"  "User way 'k'"  ["$WAY_k_REAL_OPTS"]),       
571     (WayUser_l,  Way  "l"  "User way 'l'"  ["$WAY_l_REAL_OPTS"]),       
572     (WayUser_m,  Way  "m"  "User way 'm'"  ["$WAY_m_REAL_OPTS"]),       
573     (WayUser_n,  Way  "n"  "User way 'n'"  ["$WAY_n_REAL_OPTS"]),       
574     (WayUser_o,  Way  "o"  "User way 'o'"  ["$WAY_o_REAL_OPTS"]),       
575     (WayUser_A,  Way  "A"  "User way 'A'"  ["$WAY_A_REAL_OPTS"]),       
576     (WayUser_B,  Way  "B"  "User way 'B'"  ["$WAY_B_REAL_OPTS"]) 
577   ]
578
579 unregFlags = 
580    [ "-optc-DNO_REGS"
581    , "-optc-DUSE_MINIINTERPRETER"
582    , "-fno-asm-mangling"
583    , "-funregisterised"
584    , "-fvia-C" ]
585
586 -----------------------------------------------------------------------------
587 -- Programs for particular phases
588
589 GLOBAL_VAR(v_Pgm_L,   error "pgm_L", String)
590 GLOBAL_VAR(v_Pgm_P,   cRAWCPP,       String)
591 GLOBAL_VAR(v_Pgm_c,   cGCC,          String)
592 GLOBAL_VAR(v_Pgm_m,   error "pgm_m", String)
593 GLOBAL_VAR(v_Pgm_s,   error "pgm_s", String)
594 GLOBAL_VAR(v_Pgm_a,   cGCC,          String)
595 GLOBAL_VAR(v_Pgm_l,   cGCC,          String)
596 GLOBAL_VAR(v_Pgm_dll, cMkDLL,        String)
597
598 GLOBAL_VAR(v_Opt_dep,    [], [String])
599 GLOBAL_VAR(v_Anti_opt_C, [], [String])
600 GLOBAL_VAR(v_Opt_C,      [], [String])
601 GLOBAL_VAR(v_Opt_l,      [], [String])
602 GLOBAL_VAR(v_Opt_dll,    [], [String])
603
604 getStaticOpts :: IORef [String] -> IO [String]
605 getStaticOpts ref = readIORef ref >>= return . reverse