update for changes in hetmet Makefile
[ghc-hetmet.git] / compiler / main / DynFlags.hs
1 {-# OPTIONS_GHC -w #-}
2 -- Temporary, until rtsIsProfiled is fixed
3
4 -- |
5 -- Dynamic flags
6 --
7 --
8 -- (c) The University of Glasgow 2005
9 --
10
11 -- Most flags are dynamic flags, which means they can change from
12 -- compilation to compilation using @OPTIONS_GHC@ pragmas, and in a
13 -- multi-session GHC each session can be using different dynamic
14 -- flags.  Dynamic flags can also be set at the prompt in GHCi.
15 module DynFlags (
16         -- * Dynamic flags and associated configuration types
17         DynFlag(..),
18         ExtensionFlag(..),
19         glasgowExtsFlags,
20         dopt,
21         dopt_set,
22         dopt_unset,
23         xopt,
24         xopt_set,
25         xopt_unset,
26         DynFlags(..),
27         RtsOptsEnabled(..),
28         HscTarget(..), isObjectTarget, defaultObjectTarget,
29         GhcMode(..), isOneShot,
30         GhcLink(..), isNoLink,
31         PackageFlag(..),
32         Option(..), showOpt,
33         DynLibLoader(..),
34         fFlags, fLangFlags, xFlags,
35         DPHBackend(..), dphPackageMaybe,
36         wayNames,
37
38         -- ** Manipulating DynFlags
39         defaultDynFlags,                -- DynFlags
40         initDynFlags,                   -- DynFlags -> IO DynFlags
41
42         getOpts,                        -- DynFlags -> (DynFlags -> [a]) -> [a]
43         getVerbFlag,
44         updOptLevel,
45         setTmpDir,
46         setPackageName,
47         doingTickyProfiling,
48
49         -- ** Parsing DynFlags
50         parseDynamicFlags,
51         parseDynamicNoPackageFlags,
52         allFlags,
53
54         supportedLanguagesAndExtensions,
55
56         -- ** DynFlag C compiler options
57         machdepCCOpts, picCCOpts,
58
59         -- * Configuration of the stg-to-stg passes
60         StgToDo(..),
61         getStgToDo,
62
63         -- * Compiler configuration suitable for display to the user
64         Printable(..),
65         compilerInfo
66 #ifdef GHCI
67 -- Only in stage 2 can we be sure that the RTS 
68 -- exposes the appropriate runtime boolean
69         , rtsIsProfiled
70 #endif
71   ) where
72
73 #include "HsVersions.h"
74
75 #ifndef OMIT_NATIVE_CODEGEN
76 import Platform
77 #endif
78 import Module
79 import PackageConfig
80 import PrelNames        ( mAIN )
81 import StaticFlags
82 import {-# SOURCE #-} Packages (PackageState)
83 import DriverPhases     ( Phase(..), phaseInputExt )
84 import Config
85 import CmdLineParser
86 import Constants        ( mAX_CONTEXT_REDUCTION_DEPTH )
87 import Panic
88 import Util
89 import Maybes           ( orElse )
90 import SrcLoc
91 import FastString
92 import Outputable
93 import Foreign.C        ( CInt )
94 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
95
96 import System.IO.Unsafe ( unsafePerformIO )
97 import Data.IORef
98 import Control.Monad    ( when )
99
100 import Data.Char
101 import Data.List
102 import Data.Map (Map)
103 import qualified Data.Map as Map
104 import Data.Maybe
105 import System.FilePath
106 import System.IO        ( stderr, hPutChar )
107
108 -- -----------------------------------------------------------------------------
109 -- DynFlags
110
111 -- | Enumerates the simple on-or-off dynamic flags
112 data DynFlag
113
114    -- debugging flags
115    = Opt_D_dump_cmm
116    | Opt_D_dump_cmmz
117    | Opt_D_dump_cmmz_pretty
118    | Opt_D_dump_cps_cmm
119    | Opt_D_dump_cvt_cmm
120    | Opt_D_dump_asm
121    | Opt_D_dump_asm_native
122    | Opt_D_dump_asm_liveness
123    | Opt_D_dump_asm_coalesce
124    | Opt_D_dump_asm_regalloc
125    | Opt_D_dump_asm_regalloc_stages
126    | Opt_D_dump_asm_conflicts
127    | Opt_D_dump_asm_stats
128    | Opt_D_dump_asm_expanded
129    | Opt_D_dump_llvm
130    | Opt_D_dump_cpranal
131    | Opt_D_dump_deriv
132    | Opt_D_dump_ds
133    | Opt_D_dump_flatC
134    | Opt_D_dump_foreign
135    | Opt_D_dump_inlinings
136    | Opt_D_dump_rule_firings
137    | Opt_D_dump_rule_rewrites
138    | Opt_D_dump_occur_anal
139    | Opt_D_dump_parsed
140    | Opt_D_dump_rn
141    | Opt_D_dump_simpl
142    | Opt_D_dump_simpl_iterations
143    | Opt_D_dump_simpl_phases
144    | Opt_D_dump_spec
145    | Opt_D_dump_prep
146    | Opt_D_dump_stg
147    | Opt_D_dump_stranal
148    | Opt_D_dump_tc
149    | Opt_D_dump_types
150    | Opt_D_dump_rules
151    | Opt_D_dump_cse
152    | Opt_D_dump_worker_wrapper
153    | Opt_D_dump_rn_trace
154    | Opt_D_dump_rn_stats
155    | Opt_D_dump_opt_cmm
156    | Opt_D_dump_simpl_stats
157    | Opt_D_dump_cs_trace        -- Constraint solver in type checker
158    | Opt_D_dump_tc_trace
159    | Opt_D_dump_if_trace
160    | Opt_D_dump_vt_trace
161    | Opt_D_dump_splices
162    | Opt_D_dump_BCOs
163    | Opt_D_dump_vect
164    | Opt_D_dump_hpc
165    | Opt_D_dump_rtti
166    | Opt_D_source_stats
167    | Opt_D_verbose_core2core
168    | Opt_D_verbose_stg2stg
169    | Opt_D_dump_hi
170    | Opt_D_dump_hi_diffs
171    | Opt_D_dump_minimal_imports
172    | Opt_D_dump_mod_cycles
173    | Opt_D_dump_view_pattern_commoning
174    | Opt_D_faststring_stats
175    | Opt_DumpToFile                     -- ^ Append dump output to files instead of stdout.
176    | Opt_D_no_debug_output
177    | Opt_DoCoreLinting
178    | Opt_DoStgLinting
179    | Opt_DoCmmLinting
180    | Opt_DoAsmLinting
181
182    | Opt_F_coqpass                      -- run the core-to-core   coqPass (does whatever CoqPass.hs says)
183    | Opt_D_coqpass                      -- run the core-to-string coqPass and dumps the result
184    | Opt_D_dump_coqpass                 -- dumps the output of the core-to-core coqPass
185
186    | Opt_WarnIsError                    -- -Werror; makes warnings fatal
187    | Opt_WarnDuplicateExports
188    | Opt_WarnHiShadows
189    | Opt_WarnImplicitPrelude
190    | Opt_WarnIncompletePatterns
191    | Opt_WarnIncompleteUniPatterns
192    | Opt_WarnIncompletePatternsRecUpd
193    | Opt_WarnMissingFields
194    | Opt_WarnMissingImportList
195    | Opt_WarnMissingMethods
196    | Opt_WarnMissingSigs
197    | Opt_WarnMissingLocalSigs
198    | Opt_WarnNameShadowing
199    | Opt_WarnOverlappingPatterns
200    | Opt_WarnTypeDefaults
201    | Opt_WarnMonomorphism
202    | Opt_WarnUnusedBinds
203    | Opt_WarnUnusedImports
204    | Opt_WarnUnusedMatches
205    | Opt_WarnWarningsDeprecations
206    | Opt_WarnDeprecatedFlags
207    | Opt_WarnDodgyExports
208    | Opt_WarnDodgyImports
209    | Opt_WarnOrphans
210    | Opt_WarnAutoOrphans
211    | Opt_WarnIdentities
212    | Opt_WarnTabs
213    | Opt_WarnUnrecognisedPragmas
214    | Opt_WarnDodgyForeignImports
215    | Opt_WarnLazyUnliftedBindings
216    | Opt_WarnUnusedDoBind
217    | Opt_WarnWrongDoBind
218    | Opt_WarnAlternativeLayoutRuleTransitional
219
220    | Opt_PrintExplicitForalls
221
222    -- optimisation opts
223    | Opt_Strictness
224    | Opt_FullLaziness
225    | Opt_FloatIn
226    | Opt_Specialise
227    | Opt_StaticArgumentTransformation
228    | Opt_CSE
229    | Opt_LiberateCase
230    | Opt_SpecConstr
231    | Opt_DoLambdaEtaExpansion
232    | Opt_IgnoreAsserts
233    | Opt_DoEtaReduction
234    | Opt_CaseMerge
235    | Opt_UnboxStrictFields
236    | Opt_MethodSharing  -- Now a no-op; remove in GHC 7.2
237    | Opt_DictsCheap
238    | Opt_EnableRewriteRules             -- Apply rewrite rules during simplification
239    | Opt_Vectorise
240    | Opt_RegsGraph                      -- do graph coloring register allocation
241    | Opt_RegsIterative                  -- do iterative coalescing graph coloring register allocation
242
243    -- Interface files
244    | Opt_IgnoreInterfacePragmas
245    | Opt_OmitInterfacePragmas
246    | Opt_ExposeAllUnfoldings
247
248    -- profiling opts
249    | Opt_AutoSccsOnAllToplevs
250    | Opt_AutoSccsOnExportedToplevs
251    | Opt_AutoSccsOnIndividualCafs
252
253    -- misc opts
254    | Opt_Pp
255    | Opt_ForceRecomp
256    | Opt_DryRun
257    | Opt_DoAsmMangling
258    | Opt_ExcessPrecision
259    | Opt_EagerBlackHoling
260    | Opt_ReadUserPackageConf
261    | Opt_NoHsMain
262    | Opt_SplitObjs
263    | Opt_StgStats
264    | Opt_HideAllPackages
265    | Opt_PrintBindResult
266    | Opt_Haddock
267    | Opt_HaddockOptions
268    | Opt_Hpc_No_Auto
269    | Opt_BreakOnException
270    | Opt_BreakOnError
271    | Opt_PrintEvldWithShow
272    | Opt_PrintBindContents
273    | Opt_GenManifest
274    | Opt_EmbedManifest
275    | Opt_EmitExternalCore
276    | Opt_SharedImplib
277    | Opt_BuildingCabalPackage
278    | Opt_SSE2
279    | Opt_GhciSandbox
280    | Opt_HelpfulErrors
281
282         -- temporary flags
283    | Opt_RunCPS
284    | Opt_RunCPSZ
285    | Opt_ConvertToZipCfgAndBack
286    | Opt_AutoLinkPackages
287    | Opt_ImplicitImportQualified
288    | Opt_TryNewCodeGen
289
290    -- keeping stuff
291    | Opt_KeepHiDiffs
292    | Opt_KeepHcFiles
293    | Opt_KeepSFiles
294    | Opt_KeepRawSFiles
295    | Opt_KeepTmpFiles
296    | Opt_KeepRawTokenStream
297    | Opt_KeepLlvmFiles
298
299    deriving (Eq, Show)
300
301 data Language = Haskell98 | Haskell2010
302
303 data ExtensionFlag
304    = Opt_Cpp
305    | Opt_OverlappingInstances
306    | Opt_UndecidableInstances
307    | Opt_IncoherentInstances
308    | Opt_MonomorphismRestriction
309    | Opt_MonoPatBinds
310    | Opt_MonoLocalBinds
311    | Opt_RelaxedPolyRec         -- Deprecated
312    | Opt_ExtendedDefaultRules           -- Use GHC's extended rules for defaulting
313    | Opt_ForeignFunctionInterface
314    | Opt_UnliftedFFITypes
315    | Opt_GHCForeignImportPrim
316    | Opt_ParallelArrays                 -- Syntactic support for parallel arrays
317    | Opt_Arrows                         -- Arrow-notation syntax
318    | Opt_ModalTypes                     -- Heterogeneous Metaprogramming (modal types, brackets, escape, CSP)
319    | Opt_TemplateHaskell
320    | Opt_QuasiQuotes
321    | Opt_ImplicitParams
322    | Opt_Generics                       -- "Derivable type classes"
323    | Opt_ImplicitPrelude
324    | Opt_ScopedTypeVariables
325    | Opt_UnboxedTuples
326    | Opt_BangPatterns
327    | Opt_TypeFamilies
328    | Opt_OverloadedStrings
329    | Opt_DisambiguateRecordFields
330    | Opt_RecordWildCards
331    | Opt_RecordPuns
332    | Opt_ViewPatterns
333    | Opt_GADTs
334    | Opt_GADTSyntax
335    | Opt_NPlusKPatterns
336    | Opt_DoAndIfThenElse
337    | Opt_RebindableSyntax
338
339    | Opt_StandaloneDeriving
340    | Opt_DeriveDataTypeable
341    | Opt_DeriveFunctor
342    | Opt_DeriveTraversable
343    | Opt_DeriveFoldable
344
345    | Opt_TypeSynonymInstances
346    | Opt_FlexibleContexts
347    | Opt_FlexibleInstances
348    | Opt_ConstrainedClassMethods
349    | Opt_MultiParamTypeClasses
350    | Opt_FunctionalDependencies
351    | Opt_UnicodeSyntax
352    | Opt_PolymorphicComponents
353    | Opt_ExistentialQuantification
354    | Opt_MagicHash
355    | Opt_EmptyDataDecls
356    | Opt_KindSignatures
357    | Opt_ParallelListComp
358    | Opt_TransformListComp
359    | Opt_GeneralizedNewtypeDeriving
360    | Opt_RecursiveDo
361    | Opt_DoRec
362    | Opt_PostfixOperators
363    | Opt_TupleSections
364    | Opt_PatternGuards
365    | Opt_LiberalTypeSynonyms
366    | Opt_Rank2Types
367    | Opt_RankNTypes
368    | Opt_ImpredicativeTypes
369    | Opt_TypeOperators
370    | Opt_PackageImports
371    | Opt_ExplicitForAll
372    | Opt_AlternativeLayoutRule
373    | Opt_AlternativeLayoutRuleTransitional
374    | Opt_DatatypeContexts
375    | Opt_NondecreasingIndentation
376    | Opt_RelaxedLayout
377    deriving (Eq, Show)
378
379 -- | Contains not only a collection of 'DynFlag's but also a plethora of
380 -- information relating to the compilation of a single file or GHC session
381 data DynFlags = DynFlags {
382   ghcMode               :: GhcMode,
383   ghcLink               :: GhcLink,
384   hscTarget             :: HscTarget,
385   hscOutName            :: String,      -- ^ Name of the output file
386   extCoreName           :: String,      -- ^ Name of the .hcr output file
387   verbosity             :: Int,         -- ^ Verbosity level: see Note [Verbosity levels]
388   optLevel              :: Int,         -- ^ Optimisation level
389   simplPhases           :: Int,         -- ^ Number of simplifier phases
390   maxSimplIterations    :: Int,         -- ^ Max simplifier iterations
391   shouldDumpSimplPhase  :: Maybe String,
392   ruleCheck             :: Maybe String,
393   strictnessBefore      :: [Int],       -- ^ Additional demand analysis
394
395   specConstrThreshold   :: Maybe Int,   -- ^ Threshold for SpecConstr
396   specConstrCount       :: Maybe Int,   -- ^ Max number of specialisations for any one function
397   liberateCaseThreshold :: Maybe Int,   -- ^ Threshold for LiberateCase
398   floatLamArgs          :: Maybe Int,   -- ^ Arg count for lambda floating
399                                         --   See CoreMonad.FloatOutSwitches
400
401 #ifndef OMIT_NATIVE_CODEGEN
402   targetPlatform        :: Platform,    -- ^ The platform we're compiling for. Used by the NCG.
403 #endif
404   stolen_x86_regs       :: Int,
405   cmdlineHcIncludes     :: [String],    -- ^ @\-\#includes@
406   importPaths           :: [FilePath],
407   mainModIs             :: Module,
408   mainFunIs             :: Maybe String,
409   ctxtStkDepth          :: Int,         -- ^ Typechecker context stack depth
410
411   dphBackend            :: DPHBackend,
412
413   thisPackage           :: PackageId,   -- ^ name of package currently being compiled
414
415   -- ways
416   ways                  :: [Way],       -- ^ Way flags from the command line
417   buildTag              :: String,      -- ^ The global \"way\" (e.g. \"p\" for prof)
418   rtsBuildTag           :: String,      -- ^ The RTS \"way\"
419
420   -- For object splitting
421   splitInfo             :: Maybe (String,Int),
422
423   -- paths etc.
424   objectDir             :: Maybe String,
425   dylibInstallName      :: Maybe String,
426   hiDir                 :: Maybe String,
427   stubDir               :: Maybe String,
428
429   objectSuf             :: String,
430   hcSuf                 :: String,
431   hiSuf                 :: String,
432
433   outputFile            :: Maybe String,
434   outputHi              :: Maybe String,
435   dynLibLoader          :: DynLibLoader,
436
437   -- | This is set by 'DriverPipeline.runPipeline' based on where
438   --    its output is going.
439   dumpPrefix            :: Maybe FilePath,
440
441   -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
442   --    Set by @-ddump-file-prefix@
443   dumpPrefixForce       :: Maybe FilePath,
444
445   includePaths          :: [String],
446   libraryPaths          :: [String],
447   frameworkPaths        :: [String],    -- used on darwin only
448   cmdlineFrameworks     :: [String],    -- ditto
449   tmpDir                :: String,      -- no trailing '/'
450
451   ghcUsagePath          :: FilePath,    -- Filled in by SysTools
452   ghciUsagePath         :: FilePath,    -- ditto
453   rtsOpts               :: Maybe String,
454   rtsOptsEnabled        :: RtsOptsEnabled,
455
456   hpcDir                :: String,      -- ^ Path to store the .mix files
457
458   -- options for particular phases
459   opt_L                 :: [String],
460   opt_P                 :: [String],
461   opt_F                 :: [String],
462   opt_c                 :: [String],
463   opt_m                 :: [String],
464   opt_a                 :: [String],
465   opt_l                 :: [String],
466   opt_windres           :: [String],
467   opt_lo                :: [String], -- LLVM: llvm optimiser
468   opt_lc                :: [String], -- LLVM: llc static compiler
469
470   -- commands for particular phases
471   pgm_L                 :: String,
472   pgm_P                 :: (String,[Option]),
473   pgm_F                 :: String,
474   pgm_c                 :: (String,[Option]),
475   pgm_m                 :: (String,[Option]),
476   pgm_s                 :: (String,[Option]),
477   pgm_a                 :: (String,[Option]),
478   pgm_l                 :: (String,[Option]),
479   pgm_dll               :: (String,[Option]),
480   pgm_T                 :: String,
481   pgm_sysman            :: String,
482   pgm_windres           :: String,
483   pgm_lo                :: (String,[Option]), -- LLVM: opt llvm optimiser
484   pgm_lc                :: (String,[Option]), -- LLVM: llc static compiler
485
486   --  For ghc -M
487   depMakefile           :: FilePath,
488   depIncludePkgDeps     :: Bool,
489   depExcludeMods        :: [ModuleName],
490   depSuffixes           :: [String],
491
492   --  Package flags
493   extraPkgConfs         :: [FilePath],
494   topDir                :: FilePath,    -- filled in by SysTools
495   systemPackageConfig   :: FilePath,    -- ditto
496         -- ^ The @-package-conf@ flags given on the command line, in the order
497         -- they appeared.
498
499   packageFlags          :: [PackageFlag],
500         -- ^ The @-package@ and @-hide-package@ flags from the command-line
501
502   -- Package state
503   -- NB. do not modify this field, it is calculated by
504   -- Packages.initPackages and Packages.updatePackages.
505   pkgDatabase           :: Maybe [PackageConfig],
506   pkgState              :: PackageState,
507
508   -- Temporary files
509   -- These have to be IORefs, because the defaultCleanupHandler needs to
510   -- know what to clean when an exception happens
511   filesToClean          :: IORef [FilePath],
512   dirsToClean           :: IORef (Map FilePath FilePath),
513
514   -- hsc dynamic flags
515   flags                 :: [DynFlag],
516   -- Don't change this without updating extensionFlags:
517   language              :: Maybe Language,
518   -- Don't change this without updating extensionFlags:
519   extensions            :: [OnOff ExtensionFlag],
520   -- extensionFlags should always be equal to
521   --     flattenExtensionFlags language extensions
522   extensionFlags        :: [ExtensionFlag],
523
524   -- | Message output action: use "ErrUtils" instead of this if you can
525   log_action            :: Severity -> SrcSpan -> PprStyle -> Message -> IO (),
526
527   haddockOptions :: Maybe String
528  }
529
530 wayNames :: DynFlags -> [WayName]
531 wayNames = map wayName . ways
532
533 -- | The target code type of the compilation (if any).
534 --
535 -- Whenever you change the target, also make sure to set 'ghcLink' to
536 -- something sensible.
537 --
538 -- 'HscNothing' can be used to avoid generating any output, however, note
539 -- that:
540 --
541 --  * This will not run the desugaring step, thus no warnings generated in
542 --    this step will be output.  In particular, this includes warnings related
543 --    to pattern matching.  You can run the desugarer manually using
544 --    'GHC.desugarModule'.
545 --
546 --  * If a program uses Template Haskell the typechecker may try to run code
547 --    from an imported module.  This will fail if no code has been generated
548 --    for this module.  You can use 'GHC.needsTemplateHaskell' to detect
549 --    whether this might be the case and choose to either switch to a
550 --    different target or avoid typechecking such modules.  (The latter may
551 --    preferable for security reasons.)
552 --
553 data HscTarget
554   = HscC           -- ^ Generate C code.
555   | HscAsm         -- ^ Generate assembly using the native code generator.
556   | HscLlvm        -- ^ Generate assembly using the llvm code generator.
557   | HscJava        -- ^ Generate Java bytecode.
558   | HscInterpreted -- ^ Generate bytecode.  (Requires 'LinkInMemory')
559   | HscNothing     -- ^ Don't generate any code.  See notes above.
560   deriving (Eq, Show)
561
562 -- | Will this target result in an object file on the disk?
563 isObjectTarget :: HscTarget -> Bool
564 isObjectTarget HscC     = True
565 isObjectTarget HscAsm   = True
566 isObjectTarget HscLlvm  = True
567 isObjectTarget _        = False
568
569 -- | The 'GhcMode' tells us whether we're doing multi-module
570 -- compilation (controlled via the "GHC" API) or one-shot
571 -- (single-module) compilation.  This makes a difference primarily to
572 -- the "Finder": in one-shot mode we look for interface files for
573 -- imported modules, but in multi-module mode we look for source files
574 -- in order to check whether they need to be recompiled.
575 data GhcMode
576   = CompManager         -- ^ @\-\-make@, GHCi, etc.
577   | OneShot             -- ^ @ghc -c Foo.hs@
578   | MkDepend            -- ^ @ghc -M@, see "Finder" for why we need this
579   deriving Eq
580
581 instance Outputable GhcMode where
582   ppr CompManager = ptext (sLit "CompManager")
583   ppr OneShot     = ptext (sLit "OneShot")
584   ppr MkDepend    = ptext (sLit "MkDepend")
585
586 isOneShot :: GhcMode -> Bool
587 isOneShot OneShot = True
588 isOneShot _other  = False
589
590 -- | What to do in the link step, if there is one.
591 data GhcLink
592   = NoLink              -- ^ Don't link at all
593   | LinkBinary          -- ^ Link object code into a binary
594   | LinkInMemory        -- ^ Use the in-memory dynamic linker (works for both
595                         --   bytecode and object code).
596   | LinkDynLib          -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
597   deriving (Eq, Show)
598
599 isNoLink :: GhcLink -> Bool
600 isNoLink NoLink = True
601 isNoLink _      = False
602
603 -- Is it worth evaluating this Bool and caching it in the DynFlags value
604 -- during initDynFlags?
605 doingTickyProfiling :: DynFlags -> Bool
606 doingTickyProfiling _ = opt_Ticky
607   -- XXX -ticky is a static flag, because it implies -debug which is also
608   -- static.  If the way flags were made dynamic, we could fix this.
609
610 data PackageFlag
611   = ExposePackage  String
612   | ExposePackageId String
613   | HidePackage    String
614   | IgnorePackage  String
615   deriving Eq
616
617 defaultHscTarget :: HscTarget
618 defaultHscTarget = defaultObjectTarget
619
620 -- | The 'HscTarget' value corresponding to the default way to create
621 -- object files on the current platform.
622 defaultObjectTarget :: HscTarget
623 defaultObjectTarget
624   | cGhcWithNativeCodeGen == "YES"      =  HscAsm
625   | otherwise                           =  HscC
626
627 data DynLibLoader
628   = Deployable
629   | SystemDependent
630   deriving Eq
631
632 data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll
633
634 -- | Used by 'GHC.newSession' to partially initialize a new 'DynFlags' value
635 initDynFlags :: DynFlags -> IO DynFlags
636 initDynFlags dflags = do
637  -- someday these will be dynamic flags
638  ways <- readIORef v_Ways
639  refFilesToClean <- newIORef []
640  refDirsToClean <- newIORef Map.empty
641  return dflags{
642         ways            = ways,
643         buildTag        = mkBuildTag (filter (not . wayRTSOnly) ways),
644         rtsBuildTag     = mkBuildTag ways,
645         filesToClean    = refFilesToClean,
646         dirsToClean     = refDirsToClean
647         }
648
649 -- | The normal 'DynFlags'. Note that they is not suitable for use in this form
650 -- and must be fully initialized by 'GHC.newSession' first.
651 defaultDynFlags :: DynFlags
652 defaultDynFlags =
653      DynFlags {
654         ghcMode                 = CompManager,
655         ghcLink                 = LinkBinary,
656         hscTarget               = defaultHscTarget,
657         hscOutName              = "",
658         extCoreName             = "",
659         verbosity               = 0,
660         optLevel                = 0,
661         simplPhases             = 2,
662         maxSimplIterations      = 4,
663         shouldDumpSimplPhase    = Nothing,
664         ruleCheck               = Nothing,
665         specConstrThreshold     = Just 200,
666         specConstrCount         = Just 3,
667         liberateCaseThreshold   = Just 200,
668         floatLamArgs            = Just 0,       -- Default: float only if no fvs
669         strictnessBefore        = [],
670
671 #ifndef OMIT_NATIVE_CODEGEN
672         targetPlatform          = defaultTargetPlatform,
673 #endif
674         stolen_x86_regs         = 4,
675         cmdlineHcIncludes       = [],
676         importPaths             = ["."],
677         mainModIs               = mAIN,
678         mainFunIs               = Nothing,
679         ctxtStkDepth            = mAX_CONTEXT_REDUCTION_DEPTH,
680
681         dphBackend              = DPHNone,
682
683         thisPackage             = mainPackageId,
684
685         objectDir               = Nothing,
686         dylibInstallName        = Nothing,
687         hiDir                   = Nothing,
688         stubDir                 = Nothing,
689
690         objectSuf               = phaseInputExt StopLn,
691         hcSuf                   = phaseInputExt HCc,
692         hiSuf                   = "hi",
693
694         outputFile              = Nothing,
695         outputHi                = Nothing,
696         dynLibLoader            = SystemDependent,
697         dumpPrefix              = Nothing,
698         dumpPrefixForce         = Nothing,
699         includePaths            = [],
700         libraryPaths            = [],
701         frameworkPaths          = [],
702         cmdlineFrameworks       = [],
703         tmpDir                  = cDEFAULT_TMPDIR,
704         rtsOpts                 = Nothing,
705         rtsOptsEnabled          = RtsOptsSafeOnly,
706
707         hpcDir                  = ".hpc",
708
709         opt_L                   = [],
710         opt_P                   = (if opt_PIC
711                                    then ["-D__PIC__", "-U __PIC__"] -- this list is reversed
712                                    else []),
713         opt_F                   = [],
714         opt_c                   = [],
715         opt_a                   = [],
716         opt_m                   = [],
717         opt_l                   = [],
718         opt_windres             = [],
719         opt_lo                  = [],
720         opt_lc                  = [],
721
722         extraPkgConfs           = [],
723         packageFlags            = [],
724         pkgDatabase             = Nothing,
725         pkgState                = panic "no package state yet: call GHC.setSessionDynFlags",
726         ways                    = panic "defaultDynFlags: No ways",
727         buildTag                = panic "defaultDynFlags: No buildTag",
728         rtsBuildTag             = panic "defaultDynFlags: No rtsBuildTag",
729         splitInfo               = Nothing,
730         -- initSysTools fills all these in
731         ghcUsagePath            = panic "defaultDynFlags: No ghciUsagePath",
732         ghciUsagePath           = panic "defaultDynFlags: No ghciUsagePath",
733         topDir                  = panic "defaultDynFlags: No topDir",
734         systemPackageConfig     = panic  "no systemPackageConfig: call GHC.setSessionDynFlags",
735         pgm_L                   = panic "defaultDynFlags: No pgm_L",
736         pgm_P                   = panic "defaultDynFlags: No pgm_P",
737         pgm_F                   = panic "defaultDynFlags: No pgm_F",
738         pgm_c                   = panic "defaultDynFlags: No pgm_c",
739         pgm_m                   = panic "defaultDynFlags: No pgm_m",
740         pgm_s                   = panic "defaultDynFlags: No pgm_s",
741         pgm_a                   = panic "defaultDynFlags: No pgm_a",
742         pgm_l                   = panic "defaultDynFlags: No pgm_l",
743         pgm_dll                 = panic "defaultDynFlags: No pgm_dll",
744         pgm_T                   = panic "defaultDynFlags: No pgm_T",
745         pgm_sysman              = panic "defaultDynFlags: No pgm_sysman",
746         pgm_windres             = panic "defaultDynFlags: No pgm_windres",
747         pgm_lo                  = panic "defaultDynFlags: No pgm_lo",
748         pgm_lc                  = panic "defaultDynFlags: No pgm_lc",
749         -- end of initSysTools values
750         -- ghc -M values
751         depMakefile       = "Makefile",
752         depIncludePkgDeps = False,
753         depExcludeMods    = [],
754         depSuffixes       = [],
755         -- end of ghc -M values
756         filesToClean   = panic "defaultDynFlags: No filesToClean",
757         dirsToClean    = panic "defaultDynFlags: No dirsToClean",
758         haddockOptions = Nothing,
759         flags = defaultFlags,
760         language = Nothing,
761         extensions = [],
762         extensionFlags = flattenExtensionFlags Nothing [],
763
764         log_action = \severity srcSpan style msg ->
765                         case severity of
766                           SevOutput -> printOutput (msg style)
767                           SevInfo   -> printErrs (msg style)
768                           SevFatal  -> printErrs (msg style)
769                           _         -> do 
770                                 hPutChar stderr '\n'
771                                 printErrs ((mkLocMessage srcSpan msg) style)
772                      -- careful (#2302): printErrs prints in UTF-8, whereas
773                      -- converting to string first and using hPutStr would
774                      -- just emit the low 8 bits of each unicode char.
775       }
776
777 {-
778 Note [Verbosity levels]
779 ~~~~~~~~~~~~~~~~~~~~~~~
780     0   |   print errors & warnings only
781     1   |   minimal verbosity: print "compiling M ... done." for each module.
782     2   |   equivalent to -dshow-passes
783     3   |   equivalent to existing "ghc -v"
784     4   |   "ghc -v -ddump-most"
785     5   |   "ghc -v -ddump-all"
786 -}
787
788 data OnOff a = On a
789              | Off a
790
791 -- OnOffs accumulate in reverse order, so we use foldr in order to
792 -- process them in the right order
793 flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag]
794                       -> [ExtensionFlag]
795 flattenExtensionFlags ml = foldr f defaultExtensionFlags
796     where f (On f)  flags = f : delete f flags
797           f (Off f) flags =     delete f flags
798           defaultExtensionFlags = languageExtensions ml
799
800 languageExtensions :: Maybe Language -> [ExtensionFlag]
801
802 languageExtensions Nothing
803     -- Nothing => the default case
804     = Opt_MonoPatBinds   -- Experimentally, I'm making this non-standard
805                          -- behaviour the default, to see if anyone notices
806                          -- SLPJ July 06
807       -- In due course I'd like Opt_MonoLocalBinds to be on by default
808       -- But NB it's implied by GADTs etc
809       -- SLPJ September 2010
810     : Opt_NondecreasingIndentation -- This has been on by default for some time
811     : languageExtensions (Just Haskell2010)
812
813 languageExtensions (Just Haskell98)
814     = [Opt_ImplicitPrelude,
815        Opt_MonomorphismRestriction,
816        Opt_NPlusKPatterns,
817        Opt_DatatypeContexts,
818        Opt_NondecreasingIndentation
819            -- strictly speaking non-standard, but we always had this
820            -- on implicitly before the option was added in 7.1, and
821            -- turning it off breaks code, so we're keeping it on for
822            -- backwards compatibility.  Cabal uses -XHaskell98 by
823            -- default unless you specify another language.
824       ]
825
826 languageExtensions (Just Haskell2010)
827     = [Opt_ImplicitPrelude,
828        Opt_MonomorphismRestriction,
829        Opt_DatatypeContexts,
830        Opt_EmptyDataDecls,
831        Opt_ForeignFunctionInterface,
832        Opt_PatternGuards,
833        Opt_DoAndIfThenElse,
834        Opt_RelaxedPolyRec]
835
836 -- | Test whether a 'DynFlag' is set
837 dopt :: DynFlag -> DynFlags -> Bool
838 dopt f dflags  = f `elem` (flags dflags)
839
840 -- | Set a 'DynFlag'
841 dopt_set :: DynFlags -> DynFlag -> DynFlags
842 dopt_set dfs f = dfs{ flags = f : flags dfs }
843
844 -- | Unset a 'DynFlag'
845 dopt_unset :: DynFlags -> DynFlag -> DynFlags
846 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
847
848 -- | Test whether a 'ExtensionFlag' is set
849 xopt :: ExtensionFlag -> DynFlags -> Bool
850 xopt f dflags = f `elem` extensionFlags dflags
851
852 -- | Set a 'ExtensionFlag'
853 xopt_set :: DynFlags -> ExtensionFlag -> DynFlags
854 xopt_set dfs f
855     = let onoffs = On f : extensions dfs
856       in dfs { extensions = onoffs,
857                extensionFlags = flattenExtensionFlags (language dfs) onoffs }
858
859 -- | Unset a 'ExtensionFlag'
860 xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags
861 xopt_unset dfs f
862     = let onoffs = Off f : extensions dfs
863       in dfs { extensions = onoffs,
864                extensionFlags = flattenExtensionFlags (language dfs) onoffs }
865
866 setLanguage :: Language -> DynP ()
867 setLanguage l = upd f
868     where f dfs = let mLang = Just l
869                       oneoffs = extensions dfs
870                   in dfs {
871                          language = mLang,
872                          extensionFlags = flattenExtensionFlags mLang oneoffs
873                      }
874
875 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
876 getOpts :: DynFlags             -- ^ 'DynFlags' to retrieve the options from
877         -> (DynFlags -> [a])    -- ^ Relevant record accessor: one of the @opt_*@ accessors
878         -> [a]                  -- ^ Correctly ordered extracted options
879 getOpts dflags opts = reverse (opts dflags)
880         -- We add to the options from the front, so we need to reverse the list
881
882 -- | Gets the verbosity flag for the current verbosity level. This is fed to
883 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
884 getVerbFlag :: DynFlags -> String
885 getVerbFlag dflags
886   | verbosity dflags >= 3  = "-v"
887   | otherwise =  ""
888
889 setObjectDir, setHiDir, setStubDir, setOutputDir, setDylibInstallName,
890          setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
891          setPgmP, addOptl, addOptP,
892          addCmdlineFramework, addHaddockOpts
893    :: String -> DynFlags -> DynFlags
894 setOutputFile, setOutputHi, setDumpPrefixForce
895    :: Maybe String -> DynFlags -> DynFlags
896
897 setObjectDir  f d = d{ objectDir  = Just f}
898 setHiDir      f d = d{ hiDir      = Just f}
899 setStubDir    f d = d{ stubDir    = Just f, includePaths = f : includePaths d }
900   -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
901   -- \#included from the .hc file when compiling with -fvia-C.
902 setOutputDir  f = setObjectDir f . setHiDir f . setStubDir f
903 setDylibInstallName  f d = d{ dylibInstallName = Just f}
904
905 setObjectSuf  f d = d{ objectSuf  = f}
906 setHiSuf      f d = d{ hiSuf      = f}
907 setHcSuf      f d = d{ hcSuf      = f}
908
909 setOutputFile f d = d{ outputFile = f}
910 setOutputHi   f d = d{ outputHi   = f}
911
912 parseDynLibLoaderMode f d =
913  case splitAt 8 f of
914    ("deploy", "")       -> d{ dynLibLoader = Deployable }
915    ("sysdep", "")       -> d{ dynLibLoader = SystemDependent }
916    _                    -> ghcError (CmdLineError ("Unknown dynlib loader: " ++ f))
917
918 setDumpPrefixForce f d = d { dumpPrefixForce = f}
919
920 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
921 -- Config.hs should really use Option.
922 setPgmP   f d = let (pgm:args) = words f in d{ pgm_P   = (pgm, map Option args)}
923 addOptl   f d = d{ opt_l   = f : opt_l d}
924 addOptP   f d = d{ opt_P   = f : opt_P d}
925
926
927 setDepMakefile :: FilePath -> DynFlags -> DynFlags
928 setDepMakefile f d = d { depMakefile = deOptDep f }
929
930 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
931 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
932
933 addDepExcludeMod :: String -> DynFlags -> DynFlags
934 addDepExcludeMod m d
935     = d { depExcludeMods = mkModuleName (deOptDep m) : depExcludeMods d }
936
937 addDepSuffix :: FilePath -> DynFlags -> DynFlags
938 addDepSuffix s d = d { depSuffixes = deOptDep s : depSuffixes d }
939
940 -- XXX Legacy code:
941 -- We used to use "-optdep-flag -optdeparg", so for legacy applications
942 -- we need to strip the "-optdep" off of the arg
943 deOptDep :: String -> String
944 deOptDep x = case stripPrefix "-optdep" x of
945              Just rest -> rest
946              Nothing -> x
947
948 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
949
950 addHaddockOpts f d = d{ haddockOptions = Just f}
951
952 -- -----------------------------------------------------------------------------
953 -- Command-line options
954
955 -- | When invoking external tools as part of the compilation pipeline, we
956 -- pass these a sequence of options on the command-line. Rather than
957 -- just using a list of Strings, we use a type that allows us to distinguish
958 -- between filepaths and 'other stuff'. The reason for this is that
959 -- this type gives us a handle on transforming filenames, and filenames only,
960 -- to whatever format they're expected to be on a particular platform.
961 data Option
962  = FileOption -- an entry that _contains_ filename(s) / filepaths.
963               String  -- a non-filepath prefix that shouldn't be
964                       -- transformed (e.g., "/out=")
965               String  -- the filepath/filename portion
966  | Option     String
967
968 showOpt :: Option -> String
969 showOpt (FileOption pre f) = pre ++ f
970 showOpt (Option s)  = s
971
972 -----------------------------------------------------------------------------
973 -- Setting the optimisation level
974
975 updOptLevel :: Int -> DynFlags -> DynFlags
976 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
977 updOptLevel n dfs
978   = dfs2{ optLevel = final_n }
979   where
980    final_n = max 0 (min 2 n)    -- Clamp to 0 <= n <= 2
981    dfs1 = foldr (flip dopt_unset) dfs  remove_dopts
982    dfs2 = foldr (flip dopt_set)   dfs1 extra_dopts
983
984    extra_dopts  = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
985    remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
986
987 -- -----------------------------------------------------------------------------
988 -- StgToDo:  abstraction of stg-to-stg passes to run.
989
990 data StgToDo
991   = StgDoMassageForProfiling  -- should be (next to) last
992   -- There's also setStgVarInfo, but its absolute "lastness"
993   -- is so critical that it is hardwired in (no flag).
994   | D_stg_stats
995
996 getStgToDo :: DynFlags -> [StgToDo]
997 getStgToDo dflags
998   = todo2
999   where
1000         stg_stats = dopt Opt_StgStats dflags
1001
1002         todo1 = if stg_stats then [D_stg_stats] else []
1003
1004         todo2 | WayProf `elem` wayNames dflags
1005               = StgDoMassageForProfiling : todo1
1006               | otherwise
1007               = todo1
1008
1009 {- **********************************************************************
1010 %*                                                                      *
1011                 DynFlags parser
1012 %*                                                                      *
1013 %********************************************************************* -}
1014
1015 -- -----------------------------------------------------------------------------
1016 -- Parsing the dynamic flags.
1017
1018 -- | Parse dynamic flags from a list of command line arguments.  Returns the
1019 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
1020 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
1021 -- flags or missing arguments).
1022 parseDynamicFlags :: Monad m =>
1023                      DynFlags -> [Located String]
1024                   -> m (DynFlags, [Located String], [Located String])
1025                      -- ^ Updated 'DynFlags', left-over arguments, and
1026                      -- list of warnings.
1027 parseDynamicFlags dflags args = parseDynamicFlags_ dflags args True
1028
1029 -- | Like 'parseDynamicFlags' but does not allow the package flags (-package,
1030 -- -hide-package, -ignore-package, -hide-all-packages, -package-conf).
1031 parseDynamicNoPackageFlags :: Monad m =>
1032                      DynFlags -> [Located String]
1033                   -> m (DynFlags, [Located String], [Located String])
1034                      -- ^ Updated 'DynFlags', left-over arguments, and
1035                      -- list of warnings.
1036 parseDynamicNoPackageFlags dflags args = parseDynamicFlags_ dflags args False
1037
1038 parseDynamicFlags_ :: Monad m =>
1039                       DynFlags -> [Located String] -> Bool
1040                   -> m (DynFlags, [Located String], [Located String])
1041 parseDynamicFlags_ dflags0 args pkg_flags = do
1042   -- XXX Legacy support code
1043   -- We used to accept things like
1044   --     optdep-f  -optdepdepend
1045   --     optdep-f  -optdep depend
1046   --     optdep -f -optdepdepend
1047   --     optdep -f -optdep depend
1048   -- but the spaces trip up proper argument handling. So get rid of them.
1049   let f (L p "-optdep" : L _ x : xs) = (L p ("-optdep" ++ x)) : f xs
1050       f (x : xs) = x : f xs
1051       f xs = xs
1052       args' = f args
1053
1054       -- Note: -ignore-package (package_flags) must precede -i* (dynamic_flags)
1055       flag_spec | pkg_flags = package_flags ++ dynamic_flags
1056                 | otherwise = dynamic_flags
1057
1058   let ((leftover, errs, warns), dflags1)
1059           = runCmdLine (processArgs flag_spec args') dflags0
1060   when (not (null errs)) $ ghcError $ errorsToGhcException errs
1061
1062   -- Cannot use -fPIC with registerised -fvia-C, because the mangler
1063   -- isn't up to the job.  We know that if hscTarget == HscC, then the
1064   -- user has explicitly used -fvia-C, because -fasm is the default,
1065   -- unless there is no NCG on this platform.  The latter case is
1066   -- checked when the -fPIC flag is parsed.
1067   --
1068   let (pic_warns, dflags2)
1069         | opt_PIC && hscTarget dflags1 == HscC && cGhcUnregisterised == "NO"
1070         = ([L noSrcSpan $ "Warning: -fvia-C is incompatible with -fPIC; ignoring -fvia-C"],
1071                 dflags1{ hscTarget = HscAsm })
1072 #if !(x86_64_TARGET_ARCH && linux_TARGET_OS)
1073         | (not opt_Static || opt_PIC) && hscTarget dflags1 == HscLlvm
1074         = ([L noSrcSpan $ "Warning: -fllvm is incompatible with -fPIC and -"
1075                 ++ "dynamic on this platform;\n              ignoring -fllvm"],
1076                 dflags1{ hscTarget = HscAsm })
1077 #endif
1078         | otherwise = ([], dflags1)
1079
1080   return (dflags2, leftover, pic_warns ++ warns)
1081
1082
1083 {- **********************************************************************
1084 %*                                                                      *
1085                 DynFlags specifications
1086 %*                                                                      *
1087 %********************************************************************* -}
1088
1089 allFlags :: [String]
1090 allFlags = map ('-':) $
1091            [ flagName flag | flag <- dynamic_flags, ok (flagOptKind flag) ] ++
1092            map ("fno-"++) flags ++
1093            map ("f"++) flags ++
1094            map ("f"++) flags' ++
1095            map ("X"++) supportedExtensions
1096     where ok (PrefixPred _ _) = False
1097           ok _ = True
1098           flags = [ name | (name, _, _) <- fFlags ]
1099           flags' = [ name | (name, _, _) <- fLangFlags ]
1100
1101 --------------- The main flags themselves ------------------
1102 dynamic_flags :: [Flag (CmdLineP DynFlags)]
1103 dynamic_flags = [
1104     Flag "n"        (NoArg (setDynFlag Opt_DryRun))
1105   , Flag "cpp"      (NoArg (setExtensionFlag Opt_Cpp)) 
1106   , Flag "F"        (NoArg (setDynFlag Opt_Pp)) 
1107   , Flag "#include" 
1108          (HasArg (\s -> do { addCmdlineHCInclude s
1109                            ; addWarn "-#include and INCLUDE pragmas are deprecated: They no longer have any effect" }))
1110   , Flag "v"        (OptIntSuffix setVerbosity)
1111
1112         ------- Specific phases  --------------------------------------------
1113     -- need to appear before -pgmL to be parsed as LLVM flags.
1114   , Flag "pgmlo"          (hasArg (\f d -> d{ pgm_lo  = (f,[])}))
1115   , Flag "pgmlc"          (hasArg (\f d -> d{ pgm_lc  = (f,[])}))
1116   , Flag "pgmL"           (hasArg (\f d -> d{ pgm_L   = f}))
1117   , Flag "pgmP"           (hasArg setPgmP)
1118   , Flag "pgmF"           (hasArg (\f d -> d{ pgm_F   = f}))
1119   , Flag "pgmc"           (hasArg (\f d -> d{ pgm_c   = (f,[])}))
1120   , Flag "pgmm"           (hasArg (\f d -> d{ pgm_m   = (f,[])}))
1121   , Flag "pgms"           (hasArg (\f d -> d{ pgm_s   = (f,[])}))
1122   , Flag "pgma"           (hasArg (\f d -> d{ pgm_a   = (f,[])}))
1123   , Flag "pgml"           (hasArg (\f d -> d{ pgm_l   = (f,[])}))
1124   , Flag "pgmdll"         (hasArg (\f d -> d{ pgm_dll = (f,[])}))
1125   , Flag "pgmwindres"     (hasArg (\f d -> d{ pgm_windres = f}))
1126
1127     -- need to appear before -optl/-opta to be parsed as LLVM flags.
1128   , Flag "optlo"          (hasArg (\f d -> d{ opt_lo  = f : opt_lo d}))
1129   , Flag "optlc"          (hasArg (\f d -> d{ opt_lc  = f : opt_lc d}))
1130   , Flag "optL"           (hasArg (\f d -> d{ opt_L   = f : opt_L d}))
1131   , Flag "optP"           (hasArg addOptP)
1132   , Flag "optF"           (hasArg (\f d -> d{ opt_F   = f : opt_F d}))
1133   , Flag "optc"           (hasArg (\f d -> d{ opt_c   = f : opt_c d}))
1134   , Flag "optm"           (hasArg (\f d -> d{ opt_m   = f : opt_m d}))
1135   , Flag "opta"           (hasArg (\f d -> d{ opt_a   = f : opt_a d}))
1136   , Flag "optl"           (hasArg addOptl)
1137   , Flag "optwindres"     (hasArg (\f d -> d{ opt_windres = f : opt_windres d}))
1138
1139   , Flag "split-objs"
1140          (NoArg (if can_split 
1141                  then setDynFlag Opt_SplitObjs
1142                  else addWarn "ignoring -fsplit-objs"))
1143
1144         -------- ghc -M -----------------------------------------------------
1145   , Flag "dep-suffix"     (hasArg addDepSuffix)
1146   , Flag "optdep-s"       (hasArgDF addDepSuffix "Use -dep-suffix instead")
1147   , Flag "dep-makefile"   (hasArg setDepMakefile)
1148   , Flag "optdep-f"       (hasArgDF setDepMakefile "Use -dep-makefile instead")
1149   , Flag "optdep-w"       (NoArg  (deprecate "doesn't do anything"))
1150   , Flag "include-pkg-deps"         (noArg (setDepIncludePkgDeps True))
1151   , Flag "optdep--include-prelude"  (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
1152   , Flag "optdep--include-pkg-deps" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
1153   , Flag "exclude-module"           (hasArg addDepExcludeMod)
1154   , Flag "optdep--exclude-module"   (hasArgDF addDepExcludeMod "Use -exclude-module instead")
1155   , Flag "optdep-x"                 (hasArgDF addDepExcludeMod "Use -exclude-module instead")
1156
1157         -------- Linking ----------------------------------------------------
1158   , Flag "no-link"            (noArg (\d -> d{ ghcLink=NoLink }))
1159   , Flag "shared"             (noArg (\d -> d{ ghcLink=LinkDynLib }))
1160   , Flag "dynload"            (hasArg parseDynLibLoaderMode)
1161   , Flag "dylib-install-name" (hasArg setDylibInstallName)
1162
1163         ------- Libraries ---------------------------------------------------
1164   , Flag "L"   (Prefix    addLibraryPath)
1165   , Flag "l"   (AnySuffix (upd . addOptl))
1166
1167         ------- Frameworks --------------------------------------------------
1168         -- -framework-path should really be -F ...
1169   , Flag "framework-path" (HasArg addFrameworkPath)
1170   , Flag "framework"      (hasArg addCmdlineFramework)
1171
1172         ------- Output Redirection ------------------------------------------
1173   , Flag "odir"              (hasArg setObjectDir)
1174   , Flag "o"                 (SepArg (upd . setOutputFile . Just))
1175   , Flag "ohi"               (hasArg (setOutputHi . Just ))
1176   , Flag "osuf"              (hasArg setObjectSuf)
1177   , Flag "hcsuf"             (hasArg setHcSuf)
1178   , Flag "hisuf"             (hasArg setHiSuf)
1179   , Flag "hidir"             (hasArg setHiDir)
1180   , Flag "tmpdir"            (hasArg setTmpDir)
1181   , Flag "stubdir"           (hasArg setStubDir)
1182   , Flag "outputdir"         (hasArg setOutputDir)
1183   , Flag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just))
1184
1185         ------- Keeping temporary files -------------------------------------
1186      -- These can be singular (think ghc -c) or plural (think ghc --make)
1187   , Flag "keep-hc-file"     (NoArg (setDynFlag Opt_KeepHcFiles))
1188   , Flag "keep-hc-files"    (NoArg (setDynFlag Opt_KeepHcFiles))
1189   , Flag "keep-s-file"      (NoArg (setDynFlag Opt_KeepSFiles))
1190   , Flag "keep-s-files"     (NoArg (setDynFlag Opt_KeepSFiles))
1191   , Flag "keep-raw-s-file"  (NoArg (setDynFlag Opt_KeepRawSFiles))
1192   , Flag "keep-raw-s-files" (NoArg (setDynFlag Opt_KeepRawSFiles))
1193   , Flag "keep-llvm-file"   (NoArg (setDynFlag Opt_KeepLlvmFiles))
1194   , Flag "keep-llvm-files"  (NoArg (setDynFlag Opt_KeepLlvmFiles))
1195      -- This only makes sense as plural
1196   , Flag "keep-tmp-files"   (NoArg (setDynFlag Opt_KeepTmpFiles))
1197
1198         ------- Miscellaneous ----------------------------------------------
1199   , Flag "no-auto-link-packages" (NoArg (unSetDynFlag Opt_AutoLinkPackages))
1200   , Flag "no-hs-main"     (NoArg (setDynFlag Opt_NoHsMain))
1201   , Flag "with-rtsopts"   (HasArg setRtsOpts)
1202   , Flag "rtsopts"        (NoArg (setRtsOptsEnabled RtsOptsAll))
1203   , Flag "rtsopts=all"    (NoArg (setRtsOptsEnabled RtsOptsAll))
1204   , Flag "rtsopts=some"   (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
1205   , Flag "rtsopts=none"   (NoArg (setRtsOptsEnabled RtsOptsNone))
1206   , Flag "no-rtsopts"     (NoArg (setRtsOptsEnabled RtsOptsNone))
1207   , Flag "main-is"        (SepArg setMainIs)
1208   , Flag "haddock"        (NoArg (setDynFlag Opt_Haddock))
1209   , Flag "haddock-opts"   (hasArg addHaddockOpts)
1210   , Flag "hpcdir"         (SepArg setOptHpcDir)
1211
1212         ------- recompilation checker --------------------------------------
1213   , Flag "recomp"         (NoArg (do { unSetDynFlag Opt_ForceRecomp
1214                                      ; deprecate "Use -fno-force-recomp instead" }))
1215   , Flag "no-recomp"      (NoArg (do { setDynFlag Opt_ForceRecomp
1216                                      ; deprecate "Use -fforce-recomp instead" }))
1217
1218         ------ HsCpp opts ---------------------------------------------------
1219   , Flag "D"              (AnySuffix (upd . addOptP))
1220   , Flag "U"              (AnySuffix (upd . addOptP))
1221
1222         ------- Include/Import Paths ----------------------------------------
1223   , Flag "I"              (Prefix    addIncludePath)
1224   , Flag "i"              (OptPrefix addImportPath)
1225
1226         ------ Debugging ----------------------------------------------------
1227   , Flag "dstg-stats"     (NoArg (setDynFlag Opt_StgStats))
1228
1229   , Flag "ddump-cmm"               (setDumpFlag Opt_D_dump_cmm)
1230   , Flag "ddump-cmmz"              (setDumpFlag Opt_D_dump_cmmz)
1231   , Flag "ddump-cmmz-pretty"       (setDumpFlag Opt_D_dump_cmmz_pretty)
1232   , Flag "ddump-cps-cmm"           (setDumpFlag Opt_D_dump_cps_cmm)
1233   , Flag "ddump-cvt-cmm"           (setDumpFlag Opt_D_dump_cvt_cmm)
1234   , Flag "ddump-asm"               (setDumpFlag Opt_D_dump_asm)
1235   , Flag "ddump-asm-native"        (setDumpFlag Opt_D_dump_asm_native)
1236   , Flag "ddump-asm-liveness"      (setDumpFlag Opt_D_dump_asm_liveness)
1237   , Flag "ddump-asm-coalesce"      (setDumpFlag Opt_D_dump_asm_coalesce)
1238   , Flag "ddump-asm-regalloc"      (setDumpFlag Opt_D_dump_asm_regalloc)
1239   , Flag "ddump-asm-conflicts"     (setDumpFlag Opt_D_dump_asm_conflicts)
1240   , Flag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages)
1241   , Flag "ddump-asm-stats"         (setDumpFlag Opt_D_dump_asm_stats)
1242   , Flag "ddump-asm-expanded"      (setDumpFlag Opt_D_dump_asm_expanded)
1243   , Flag "ddump-llvm"              (NoArg (do { setObjTarget HscLlvm
1244                                               ; setDumpFlag' Opt_D_dump_llvm}))
1245   , Flag "ddump-cpranal"           (setDumpFlag Opt_D_dump_cpranal)
1246   , Flag "ddump-deriv"             (setDumpFlag Opt_D_dump_deriv)
1247   , Flag "ddump-ds"                (setDumpFlag Opt_D_dump_ds)
1248   , Flag "ddump-flatC"             (setDumpFlag Opt_D_dump_flatC)
1249   , Flag "ddump-foreign"           (setDumpFlag Opt_D_dump_foreign)
1250   , Flag "ddump-inlinings"         (setDumpFlag Opt_D_dump_inlinings)
1251   , Flag "ddump-rule-firings"      (setDumpFlag Opt_D_dump_rule_firings)
1252   , Flag "ddump-rule-rewrites"     (setDumpFlag Opt_D_dump_rule_rewrites)
1253   , Flag "ddump-occur-anal"        (setDumpFlag Opt_D_dump_occur_anal)
1254   , Flag "ddump-parsed"            (setDumpFlag Opt_D_dump_parsed)
1255   , Flag "ddump-rn"                (setDumpFlag Opt_D_dump_rn)
1256   , Flag "ddump-simpl"             (setDumpFlag Opt_D_dump_simpl)
1257   , Flag "ddump-simpl-iterations"  (setDumpFlag Opt_D_dump_simpl_iterations)
1258   , Flag "ddump-simpl-phases"      (OptPrefix setDumpSimplPhases)
1259   , Flag "ddump-spec"              (setDumpFlag Opt_D_dump_spec)
1260   , Flag "ddump-prep"              (setDumpFlag Opt_D_dump_prep)
1261   , Flag "ddump-stg"               (setDumpFlag Opt_D_dump_stg)
1262   , Flag "ddump-stranal"           (setDumpFlag Opt_D_dump_stranal)
1263   , Flag "ddump-tc"                (setDumpFlag Opt_D_dump_tc)
1264   , Flag "ddump-types"             (setDumpFlag Opt_D_dump_types)
1265   , Flag "ddump-rules"             (setDumpFlag Opt_D_dump_rules)
1266   , Flag "ddump-cse"               (setDumpFlag Opt_D_dump_cse)
1267   , Flag "ddump-worker-wrapper"    (setDumpFlag Opt_D_dump_worker_wrapper)
1268   , Flag "ddump-rn-trace"          (setDumpFlag Opt_D_dump_rn_trace)
1269   , Flag "ddump-if-trace"          (setDumpFlag Opt_D_dump_if_trace)
1270   , Flag "ddump-cs-trace"          (setDumpFlag Opt_D_dump_cs_trace)
1271   , Flag "ddump-tc-trace"          (setDumpFlag Opt_D_dump_tc_trace)
1272   , Flag "ddump-vt-trace"          (setDumpFlag Opt_D_dump_vt_trace)
1273   , Flag "ddump-splices"           (setDumpFlag Opt_D_dump_splices)
1274   , Flag "ddump-rn-stats"          (setDumpFlag Opt_D_dump_rn_stats)
1275   , Flag "ddump-opt-cmm"           (setDumpFlag Opt_D_dump_opt_cmm)
1276   , Flag "ddump-simpl-stats"       (setDumpFlag Opt_D_dump_simpl_stats)
1277   , Flag "ddump-bcos"              (setDumpFlag Opt_D_dump_BCOs)
1278   , Flag "dsource-stats"           (setDumpFlag Opt_D_source_stats)
1279   , Flag "dverbose-core2core"      (NoArg (do { setVerbosity (Just 2)
1280                                               ; setVerboseCore2Core }))
1281   , Flag "dverbose-stg2stg"        (setDumpFlag Opt_D_verbose_stg2stg)
1282   , Flag "ddump-hi"                (setDumpFlag Opt_D_dump_hi)
1283   , Flag "ddump-minimal-imports"   (setDumpFlag Opt_D_dump_minimal_imports)
1284   , Flag "ddump-vect"              (setDumpFlag Opt_D_dump_vect)
1285   , Flag "ddump-hpc"               (setDumpFlag Opt_D_dump_hpc)
1286   , Flag "ddump-mod-cycles"        (setDumpFlag Opt_D_dump_mod_cycles)
1287   , Flag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning)
1288   , Flag "ddump-to-file"           (setDumpFlag Opt_DumpToFile)
1289   , Flag "ddump-hi-diffs"          (setDumpFlag Opt_D_dump_hi_diffs)
1290   , Flag "ddump-rtti"              (setDumpFlag Opt_D_dump_rtti)
1291   , Flag "dcore-lint"              (NoArg (setDynFlag Opt_DoCoreLinting))
1292   , Flag "dstg-lint"               (NoArg (setDynFlag Opt_DoStgLinting))
1293   , Flag "dcmm-lint"               (NoArg (setDynFlag Opt_DoCmmLinting))
1294   , Flag "dasm-lint"               (NoArg (setDynFlag Opt_DoAsmLinting))
1295   , Flag "dshow-passes"            (NoArg (do forceRecompile
1296                                               setVerbosity (Just 2)))
1297   , Flag "dfaststring-stats"       (NoArg (setDynFlag Opt_D_faststring_stats))
1298
1299         ------ Coq-in-GHC ---------------------------
1300   , Flag "dcoqpass"                (NoArg (setDynFlag Opt_D_coqpass))
1301   , Flag "ddump-coqpass"           (NoArg (setDynFlag Opt_D_dump_coqpass))
1302   , Flag "fcoqpass"                (NoArg (setDynFlag Opt_F_coqpass))
1303
1304         ------ Machine dependant (-m<blah>) stuff ---------------------------
1305
1306   , Flag "monly-2-regs" (noArg (\s -> s{stolen_x86_regs = 2}))
1307   , Flag "monly-3-regs" (noArg (\s -> s{stolen_x86_regs = 3}))
1308   , Flag "monly-4-regs" (noArg (\s -> s{stolen_x86_regs = 4}))
1309   , Flag "msse2"        (NoArg (setDynFlag Opt_SSE2))
1310
1311      ------ Warning opts -------------------------------------------------
1312   , Flag "W"      (NoArg (mapM_ setDynFlag   minusWOpts))
1313   , Flag "Werror" (NoArg (setDynFlag         Opt_WarnIsError))
1314   , Flag "Wwarn"  (NoArg (unSetDynFlag       Opt_WarnIsError))
1315   , Flag "Wall"   (NoArg (mapM_ setDynFlag   minusWallOpts))
1316   , Flag "Wnot"   (NoArg (do { mapM_ unSetDynFlag minusWallOpts
1317                              ; deprecate "Use -w instead" }))
1318   , Flag "w"      (NoArg (mapM_ unSetDynFlag minuswRemovesOpts))
1319
1320         ------ Optimisation flags ------------------------------------------
1321   , Flag "O"      (noArg (setOptLevel 1))
1322   , Flag "Onot"   (noArgDF (setOptLevel 0) "Use -O0 instead")
1323   , Flag "Odph"   (noArg setDPHOpt)
1324   , Flag "O"      (OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1325                 -- If the number is missing, use 1
1326
1327   , Flag "fsimplifier-phases"          (intSuffix (\n d -> d{ simplPhases = n }))
1328   , Flag "fmax-simplifier-iterations"  (intSuffix (\n d -> d{ maxSimplIterations = n }))
1329   , Flag "fspec-constr-threshold"      (intSuffix (\n d -> d{ specConstrThreshold = Just n }))
1330   , Flag "fno-spec-constr-threshold"   (noArg (\d -> d{ specConstrThreshold = Nothing }))
1331   , Flag "fspec-constr-count"          (intSuffix (\n d -> d{ specConstrCount = Just n }))
1332   , Flag "fno-spec-constr-count"       (noArg (\d -> d{ specConstrCount = Nothing }))
1333   , Flag "fliberate-case-threshold"    (intSuffix (\n d -> d{ liberateCaseThreshold = Just n }))
1334   , Flag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing }))
1335   , Flag "frule-check"                 (SepArg (\s -> upd (\d -> d{ ruleCheck = Just s })))
1336   , Flag "fcontext-stack"              (intSuffix (\n d -> d{ ctxtStkDepth = n }))
1337   , Flag "fstrictness-before"          (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d }))
1338   , Flag "ffloat-lam-args"             (intSuffix (\n d -> d{ floatLamArgs = Just n }))
1339   , Flag "ffloat-all-lams"             (intSuffix (\n d -> d{ floatLamArgs = Nothing }))
1340
1341         ------ Profiling ----------------------------------------------------
1342
1343   -- XXX Should the -f* flags be deprecated?
1344   -- They don't seem to be documented
1345   , Flag "fauto-sccs-on-all-toplevs"       (NoArg (setDynFlag Opt_AutoSccsOnAllToplevs))
1346   , Flag "auto-all"                        (NoArg (setDynFlag Opt_AutoSccsOnAllToplevs))
1347   , Flag "no-auto-all"                     (NoArg (unSetDynFlag Opt_AutoSccsOnAllToplevs))
1348   , Flag "fauto-sccs-on-exported-toplevs"  (NoArg (setDynFlag Opt_AutoSccsOnExportedToplevs))
1349   , Flag "auto"                            (NoArg (setDynFlag Opt_AutoSccsOnExportedToplevs))
1350   , Flag "no-auto"                         (NoArg (unSetDynFlag Opt_AutoSccsOnExportedToplevs))
1351   , Flag "fauto-sccs-on-individual-cafs"   (NoArg (setDynFlag Opt_AutoSccsOnIndividualCafs))
1352   , Flag "caf-all"                         (NoArg (setDynFlag Opt_AutoSccsOnIndividualCafs))
1353   , Flag "no-caf-all"                      (NoArg (unSetDynFlag Opt_AutoSccsOnIndividualCafs))
1354
1355         ------ DPH flags ----------------------------------------------------
1356
1357   , Flag "fdph-seq"         (NoArg (setDPHBackend DPHSeq))
1358   , Flag "fdph-par"         (NoArg (setDPHBackend DPHPar))
1359   , Flag "fdph-this"        (NoArg (setDPHBackend DPHThis))
1360   , Flag "fdph-none"        (NoArg (setDPHBackend DPHNone))
1361
1362         ------ Compiler flags -----------------------------------------------
1363
1364   , Flag "fasm"             (NoArg (setObjTarget HscAsm))
1365   , Flag "fvia-c"           (NoArg (setObjTarget HscC >>
1366          (addWarn "The -fvia-c flag will be removed in a future GHC release")))
1367   , Flag "fvia-C"           (NoArg (setObjTarget HscC >>
1368          (addWarn "The -fvia-C flag will be removed in a future GHC release")))
1369   , Flag "fllvm"            (NoArg (setObjTarget HscLlvm))
1370
1371   , Flag "fno-code"         (NoArg (do upd $ \d -> d{ ghcLink=NoLink }
1372                                        setTarget HscNothing))
1373   , Flag "fbyte-code"       (NoArg (setTarget HscInterpreted))
1374   , Flag "fobject-code"     (NoArg (setTarget defaultHscTarget))
1375   , Flag "fglasgow-exts"    (NoArg (enableGlasgowExts >> deprecate "Use individual extensions instead"))
1376   , Flag "fno-glasgow-exts" (NoArg (disableGlasgowExts >> deprecate "Use individual extensions instead"))
1377  ]
1378  ++ map (mkFlag turnOn  "f"    setDynFlag  ) fFlags
1379  ++ map (mkFlag turnOff "fno-" unSetDynFlag) fFlags
1380  ++ map (mkFlag turnOn  "f"    setExtensionFlag  ) fLangFlags
1381  ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags
1382  ++ map (mkFlag turnOn  "X"    setExtensionFlag  ) xFlags
1383  ++ map (mkFlag turnOff "XNo"  unSetExtensionFlag) xFlags
1384  ++ map (mkFlag turnOn  "X"    setLanguage) languageFlags
1385
1386 package_flags :: [Flag (CmdLineP DynFlags)]
1387 package_flags = [
1388         ------- Packages ----------------------------------------------------
1389     Flag "package-conf"         (HasArg extraPkgConf_)
1390   , Flag "no-user-package-conf" (NoArg (unSetDynFlag Opt_ReadUserPackageConf))
1391   , Flag "package-name"         (hasArg setPackageName)
1392   , Flag "package-id"           (HasArg exposePackageId)
1393   , Flag "package"              (HasArg exposePackage)
1394   , Flag "hide-package"         (HasArg hidePackage)
1395   , Flag "hide-all-packages"    (NoArg (setDynFlag Opt_HideAllPackages))
1396   , Flag "ignore-package"       (HasArg ignorePackage)
1397   , Flag "syslib"               (HasArg (\s -> do { exposePackage s
1398                                                   ; deprecate "Use -package instead" }))
1399   ]
1400
1401 type TurnOnFlag = Bool   -- True  <=> we are turning the flag on
1402                          -- False <=> we are turning the flag off
1403 turnOn  :: TurnOnFlag; turnOn = True
1404 turnOff :: TurnOnFlag; turnOff = False
1405
1406 type FlagSpec flag
1407    = ( String   -- Flag in string form
1408      , flag     -- Flag in internal form
1409      , TurnOnFlag -> DynP ())    -- Extra action to run when the flag is found
1410                                  -- Typically, emit a warning or error
1411
1412 mkFlag :: TurnOnFlag            -- ^ True <=> it should be turned on
1413        -> String                -- ^ The flag prefix
1414        -> (flag -> DynP ())     -- ^ What to do when the flag is found
1415        -> FlagSpec flag         -- ^ Specification of this particular flag
1416        -> Flag (CmdLineP DynFlags)
1417 mkFlag turn_on flagPrefix f (name, flag, extra_action)
1418     = Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on))
1419
1420 deprecatedForExtension :: String -> TurnOnFlag -> DynP ()
1421 deprecatedForExtension lang turn_on
1422     = deprecate ("use -X"  ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead")
1423     where 
1424       flag | turn_on    = lang
1425            | otherwise = "No"++lang
1426
1427 useInstead :: String -> TurnOnFlag -> DynP ()
1428 useInstead flag turn_on
1429   = deprecate ("Use -f" ++ no ++ flag ++ " instead")
1430   where
1431     no = if turn_on then "" else "no-"
1432
1433 nop :: TurnOnFlag -> DynP ()
1434 nop _ = return ()
1435
1436 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
1437 fFlags :: [FlagSpec DynFlag]
1438 fFlags = [
1439   ( "warn-dodgy-foreign-imports",       Opt_WarnDodgyForeignImports, nop ),
1440   ( "warn-dodgy-exports",               Opt_WarnDodgyExports, nop ),
1441   ( "warn-dodgy-imports",               Opt_WarnDodgyImports, nop ),
1442   ( "warn-duplicate-exports",           Opt_WarnDuplicateExports, nop ),
1443   ( "warn-hi-shadowing",                Opt_WarnHiShadows, nop ),
1444   ( "warn-implicit-prelude",            Opt_WarnImplicitPrelude, nop ),
1445   ( "warn-incomplete-patterns",         Opt_WarnIncompletePatterns, nop ),
1446   ( "warn-incomplete-uni-patterns",     Opt_WarnIncompleteUniPatterns, nop ),
1447   ( "warn-incomplete-record-updates",   Opt_WarnIncompletePatternsRecUpd, nop ),
1448   ( "warn-missing-fields",              Opt_WarnMissingFields, nop ),
1449   ( "warn-missing-import-lists",        Opt_WarnMissingImportList, nop ),
1450   ( "warn-missing-methods",             Opt_WarnMissingMethods, nop ),
1451   ( "warn-missing-signatures",          Opt_WarnMissingSigs, nop ),
1452   ( "warn-missing-local-sigs",          Opt_WarnMissingLocalSigs, nop ),
1453   ( "warn-name-shadowing",              Opt_WarnNameShadowing, nop ),
1454   ( "warn-overlapping-patterns",        Opt_WarnOverlappingPatterns, nop ),
1455   ( "warn-type-defaults",               Opt_WarnTypeDefaults, nop ),
1456   ( "warn-monomorphism-restriction",    Opt_WarnMonomorphism, nop ),
1457   ( "warn-unused-binds",                Opt_WarnUnusedBinds, nop ),
1458   ( "warn-unused-imports",              Opt_WarnUnusedImports, nop ),
1459   ( "warn-unused-matches",              Opt_WarnUnusedMatches, nop ),
1460   ( "warn-warnings-deprecations",       Opt_WarnWarningsDeprecations, nop ),
1461   ( "warn-deprecations",                Opt_WarnWarningsDeprecations, nop ),
1462   ( "warn-deprecated-flags",            Opt_WarnDeprecatedFlags, nop ),
1463   ( "warn-orphans",                     Opt_WarnOrphans, nop ),
1464   ( "warn-identities",                  Opt_WarnIdentities, nop ),
1465   ( "warn-auto-orphans",                Opt_WarnAutoOrphans, nop ),
1466   ( "warn-tabs",                        Opt_WarnTabs, nop ),
1467   ( "warn-unrecognised-pragmas",        Opt_WarnUnrecognisedPragmas, nop ),
1468   ( "warn-lazy-unlifted-bindings",      Opt_WarnLazyUnliftedBindings, nop),
1469   ( "warn-unused-do-bind",              Opt_WarnUnusedDoBind, nop ),
1470   ( "warn-wrong-do-bind",               Opt_WarnWrongDoBind, nop ),
1471   ( "warn-alternative-layout-rule-transitional", Opt_WarnAlternativeLayoutRuleTransitional, nop ),
1472   ( "print-explicit-foralls",           Opt_PrintExplicitForalls, nop ),
1473   ( "strictness",                       Opt_Strictness, nop ),
1474   ( "specialise",                       Opt_Specialise, nop ),
1475   ( "float-in",                         Opt_FloatIn, nop ),
1476   ( "static-argument-transformation",   Opt_StaticArgumentTransformation, nop ),
1477   ( "full-laziness",                    Opt_FullLaziness, nop ),
1478   ( "liberate-case",                    Opt_LiberateCase, nop ),
1479   ( "spec-constr",                      Opt_SpecConstr, nop ),
1480   ( "cse",                              Opt_CSE, nop ),
1481   ( "ignore-interface-pragmas",         Opt_IgnoreInterfacePragmas, nop ),
1482   ( "omit-interface-pragmas",           Opt_OmitInterfacePragmas, nop ),
1483   ( "expose-all-unfoldings",            Opt_ExposeAllUnfoldings, nop ),
1484   ( "do-lambda-eta-expansion",          Opt_DoLambdaEtaExpansion, nop ),
1485   ( "ignore-asserts",                   Opt_IgnoreAsserts, nop ),
1486   ( "do-eta-reduction",                 Opt_DoEtaReduction, nop ),
1487   ( "case-merge",                       Opt_CaseMerge, nop ),
1488   ( "unbox-strict-fields",              Opt_UnboxStrictFields, nop ),
1489   ( "method-sharing",                   Opt_MethodSharing, 
1490      \_ -> deprecate "doesn't do anything any more"),
1491      -- Remove altogether in GHC 7.2
1492   ( "dicts-cheap",                      Opt_DictsCheap, nop ),
1493   ( "excess-precision",                 Opt_ExcessPrecision, nop ),
1494   ( "eager-blackholing",                Opt_EagerBlackHoling, nop ),
1495   ( "asm-mangling",                     Opt_DoAsmMangling, nop ),
1496   ( "print-bind-result",                Opt_PrintBindResult, nop ),
1497   ( "force-recomp",                     Opt_ForceRecomp, nop ),
1498   ( "hpc-no-auto",                      Opt_Hpc_No_Auto, nop ),
1499   ( "rewrite-rules",                    Opt_EnableRewriteRules, useInstead "enable-rewrite-rules" ),
1500   ( "enable-rewrite-rules",             Opt_EnableRewriteRules, nop ),
1501   ( "break-on-exception",               Opt_BreakOnException, nop ),
1502   ( "break-on-error",                   Opt_BreakOnError, nop ),
1503   ( "print-evld-with-show",             Opt_PrintEvldWithShow, nop ),
1504   ( "print-bind-contents",              Opt_PrintBindContents, nop ),
1505   ( "run-cps",                          Opt_RunCPS, nop ),
1506   ( "run-cpsz",                         Opt_RunCPSZ, nop ),
1507   ( "new-codegen",                      Opt_TryNewCodeGen, nop ),
1508   ( "convert-to-zipper-and-back",       Opt_ConvertToZipCfgAndBack, nop ),
1509   ( "vectorise",                        Opt_Vectorise, nop ),
1510   ( "regs-graph",                       Opt_RegsGraph, nop ),
1511   ( "regs-iterative",                   Opt_RegsIterative, nop ),
1512   ( "gen-manifest",                     Opt_GenManifest, nop ),
1513   ( "embed-manifest",                   Opt_EmbedManifest, nop ),
1514   ( "ext-core",                         Opt_EmitExternalCore, nop ),
1515   ( "shared-implib",                    Opt_SharedImplib, nop ),
1516   ( "ghci-sandbox",                     Opt_GhciSandbox, nop ),
1517   ( "helpful-errors",                   Opt_HelpfulErrors, nop ),
1518   ( "building-cabal-package",           Opt_BuildingCabalPackage, nop ),
1519   ( "implicit-import-qualified",        Opt_ImplicitImportQualified, nop )
1520   ]
1521
1522 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
1523 fLangFlags :: [FlagSpec ExtensionFlag]
1524 fLangFlags = [
1525   ( "th",                               Opt_TemplateHaskell,
1526     deprecatedForExtension "TemplateHaskell" >> checkTemplateHaskellOk ),
1527   ( "fi",                               Opt_ForeignFunctionInterface,
1528     deprecatedForExtension "ForeignFunctionInterface" ),
1529   ( "ffi",                              Opt_ForeignFunctionInterface,
1530     deprecatedForExtension "ForeignFunctionInterface" ),
1531   ( "arrows",                           Opt_Arrows,
1532     deprecatedForExtension "Arrows" ),
1533   ( "generics",                         Opt_Generics,
1534     deprecatedForExtension "Generics" ),
1535   ( "implicit-prelude",                 Opt_ImplicitPrelude,
1536     deprecatedForExtension "ImplicitPrelude" ),
1537   ( "bang-patterns",                    Opt_BangPatterns,
1538     deprecatedForExtension "BangPatterns" ),
1539   ( "monomorphism-restriction",         Opt_MonomorphismRestriction,
1540     deprecatedForExtension "MonomorphismRestriction" ),
1541   ( "mono-pat-binds",                   Opt_MonoPatBinds,
1542     deprecatedForExtension "MonoPatBinds" ),
1543   ( "extended-default-rules",           Opt_ExtendedDefaultRules,
1544     deprecatedForExtension "ExtendedDefaultRules" ),
1545   ( "implicit-params",                  Opt_ImplicitParams,
1546     deprecatedForExtension "ImplicitParams" ),
1547   ( "scoped-type-variables",            Opt_ScopedTypeVariables,
1548     deprecatedForExtension "ScopedTypeVariables" ),
1549   ( "parr",                             Opt_ParallelArrays,
1550     deprecatedForExtension "ParallelArrays" ),
1551   ( "PArr",                             Opt_ParallelArrays,
1552     deprecatedForExtension "ParallelArrays" ),
1553   ( "allow-overlapping-instances",      Opt_OverlappingInstances,
1554     deprecatedForExtension "OverlappingInstances" ),
1555   ( "allow-undecidable-instances",      Opt_UndecidableInstances,
1556     deprecatedForExtension "UndecidableInstances" ),
1557   ( "allow-incoherent-instances",       Opt_IncoherentInstances,
1558     deprecatedForExtension "IncoherentInstances" )
1559   ]
1560
1561 supportedLanguages :: [String]
1562 supportedLanguages = [ name | (name, _, _) <- languageFlags ]
1563
1564 supportedExtensions :: [String]
1565 supportedExtensions = [ name' | (name, _, _) <- xFlags, name' <- [name, "No" ++ name] ]
1566
1567 supportedLanguagesAndExtensions :: [String]
1568 supportedLanguagesAndExtensions = supportedLanguages ++ supportedExtensions
1569
1570 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
1571 languageFlags :: [FlagSpec Language]
1572 languageFlags = [
1573   ( "Haskell98",                        Haskell98, nop ),
1574   ( "Haskell2010",                      Haskell2010, nop )
1575   ]
1576
1577 -- | These -X<blah> flags can all be reversed with -XNo<blah>
1578 xFlags :: [FlagSpec ExtensionFlag]
1579 xFlags = [
1580   ( "CPP",                              Opt_Cpp, nop ),
1581   ( "PostfixOperators",                 Opt_PostfixOperators, nop ),
1582   ( "TupleSections",                    Opt_TupleSections, nop ),
1583   ( "PatternGuards",                    Opt_PatternGuards, nop ),
1584   ( "UnicodeSyntax",                    Opt_UnicodeSyntax, nop ),
1585   ( "MagicHash",                        Opt_MagicHash, nop ),
1586   ( "PolymorphicComponents",            Opt_PolymorphicComponents, nop ),
1587   ( "ExistentialQuantification",        Opt_ExistentialQuantification, nop ),
1588   ( "KindSignatures",                   Opt_KindSignatures, nop ),
1589   ( "EmptyDataDecls",                   Opt_EmptyDataDecls, nop ),
1590   ( "ParallelListComp",                 Opt_ParallelListComp, nop ),
1591   ( "TransformListComp",                Opt_TransformListComp, nop ),
1592   ( "ForeignFunctionInterface",         Opt_ForeignFunctionInterface, nop ),
1593   ( "UnliftedFFITypes",                 Opt_UnliftedFFITypes, nop ),
1594   ( "GHCForeignImportPrim",             Opt_GHCForeignImportPrim, nop ),
1595   ( "LiberalTypeSynonyms",              Opt_LiberalTypeSynonyms, nop ),
1596   ( "Rank2Types",                       Opt_Rank2Types, nop ),
1597   ( "RankNTypes",                       Opt_RankNTypes, nop ),
1598   ( "ImpredicativeTypes",               Opt_ImpredicativeTypes, nop), 
1599   ( "TypeOperators",                    Opt_TypeOperators, nop ),
1600   ( "RecursiveDo",                      Opt_RecursiveDo,
1601     deprecatedForExtension "DoRec"),
1602   ( "DoRec",                            Opt_DoRec, nop ),
1603   ( "Arrows",                           Opt_Arrows, nop ),
1604   ( "ModalTypes",                       Opt_ModalTypes, nop ),
1605   ( "ParallelArrays",                   Opt_ParallelArrays, nop ),
1606   ( "TemplateHaskell",                  Opt_TemplateHaskell, checkTemplateHaskellOk ),
1607   ( "QuasiQuotes",                      Opt_QuasiQuotes, nop ),
1608   ( "Generics",                         Opt_Generics, nop ),
1609   ( "ImplicitPrelude",                  Opt_ImplicitPrelude, nop ),
1610   ( "RecordWildCards",                  Opt_RecordWildCards, nop ),
1611   ( "NamedFieldPuns",                   Opt_RecordPuns, nop ),
1612   ( "RecordPuns",                       Opt_RecordPuns,
1613     deprecatedForExtension "NamedFieldPuns" ),
1614   ( "DisambiguateRecordFields",         Opt_DisambiguateRecordFields, nop ),
1615   ( "OverloadedStrings",                Opt_OverloadedStrings, nop ),
1616   ( "GADTs",                            Opt_GADTs, nop ),
1617   ( "GADTSyntax",                       Opt_GADTSyntax, nop ),
1618   ( "ViewPatterns",                     Opt_ViewPatterns, nop ),
1619   ( "TypeFamilies",                     Opt_TypeFamilies, nop ),
1620   ( "BangPatterns",                     Opt_BangPatterns, nop ),
1621   ( "MonomorphismRestriction",          Opt_MonomorphismRestriction, nop ),
1622   ( "NPlusKPatterns",                   Opt_NPlusKPatterns, nop ),
1623   ( "DoAndIfThenElse",                  Opt_DoAndIfThenElse, nop ),
1624   ( "RebindableSyntax",                 Opt_RebindableSyntax, nop ),
1625   ( "MonoPatBinds",                     Opt_MonoPatBinds, nop ),
1626   ( "ExplicitForAll",                   Opt_ExplicitForAll, nop ),
1627   ( "AlternativeLayoutRule",            Opt_AlternativeLayoutRule, nop ),
1628   ( "AlternativeLayoutRuleTransitional",Opt_AlternativeLayoutRuleTransitional, nop ),
1629   ( "DatatypeContexts",                 Opt_DatatypeContexts, nop ),
1630   ( "NondecreasingIndentation",         Opt_NondecreasingIndentation, nop ),
1631   ( "RelaxedLayout",                    Opt_RelaxedLayout, nop ),
1632   ( "MonoLocalBinds",                   Opt_MonoLocalBinds, nop ),
1633   ( "RelaxedPolyRec",                   Opt_RelaxedPolyRec, 
1634     \ turn_on -> if not turn_on 
1635                  then deprecate "You can't turn off RelaxedPolyRec any more"
1636                  else return () ),
1637   ( "ExtendedDefaultRules",             Opt_ExtendedDefaultRules, nop ),
1638   ( "ImplicitParams",                   Opt_ImplicitParams, nop ),
1639   ( "ScopedTypeVariables",              Opt_ScopedTypeVariables, nop ),
1640
1641   ( "PatternSignatures",                Opt_ScopedTypeVariables, 
1642     deprecatedForExtension "ScopedTypeVariables" ),
1643
1644   ( "UnboxedTuples",                    Opt_UnboxedTuples, nop ),
1645   ( "StandaloneDeriving",               Opt_StandaloneDeriving, nop ),
1646   ( "DeriveDataTypeable",               Opt_DeriveDataTypeable, nop ),
1647   ( "DeriveFunctor",                    Opt_DeriveFunctor, nop ),
1648   ( "DeriveTraversable",                Opt_DeriveTraversable, nop ),
1649   ( "DeriveFoldable",                   Opt_DeriveFoldable, nop ),
1650   ( "TypeSynonymInstances",             Opt_TypeSynonymInstances, nop ),
1651   ( "FlexibleContexts",                 Opt_FlexibleContexts, nop ),
1652   ( "FlexibleInstances",                Opt_FlexibleInstances, nop ),
1653   ( "ConstrainedClassMethods",          Opt_ConstrainedClassMethods, nop ),
1654   ( "MultiParamTypeClasses",            Opt_MultiParamTypeClasses, nop ),
1655   ( "FunctionalDependencies",           Opt_FunctionalDependencies, nop ),
1656   ( "GeneralizedNewtypeDeriving",       Opt_GeneralizedNewtypeDeriving, nop ),
1657   ( "OverlappingInstances",             Opt_OverlappingInstances, nop ),
1658   ( "UndecidableInstances",             Opt_UndecidableInstances, nop ),
1659   ( "IncoherentInstances",              Opt_IncoherentInstances, nop ),
1660   ( "PackageImports",                   Opt_PackageImports, nop )
1661   ]
1662
1663 defaultFlags :: [DynFlag]
1664 defaultFlags 
1665   = [ Opt_AutoLinkPackages,
1666       Opt_ReadUserPackageConf,
1667
1668       Opt_DoAsmMangling,
1669
1670       Opt_SharedImplib,
1671
1672       Opt_GenManifest,
1673       Opt_EmbedManifest,
1674       Opt_PrintBindContents,
1675       Opt_GhciSandbox,
1676       Opt_HelpfulErrors
1677     ]
1678
1679     ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
1680              -- The default -O0 options
1681
1682     ++ standardWarnings
1683
1684 impliedFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)]
1685 impliedFlags
1686   = [ (Opt_RankNTypes,                turnOn, Opt_ExplicitForAll)
1687     , (Opt_Rank2Types,                turnOn, Opt_ExplicitForAll)
1688     , (Opt_ScopedTypeVariables,       turnOn, Opt_ExplicitForAll)
1689     , (Opt_LiberalTypeSynonyms,       turnOn, Opt_ExplicitForAll)
1690     , (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll)
1691     , (Opt_PolymorphicComponents,     turnOn, Opt_ExplicitForAll)
1692     , (Opt_FlexibleInstances,         turnOn, Opt_TypeSynonymInstances)
1693
1694     , (Opt_ModalTypes,                 turnOn,  Opt_RankNTypes)
1695     , (Opt_ModalTypes,                 turnOn,  Opt_ExplicitForAll)
1696     --, (Opt_ModalTypes,                 turnOn,  Opt_RebindableSyntax)
1697     , (Opt_ModalTypes,                 turnOff, Opt_MonomorphismRestriction)
1698
1699     , (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude)      -- NB: turn off!
1700
1701     , (Opt_GADTs,            turnOn, Opt_GADTSyntax)
1702     , (Opt_GADTs,            turnOn, Opt_MonoLocalBinds)
1703     , (Opt_TypeFamilies,     turnOn, Opt_MonoLocalBinds)
1704
1705     , (Opt_TypeFamilies,     turnOn, Opt_KindSignatures)  -- Type families use kind signatures
1706                                                      -- all over the place
1707
1708     , (Opt_ImpredicativeTypes,  turnOn, Opt_RankNTypes)
1709
1710         -- Record wild-cards implies field disambiguation
1711         -- Otherwise if you write (C {..}) you may well get
1712         -- stuff like " 'a' not in scope ", which is a bit silly
1713         -- if the compiler has just filled in field 'a' of constructor 'C'
1714     , (Opt_RecordWildCards,     turnOn, Opt_DisambiguateRecordFields)
1715     
1716     , (Opt_ParallelArrays, turnOn, Opt_ParallelListComp)
1717   ]
1718
1719 optLevelFlags :: [([Int], DynFlag)]
1720 optLevelFlags
1721   = [ ([0],     Opt_IgnoreInterfacePragmas)
1722     , ([0],     Opt_OmitInterfacePragmas)
1723
1724     , ([1,2],   Opt_IgnoreAsserts)
1725     , ([1,2],   Opt_EnableRewriteRules)  -- Off for -O0; see Note [Scoping for Builtin rules]
1726                                          --              in PrelRules
1727     , ([1,2],   Opt_DoEtaReduction)
1728     , ([1,2],   Opt_CaseMerge)
1729     , ([1,2],   Opt_Strictness)
1730     , ([1,2],   Opt_CSE)
1731     , ([1,2],   Opt_FullLaziness)
1732     , ([1,2],   Opt_Specialise)
1733     , ([1,2],   Opt_FloatIn)
1734
1735     , ([2],     Opt_LiberateCase)
1736     , ([2],     Opt_SpecConstr)
1737     , ([2],     Opt_RegsGraph)
1738
1739 --     , ([2],     Opt_StaticArgumentTransformation)
1740 -- Max writes: I think it's probably best not to enable SAT with -O2 for the
1741 -- 6.10 release. The version of SAT in HEAD at the moment doesn't incorporate
1742 -- several improvements to the heuristics, and I'm concerned that without
1743 -- those changes SAT will interfere with some attempts to write "high
1744 -- performance Haskell", as we saw in some posts on Haskell-Cafe earlier
1745 -- this year. In particular, the version in HEAD lacks the tail call
1746 -- criterion, so many things that look like reasonable loops will be
1747 -- turned into functions with extra (unneccesary) thunk creation.
1748
1749     , ([0,1,2], Opt_DoLambdaEtaExpansion)
1750                 -- This one is important for a tiresome reason:
1751                 -- we want to make sure that the bindings for data
1752                 -- constructors are eta-expanded.  This is probably
1753                 -- a good thing anyway, but it seems fragile.
1754     ]
1755
1756 -- -----------------------------------------------------------------------------
1757 -- Standard sets of warning options
1758
1759 standardWarnings :: [DynFlag]
1760 standardWarnings
1761     = [ Opt_WarnWarningsDeprecations,
1762         Opt_WarnDeprecatedFlags,
1763         Opt_WarnUnrecognisedPragmas,
1764         Opt_WarnOverlappingPatterns,
1765         Opt_WarnMissingFields,
1766         Opt_WarnMissingMethods,
1767         Opt_WarnDuplicateExports,
1768         Opt_WarnLazyUnliftedBindings,
1769         Opt_WarnDodgyForeignImports,
1770         Opt_WarnWrongDoBind,
1771         Opt_WarnAlternativeLayoutRuleTransitional
1772       ]
1773
1774 minusWOpts :: [DynFlag]
1775 -- Things you get with -W
1776 minusWOpts
1777     = standardWarnings ++
1778       [ Opt_WarnUnusedBinds,
1779         Opt_WarnUnusedMatches,
1780         Opt_WarnUnusedImports,
1781         Opt_WarnIncompletePatterns,
1782         Opt_WarnDodgyExports,
1783         Opt_WarnDodgyImports
1784       ]
1785
1786 minusWallOpts :: [DynFlag]
1787 -- Things you get with -Wall
1788 minusWallOpts
1789     = minusWOpts ++
1790       [ Opt_WarnTypeDefaults,
1791         Opt_WarnNameShadowing,
1792         Opt_WarnMissingSigs,
1793         Opt_WarnHiShadows,
1794         Opt_WarnOrphans,
1795         Opt_WarnUnusedDoBind
1796       ]
1797
1798 minuswRemovesOpts :: [DynFlag]
1799 -- minuswRemovesOpts should be every warning option 
1800 minuswRemovesOpts
1801     = minusWallOpts ++
1802       [Opt_WarnTabs,
1803        Opt_WarnIncompletePatternsRecUpd,
1804        Opt_WarnIncompleteUniPatterns,
1805        Opt_WarnMonomorphism,
1806        Opt_WarnUnrecognisedPragmas,
1807        Opt_WarnAutoOrphans,
1808        Opt_WarnImplicitPrelude
1809      ]       
1810
1811 enableGlasgowExts :: DynP ()
1812 enableGlasgowExts = do setDynFlag Opt_PrintExplicitForalls
1813                        mapM_ setExtensionFlag glasgowExtsFlags
1814
1815 disableGlasgowExts :: DynP ()
1816 disableGlasgowExts = do unSetDynFlag Opt_PrintExplicitForalls
1817                         mapM_ unSetExtensionFlag glasgowExtsFlags
1818
1819 glasgowExtsFlags :: [ExtensionFlag]
1820 glasgowExtsFlags = [
1821              Opt_ForeignFunctionInterface
1822            , Opt_UnliftedFFITypes
1823            , Opt_ImplicitParams
1824            , Opt_ScopedTypeVariables
1825            , Opt_UnboxedTuples
1826            , Opt_TypeSynonymInstances
1827            , Opt_StandaloneDeriving
1828            , Opt_DeriveDataTypeable
1829            , Opt_DeriveFunctor
1830            , Opt_DeriveFoldable
1831            , Opt_DeriveTraversable
1832            , Opt_FlexibleContexts
1833            , Opt_FlexibleInstances
1834            , Opt_ConstrainedClassMethods
1835            , Opt_MultiParamTypeClasses
1836            , Opt_FunctionalDependencies
1837            , Opt_MagicHash
1838            , Opt_PolymorphicComponents
1839            , Opt_ExistentialQuantification
1840            , Opt_UnicodeSyntax
1841            , Opt_PostfixOperators
1842            , Opt_PatternGuards
1843            , Opt_LiberalTypeSynonyms
1844            , Opt_RankNTypes
1845            , Opt_TypeOperators
1846            , Opt_DoRec
1847            , Opt_ParallelListComp
1848            , Opt_EmptyDataDecls
1849            , Opt_KindSignatures
1850            , Opt_GeneralizedNewtypeDeriving ]
1851
1852 #ifdef GHCI
1853 -- Consult the RTS to find whether GHC itself has been built profiled
1854 -- If so, you can't use Template Haskell
1855 foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt
1856
1857 rtsIsProfiled :: Bool
1858 rtsIsProfiled = unsafePerformIO rtsIsProfiledIO /= 0
1859
1860 checkTemplateHaskellOk :: Bool -> DynP ()
1861 checkTemplateHaskellOk turn_on 
1862   | turn_on && rtsIsProfiled
1863   = addErr "You can't use Template Haskell with a profiled compiler"
1864   | otherwise
1865   = return ()
1866 #else
1867 -- In stage 1 we don't know that the RTS has rts_isProfiled, 
1868 -- so we simply say "ok".  It doesn't matter because TH isn't
1869 -- available in stage 1 anyway.
1870 checkTemplateHaskellOk turn_on = return ()
1871 #endif
1872
1873 {- **********************************************************************
1874 %*                                                                      *
1875                 DynFlags constructors
1876 %*                                                                      *
1877 %********************************************************************* -}
1878
1879 type DynP = EwM (CmdLineP DynFlags)
1880
1881 upd :: (DynFlags -> DynFlags) -> DynP ()
1882 upd f = liftEwM (do { dfs <- getCmdLineState
1883                     ; putCmdLineState $! (f dfs) })
1884
1885 --------------- Constructor functions for OptKind -----------------
1886 noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
1887 noArg fn = NoArg (upd fn)
1888
1889 noArgDF :: (DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
1890 noArgDF fn deprec = NoArg (upd fn >> deprecate deprec)
1891
1892 hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
1893 hasArg fn = HasArg (upd . fn)
1894
1895 hasArgDF :: (String -> DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
1896 hasArgDF fn deprec = HasArg (\s -> do { upd (fn s)
1897                                       ; deprecate deprec })
1898
1899 intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
1900 intSuffix fn = IntSuffix (\n -> upd (fn n))
1901
1902 setDumpFlag :: DynFlag -> OptKind (CmdLineP DynFlags)
1903 setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
1904
1905 --------------------------
1906 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1907 setDynFlag   f = upd (\dfs -> dopt_set dfs f)
1908 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1909
1910 --------------------------
1911 setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP ()
1912 setExtensionFlag f = do { upd (\dfs -> xopt_set dfs f)
1913                         ; sequence_ deps }
1914   where
1915     deps = [ if turn_on then setExtensionFlag   d
1916                         else unSetExtensionFlag d
1917            | (f', turn_on, d) <- impliedFlags, f' == f ]
1918         -- When you set f, set the ones it implies
1919         -- NB: use setExtensionFlag recursively, in case the implied flags
1920         --     implies further flags
1921
1922 unSetExtensionFlag f = upd (\dfs -> xopt_unset dfs f)
1923    -- When you un-set f, however, we don't un-set the things it implies
1924    --      (except for -fno-glasgow-exts, which is treated specially)
1925
1926 --------------------------
1927 setDumpFlag' :: DynFlag -> DynP ()
1928 setDumpFlag' dump_flag
1929   = do { setDynFlag dump_flag
1930        ; when want_recomp forceRecompile }
1931   where
1932         -- Certain dumpy-things are really interested in what's going
1933         -- on during recompilation checking, so in those cases we
1934         -- don't want to turn it off.
1935     want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace,
1936                                        Opt_D_dump_hi_diffs]
1937
1938 forceRecompile :: DynP ()
1939 -- Whenver we -ddump, force recompilation (by switching off the 
1940 -- recompilation checker), else you don't see the dump! However, 
1941 -- don't switch it off in --make mode, else *everything* gets
1942 -- recompiled which probably isn't what you want
1943 forceRecompile = do { dfs <- liftEwM getCmdLineState
1944                     ; when (force_recomp dfs) (setDynFlag Opt_ForceRecomp) }
1945         where
1946           force_recomp dfs = isOneShot (ghcMode dfs)
1947
1948 setVerboseCore2Core :: DynP ()
1949 setVerboseCore2Core = do forceRecompile
1950                          setDynFlag Opt_D_verbose_core2core 
1951                          upd (\dfs -> dfs { shouldDumpSimplPhase = Nothing })
1952                          
1953
1954 setDumpSimplPhases :: String -> DynP ()
1955 setDumpSimplPhases s = do forceRecompile
1956                           upd (\dfs -> dfs { shouldDumpSimplPhase = Just spec })
1957   where
1958     spec = case s of { ('=' : s') -> s';  _ -> s }
1959
1960 setVerbosity :: Maybe Int -> DynP ()
1961 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1962
1963 addCmdlineHCInclude :: String -> DynP ()
1964 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes =  a : cmdlineHcIncludes s})
1965
1966 extraPkgConf_ :: FilePath -> DynP ()
1967 extraPkgConf_  p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1968
1969 exposePackage, exposePackageId, hidePackage, ignorePackage :: String -> DynP ()
1970 exposePackage p =
1971   upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1972 exposePackageId p =
1973   upd (\s -> s{ packageFlags = ExposePackageId p : packageFlags s })
1974 hidePackage p =
1975   upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1976 ignorePackage p =
1977   upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1978
1979 setPackageName :: String -> DynFlags -> DynFlags
1980 setPackageName p s =  s{ thisPackage = stringToPackageId p }
1981
1982 -- If we're linking a binary, then only targets that produce object
1983 -- code are allowed (requests for other target types are ignored).
1984 setTarget :: HscTarget -> DynP ()
1985 setTarget l = upd set
1986   where
1987    set dfs
1988      | ghcLink dfs /= LinkBinary || isObjectTarget l  = dfs{ hscTarget = l }
1989      | otherwise = dfs
1990
1991 -- Changes the target only if we're compiling object code.  This is
1992 -- used by -fasm and -fvia-C, which switch from one to the other, but
1993 -- not from bytecode to object-code.  The idea is that -fasm/-fvia-C
1994 -- can be safely used in an OPTIONS_GHC pragma.
1995 setObjTarget :: HscTarget -> DynP ()
1996 setObjTarget l = upd set
1997   where
1998    set dfs
1999      | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
2000      | otherwise = dfs
2001
2002 setOptLevel :: Int -> DynFlags -> DynFlags
2003 setOptLevel n dflags
2004    | hscTarget dflags == HscInterpreted && n > 0
2005         = dflags
2006             -- not in IO any more, oh well:
2007             -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
2008    | otherwise
2009         = updOptLevel n dflags
2010
2011
2012 -- -Odph is equivalent to
2013 --
2014 --    -O2                               optimise as much as possible
2015 --    -fmax-simplifier-iterations20     this is necessary sometimes
2016 --    -fsimplifier-phases=3             we use an additional simplifier phase for fusion
2017 --
2018 setDPHOpt :: DynFlags -> DynFlags
2019 setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations  = 20
2020                                          , simplPhases         = 3
2021                                          })
2022
2023 -- Determines the package used by the vectoriser for the symbols of the vectorised code.
2024 -- 'DPHNone' indicates that no data-parallel backend library is available; hence, the
2025 -- vectoriser cannot be used.
2026 --
2027 data DPHBackend = DPHPar    -- "dph-par"
2028                 | DPHSeq    -- "dph-seq"
2029                 | DPHThis   -- the currently compiled package
2030                 | DPHNone   -- no DPH library available
2031         deriving(Eq, Ord, Enum, Show)
2032
2033 setDPHBackend :: DPHBackend -> DynP ()
2034 setDPHBackend backend = upd $ \dflags -> dflags { dphBackend = backend }
2035
2036 -- Query the DPH backend package to be used by the vectoriser and desugaring of DPH syntax.
2037 --
2038 dphPackageMaybe :: DynFlags -> Maybe PackageId
2039 dphPackageMaybe dflags 
2040   = case dphBackend dflags of
2041       DPHPar  -> Just dphParPackageId
2042       DPHSeq  -> Just dphSeqPackageId
2043       DPHThis -> Just (thisPackage dflags)
2044       DPHNone -> Nothing
2045
2046 setMainIs :: String -> DynP ()
2047 setMainIs arg
2048   | not (null main_fn) && isLower (head main_fn)
2049      -- The arg looked like "Foo.Bar.baz"
2050   = upd $ \d -> d{ mainFunIs = Just main_fn,
2051                    mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
2052
2053   | isUpper (head arg)  -- The arg looked like "Foo" or "Foo.Bar"
2054   = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) }
2055
2056   | otherwise                   -- The arg looked like "baz"
2057   = upd $ \d -> d{ mainFunIs = Just arg }
2058   where
2059     (main_mod, main_fn) = splitLongestPrefix arg (== '.')
2060
2061 -----------------------------------------------------------------------------
2062 -- Paths & Libraries
2063
2064 addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP ()
2065
2066 -- -i on its own deletes the import paths
2067 addImportPath "" = upd (\s -> s{importPaths = []})
2068 addImportPath p  = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
2069
2070
2071 addLibraryPath p =
2072   upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
2073
2074 addIncludePath p =
2075   upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
2076
2077 addFrameworkPath p =
2078   upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
2079
2080 #ifndef mingw32_TARGET_OS
2081 split_marker :: Char
2082 split_marker = ':'   -- not configurable (ToDo)
2083 #endif
2084
2085 splitPathList :: String -> [String]
2086 splitPathList s = filter notNull (splitUp s)
2087                 -- empty paths are ignored: there might be a trailing
2088                 -- ':' in the initial list, for example.  Empty paths can
2089                 -- cause confusion when they are translated into -I options
2090                 -- for passing to gcc.
2091   where
2092 #ifndef mingw32_TARGET_OS
2093     splitUp xs = split split_marker xs
2094 #else
2095      -- Windows: 'hybrid' support for DOS-style paths in directory lists.
2096      --
2097      -- That is, if "foo:bar:baz" is used, this interpreted as
2098      -- consisting of three entries, 'foo', 'bar', 'baz'.
2099      -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
2100      -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
2101      --
2102      -- Notice that no attempt is made to fully replace the 'standard'
2103      -- split marker ':' with the Windows / DOS one, ';'. The reason being
2104      -- that this will cause too much breakage for users & ':' will
2105      -- work fine even with DOS paths, if you're not insisting on being silly.
2106      -- So, use either.
2107     splitUp []             = []
2108     splitUp (x:':':div:xs) | div `elem` dir_markers
2109                            = ((x:':':div:p): splitUp rs)
2110                            where
2111                               (p,rs) = findNextPath xs
2112           -- we used to check for existence of the path here, but that
2113           -- required the IO monad to be threaded through the command-line
2114           -- parser which is quite inconvenient.  The
2115     splitUp xs = cons p (splitUp rs)
2116                where
2117                  (p,rs) = findNextPath xs
2118
2119                  cons "" xs = xs
2120                  cons x  xs = x:xs
2121
2122     -- will be called either when we've consumed nought or the
2123     -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
2124     -- finding the next split marker.
2125     findNextPath xs =
2126         case break (`elem` split_markers) xs of
2127            (p, _:ds) -> (p, ds)
2128            (p, xs)   -> (p, xs)
2129
2130     split_markers :: [Char]
2131     split_markers = [':', ';']
2132
2133     dir_markers :: [Char]
2134     dir_markers = ['/', '\\']
2135 #endif
2136
2137 -- -----------------------------------------------------------------------------
2138 -- tmpDir, where we store temporary files.
2139
2140 setTmpDir :: FilePath -> DynFlags -> DynFlags
2141 setTmpDir dir dflags = dflags{ tmpDir = normalise dir }
2142   -- we used to fix /cygdrive/c/.. on Windows, but this doesn't
2143   -- seem necessary now --SDM 7/2/2008
2144
2145 -----------------------------------------------------------------------------
2146 -- RTS opts
2147
2148 setRtsOpts :: String -> DynP ()
2149 setRtsOpts arg  = upd $ \ d -> d {rtsOpts = Just arg}
2150
2151 setRtsOptsEnabled :: RtsOptsEnabled -> DynP ()
2152 setRtsOptsEnabled arg  = upd $ \ d -> d {rtsOptsEnabled = arg}
2153
2154 -----------------------------------------------------------------------------
2155 -- Hpc stuff
2156
2157 setOptHpcDir :: String -> DynP ()
2158 setOptHpcDir arg  = upd $ \ d -> d{hpcDir = arg}
2159
2160 -----------------------------------------------------------------------------
2161 -- Via-C compilation stuff
2162
2163 -- There are some options that we need to pass to gcc when compiling
2164 -- Haskell code via C, but are only supported by recent versions of
2165 -- gcc.  The configure script decides which of these options we need,
2166 -- and puts them in the file "extra-gcc-opts" in $topdir, which is
2167 -- read before each via-C compilation.  The advantage of having these
2168 -- in a separate file is that the file can be created at install-time
2169 -- depending on the available gcc version, and even re-generated  later
2170 -- if gcc is upgraded.
2171 --
2172 -- The options below are not dependent on the version of gcc, only the
2173 -- platform.
2174
2175 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
2176                               [String]) -- for registerised HC compilations
2177 machdepCCOpts dflags = let (flagsAll, flagsRegHc) = machdepCCOpts' dflags
2178                        in (cCcOpts ++ flagsAll, flagsRegHc)
2179
2180 machdepCCOpts' :: DynFlags -> ([String], -- flags for all C compilations
2181                                [String]) -- for registerised HC compilations
2182 machdepCCOpts' _dflags
2183 #if alpha_TARGET_ARCH
2184         =       ( ["-w", "-mieee"
2185 #ifdef HAVE_THREADED_RTS_SUPPORT
2186                     , "-D_REENTRANT"
2187 #endif
2188                    ], [] )
2189         -- For now, to suppress the gcc warning "call-clobbered
2190         -- register used for global register variable", we simply
2191         -- disable all warnings altogether using the -w flag. Oh well.
2192
2193 #elif hppa_TARGET_ARCH
2194         -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
2195         -- (very nice, but too bad the HP /usr/include files don't agree.)
2196         = ( ["-D_HPUX_SOURCE"], [] )
2197
2198 #elif m68k_TARGET_ARCH
2199       -- -fno-defer-pop : for the .hc files, we want all the pushing/
2200       --    popping of args to routines to be explicit; if we let things
2201       --    be deferred 'til after an STGJUMP, imminent death is certain!
2202       --
2203       -- -fomit-frame-pointer : *don't*
2204       --     It's better to have a6 completely tied up being a frame pointer
2205       --     rather than let GCC pick random things to do with it.
2206       --     (If we want to steal a6, then we would try to do things
2207       --     as on iX86, where we *do* steal the frame pointer [%ebp].)
2208         = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
2209
2210 #elif i386_TARGET_ARCH
2211       -- -fno-defer-pop : basically the same game as for m68k
2212       --
2213       -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
2214       --   the fp (%ebp) for our register maps.
2215         =  let n_regs = stolen_x86_regs _dflags
2216            in
2217                     (
2218                       [ if opt_Static then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
2219                       ],
2220                       [ "-fno-defer-pop",
2221                         "-fomit-frame-pointer",
2222                         -- we want -fno-builtin, because when gcc inlines
2223                         -- built-in functions like memcpy() it tends to
2224                         -- run out of registers, requiring -monly-n-regs
2225                         "-fno-builtin",
2226                         "-DSTOLEN_X86_REGS="++show n_regs ]
2227                     )
2228
2229 #elif ia64_TARGET_ARCH
2230         = ( [], ["-fomit-frame-pointer", "-G0"] )
2231
2232 #elif x86_64_TARGET_ARCH
2233         = (
2234                 [],
2235                 ["-fomit-frame-pointer",
2236                  "-fno-asynchronous-unwind-tables",
2237                         -- the unwind tables are unnecessary for HC code,
2238                         -- and get in the way of -split-objs.  Another option
2239                         -- would be to throw them away in the mangler, but this
2240                         -- is easier.
2241                  "-fno-builtin"
2242                         -- calling builtins like strlen() using the FFI can
2243                         -- cause gcc to run out of regs, so use the external
2244                         -- version.
2245                 ] )
2246
2247 #elif sparc_TARGET_ARCH
2248         = ( [], ["-w"] )
2249         -- For now, to suppress the gcc warning "call-clobbered
2250         -- register used for global register variable", we simply
2251         -- disable all warnings altogether using the -w flag. Oh well.
2252
2253 #elif powerpc_apple_darwin_TARGET
2254       -- -no-cpp-precomp:
2255       --     Disable Apple's precompiling preprocessor. It's a great thing
2256       --     for "normal" programs, but it doesn't support register variable
2257       --     declarations.
2258         = ( [], ["-no-cpp-precomp"] )
2259 #else
2260         = ( [], [] )
2261 #endif
2262
2263 picCCOpts :: DynFlags -> [String]
2264 picCCOpts _dflags
2265 #if darwin_TARGET_OS
2266       -- Apple prefers to do things the other way round.
2267       -- PIC is on by default.
2268       -- -mdynamic-no-pic:
2269       --     Turn off PIC code generation.
2270       -- -fno-common:
2271       --     Don't generate "common" symbols - these are unwanted
2272       --     in dynamic libraries.
2273
2274     | opt_PIC
2275         = ["-fno-common", "-U __PIC__","-D__PIC__"]
2276     | otherwise
2277         = ["-mdynamic-no-pic"]
2278 #elif mingw32_TARGET_OS
2279       -- no -fPIC for Windows
2280     | opt_PIC
2281         = ["-U __PIC__","-D__PIC__"]
2282     | otherwise
2283         = []
2284 #else
2285       -- we need -fPIC for C files when we are compiling with -dynamic,
2286       -- otherwise things like stub.c files don't get compiled
2287       -- correctly.  They need to reference data in the Haskell
2288       -- objects, but can't without -fPIC.  See
2289       -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode
2290     | opt_PIC || not opt_Static
2291         = ["-fPIC", "-U __PIC__", "-D__PIC__"]
2292     | otherwise
2293         = []
2294 #endif
2295
2296 -- -----------------------------------------------------------------------------
2297 -- Splitting
2298
2299 can_split :: Bool
2300 can_split = cSupportsSplitObjs == "YES"
2301
2302 -- -----------------------------------------------------------------------------
2303 -- Compiler Info
2304
2305 data Printable = String String
2306                | FromDynFlags (DynFlags -> String)
2307
2308 compilerInfo :: [(String, Printable)]
2309 compilerInfo = [("Project name",                String cProjectName),
2310                 ("Project version",             String cProjectVersion),
2311                 ("Booter version",              String cBooterVersion),
2312                 ("Stage",                       String cStage),
2313                 ("Build platform",              String cBuildPlatformString),
2314                 ("Host platform",               String cHostPlatformString),
2315                 ("Target platform",             String cTargetPlatformString),
2316                 ("Have interpreter",            String cGhcWithInterpreter),
2317                 ("Object splitting supported",  String cSupportsSplitObjs),
2318                 ("Have native code generator",  String cGhcWithNativeCodeGen),
2319                 ("Support SMP",                 String cGhcWithSMP),
2320                 ("Unregisterised",              String cGhcUnregisterised),
2321                 ("Tables next to code",         String cGhcEnableTablesNextToCode),
2322                 ("RTS ways",                    String cGhcRTSWays),
2323                 ("Leading underscore",          String cLeadingUnderscore),
2324                 ("Debug on",                    String (show debugIsOn)),
2325                 ("LibDir",                      FromDynFlags topDir),
2326                 ("Global Package DB",           FromDynFlags systemPackageConfig),
2327                 ("C compiler flags",            String (show cCcOpts)),
2328                 ("Gcc Linker flags",            String (show cGccLinkerOpts)),
2329                 ("Ld Linker flags",             String (show cLdLinkerOpts))
2330                ]
2331