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