[project @ 2005-03-21 10:50:22 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / DynFlags.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Dynamic flags
4 --
5 -- Most flags are dynamic flags, which means they can change from
6 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
7 -- multi-session GHC each session can be using different dynamic
8 -- flags.  Dynamic flags can also be set at the prompt in GHCi.
9 --
10 -- (c) The University of Glasgow 2005
11 --
12 -----------------------------------------------------------------------------
13
14 module DynFlags (
15         -- Dynamic flags
16         DynFlag(..),
17         DynFlags(..),
18         HscTarget(..),
19         GhcMode(..), isOneShot,
20         GhcLink(..), isNoLink,
21         PackageFlag(..),
22         Option(..),
23
24         -- Configuration of the core-to-core and stg-to-stg phases
25         CoreToDo(..),
26         StgToDo(..),
27         SimplifierSwitch(..), 
28         SimplifierMode(..), FloatOutSwitches(..),
29         getCoreToDo, getStgToDo,
30         
31         -- Manipulating DynFlags
32         defaultDynFlags,                -- DynFlags
33         initDynFlags,                   -- DynFlags -> IO DynFlags
34
35         dopt,                           -- DynFlag -> DynFlags -> Bool
36         dopt_set, dopt_unset,           -- DynFlags -> DynFlag -> DynFlags
37         getOpts,                        -- (DynFlags -> [a]) -> IO [a]
38         getVerbFlag,
39         updOptLevel,
40         setTmpDir,
41         
42         -- parsing DynFlags
43         parseDynamicFlags,
44
45         -- misc stuff
46         machdepCCOpts, picCCOpts,
47   ) where
48
49 #include "HsVersions.h"
50
51 import StaticFlags      ( opt_Static, opt_PIC, 
52                           WayName(..), v_Ways, v_Build_tag, v_RTS_Build_tag )
53 import {-# SOURCE #-} Packages (PackageState)
54 import DriverPhases     ( Phase(..), phaseInputExt )
55 import Config
56 import CmdLineParser
57 import Panic            ( panic, GhcException(..) )
58 import Util             ( notNull, splitLongestPrefix, split, normalisePath )
59
60 import DATA_IOREF       ( readIORef )
61 import EXCEPTION        ( throwDyn )
62 import Monad            ( when )
63 import Maybe            ( fromJust )
64 import Char             ( isDigit, isUpper )
65
66 -- -----------------------------------------------------------------------------
67 -- DynFlags
68
69 data DynFlag
70
71    -- debugging flags
72    = Opt_D_dump_cmm
73    | Opt_D_dump_asm
74    | Opt_D_dump_cpranal
75    | Opt_D_dump_deriv
76    | Opt_D_dump_ds
77    | Opt_D_dump_flatC
78    | Opt_D_dump_foreign
79    | Opt_D_dump_inlinings
80    | Opt_D_dump_occur_anal
81    | Opt_D_dump_parsed
82    | Opt_D_dump_rn
83    | Opt_D_dump_simpl
84    | Opt_D_dump_simpl_iterations
85    | Opt_D_dump_spec
86    | Opt_D_dump_prep
87    | Opt_D_dump_stg
88    | Opt_D_dump_stranal
89    | Opt_D_dump_tc
90    | Opt_D_dump_types
91    | Opt_D_dump_rules
92    | Opt_D_dump_cse
93    | Opt_D_dump_worker_wrapper
94    | Opt_D_dump_rn_trace
95    | Opt_D_dump_rn_stats
96    | Opt_D_dump_opt_cmm
97    | Opt_D_dump_simpl_stats
98    | Opt_D_dump_tc_trace
99    | Opt_D_dump_if_trace
100    | Opt_D_dump_splices
101    | Opt_D_dump_BCOs
102    | Opt_D_dump_vect
103    | Opt_D_source_stats
104    | Opt_D_verbose_core2core
105    | Opt_D_verbose_stg2stg
106    | Opt_D_dump_hi
107    | Opt_D_dump_hi_diffs
108    | Opt_D_dump_minimal_imports
109    | Opt_DoCoreLinting
110    | Opt_DoStgLinting
111    | Opt_DoCmmLinting
112
113    | Opt_WarnIsError            -- -Werror; makes warnings fatal
114    | Opt_WarnDuplicateExports
115    | Opt_WarnHiShadows
116    | Opt_WarnIncompletePatterns
117    | Opt_WarnIncompletePatternsRecUpd
118    | Opt_WarnMissingFields
119    | Opt_WarnMissingMethods
120    | Opt_WarnMissingSigs
121    | Opt_WarnNameShadowing
122    | Opt_WarnOverlappingPatterns
123    | Opt_WarnSimplePatterns
124    | Opt_WarnTypeDefaults
125    | Opt_WarnUnusedBinds
126    | Opt_WarnUnusedImports
127    | Opt_WarnUnusedMatches
128    | Opt_WarnDeprecations
129    | Opt_WarnDodgyImports
130    | Opt_WarnOrphans
131
132    -- language opts
133    | Opt_AllowOverlappingInstances
134    | Opt_AllowUndecidableInstances
135    | Opt_AllowIncoherentInstances
136    | Opt_MonomorphismRestriction
137    | Opt_GlasgowExts
138    | Opt_FFI
139    | Opt_PArr                          -- syntactic support for parallel arrays
140    | Opt_Arrows                        -- Arrow-notation syntax
141    | Opt_TH
142    | Opt_ImplicitParams
143    | Opt_Generics
144    | Opt_ImplicitPrelude 
145    | Opt_ScopedTypeVariables
146
147    -- optimisation opts
148    | Opt_Strictness
149    | Opt_FullLaziness
150    | Opt_CSE
151    | Opt_IgnoreInterfacePragmas
152    | Opt_OmitInterfacePragmas
153    | Opt_DoLambdaEtaExpansion
154    | Opt_IgnoreAsserts
155    | Opt_DoEtaReduction
156    | Opt_CaseMerge
157    | Opt_UnboxStrictFields
158
159    -- misc opts
160    | Opt_Cpp
161    | Opt_Pp
162    | Opt_RecompChecking
163    | Opt_DryRun
164    | Opt_DoAsmMangling
165    | Opt_ExcessPrecision
166    | Opt_ReadUserPackageConf
167    | Opt_NoHsMain
168    | Opt_SplitObjs
169    | Opt_StgStats
170
171    -- keeping stuff
172    | Opt_KeepHiDiffs
173    | Opt_KeepHcFiles
174    | Opt_KeepSFiles
175    | Opt_KeepRawSFiles
176    | Opt_KeepTmpFiles
177
178    deriving (Eq)
179
180 data DynFlags = DynFlags {
181   ghcMode               :: GhcMode,
182   ghcLink               :: GhcLink,
183   coreToDo              :: Maybe [CoreToDo], -- reserved for -Ofile
184   stgToDo               :: Maybe [StgToDo],  -- similarly
185   hscTarget             :: HscTarget,
186   hscOutName            :: String,      -- name of the output file
187   hscStubHOutName       :: String,      -- name of the .stub_h output file
188   hscStubCOutName       :: String,      -- name of the .stub_c output file
189   extCoreName           :: String,      -- name of the .core output file
190   verbosity             :: Int,         -- verbosity level
191   optLevel              :: Int,         -- optimisation level
192   maxSimplIterations    :: Int,         -- max simplifier iterations
193   ruleCheck             :: Maybe String,
194   stolen_x86_regs       :: Int,         
195   cmdlineHcIncludes     :: [String],    -- -#includes
196   importPaths           :: [FilePath],
197   mainModIs             :: Maybe String,
198   mainFunIs             :: Maybe String,
199
200   -- ways
201   wayNames              :: [WayName],   -- way flags from the cmd line
202   buildTag              :: String,      -- the global "way" (eg. "p" for prof)
203   rtsBuildTag           :: String,      -- the RTS "way"
204   
205   -- paths etc.
206   outputDir             :: Maybe String,
207   outputFile            :: Maybe String,
208   outputHi              :: Maybe String,
209   objectSuf             :: String,
210   hcSuf                 :: String,
211   hiDir                 :: Maybe String,
212   hiSuf                 :: String,
213   includePaths          :: [String],
214   libraryPaths          :: [String],
215   frameworkPaths        :: [String],    -- used on darwin only
216   cmdlineFrameworks     :: [String],    -- ditto
217   tmpDir                :: String,      -- no trailing '/'
218   
219   -- options for particular phases
220   opt_L                 :: [String],
221   opt_P                 :: [String],
222   opt_F                 :: [String],
223   opt_c                 :: [String],
224   opt_m                 :: [String],
225   opt_a                 :: [String],
226   opt_l                 :: [String],
227   opt_dll               :: [String],
228   opt_dep               :: [String],
229
230   -- commands for particular phases
231   pgm_L                 :: String,
232   pgm_P                 :: (String,[Option]),
233   pgm_F                 :: String,
234   pgm_c                 :: (String,[Option]),
235   pgm_m                 :: (String,[Option]),
236   pgm_s                 :: (String,[Option]),
237   pgm_a                 :: (String,[Option]),
238   pgm_l                 :: (String,[Option]),
239   pgm_dll               :: (String,[Option]),
240
241   -- ** Package flags
242   extraPkgConfs         :: [FilePath],
243         -- The -package-conf flags given on the command line, in the order
244         -- they appeared.
245
246   packageFlags          :: [PackageFlag],
247         -- The -package and -hide-package flags from the command-line
248
249   -- ** Package state
250   pkgState              :: PackageState,
251
252   -- hsc dynamic flags
253   flags                 :: [DynFlag]
254  }
255
256 data HscTarget
257   = HscC
258   | HscAsm
259   | HscJava
260   | HscILX
261   | HscInterpreted
262   | HscNothing
263   deriving (Eq, Show)
264
265 data GhcMode
266   = BatchCompile        -- | @ghc --make Main@
267   | Interactive         -- | @ghc --interactive@
268   | OneShot             -- | @ghc -c Foo.hs@
269   | JustTypecheck       -- | Development environemnts, refactorer, etc.
270   | MkDepend
271   deriving Eq
272
273 isOneShot :: GhcMode -> Bool
274 isOneShot OneShot = True
275 isOneShot _other  = False
276
277 data GhcLink    -- What to do in the link step, if there is one
278   =             -- Only relevant for modes
279                 --      DoMake and StopBefore StopLn
280     NoLink              -- Don't link at all
281   | StaticLink          -- Ordinary linker [the default]
282   | MkDLL               -- Make a DLL
283
284 isNoLink :: GhcLink -> Bool
285 isNoLink NoLink = True
286 isNoLink other  = False
287
288 data PackageFlag
289   = ExposePackage  String
290   | HidePackage    String
291   | IgnorePackage  String
292
293 defaultHscTarget
294 #if defined(i386_TARGET_ARCH) || defined(sparc_TARGET_ARCH) || defined(powerpc_TARGET_ARCH)
295   | cGhcWithNativeCodeGen == "YES"      =  HscAsm
296 #endif
297   | otherwise                           =  HscC
298
299 initDynFlags dflags = do
300  -- someday these will be dynamic flags
301  ways <- readIORef v_Ways
302  build_tag <- readIORef v_Build_tag
303  rts_build_tag <- readIORef v_RTS_Build_tag
304  return dflags{
305         wayNames        = ways,
306         buildTag        = build_tag,
307         rtsBuildTag     = rts_build_tag
308         }
309
310 defaultDynFlags =
311      DynFlags {
312         ghcMode                 = OneShot,
313         ghcLink                 = StaticLink,
314         coreToDo                = Nothing,
315         stgToDo                 = Nothing, 
316         hscTarget               = defaultHscTarget, 
317         hscOutName              = "", 
318         hscStubHOutName         = "",
319         hscStubCOutName         = "",
320         extCoreName             = "",
321         verbosity               = 0, 
322         optLevel                = 0,
323         maxSimplIterations      = 4,
324         ruleCheck               = Nothing,
325         stolen_x86_regs         = 4,
326         cmdlineHcIncludes       = [],
327         importPaths             = ["."],
328         mainModIs               = Nothing,
329         mainFunIs               = Nothing,
330         
331         wayNames                = panic "ways",
332         buildTag                = panic "buildTag",
333         rtsBuildTag             = panic "rtsBuildTag",
334
335         outputDir               = Nothing,
336         outputFile              = Nothing,
337         outputHi                = Nothing,
338         objectSuf               = phaseInputExt StopLn,
339         hcSuf                   = phaseInputExt HCc,
340         hiDir                   = Nothing,
341         hiSuf                   = "hi",
342         includePaths            = [],
343         libraryPaths            = [],
344         frameworkPaths          = [],
345         cmdlineFrameworks       = [],
346         tmpDir                  = cDEFAULT_TMPDIR,
347         
348         opt_L                   = [],
349         opt_P                   = [],
350         opt_F                   = [],
351         opt_c                   = [],
352         opt_a                   = [],
353         opt_m                   = [],
354         opt_l                   = [],
355         opt_dll                 = [],
356         opt_dep                 = [],
357         
358         pgm_L                   = panic "pgm_L",
359         pgm_P                   = panic "pgm_P",
360         pgm_F                   = panic "pgm_F",
361         pgm_c                   = panic "pgm_c",
362         pgm_m                   = panic "pgm_m",
363         pgm_s                   = panic "pgm_s",
364         pgm_a                   = panic "pgm_a",
365         pgm_l                   = panic "pgm_l",
366         pgm_dll                 = panic "pgm_mkdll",
367         
368         extraPkgConfs           = [],
369         packageFlags            = [],
370         pkgState                = panic "pkgState",
371         
372         flags = [ 
373             Opt_RecompChecking,
374             Opt_ReadUserPackageConf,
375     
376             Opt_ImplicitPrelude,
377             Opt_MonomorphismRestriction,
378             Opt_Strictness,
379                         -- strictness is on by default, but this only
380                         -- applies to -O.
381             Opt_CSE,            -- similarly for CSE.
382             Opt_FullLaziness,   -- ...and for full laziness
383     
384             Opt_DoLambdaEtaExpansion,
385                         -- This one is important for a tiresome reason:
386                         -- we want to make sure that the bindings for data 
387                         -- constructors are eta-expanded.  This is probably
388                         -- a good thing anyway, but it seems fragile.
389     
390             Opt_DoAsmMangling,
391     
392             -- and the default no-optimisation options:
393             Opt_IgnoreInterfacePragmas,
394             Opt_OmitInterfacePragmas
395     
396                ] ++ standardWarnings
397       }
398
399 {- 
400     Verbosity levels:
401         
402     0   |   print errors & warnings only
403     1   |   minimal verbosity: print "compiling M ... done." for each module.
404     2   |   equivalent to -dshow-passes
405     3   |   equivalent to existing "ghc -v"
406     4   |   "ghc -v -ddump-most"
407     5   |   "ghc -v -ddump-all"
408 -}
409
410 dopt :: DynFlag -> DynFlags -> Bool
411 dopt f dflags  = f `elem` (flags dflags)
412
413 dopt_set :: DynFlags -> DynFlag -> DynFlags
414 dopt_set dfs f = dfs{ flags = f : flags dfs }
415
416 dopt_unset :: DynFlags -> DynFlag -> DynFlags
417 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
418
419 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
420 getOpts dflags opts = reverse (opts dflags)
421         -- We add to the options from the front, so we need to reverse the list
422
423 getVerbFlag :: DynFlags -> String
424 getVerbFlag dflags 
425   | verbosity dflags >= 3  = "-v" 
426   | otherwise =  ""
427
428 setOutputDir  f d = d{ outputDir  = f}
429 setOutputFile f d = d{ outputFile = f}
430 setOutputHi   f d = d{ outputHi   = f}
431 setObjectSuf  f d = d{ objectSuf  = f}
432 setHcSuf      f d = d{ hcSuf      = f}
433 setHiSuf      f d = d{ hiSuf      = f}
434 setHiDir      f d = d{ hiDir      = f}
435
436 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
437 -- Config.hs should really use Option.
438 setPgmP   f d = let (pgm:args) = words f in d{ pgm_P   = (pgm, map Option args)}
439
440 setPgmL   f d = d{ pgm_L   = f}
441 setPgmF   f d = d{ pgm_F   = f}
442 setPgmc   f d = d{ pgm_c   = (f,[])}
443 setPgmm   f d = d{ pgm_m   = (f,[])}
444 setPgms   f d = d{ pgm_s   = (f,[])}
445 setPgma   f d = d{ pgm_a   = (f,[])}
446 setPgml   f d = d{ pgm_l   = (f,[])}
447 setPgmdll f d = d{ pgm_dll = (f,[])}
448
449 addOptL   f d = d{ opt_L   = f : opt_L d}
450 addOptP   f d = d{ opt_P   = f : opt_P d}
451 addOptF   f d = d{ opt_F   = f : opt_F d}
452 addOptc   f d = d{ opt_c   = f : opt_c d}
453 addOptm   f d = d{ opt_m   = f : opt_m d}
454 addOpta   f d = d{ opt_a   = f : opt_a d}
455 addOptl   f d = d{ opt_l   = f : opt_l d}
456 addOptdll f d = d{ opt_dll = f : opt_dll d}
457 addOptdep f d = d{ opt_dep = f : opt_dep d}
458
459 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
460
461 -- -----------------------------------------------------------------------------
462 -- Command-line options
463
464 -- When invoking external tools as part of the compilation pipeline, we
465 -- pass these a sequence of options on the command-line. Rather than
466 -- just using a list of Strings, we use a type that allows us to distinguish
467 -- between filepaths and 'other stuff'. [The reason being, of course, that
468 -- this type gives us a handle on transforming filenames, and filenames only,
469 -- to whatever format they're expected to be on a particular platform.]
470
471 data Option
472  = FileOption -- an entry that _contains_ filename(s) / filepaths.
473               String  -- a non-filepath prefix that shouldn't be 
474                       -- transformed (e.g., "/out=")
475               String  -- the filepath/filename portion
476  | Option     String
477  
478 -----------------------------------------------------------------------------
479 -- Setting the optimisation level
480
481 updOptLevel :: Int -> DynFlags -> DynFlags
482 -- Set dynflags appropriate to the optimisation level
483 updOptLevel n dfs
484   = if (n >= 1)
485      then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
486      else dfs2{ optLevel = n }
487   where
488    dfs1 = foldr (flip dopt_unset) dfs  remove_dopts
489    dfs2 = foldr (flip dopt_set)   dfs1 extra_dopts
490
491    extra_dopts
492         | n == 0    = opt_0_dopts
493         | otherwise = opt_1_dopts
494
495    remove_dopts
496         | n == 0    = opt_1_dopts
497         | otherwise = opt_0_dopts
498         
499 opt_0_dopts =  [ 
500         Opt_IgnoreInterfacePragmas,
501         Opt_OmitInterfacePragmas
502     ]
503
504 opt_1_dopts = [
505         Opt_IgnoreAsserts,
506         Opt_DoEtaReduction,
507         Opt_CaseMerge
508      ]
509
510 -- -----------------------------------------------------------------------------
511 -- Standard sets of warning options
512
513 standardWarnings
514     = [ Opt_WarnDeprecations,
515         Opt_WarnOverlappingPatterns,
516         Opt_WarnMissingFields,
517         Opt_WarnMissingMethods,
518         Opt_WarnDuplicateExports
519       ]
520
521 minusWOpts
522     = standardWarnings ++ 
523       [ Opt_WarnUnusedBinds,
524         Opt_WarnUnusedMatches,
525         Opt_WarnUnusedImports,
526         Opt_WarnIncompletePatterns,
527         Opt_WarnDodgyImports
528       ]
529
530 minusWallOpts
531     = minusWOpts ++
532       [ Opt_WarnTypeDefaults,
533         Opt_WarnNameShadowing,
534         Opt_WarnMissingSigs,
535         Opt_WarnHiShadows,
536         Opt_WarnOrphans
537       ]
538
539 -- -----------------------------------------------------------------------------
540 -- CoreToDo:  abstraction of core-to-core passes to run.
541
542 data CoreToDo           -- These are diff core-to-core passes,
543                         -- which may be invoked in any order,
544                         -- as many times as you like.
545
546   = CoreDoSimplify      -- The core-to-core simplifier.
547         SimplifierMode
548         [SimplifierSwitch]
549                         -- Each run of the simplifier can take a different
550                         -- set of simplifier-specific flags.
551   | CoreDoFloatInwards
552   | CoreDoFloatOutwards FloatOutSwitches
553   | CoreLiberateCase
554   | CoreDoPrintCore
555   | CoreDoStaticArgs
556   | CoreDoStrictness
557   | CoreDoWorkerWrapper
558   | CoreDoSpecialising
559   | CoreDoSpecConstr
560   | CoreDoOldStrictness
561   | CoreDoGlomBinds
562   | CoreCSE
563   | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules 
564                                                 -- matching this string
565
566   | CoreDoNothing        -- useful when building up lists of these things
567
568 data SimplifierMode             -- See comments in SimplMonad
569   = SimplGently
570   | SimplPhase Int
571
572 data SimplifierSwitch
573   = MaxSimplifierIterations Int
574   | NoCaseOfCase
575
576 data FloatOutSwitches
577   = FloatOutSw  Bool    -- True <=> float lambdas to top level
578                 Bool    -- True <=> float constants to top level,
579                         --          even if they do not escape a lambda
580
581
582 -- The core-to-core pass ordering is derived from the DynFlags:
583
584 getCoreToDo :: DynFlags -> [CoreToDo]
585 getCoreToDo dflags
586   | Just todo <- coreToDo dflags = todo -- set explicitly by user
587   | otherwise = core_todo
588   where
589     opt_level     = optLevel dflags
590     max_iter      = maxSimplIterations dflags
591     strictness    = dopt Opt_Strictness dflags
592     full_laziness = dopt Opt_FullLaziness dflags
593     cse           = dopt Opt_CSE dflags
594     rule_check    = ruleCheck dflags
595
596     core_todo = 
597      if opt_level == 0 then
598       [
599         CoreDoSimplify (SimplPhase 0) [
600             MaxSimplifierIterations max_iter
601         ]
602       ]
603
604      else {- opt_level >= 1 -} [ 
605
606         -- initial simplify: mk specialiser happy: minimum effort please
607         CoreDoSimplify SimplGently [
608                         --      Simplify "gently"
609                         -- Don't inline anything till full laziness has bitten
610                         -- In particular, inlining wrappers inhibits floating
611                         -- e.g. ...(case f x of ...)...
612                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
613                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
614                         -- and now the redex (f x) isn't floatable any more
615                         -- Similarly, don't apply any rules until after full 
616                         -- laziness.  Notably, list fusion can prevent floating.
617
618             NoCaseOfCase,
619                         -- Don't do case-of-case transformations.
620                         -- This makes full laziness work better
621             MaxSimplifierIterations max_iter
622         ],
623
624         -- Specialisation is best done before full laziness
625         -- so that overloaded functions have all their dictionary lambdas manifest
626         CoreDoSpecialising,
627
628         if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
629                          else CoreDoNothing,
630
631         CoreDoFloatInwards,
632
633         CoreDoSimplify (SimplPhase 2) [
634                 -- Want to run with inline phase 2 after the specialiser to give
635                 -- maximum chance for fusion to work before we inline build/augment
636                 -- in phase 1.  This made a difference in 'ansi' where an 
637                 -- overloaded function wasn't inlined till too late.
638            MaxSimplifierIterations max_iter
639         ],
640         case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
641
642         CoreDoSimplify (SimplPhase 1) [
643                 -- Need inline-phase2 here so that build/augment get 
644                 -- inlined.  I found that spectral/hartel/genfft lost some useful
645                 -- strictness in the function sumcode' if augment is not inlined
646                 -- before strictness analysis runs
647            MaxSimplifierIterations max_iter
648         ],
649         case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
650
651         CoreDoSimplify (SimplPhase 0) [
652                 -- Phase 0: allow all Ids to be inlined now
653                 -- This gets foldr inlined before strictness analysis
654
655            MaxSimplifierIterations 3
656                 -- At least 3 iterations because otherwise we land up with
657                 -- huge dead expressions because of an infelicity in the 
658                 -- simpifier.   
659                 --      let k = BIG in foldr k z xs
660                 -- ==>  let k = BIG in letrec go = \xs -> ...(k x).... in go xs
661                 -- ==>  let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
662                 -- Don't stop now!
663
664         ],
665         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
666
667 #ifdef OLD_STRICTNESS
668         CoreDoOldStrictness
669 #endif
670         if strictness then CoreDoStrictness else CoreDoNothing,
671         CoreDoWorkerWrapper,
672         CoreDoGlomBinds,
673
674         CoreDoSimplify (SimplPhase 0) [
675            MaxSimplifierIterations max_iter
676         ],
677
678         if full_laziness then
679           CoreDoFloatOutwards (FloatOutSw False   -- Not lambdas
680                                           True)   -- Float constants
681         else CoreDoNothing,
682                 -- nofib/spectral/hartel/wang doubles in speed if you
683                 -- do full laziness late in the day.  It only happens
684                 -- after fusion and other stuff, so the early pass doesn't
685                 -- catch it.  For the record, the redex is 
686                 --        f_el22 (f_el21 r_midblock)
687
688
689         -- We want CSE to follow the final full-laziness pass, because it may
690         -- succeed in commoning up things floated out by full laziness.
691         -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
692
693         if cse then CoreCSE else CoreDoNothing,
694
695         CoreDoFloatInwards,
696
697 -- Case-liberation for -O2.  This should be after
698 -- strictness analysis and the simplification which follows it.
699
700         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
701
702         if opt_level >= 2 then
703            CoreLiberateCase
704         else
705            CoreDoNothing,
706         if opt_level >= 2 then
707            CoreDoSpecConstr
708         else
709            CoreDoNothing,
710
711         -- Final clean-up simplification:
712         CoreDoSimplify (SimplPhase 0) [
713           MaxSimplifierIterations max_iter
714         ]
715      ]
716
717 -- -----------------------------------------------------------------------------
718 -- StgToDo:  abstraction of stg-to-stg passes to run.
719
720 data StgToDo
721   = StgDoMassageForProfiling  -- should be (next to) last
722   -- There's also setStgVarInfo, but its absolute "lastness"
723   -- is so critical that it is hardwired in (no flag).
724   | D_stg_stats
725
726 getStgToDo :: DynFlags -> [StgToDo]
727 getStgToDo dflags
728   | Just todo <- stgToDo dflags = todo -- set explicitly by user
729   | otherwise = todo2
730   where
731         stg_stats = dopt Opt_StgStats dflags
732
733         todo1 = if stg_stats then [D_stg_stats] else []
734
735         todo2 | WayProf `elem` wayNames dflags
736               = StgDoMassageForProfiling : todo1
737               | otherwise
738               = todo1
739
740 -- -----------------------------------------------------------------------------
741 -- DynFlags parser
742
743 dynamic_flags :: [(String, OptKind DynP)]
744 dynamic_flags = [
745      ( "n"              , NoArg  (setDynFlag Opt_DryRun) )
746   ,  ( "cpp"            , NoArg  (setDynFlag Opt_Cpp))
747   ,  ( "F"              , NoArg  (setDynFlag Opt_Pp))
748   ,  ( "#include"       , HasArg (addCmdlineHCInclude) )
749   ,  ( "v"              , OptPrefix (setVerbosity) )
750
751         ------- Specific phases  --------------------------------------------
752   ,  ( "pgmL"           , HasArg (upd . setPgmL) )  
753   ,  ( "pgmP"           , HasArg (upd . setPgmP) )  
754   ,  ( "pgmF"           , HasArg (upd . setPgmF) )  
755   ,  ( "pgmc"           , HasArg (upd . setPgmc) )  
756   ,  ( "pgmm"           , HasArg (upd . setPgmm) )  
757   ,  ( "pgms"           , HasArg (upd . setPgms) )  
758   ,  ( "pgma"           , HasArg (upd . setPgma) )  
759   ,  ( "pgml"           , HasArg (upd . setPgml) )  
760   ,  ( "pgmdll"         , HasArg (upd . setPgmdll) )
761
762   ,  ( "optL"           , HasArg (upd . addOptL) )  
763   ,  ( "optP"           , HasArg (upd . addOptP) )  
764   ,  ( "optF"           , HasArg (upd . addOptF) )  
765   ,  ( "optc"           , HasArg (upd . addOptc) )  
766   ,  ( "optm"           , HasArg (upd . addOptm) )  
767   ,  ( "opta"           , HasArg (upd . addOpta) )  
768   ,  ( "optl"           , HasArg (upd . addOptl) )  
769   ,  ( "optdll"         , HasArg (upd . addOptdll) )  
770   ,  ( "optdep"         , HasArg (upd . addOptdep) )
771
772   ,  ( "split-objs"     , NoArg (if can_split
773                                     then setDynFlag Opt_SplitObjs
774                                     else return ()) )
775
776         -------- Linking ----------------------------------------------------
777   ,  ( "c"              , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
778   ,  ( "no-link"        , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
779   ,  ( "-mk-dll"        , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
780
781         ------- Libraries ---------------------------------------------------
782   ,  ( "L"              , Prefix addLibraryPath )
783   ,  ( "l"              , AnySuffix (\s -> do upd (addOptl s)
784                                               upd (addOptdll s)))
785
786         ------- Frameworks --------------------------------------------------
787         -- -framework-path should really be -F ...
788   ,  ( "framework-path" , HasArg addFrameworkPath )
789   ,  ( "framework"      , HasArg (upd . addCmdlineFramework) )
790
791         ------- Output Redirection ------------------------------------------
792   ,  ( "odir"           , HasArg (upd . setOutputDir  . Just))
793   ,  ( "o"              , SepArg (upd . setOutputFile . Just))
794   ,  ( "ohi"            , HasArg (upd . setOutputHi   . Just ))
795   ,  ( "osuf"           , HasArg (upd . setObjectSuf))
796   ,  ( "hcsuf"          , HasArg (upd . setHcSuf))
797   ,  ( "hisuf"          , HasArg (upd . setHiSuf))
798   ,  ( "hidir"          , HasArg (upd . setHiDir . Just))
799   ,  ( "tmpdir"         , HasArg (upd . setTmpDir))
800
801         ------- Keeping temporary files -------------------------------------
802   ,  ( "keep-hc-file"   , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
803   ,  ( "keep-s-file"    , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
804   ,  ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
805   ,  ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
806
807         ------- Miscellaneous ----------------------------------------------
808   ,  ( "no-hs-main"     , NoArg (setDynFlag Opt_NoHsMain))
809   ,  ( "main-is"        , SepArg setMainIs )
810
811         ------- recompilation checker --------------------------------------
812   ,  ( "recomp"         , NoArg (setDynFlag   Opt_RecompChecking) )
813   ,  ( "no-recomp"      , NoArg (unSetDynFlag Opt_RecompChecking) )
814
815         ------- Packages ----------------------------------------------------
816   ,  ( "package-conf"   , HasArg extraPkgConf_ )
817   ,  ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
818   ,  ( "package-name"   , HasArg ignorePackage ) -- for compatibility
819   ,  ( "package"        , HasArg exposePackage )
820   ,  ( "hide-package"   , HasArg hidePackage )
821   ,  ( "ignore-package" , HasArg ignorePackage )
822   ,  ( "syslib"         , HasArg exposePackage )  -- for compatibility
823
824         ------ HsCpp opts ---------------------------------------------------
825   ,  ( "D",             AnySuffix (upd . addOptP) )
826   ,  ( "U",             AnySuffix (upd . addOptP) )
827
828         ------- Include/Import Paths ----------------------------------------
829   ,  ( "I"              , Prefix    addIncludePath)
830   ,  ( "i"              , OptPrefix addImportPath )
831
832         ------ Debugging ----------------------------------------------------
833   ,  ( "dstg-stats",    NoArg (setDynFlag Opt_StgStats))
834
835   ,  ( "ddump-cmm",              setDumpFlag Opt_D_dump_cmm)
836   ,  ( "ddump-asm",              setDumpFlag Opt_D_dump_asm)
837   ,  ( "ddump-cpranal",          setDumpFlag Opt_D_dump_cpranal)
838   ,  ( "ddump-deriv",            setDumpFlag Opt_D_dump_deriv)
839   ,  ( "ddump-ds",               setDumpFlag Opt_D_dump_ds)
840   ,  ( "ddump-flatC",            setDumpFlag Opt_D_dump_flatC)
841   ,  ( "ddump-foreign",          setDumpFlag Opt_D_dump_foreign)
842   ,  ( "ddump-inlinings",        setDumpFlag Opt_D_dump_inlinings)
843   ,  ( "ddump-occur-anal",       setDumpFlag Opt_D_dump_occur_anal)
844   ,  ( "ddump-parsed",           setDumpFlag Opt_D_dump_parsed)
845   ,  ( "ddump-rn",               setDumpFlag Opt_D_dump_rn)
846   ,  ( "ddump-simpl",            setDumpFlag Opt_D_dump_simpl)
847   ,  ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
848   ,  ( "ddump-spec",             setDumpFlag Opt_D_dump_spec)
849   ,  ( "ddump-prep",             setDumpFlag Opt_D_dump_prep)
850   ,  ( "ddump-stg",              setDumpFlag Opt_D_dump_stg)
851   ,  ( "ddump-stranal",          setDumpFlag Opt_D_dump_stranal)
852   ,  ( "ddump-tc",               setDumpFlag Opt_D_dump_tc)
853   ,  ( "ddump-types",            setDumpFlag Opt_D_dump_types)
854   ,  ( "ddump-rules",            setDumpFlag Opt_D_dump_rules)
855   ,  ( "ddump-cse",              setDumpFlag Opt_D_dump_cse)
856   ,  ( "ddump-worker-wrapper",   setDumpFlag Opt_D_dump_worker_wrapper)
857   ,  ( "ddump-rn-trace",         NoArg (setDynFlag Opt_D_dump_rn_trace))
858   ,  ( "ddump-if-trace",         NoArg (setDynFlag Opt_D_dump_if_trace))
859   ,  ( "ddump-tc-trace",         setDumpFlag Opt_D_dump_tc_trace)
860   ,  ( "ddump-splices",          setDumpFlag Opt_D_dump_splices)
861   ,  ( "ddump-rn-stats",         NoArg (setDynFlag Opt_D_dump_rn_stats))
862   ,  ( "ddump-opt-cmm",          setDumpFlag Opt_D_dump_opt_cmm)
863   ,  ( "ddump-simpl-stats",      setDumpFlag Opt_D_dump_simpl_stats)
864   ,  ( "ddump-bcos",             setDumpFlag Opt_D_dump_BCOs)
865   ,  ( "dsource-stats",          setDumpFlag Opt_D_source_stats)
866   ,  ( "dverbose-core2core",     setDumpFlag Opt_D_verbose_core2core)
867   ,  ( "dverbose-stg2stg",       setDumpFlag Opt_D_verbose_stg2stg)
868   ,  ( "ddump-hi-diffs",         setDumpFlag Opt_D_dump_hi_diffs)
869   ,  ( "ddump-hi",               setDumpFlag Opt_D_dump_hi)
870   ,  ( "ddump-minimal-imports",  setDumpFlag Opt_D_dump_minimal_imports)
871   ,  ( "ddump-vect",             setDumpFlag Opt_D_dump_vect)
872   ,  ( "dcore-lint",             NoArg (setDynFlag Opt_DoCoreLinting))
873   ,  ( "dstg-lint",              NoArg (setDynFlag Opt_DoStgLinting))
874   ,  ( "dcmm-lint",              NoArg (setDynFlag Opt_DoCmmLinting))
875   ,  ( "dshow-passes",           NoArg (do unSetDynFlag Opt_RecompChecking
876                                            setVerbosity "2") )
877
878         ------ Machine dependant (-m<blah>) stuff ---------------------------
879
880   ,  ( "monly-2-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
881   ,  ( "monly-3-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
882   ,  ( "monly-4-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
883
884         ------ Warning opts -------------------------------------------------
885   ,  ( "W"              , NoArg (mapM_ setDynFlag   minusWOpts)    )
886   ,  ( "Werror"         , NoArg (setDynFlag         Opt_WarnIsError) )
887   ,  ( "Wall"           , NoArg (mapM_ setDynFlag   minusWallOpts) )
888   ,  ( "Wnot"           , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
889   ,  ( "w"              , NoArg (mapM_ unSetDynFlag minusWallOpts) )
890
891         ------ Optimisation flags ------------------------------------------
892   ,  ( "O"                 , NoArg (upd (setOptLevel 1)))
893   ,  ( "Onot"              , NoArg (upd (setOptLevel 0)))
894   ,  ( "O"                 , PrefixPred (all isDigit) 
895                                 (\f -> upd (setOptLevel (read f))))
896
897   ,  ( "fmax-simplifier-iterations", 
898                 PrefixPred (all isDigit) 
899                   (\n -> upd (\dfs -> 
900                         dfs{ maxSimplIterations = read n })) )
901
902   ,  ( "frule-check", 
903                 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
904
905         ------ Compiler flags -----------------------------------------------
906
907   ,  ( "fasm",          AnySuffix (\_ -> setTarget HscAsm) )
908   ,  ( "fvia-c",        NoArg (setTarget HscC) )
909   ,  ( "fvia-C",        NoArg (setTarget HscC) )
910   ,  ( "filx",          NoArg (setTarget HscILX) )
911
912   ,  ( "fglasgow-exts",    NoArg (mapM_ setDynFlag   glasgowExtsFlags) )
913   ,  ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
914
915         -- the rest of the -f* and -fno-* flags
916   ,  ( "fno-",          PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
917   ,  ( "f",             PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
918  ]
919
920 -- these -f<blah> flags can all be reversed with -fno-<blah>
921
922 fFlags = [
923   ( "warn-duplicate-exports",           Opt_WarnDuplicateExports ),
924   ( "warn-hi-shadowing",                Opt_WarnHiShadows ),
925   ( "warn-incomplete-patterns",         Opt_WarnIncompletePatterns ),
926   ( "warn-incomplete-record-updates",   Opt_WarnIncompletePatternsRecUpd ),
927   ( "warn-missing-fields",              Opt_WarnMissingFields ),
928   ( "warn-missing-methods",             Opt_WarnMissingMethods ),
929   ( "warn-missing-signatures",          Opt_WarnMissingSigs ),
930   ( "warn-name-shadowing",              Opt_WarnNameShadowing ),
931   ( "warn-overlapping-patterns",        Opt_WarnOverlappingPatterns ),
932   ( "warn-simple-patterns",             Opt_WarnSimplePatterns ),
933   ( "warn-type-defaults",               Opt_WarnTypeDefaults ),
934   ( "warn-unused-binds",                Opt_WarnUnusedBinds ),
935   ( "warn-unused-imports",              Opt_WarnUnusedImports ),
936   ( "warn-unused-matches",              Opt_WarnUnusedMatches ),
937   ( "warn-deprecations",                Opt_WarnDeprecations ),
938   ( "warn-orphans",                     Opt_WarnOrphans ),
939   ( "fi",                               Opt_FFI ),  -- support `-ffi'...
940   ( "ffi",                              Opt_FFI ),  -- ...and also `-fffi'
941   ( "arrows",                           Opt_Arrows ), -- arrow syntax
942   ( "parr",                             Opt_PArr ),
943   ( "th",                               Opt_TH ),
944   ( "implicit-prelude",                 Opt_ImplicitPrelude ),
945   ( "scoped-type-variables",            Opt_ScopedTypeVariables ),
946   ( "monomorphism-restriction",         Opt_MonomorphismRestriction ),
947   ( "implicit-params",                  Opt_ImplicitParams ),
948   ( "allow-overlapping-instances",      Opt_AllowOverlappingInstances ),
949   ( "allow-undecidable-instances",      Opt_AllowUndecidableInstances ),
950   ( "allow-incoherent-instances",       Opt_AllowIncoherentInstances ),
951   ( "generics",                         Opt_Generics ),
952   ( "strictness",                       Opt_Strictness ),
953   ( "full-laziness",                    Opt_FullLaziness ),
954   ( "cse",                              Opt_CSE ),
955   ( "ignore-interface-pragmas",         Opt_IgnoreInterfacePragmas ),
956   ( "omit-interface-pragmas",           Opt_OmitInterfacePragmas ),
957   ( "do-lambda-eta-expansion",          Opt_DoLambdaEtaExpansion ),
958   ( "ignore-asserts",                   Opt_IgnoreAsserts ),
959   ( "do-eta-reduction",                 Opt_DoEtaReduction ),
960   ( "case-merge",                       Opt_CaseMerge ),
961   ( "unbox-strict-fields",              Opt_UnboxStrictFields ),
962   ( "excess-precision",                 Opt_ExcessPrecision ),
963   ( "asm-mangling",                     Opt_DoAsmMangling )
964   ]
965
966 glasgowExtsFlags = [ 
967   Opt_GlasgowExts, 
968   Opt_FFI, 
969   Opt_TH, 
970   Opt_ImplicitParams, 
971   Opt_ScopedTypeVariables ]
972
973 isFFlag f = f `elem` (map fst fFlags)
974 getFFlag f = fromJust (lookup f fFlags)
975
976 -- -----------------------------------------------------------------------------
977 -- Parsing the dynamic flags.
978
979 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
980 parseDynamicFlags dflags args = do
981   let ((leftover,errs),dflags') 
982           = runCmdLine (processArgs dynamic_flags args) dflags
983   when (not (null errs)) $ do
984     throwDyn (UsageError (unlines errs))
985   return (dflags', leftover)
986
987
988 type DynP = CmdLineP DynFlags
989
990 upd :: (DynFlags -> DynFlags) -> DynP ()
991 upd f = do 
992    dfs <- getCmdLineState
993    putCmdLineState $! (f dfs)
994
995 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
996 setDynFlag f   = upd (\dfs -> dopt_set dfs f)
997 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
998
999 setDumpFlag :: DynFlag -> OptKind DynP
1000 setDumpFlag dump_flag 
1001   = NoArg (unSetDynFlag Opt_RecompChecking >> setDynFlag dump_flag)
1002         -- Whenver we -ddump, switch off the recompilation checker,
1003         -- else you don't see the dump!
1004
1005 setVerbosity "" = upd (\dfs -> dfs{ verbosity = 3 })
1006 setVerbosity n 
1007   | all isDigit n = upd (\dfs -> dfs{ verbosity = read n })
1008   | otherwise     = throwDyn (UsageError "can't parse verbosity flag (-v<n>)")
1009
1010 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes =  a : cmdlineHcIncludes s})
1011
1012 extraPkgConf_  p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1013
1014 exposePackage p = 
1015   upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1016 hidePackage p = 
1017   upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1018 ignorePackage p = 
1019   upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1020
1021 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags 
1022 -- (-fvia-C, -fasm, -filx respectively).
1023 setTarget l = upd (\dfs -> case hscTarget dfs of
1024                                         HscC   -> dfs{ hscTarget = l }
1025                                         HscAsm -> dfs{ hscTarget = l }
1026                                         HscILX -> dfs{ hscTarget = l }
1027                                         _      -> dfs)
1028
1029 setOptLevel :: Int -> DynFlags -> DynFlags
1030 setOptLevel n dflags
1031    | hscTarget dflags == HscInterpreted && n > 0
1032         = dflags
1033             -- not in IO any more, oh well:
1034             -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1035    | otherwise
1036         = updOptLevel n dflags
1037
1038
1039 setMainIs :: String -> DynP ()
1040 setMainIs arg
1041   | not (null main_mod)         -- The arg looked like "Foo.baz"
1042   = upd $ \d -> d{ mainFunIs = Just main_fn,
1043                    mainModIs = Just main_mod }
1044
1045   | isUpper (head main_fn)      -- The arg looked like "Foo"
1046   = upd $ \d -> d{ mainModIs = Just main_fn }
1047   
1048   | otherwise                   -- The arg looked like "baz"
1049   = upd $ \d -> d{ mainFunIs = Just main_fn }
1050   where
1051     (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1052   
1053
1054 -----------------------------------------------------------------------------
1055 -- Paths & Libraries
1056
1057 -- -i on its own deletes the import paths
1058 addImportPath "" = upd (\s -> s{importPaths = []})
1059 addImportPath p  = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1060
1061
1062 addLibraryPath p = 
1063   upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1064
1065 addIncludePath p = 
1066   upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1067
1068 addFrameworkPath p = 
1069   upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1070
1071 split_marker = ':'   -- not configurable (ToDo)
1072
1073 splitPathList :: String -> [String]
1074 splitPathList s = filter notNull (splitUp s)
1075                 -- empty paths are ignored: there might be a trailing
1076                 -- ':' in the initial list, for example.  Empty paths can
1077                 -- cause confusion when they are translated into -I options
1078                 -- for passing to gcc.
1079   where
1080 #ifndef mingw32_TARGET_OS
1081     splitUp xs = split split_marker xs
1082 #else 
1083      -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1084      -- 
1085      -- That is, if "foo:bar:baz" is used, this interpreted as
1086      -- consisting of three entries, 'foo', 'bar', 'baz'.
1087      -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1088      -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1089      --
1090      -- Notice that no attempt is made to fully replace the 'standard'
1091      -- split marker ':' with the Windows / DOS one, ';'. The reason being
1092      -- that this will cause too much breakage for users & ':' will
1093      -- work fine even with DOS paths, if you're not insisting on being silly.
1094      -- So, use either.
1095     splitUp []         = []
1096     splitUp (x:':':div:xs) 
1097       | div `elem` dir_markers = do
1098           let (p,rs) = findNextPath xs
1099           in ((x:':':div:p): splitUp rs)
1100           -- we used to check for existence of the path here, but that
1101           -- required the IO monad to be threaded through the command-line
1102           -- parser which is quite inconvenient.  The 
1103     splitUp xs = do
1104       let (p,rs) = findNextPath xs
1105       return (cons p (splitUp rs))
1106     
1107     cons "" xs = xs
1108     cons x  xs = x:xs
1109
1110     -- will be called either when we've consumed nought or the
1111     -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1112     -- finding the next split marker.
1113     findNextPath xs = 
1114         case break (`elem` split_markers) xs of
1115            (p, d:ds) -> (p, ds)
1116            (p, xs)   -> (p, xs)
1117
1118     split_markers :: [Char]
1119     split_markers = [':', ';']
1120
1121     dir_markers :: [Char]
1122     dir_markers = ['/', '\\']
1123 #endif
1124
1125 -- -----------------------------------------------------------------------------
1126 -- tmpDir, where we store temporary files.
1127
1128 setTmpDir :: FilePath -> DynFlags -> DynFlags
1129 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1130   where
1131 #if !defined(mingw32_HOST_OS)
1132      canonicalise p = normalisePath p
1133 #else
1134         -- Canonicalisation of temp path under win32 is a bit more
1135         -- involved: (a) strip trailing slash, 
1136         --           (b) normalise slashes
1137         --           (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1138         -- 
1139      canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1140
1141         -- if we're operating under cygwin, and TMP/TEMP is of
1142         -- the form "/cygdrive/drive/path", translate this to
1143         -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1144         -- understand /cygdrive paths.)
1145      xltCygdrive path
1146       | "/cygdrive/" `isPrefixOf` path = 
1147           case drop (length "/cygdrive/") path of
1148             drive:xs@('/':_) -> drive:':':xs
1149             _ -> path
1150       | otherwise = path
1151
1152         -- strip the trailing backslash (awful, but we only do this once).
1153      removeTrailingSlash path = 
1154        case last path of
1155          '/'  -> init path
1156          '\\' -> init path
1157          _    -> path
1158 #endif
1159
1160 -----------------------------------------------------------------------------
1161 -- Via-C compilation stuff
1162
1163 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1164                               [String]) -- for registerised HC compilations
1165 machdepCCOpts dflags
1166 #if alpha_TARGET_ARCH
1167         =       ( ["-w", "-mieee"
1168 #ifdef HAVE_THREADED_RTS_SUPPORT
1169                     , "-D_REENTRANT"
1170 #endif
1171                    ], [] )
1172         -- For now, to suppress the gcc warning "call-clobbered
1173         -- register used for global register variable", we simply
1174         -- disable all warnings altogether using the -w flag. Oh well.
1175
1176 #elif hppa_TARGET_ARCH
1177         -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1178         -- (very nice, but too bad the HP /usr/include files don't agree.)
1179         = ( ["-D_HPUX_SOURCE"], [] )
1180
1181 #elif m68k_TARGET_ARCH
1182       -- -fno-defer-pop : for the .hc files, we want all the pushing/
1183       --    popping of args to routines to be explicit; if we let things
1184       --    be deferred 'til after an STGJUMP, imminent death is certain!
1185       --
1186       -- -fomit-frame-pointer : *don't*
1187       --     It's better to have a6 completely tied up being a frame pointer
1188       --     rather than let GCC pick random things to do with it.
1189       --     (If we want to steal a6, then we would try to do things
1190       --     as on iX86, where we *do* steal the frame pointer [%ebp].)
1191         = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1192
1193 #elif i386_TARGET_ARCH
1194       -- -fno-defer-pop : basically the same game as for m68k
1195       --
1196       -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1197       --   the fp (%ebp) for our register maps.
1198         =  let n_regs = stolen_x86_regs dflags
1199                sta = opt_Static
1200            in
1201                     ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1202 --                    , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else "" 
1203                       ],
1204                       [ "-fno-defer-pop",
1205 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1206                         -- Some gccs are configured with
1207                         -- -momit-leaf-frame-pointer on by default, and it
1208                         -- apparently takes precedence over 
1209                         -- -fomit-frame-pointer, so we disable it first here.
1210                         "-mno-omit-leaf-frame-pointer",
1211 #endif
1212                         "-fomit-frame-pointer",
1213                         -- we want -fno-builtin, because when gcc inlines
1214                         -- built-in functions like memcpy() it tends to
1215                         -- run out of registers, requiring -monly-n-regs
1216                         "-fno-builtin",
1217                         "-DSTOLEN_X86_REGS="++show n_regs ]
1218                     )
1219
1220 #elif ia64_TARGET_ARCH
1221         = ( [], ["-fomit-frame-pointer", "-G0"] )
1222
1223 #elif x86_64_TARGET_ARCH
1224         = ( [], ["-fomit-frame-pointer"] )
1225
1226 #elif mips_TARGET_ARCH
1227         = ( ["-static"], [] )
1228
1229 #elif sparc_TARGET_ARCH
1230         = ( [], ["-w"] )
1231         -- For now, to suppress the gcc warning "call-clobbered
1232         -- register used for global register variable", we simply
1233         -- disable all warnings altogether using the -w flag. Oh well.
1234
1235 #elif powerpc_apple_darwin_TARGET
1236       -- -no-cpp-precomp:
1237       --     Disable Apple's precompiling preprocessor. It's a great thing
1238       --     for "normal" programs, but it doesn't support register variable
1239       --     declarations.
1240         = ( [], ["-no-cpp-precomp"] )
1241 #else
1242         = ( [], [] )
1243 #endif
1244
1245 picCCOpts :: DynFlags -> [String]
1246 picCCOpts dflags
1247 #if darwin_TARGET_OS
1248       -- Apple prefers to do things the other way round.
1249       -- PIC is on by default.
1250       -- -mdynamic-no-pic:
1251       --     Turn off PIC code generation.
1252       -- -fno-common:
1253       --     Don't generate "common" symbols - these are unwanted
1254       --     in dynamic libraries.
1255
1256     | opt_PIC
1257         = ["-fno-common"]
1258     | otherwise
1259         = ["-mdynamic-no-pic"]
1260 #elif mingw32_TARGET_OS
1261       -- no -fPIC for Windows
1262         = []
1263 #else
1264     | opt_PIC
1265         = ["-fPIC"]
1266     | otherwise
1267         = []
1268 #endif
1269
1270 -- -----------------------------------------------------------------------------
1271 -- Splitting
1272
1273 can_split :: Bool
1274 can_split =  
1275 #if    defined(i386_TARGET_ARCH)     \
1276     || defined(alpha_TARGET_ARCH)    \
1277     || defined(hppa_TARGET_ARCH)     \
1278     || defined(m68k_TARGET_ARCH)     \
1279     || defined(mips_TARGET_ARCH)     \
1280     || defined(powerpc_TARGET_ARCH)  \
1281     || defined(rs6000_TARGET_ARCH)   \
1282     || defined(sparc_TARGET_ARCH) 
1283    True
1284 #else
1285    False
1286 #endif
1287