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