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