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