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