[project @ 2000-11-14 16:28:38 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / DriverState.hs
1 -----------------------------------------------------------------------------
2 -- $Id: DriverState.hs,v 1.13 2000/11/14 16:28:38 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
26 import System
27 import IO
28 import List
29 import Char  
30 import Monad
31
32 -----------------------------------------------------------------------------
33 -- Driver state
34
35 -- certain flags can be specified on a per-file basis, in an OPTIONS
36 -- pragma at the beginning of the source file.  This means that when
37 -- compiling mulitple files, we have to restore the global option
38 -- settings before compiling a new file.  
39 --
40 -- The DriverState record contains the per-file-mutable state.
41
42 data DriverState = DriverState {
43
44         -- are we runing cpp on this file?
45         cpp_flag                :: Bool,
46
47         -- misc
48         stolen_x86_regs         :: Int,
49         cmdline_hc_includes     :: [String],
50
51         -- options for a particular phase
52         opt_L                   :: [String],
53         opt_P                   :: [String],
54         opt_c                   :: [String],
55         opt_a                   :: [String],
56         opt_m                   :: [String]
57    }
58
59 initDriverState = DriverState {
60         cpp_flag                = False,
61         stolen_x86_regs         = 4,
62         cmdline_hc_includes     = [],
63         opt_L                   = [],
64         opt_P                   = [],
65         opt_c                   = [],
66         opt_a                   = [],
67         opt_m                   = [],
68    }
69         
70 GLOBAL_VAR(v_Driver_state, initDriverState, DriverState)
71
72 readState :: (DriverState -> a) -> IO a
73 readState f = readIORef v_Driver_state >>= return . f
74
75 updateState :: (DriverState -> DriverState) -> IO ()
76 updateState f = readIORef v_Driver_state >>= writeIORef v_Driver_state . f
77
78 addOpt_L     a = updateState (\s -> s{opt_L      =  a : opt_L      s})
79 addOpt_P     a = updateState (\s -> s{opt_P      =  a : opt_P      s})
80 addOpt_c     a = updateState (\s -> s{opt_c      =  a : opt_c      s})
81 addOpt_a     a = updateState (\s -> s{opt_a      =  a : opt_a      s})
82 addOpt_m     a = updateState (\s -> s{opt_m      =  a : opt_m      s})
83
84 addCmdlineHCInclude a = 
85    updateState (\s -> s{cmdline_hc_includes =  a : cmdline_hc_includes s})
86
87         -- we add to the options from the front, so we need to reverse the list
88 getOpts :: (DriverState -> [a]) -> IO [a]
89 getOpts opts = readState opts >>= return . reverse
90
91 -----------------------------------------------------------------------------
92 -- non-configured things
93
94 cHaskell1Version = "5" -- i.e., Haskell 98
95
96 -----------------------------------------------------------------------------
97 -- Global compilation flags
98
99 -- location of compiler-related files
100 GLOBAL_VAR(v_TopDir,  clibdir, String)
101 GLOBAL_VAR(v_Inplace, False,   Bool)
102
103 -- Cpp-related flags
104 v_Hs_source_cpp_opts = global
105         [ "-D__HASKELL1__="++cHaskell1Version
106         , "-D__GLASGOW_HASKELL__="++cProjectVersionInt                          
107         , "-D__HASKELL98__"
108         , "-D__CONCURRENT_HASKELL__"
109         ]
110 {-# NOINLINE v_Hs_source_cpp_opts #-}
111
112 -- Verbose
113 GLOBAL_VAR(v_Verbose, False, Bool)
114 is_verbose = do v <- readIORef v_Verbose; if v then return "-v" else return ""
115
116 -- Keep output from intermediate phases
117 GLOBAL_VAR(v_Keep_hi_diffs,             False,          Bool)
118 GLOBAL_VAR(v_Keep_hc_files,             False,          Bool)
119 GLOBAL_VAR(v_Keep_s_files,              False,          Bool)
120 GLOBAL_VAR(v_Keep_raw_s_files,          False,          Bool)
121 GLOBAL_VAR(v_Keep_tmp_files,            False,          Bool)
122
123 -- Misc
124 GLOBAL_VAR(v_Scale_sizes_by,            1.0,            Double)
125 GLOBAL_VAR(v_Dry_run,                   False,          Bool)
126 #if !defined(HAVE_WIN32_DLL_SUPPORT) || defined(DONT_WANT_WIN32_DLL_SUPPORT)
127 GLOBAL_VAR(v_Static,                    True,           Bool)
128 #else
129 GLOBAL_VAR(v_Static,                    False,          Bool)
130 #endif
131 GLOBAL_VAR(v_NoHsMain,                  False,          Bool)
132 GLOBAL_VAR(v_Recomp,                    True,           Bool)
133 GLOBAL_VAR(v_Collect_ghc_timing,        False,          Bool)
134 GLOBAL_VAR(v_Do_asm_mangling,           True,           Bool)
135 GLOBAL_VAR(v_Excess_precision,          False,          Bool)
136
137 -----------------------------------------------------------------------------
138 -- Splitting object files (for libraries)
139
140 GLOBAL_VAR(v_Split_object_files,        False,          Bool)
141 GLOBAL_VAR(v_Split_prefix,              "",             String)
142 GLOBAL_VAR(v_N_split_files,             0,              Int)
143         
144 can_split :: Bool
145 can_split =  prefixMatch "i386" cTARGETPLATFORM
146           || prefixMatch "alpha" cTARGETPLATFORM
147           || prefixMatch "hppa" cTARGETPLATFORM
148           || prefixMatch "m68k" cTARGETPLATFORM
149           || prefixMatch "mips" cTARGETPLATFORM
150           || prefixMatch "powerpc" cTARGETPLATFORM
151           || prefixMatch "rs6000" cTARGETPLATFORM
152           || prefixMatch "sparc" cTARGETPLATFORM
153
154 -----------------------------------------------------------------------------
155 -- Compiler output options
156
157 defaultHscLang
158   | cGhcWithNativeCodeGen == "YES" && 
159         (prefixMatch "i386" cTARGETPLATFORM ||
160          prefixMatch "sparc" cTARGETPLATFORM)   =  HscAsm
161   | otherwise                                   =  HscC
162
163 GLOBAL_VAR(v_Output_dir,  Nothing, Maybe String)
164 GLOBAL_VAR(v_Object_suf,  Nothing, Maybe String)
165 GLOBAL_VAR(v_Output_file, Nothing, Maybe String)
166 GLOBAL_VAR(v_Output_hi,   Nothing, Maybe String)
167
168 GLOBAL_VAR(v_Ld_inputs, [],      [String])
169
170 odir_ify :: String -> IO String
171 odir_ify f = do
172   odir_opt <- readIORef v_Output_dir
173   case odir_opt of
174         Nothing -> return f
175         Just d  -> return (newdir d f)
176
177 osuf_ify :: String -> IO String
178 osuf_ify f = do
179   osuf_opt <- readIORef v_Object_suf
180   case osuf_opt of
181         Nothing -> return f
182         Just s  -> return (newsuf s f)
183
184 -----------------------------------------------------------------------------
185 -- Hi Files
186
187 GLOBAL_VAR(v_ProduceHi,         True,   Bool)
188 GLOBAL_VAR(v_Hi_on_stdout,      False,  Bool)
189 GLOBAL_VAR(v_Hi_suf,            "hi",   String)
190
191 -----------------------------------------------------------------------------
192 -- Warnings & sanity checking
193
194 -- Warning packages that are controlled by -W and -Wall.  The 'standard'
195 -- warnings that you get all the time are
196 --         
197 --         -fwarn-overlapping-patterns
198 --         -fwarn-missing-methods
199 --         -fwarn-missing-fields
200 --         -fwarn-deprecations
201 --         -fwarn-duplicate-exports
202 -- 
203 -- these are turned off by -Wnot.
204
205
206 standardWarnings  = [ "-fwarn-overlapping-patterns"
207                     , "-fwarn-missing-methods"
208                     , "-fwarn-missing-fields"
209                     , "-fwarn-deprecations"
210                     , "-fwarn-duplicate-exports"
211                     ]
212 minusWOpts        = standardWarnings ++ 
213                     [ "-fwarn-unused-binds"
214                     , "-fwarn-unused-matches"
215                     , "-fwarn-incomplete-patterns"
216                     , "-fwarn-unused-imports"
217                     ]
218 minusWallOpts     = minusWOpts ++
219                     [ "-fwarn-type-defaults"
220                     , "-fwarn-name-shadowing"
221                     , "-fwarn-missing-signatures"
222                     , "-fwarn-hi-shadowing"
223                     ]
224
225 data WarningState = W_default | W_ | W_all | W_not
226 GLOBAL_VAR(v_Warning_opt, W_default, WarningState)
227
228 -----------------------------------------------------------------------------
229 -- Compiler optimisation options
230
231 GLOBAL_VAR(v_OptLevel, 0, Int)
232
233 setOptLevel :: String -> IO ()
234 setOptLevel ""              = do { writeIORef v_OptLevel 1 }
235 setOptLevel "not"           = writeIORef v_OptLevel 0
236 setOptLevel [c] | isDigit c = do
237    let level = ord c - ord '0'
238    writeIORef v_OptLevel level
239 setOptLevel s = unknownFlagErr ("-O"++s)
240
241 GLOBAL_VAR(v_minus_o2_for_C,            False, Bool)
242 GLOBAL_VAR(v_MaxSimplifierIterations,   4,     Int)
243 GLOBAL_VAR(v_StgStats,                  False, Bool)
244 GLOBAL_VAR(v_UsageSPInf,                False, Bool)  -- Off by default
245 GLOBAL_VAR(v_Strictness,                True,  Bool)
246 GLOBAL_VAR(v_CPR,                       True,  Bool)
247 GLOBAL_VAR(v_CSE,                       True,  Bool)
248
249 hsc_minusO2_flags = hsc_minusO_flags    -- for now
250
251 hsc_minusNoO_flags =
252        [ 
253         "-fignore-interface-pragmas",
254         "-fomit-interface-pragmas"
255         ]
256
257 hsc_minusO_flags =
258   [ 
259         "-ffoldr-build-on",
260         "-fdo-eta-reduction",
261         "-fdo-lambda-eta-expansion",
262         "-fcase-of-case",
263         "-fcase-merge",
264         "-flet-to-case"
265    ]
266
267 buildCoreToDo :: IO [CoreToDo]
268 buildCoreToDo = do
269    opt_level  <- readIORef v_OptLevel
270    max_iter   <- readIORef v_MaxSimplifierIterations
271    usageSP    <- readIORef v_UsageSPInf
272    strictness <- readIORef v_Strictness
273    cpr        <- readIORef v_CPR
274    cse        <- readIORef v_CSE
275
276    if opt_level == 0 then return
277       [
278         CoreDoSimplify (isAmongSimpl [
279             MaxSimplifierIterations max_iter
280         ])
281       ]
282
283     else {- level >= 1 -} return [ 
284
285         -- initial simplify: mk specialiser happy: minimum effort please
286         CoreDoSimplify (isAmongSimpl [
287             SimplInlinePhase 0,
288                         -- Don't inline anything till full laziness has bitten
289                         -- In particular, inlining wrappers inhibits floating
290                         -- e.g. ...(case f x of ...)...
291                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
292                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
293                         -- and now the redex (f x) isn't floatable any more
294             DontApplyRules,
295                         -- Similarly, don't apply any rules until after full 
296                         -- laziness.  Notably, list fusion can prevent floating.
297             NoCaseOfCase,
298                         -- Don't do case-of-case transformations.
299                         -- This makes full laziness work better
300             MaxSimplifierIterations max_iter
301         ]),
302
303         -- Specialisation is best done before full laziness
304         -- so that overloaded functions have all their dictionary lambdas manifest
305         CoreDoSpecialising,
306
307         CoreDoFloatOutwards False{-not full-},
308         CoreDoFloatInwards,
309
310         CoreDoSimplify (isAmongSimpl [
311            SimplInlinePhase 1,
312                 -- Want to run with inline phase 1 after the specialiser to give
313                 -- maximum chance for fusion to work before we inline build/augment
314                 -- in phase 2.  This made a difference in 'ansi' where an 
315                 -- overloaded function wasn't inlined till too late.
316            MaxSimplifierIterations max_iter
317         ]),
318
319         -- infer usage information here in case we need it later.
320         -- (add more of these where you need them --KSW 1999-04)
321         if usageSP then CoreDoUSPInf else CoreDoNothing,
322
323         CoreDoSimplify (isAmongSimpl [
324                 -- Need inline-phase2 here so that build/augment get 
325                 -- inlined.  I found that spectral/hartel/genfft lost some useful
326                 -- strictness in the function sumcode' if augment is not inlined
327                 -- before strictness analysis runs
328            SimplInlinePhase 2,
329            MaxSimplifierIterations max_iter
330         ]),
331
332         CoreDoSimplify (isAmongSimpl [
333            MaxSimplifierIterations 2
334                 -- No -finline-phase: allow all Ids to be inlined now
335                 -- This gets foldr inlined before strictness analysis
336         ]),
337
338         if strictness then CoreDoStrictness else CoreDoNothing,
339         if cpr        then CoreDoCPResult   else CoreDoNothing,
340         CoreDoWorkerWrapper,
341         CoreDoGlomBinds,
342
343         CoreDoSimplify (isAmongSimpl [
344            MaxSimplifierIterations max_iter
345                 -- No -finline-phase: allow all Ids to be inlined now
346         ]),
347
348         CoreDoFloatOutwards False{-not full-},
349                 -- nofib/spectral/hartel/wang doubles in speed if you
350                 -- do full laziness late in the day.  It only happens
351                 -- after fusion and other stuff, so the early pass doesn't
352                 -- catch it.  For the record, the redex is 
353                 --        f_el22 (f_el21 r_midblock)
354
355 -- Leave out lambda lifting for now
356 --        "-fsimplify", -- Tidy up results of full laziness
357 --          "[", 
358 --                "-fmax-simplifier-iterations2",
359 --          "]",
360 --        "-ffloat-outwards-full",      
361
362         -- We want CSE to follow the final full-laziness pass, because it may
363         -- succeed in commoning up things floated out by full laziness.
364         --
365         -- CSE must immediately follow a simplification pass, because it relies
366         -- on the no-shadowing invariant.  See comments at the top of CSE.lhs
367         -- So it must NOT follow float-inwards, which can give rise to shadowing,
368         -- even if its input doesn't have shadows.  Hence putting it between
369         -- the two passes.
370         if cse then CoreCSE else CoreDoNothing,
371
372         CoreDoFloatInwards,
373
374 -- Case-liberation for -O2.  This should be after
375 -- strictness analysis and the simplification which follows it.
376
377 --        ( ($OptLevel != 2)
378 --        ? ""
379 --        : "-fliberate-case -fsimplify [ $Oopt_FB_Support -ffloat-lets-exposing-whnf -ffloat-primops-ok -fcase-of-case -fdo-case-elim -fcase-merge -fdo-lambda-eta-expansion -freuse-con -flet-to-case $Oopt_PedanticBottoms $Oopt_MaxSimplifierIterations $Oopt_ShowSimplifierProgress ]" ),
380 --
381 --        "-fliberate-case",
382
383         -- Final clean-up simplification:
384         CoreDoSimplify (isAmongSimpl [
385           MaxSimplifierIterations max_iter
386                 -- No -finline-phase: allow all Ids to be inlined now
387         ])
388      ]
389
390 buildStgToDo :: IO [ StgToDo ]
391 buildStgToDo = do
392   stg_stats <- readIORef v_StgStats
393   let flags1 | stg_stats = [ D_stg_stats ]
394              | otherwise = [ ]
395
396         -- STG passes
397   ways_ <- readIORef v_Ways
398   let flags2 | WayProf `elem` ways_ = StgDoMassageForProfiling : flags1
399              | otherwise            = flags1
400
401   return flags2
402
403 -----------------------------------------------------------------------------
404 -- Paths & Libraries
405
406 split_marker = ':'   -- not configurable (ToDo)
407
408 v_Import_paths, v_Include_paths, v_Library_paths :: IORef [String]
409 GLOBAL_VAR(v_Import_paths,  ["."], [String])
410 GLOBAL_VAR(v_Include_paths, ["."], [String])
411 GLOBAL_VAR(v_Library_paths, [],  [String])
412
413 GLOBAL_VAR(v_Cmdline_libraries,   [], [String])
414
415 addToDirList :: IORef [String] -> String -> IO ()
416 addToDirList ref path
417   = do paths <- readIORef ref
418        writeIORef ref (paths ++ split split_marker path)
419
420 -----------------------------------------------------------------------------
421 -- Packages
422
423 GLOBAL_VAR(v_Path_package_config, error "path_package_config", String)
424
425 -- package list is maintained in dependency order
426 GLOBAL_VAR(v_Packages, ("std":"rts":"gmp":[]), [String])
427
428 addPackage :: String -> IO ()
429 addPackage package
430   = do pkg_details <- readIORef v_Package_details
431        case lookupPkg package pkg_details of
432           Nothing -> throwDyn (OtherError ("unknown package name: " ++ package))
433           Just details -> do
434             ps <- readIORef v_Packages
435             unless (package `elem` ps) $ do
436                 mapM_ addPackage (package_deps details)
437                 ps <- readIORef v_Packages
438                 writeIORef v_Packages (package:ps)
439
440 getPackageImportPath   :: IO [String]
441 getPackageImportPath = do
442   ps <- readIORef v_Packages
443   ps' <- getPackageDetails ps
444   return (nub (concat (map import_dirs ps')))
445
446 getPackageIncludePath   :: IO [String]
447 getPackageIncludePath = do
448   ps <- readIORef v_Packages 
449   ps' <- getPackageDetails ps
450   return (nub (filter (not.null) (concatMap include_dirs ps')))
451
452         -- includes are in reverse dependency order (i.e. rts first)
453 getPackageCIncludes   :: IO [String]
454 getPackageCIncludes = do
455   ps <- readIORef v_Packages
456   ps' <- getPackageDetails ps
457   return (reverse (nub (filter (not.null) (concatMap c_includes ps'))))
458
459 getPackageLibraryPath  :: IO [String]
460 getPackageLibraryPath = do
461   ps <- readIORef v_Packages
462   ps' <- getPackageDetails ps
463   return (nub (concat (map library_dirs ps')))
464
465 getPackageLibraries    :: IO [String]
466 getPackageLibraries = do
467   ps <- readIORef v_Packages
468   ps' <- getPackageDetails ps
469   tag <- readIORef v_Build_tag
470   let suffix = if null tag then "" else '_':tag
471   return (concat (
472         map (\p -> map (++suffix) (hs_libraries p) ++ extra_libraries p) ps'
473      ))
474
475 getPackageExtraGhcOpts :: IO [String]
476 getPackageExtraGhcOpts = do
477   ps <- readIORef v_Packages
478   ps' <- getPackageDetails ps
479   return (concatMap extra_ghc_opts ps')
480
481 getPackageExtraCcOpts  :: IO [String]
482 getPackageExtraCcOpts = do
483   ps <- readIORef v_Packages
484   ps' <- getPackageDetails ps
485   return (concatMap extra_cc_opts ps')
486
487 getPackageExtraLdOpts  :: IO [String]
488 getPackageExtraLdOpts = do
489   ps <- readIORef v_Packages
490   ps' <- getPackageDetails ps
491   return (concatMap extra_ld_opts ps')
492
493 getPackageDetails :: [String] -> IO [Package]
494 getPackageDetails ps = do
495   pkg_details <- readIORef v_Package_details
496   return [ pkg | p <- ps, Just pkg <- [ lookupPkg p pkg_details ] ]
497
498 GLOBAL_VAR(v_Package_details, (error "package_details"), [Package])
499
500 lookupPkg :: String -> [Package] -> Maybe Package
501 lookupPkg nm ps
502    = case [p | p <- ps, name p == nm] of
503         []    -> Nothing
504         (p:_) -> Just p
505 -----------------------------------------------------------------------------
506 -- Ways
507
508 -- The central concept of a "way" is that all objects in a given
509 -- program must be compiled in the same "way".  Certain options change
510 -- parameters of the virtual machine, eg. profiling adds an extra word
511 -- to the object header, so profiling objects cannot be linked with
512 -- non-profiling objects.
513
514 -- After parsing the command-line options, we determine which "way" we
515 -- are building - this might be a combination way, eg. profiling+ticky-ticky.
516
517 -- We then find the "build-tag" associated with this way, and this
518 -- becomes the suffix used to find .hi files and libraries used in
519 -- this compilation.
520
521 GLOBAL_VAR(v_Build_tag, "", String)
522
523 data WayName
524   = WayProf
525   | WayUnreg
526   | WayDll
527   | WayTicky
528   | WayPar
529   | WayGran
530   | WaySMP
531   | WayDebug
532   | WayUser_a
533   | WayUser_b
534   | WayUser_c
535   | WayUser_d
536   | WayUser_e
537   | WayUser_f
538   | WayUser_g
539   | WayUser_h
540   | WayUser_i
541   | WayUser_j
542   | WayUser_k
543   | WayUser_l
544   | WayUser_m
545   | WayUser_n
546   | WayUser_o
547   | WayUser_A
548   | WayUser_B
549   deriving (Eq,Ord)
550
551 GLOBAL_VAR(v_Ways, [] ,[WayName])
552
553 -- ToDo: allow WayDll with any other allowed combination
554
555 allowed_combinations = 
556    [  [WayProf,WayUnreg],
557       [WayProf,WaySMP]     -- works???
558    ]
559
560 findBuildTag :: IO [String]  -- new options
561 findBuildTag = do
562   way_names <- readIORef v_Ways
563   case sort way_names of
564      []  -> do  writeIORef v_Build_tag ""
565                 return []
566
567      [w] -> do let details = lkupWay w
568                writeIORef v_Build_tag (wayTag details)
569                return (wayOpts details)
570
571      ws  -> if  ws `notElem` allowed_combinations
572                 then throwDyn (OtherError $
573                                 "combination not supported: "  ++
574                                 foldr1 (\a b -> a ++ '/':b) 
575                                 (map (wayName . lkupWay) ws))
576                 else let stuff = map lkupWay ws
577                          tag   = concat (map wayTag stuff)
578                          flags = map wayOpts stuff
579                      in do
580                      writeIORef v_Build_tag tag
581                      return (concat flags)
582
583 lkupWay w = 
584    case lookup w way_details of
585         Nothing -> error "findBuildTag"
586         Just details -> details
587
588 data Way = Way {
589   wayTag   :: String,
590   wayName  :: String,
591   wayOpts  :: [String]
592   }
593
594 way_details :: [ (WayName, Way) ]
595 way_details =
596   [ (WayProf, Way  "p" "Profiling"  
597         [ "-fscc-profiling"
598         , "-DPROFILING"
599         , "-optc-DPROFILING"
600         , "-fvia-C" ]),
601
602     (WayTicky, Way  "t" "Ticky-ticky Profiling"  
603         [ "-fticky-ticky"
604         , "-DTICKY_TICKY"
605         , "-optc-DTICKY_TICKY"
606         , "-fvia-C" ]),
607
608     (WayUnreg, Way  "u" "Unregisterised" 
609         [ "-optc-DNO_REGS"
610         , "-optc-DUSE_MINIINTERPRETER"
611         , "-fno-asm-mangling"
612         , "-funregisterised"
613         , "-fvia-C" ]),
614
615     (WayDll, Way  "dll" "DLLized"
616         [ ]),
617
618     (WayPar, Way  "mp" "Parallel" 
619         [ "-fparallel"
620         , "-D__PARALLEL_HASKELL__"
621         , "-optc-DPAR"
622         , "-package concurrent"
623         , "-fvia-C" ]),
624
625     (WayGran, Way  "mg" "Gransim" 
626         [ "-fgransim"
627         , "-D__GRANSIM__"
628         , "-optc-DGRAN"
629         , "-package concurrent"
630         , "-fvia-C" ]),
631
632     (WaySMP, Way  "s" "SMP"
633         [ "-fsmp"
634         , "-optc-pthread"
635         , "-optl-pthread"
636         , "-optc-DSMP"
637         , "-fvia-C" ]),
638
639     (WayUser_a,  Way  "a"  "User way 'a'"  ["$WAY_a_REAL_OPTS"]),       
640     (WayUser_b,  Way  "b"  "User way 'b'"  ["$WAY_b_REAL_OPTS"]),       
641     (WayUser_c,  Way  "c"  "User way 'c'"  ["$WAY_c_REAL_OPTS"]),       
642     (WayUser_d,  Way  "d"  "User way 'd'"  ["$WAY_d_REAL_OPTS"]),       
643     (WayUser_e,  Way  "e"  "User way 'e'"  ["$WAY_e_REAL_OPTS"]),       
644     (WayUser_f,  Way  "f"  "User way 'f'"  ["$WAY_f_REAL_OPTS"]),       
645     (WayUser_g,  Way  "g"  "User way 'g'"  ["$WAY_g_REAL_OPTS"]),       
646     (WayUser_h,  Way  "h"  "User way 'h'"  ["$WAY_h_REAL_OPTS"]),       
647     (WayUser_i,  Way  "i"  "User way 'i'"  ["$WAY_i_REAL_OPTS"]),       
648     (WayUser_j,  Way  "j"  "User way 'j'"  ["$WAY_j_REAL_OPTS"]),       
649     (WayUser_k,  Way  "k"  "User way 'k'"  ["$WAY_k_REAL_OPTS"]),       
650     (WayUser_l,  Way  "l"  "User way 'l'"  ["$WAY_l_REAL_OPTS"]),       
651     (WayUser_m,  Way  "m"  "User way 'm'"  ["$WAY_m_REAL_OPTS"]),       
652     (WayUser_n,  Way  "n"  "User way 'n'"  ["$WAY_n_REAL_OPTS"]),       
653     (WayUser_o,  Way  "o"  "User way 'o'"  ["$WAY_o_REAL_OPTS"]),       
654     (WayUser_A,  Way  "A"  "User way 'A'"  ["$WAY_A_REAL_OPTS"]),       
655     (WayUser_B,  Way  "B"  "User way 'B'"  ["$WAY_B_REAL_OPTS"]) 
656   ]
657
658 -----------------------------------------------------------------------------
659 -- Programs for particular phases
660
661 GLOBAL_VAR(v_Pgm_L,   error "pgm_L", String)
662 GLOBAL_VAR(v_Pgm_P,   cRAWCPP,       String)
663 GLOBAL_VAR(v_Pgm_c,   cGCC,          String)
664 GLOBAL_VAR(v_Pgm_m,   error "pgm_m", String)
665 GLOBAL_VAR(v_Pgm_s,   error "pgm_s", String)
666 GLOBAL_VAR(v_Pgm_a,   cGCC,          String)
667 GLOBAL_VAR(v_Pgm_l,   cGCC,          String)
668
669 GLOBAL_VAR(v_Opt_dep,    [], [String])
670 GLOBAL_VAR(v_Anti_opt_C, [], [String])
671 GLOBAL_VAR(v_Opt_C,      [], [String])
672 GLOBAL_VAR(v_Opt_l,      [], [String])
673 GLOBAL_VAR(v_Opt_dll,    [], [String])
674
675 getStaticOpts :: IORef [String] -> IO [String]
676 getStaticOpts ref = readIORef ref >>= return . reverse
677
678 -----------------------------------------------------------------------------
679 -- Via-C compilation stuff
680
681 -- flags returned are: ( all C compilations
682 --                     , registerised HC compilations
683 --                     )
684
685 machdepCCOpts 
686    | prefixMatch "alpha"   cTARGETPLATFORM  
687         = return ( ["-static"], [] )
688
689    | prefixMatch "hppa"    cTARGETPLATFORM  
690         -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
691         -- (very nice, but too bad the HP /usr/include files don't agree.)
692         = return ( ["-static", "-D_HPUX_SOURCE"], [] )
693
694    | prefixMatch "m68k"    cTARGETPLATFORM
695       -- -fno-defer-pop : for the .hc files, we want all the pushing/
696       --    popping of args to routines to be explicit; if we let things
697       --    be deferred 'til after an STGJUMP, imminent death is certain!
698       --
699       -- -fomit-frame-pointer : *don't*
700       --     It's better to have a6 completely tied up being a frame pointer
701       --     rather than let GCC pick random things to do with it.
702       --     (If we want to steal a6, then we would try to do things
703       --     as on iX86, where we *do* steal the frame pointer [%ebp].)
704         = return ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
705
706    | prefixMatch "i386"    cTARGETPLATFORM  
707       -- -fno-defer-pop : basically the same game as for m68k
708       --
709       -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
710       --   the fp (%ebp) for our register maps.
711         = do n_regs <- readState stolen_x86_regs
712              sta    <- readIORef v_Static
713              return ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else "" ],
714                       [ "-fno-defer-pop", "-fomit-frame-pointer",
715                         "-DSTOLEN_X86_REGS="++show n_regs ]
716                     )
717
718    | prefixMatch "mips"    cTARGETPLATFORM
719         = return ( ["static"], [] )
720
721    | prefixMatch "powerpc" cTARGETPLATFORM || prefixMatch "rs6000" cTARGETPLATFORM
722         = return ( ["static"], ["-finhibit-size-directive"] )
723
724    | otherwise
725         = return ( [], [] )
726
727
728 -----------------------------------------------------------------------------
729 -- Running an external program
730
731 run_something phase_name cmd
732  = do
733    verb <- readIORef v_Verbose
734    when verb $ do
735         putStr phase_name
736         putStrLn ":"
737         putStrLn cmd
738         hFlush stdout
739
740    -- test for -n flag
741    n <- readIORef v_Dry_run
742    unless n $ do 
743
744    -- and run it!
745 #ifndef mingw32_TARGET_OS
746    exit_code <- system cmd `catchAllIO` 
747                    (\_ -> throwDyn (PhaseFailed phase_name (ExitFailure 1)))
748 #else
749    tmp <- newTempName "sh"
750    h <- openFile tmp WriteMode
751    hPutStrLn h cmd
752    hClose h
753    exit_code <- system ("sh - " ++ tmp) `catchAllIO` 
754                    (\e -> throwDyn (PhaseFailed phase_name (ExitFailure 1)))
755    removeFile tmp
756 #endif
757
758    if exit_code /= ExitSuccess
759         then throwDyn (PhaseFailed phase_name exit_code)
760         else do when verb (putStr "\n")
761                 return ()
762