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