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