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