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