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