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