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