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