2 {-# OPTIONS -fno-warn-missing-fields #-}
3 -----------------------------------------------------------------------------
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.
12 -- (c) The University of Glasgow 2005
14 -----------------------------------------------------------------------------
20 HscTarget(..), isObjectTarget, defaultObjectTarget,
21 GhcMode(..), isOneShot,
22 GhcLink(..), isNoLink,
26 -- Configuration of the core-to-core and stg-to-stg phases
30 SimplifierMode(..), FloatOutSwitches(..),
31 getCoreToDo, getStgToDo,
33 -- Manipulating DynFlags
34 defaultDynFlags, -- DynFlags
35 initDynFlags, -- DynFlags -> IO DynFlags
37 dopt, -- DynFlag -> DynFlags -> Bool
38 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
39 getOpts, -- (DynFlags -> [a]) -> IO [a]
50 machdepCCOpts, picCCOpts
53 #include "HsVersions.h"
55 import Module ( Module, mkModuleName, mkModule )
57 import PrelNames ( mAIN )
58 #ifdef i386_TARGET_ARCH
59 import StaticFlags ( opt_Static )
61 import StaticFlags ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
63 import {-# SOURCE #-} Packages (PackageState)
64 import DriverPhases ( Phase(..), phaseInputExt )
67 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
68 import Panic ( panic, GhcException(..) )
69 import UniqFM ( UniqFM )
70 import Util ( notNull, splitLongestPrefix, normalisePath )
71 import Maybes ( orElse, fromJust )
72 import SrcLoc ( SrcSpan )
74 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
76 import Data.IORef ( readIORef )
77 import Control.Exception ( throwDyn )
78 import Control.Monad ( when )
79 #ifdef mingw32_TARGET_OS
80 import Data.List ( isPrefixOf )
85 import Data.Char ( isUpper, toLower )
86 import System.IO ( hPutStrLn, stderr )
88 -- -----------------------------------------------------------------------------
102 | Opt_D_dump_inlinings
103 | Opt_D_dump_rule_firings
104 | Opt_D_dump_occur_anal
108 | Opt_D_dump_simpl_iterations
117 | Opt_D_dump_worker_wrapper
118 | Opt_D_dump_rn_trace
119 | Opt_D_dump_rn_stats
121 | Opt_D_dump_simpl_stats
122 | Opt_D_dump_tc_trace
123 | Opt_D_dump_if_trace
129 | Opt_D_verbose_core2core
130 | Opt_D_verbose_stg2stg
132 | Opt_D_dump_hi_diffs
133 | Opt_D_dump_minimal_imports
134 | Opt_D_dump_mod_cycles
135 | Opt_D_faststring_stats
140 | Opt_WarnIsError -- -Werror; makes warnings fatal
141 | Opt_WarnDuplicateExports
143 | Opt_WarnImplicitPrelude
144 | Opt_WarnIncompletePatterns
145 | Opt_WarnIncompletePatternsRecUpd
146 | Opt_WarnMissingFields
147 | Opt_WarnMissingMethods
148 | Opt_WarnMissingSigs
149 | Opt_WarnNameShadowing
150 | Opt_WarnOverlappingPatterns
151 | Opt_WarnSimplePatterns
152 | Opt_WarnTypeDefaults
153 | Opt_WarnMonomorphism
154 | Opt_WarnUnusedBinds
155 | Opt_WarnUnusedImports
156 | Opt_WarnUnusedMatches
157 | Opt_WarnDeprecations
158 | Opt_WarnDodgyImports
163 | Opt_AllowOverlappingInstances
164 | Opt_AllowUndecidableInstances
165 | Opt_AllowIncoherentInstances
166 | Opt_MonomorphismRestriction
168 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
171 | Opt_PArr -- Syntactic support for parallel arrays
172 | Opt_Arrows -- Arrow-notation syntax
176 | Opt_ImplicitPrelude
177 | Opt_ScopedTypeVariables
180 | Opt_OverloadedStrings
181 | Opt_DisambiguateRecordFields
182 | Opt_RecordWildCards
185 | Opt_RelaxedPolyRec -- -X=RelaxedPolyRec
186 | Opt_TypeSynonymInstances
187 | Opt_FlexibleInstances
188 | Opt_MultiParamTypeClasses
189 | Opt_FunctionalDependencies
191 | Opt_PolymorphicComponents
192 | Opt_ExistentialQuantification
196 | Opt_ParallelListComp
197 | Opt_GeneralizedNewtypeDeriving
209 | Opt_IgnoreInterfacePragmas
210 | Opt_OmitInterfacePragmas
211 | Opt_DoLambdaEtaExpansion
213 | Opt_IgnoreBreakpoints
216 | Opt_UnboxStrictFields
227 | Opt_ExcessPrecision
228 | Opt_ReadUserPackageConf
232 | Opt_HideAllPackages
233 | Opt_PrintBindResult
236 | Opt_BreakOnException
247 data DynFlags = DynFlags {
250 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
251 stgToDo :: Maybe [StgToDo], -- similarly
252 hscTarget :: HscTarget,
253 hscOutName :: String, -- name of the output file
254 extCoreName :: String, -- name of the .core output file
255 verbosity :: Int, -- verbosity level
256 optLevel :: Int, -- optimisation level
257 maxSimplIterations :: Int, -- max simplifier iterations
258 ruleCheck :: Maybe String,
260 specThreshold :: Int, -- Threshold for function specialisation
262 stolen_x86_regs :: Int,
263 cmdlineHcIncludes :: [String], -- -#includes
264 importPaths :: [FilePath],
266 mainFunIs :: Maybe String,
267 ctxtStkDepth :: Int, -- Typechecker context stack depth
269 thisPackage :: PackageId,
272 wayNames :: [WayName], -- way flags from the cmd line
273 buildTag :: String, -- the global "way" (eg. "p" for prof)
274 rtsBuildTag :: String, -- the RTS "way"
277 objectDir :: Maybe String,
278 hiDir :: Maybe String,
279 stubDir :: Maybe String,
285 outputFile :: Maybe String,
286 outputHi :: Maybe String,
288 includePaths :: [String],
289 libraryPaths :: [String],
290 frameworkPaths :: [String], -- used on darwin only
291 cmdlineFrameworks :: [String], -- ditto
292 tmpDir :: String, -- no trailing '/'
294 ghcUsagePath :: FilePath, -- Filled in by SysTools
295 ghciUsagePath :: FilePath, -- ditto
297 hpcDir :: String, -- ^ path to store the .mix files
299 -- options for particular phases
310 -- commands for particular phases
312 pgm_P :: (String,[Option]),
314 pgm_c :: (String,[Option]),
315 pgm_m :: (String,[Option]),
316 pgm_s :: (String,[Option]),
317 pgm_a :: (String,[Option]),
318 pgm_l :: (String,[Option]),
319 pgm_dll :: (String,[Option]),
321 pgm_sysman :: String,
324 extraPkgConfs :: [FilePath],
325 topDir :: FilePath, -- filled in by SysTools
326 systemPackageConfig :: FilePath, -- ditto
327 -- The -package-conf flags given on the command line, in the order
330 packageFlags :: [PackageFlag],
331 -- The -package and -hide-package flags from the command-line
334 -- NB. do not modify this field, it is calculated by
335 -- Packages.initPackages and Packages.updatePackages.
336 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
337 pkgState :: PackageState,
343 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
354 -- | will this target result in an object file on the disk?
355 isObjectTarget :: HscTarget -> Bool
356 isObjectTarget HscC = True
357 isObjectTarget HscAsm = True
358 isObjectTarget _ = False
360 -- | The 'GhcMode' tells us whether we're doing multi-module
361 -- compilation (controlled via the "GHC" API) or one-shot
362 -- (single-module) compilation. This makes a difference primarily to
363 -- the "Finder": in one-shot mode we look for interface files for
364 -- imported modules, but in multi-module mode we look for source files
365 -- in order to check whether they need to be recompiled.
367 = CompManager -- ^ --make, GHCi, etc.
368 | OneShot -- ^ ghc -c Foo.hs
369 | MkDepend -- ^ ghc -M, see Finder for why we need this
372 isOneShot :: GhcMode -> Bool
373 isOneShot OneShot = True
374 isOneShot _other = False
376 -- | What kind of linking to do.
377 data GhcLink -- What to do in the link step, if there is one
378 = NoLink -- Don't link at all
379 | LinkBinary -- Link object code into a binary
380 | LinkInMemory -- Use the in-memory dynamic linker
381 | LinkDynLib -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
384 isNoLink :: GhcLink -> Bool
385 isNoLink NoLink = True
386 isNoLink other = False
389 = ExposePackage String
391 | IgnorePackage String
394 defaultHscTarget = defaultObjectTarget
396 -- | the 'HscTarget' value corresponding to the default way to create
397 -- object files on the current platform.
399 | cGhcWithNativeCodeGen == "YES" = HscAsm
402 initDynFlags dflags = do
403 -- someday these will be dynamic flags
404 ways <- readIORef v_Ways
405 build_tag <- readIORef v_Build_tag
406 rts_build_tag <- readIORef v_RTS_Build_tag
409 buildTag = build_tag,
410 rtsBuildTag = rts_build_tag
415 ghcMode = CompManager,
416 ghcLink = LinkBinary,
419 hscTarget = defaultHscTarget,
424 maxSimplIterations = 4,
428 cmdlineHcIncludes = [],
432 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
434 thisPackage = mainPackageId,
440 objectSuf = phaseInputExt StopLn,
441 hcSuf = phaseInputExt HCc,
444 outputFile = Nothing,
449 cmdlineFrameworks = [],
450 tmpDir = cDEFAULT_TMPDIR,
466 pkgDatabase = Nothing,
467 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
469 Opt_ReadUserPackageConf,
471 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
472 -- behaviour the default, to see if anyone notices
476 Opt_MonomorphismRestriction,
481 Opt_PrintBindResult ]
482 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
483 -- The default -O0 options
486 log_action = \severity srcSpan style msg ->
488 SevInfo -> hPutStrLn stderr (show (msg style))
489 SevFatal -> hPutStrLn stderr (show (msg style))
490 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
496 0 | print errors & warnings only
497 1 | minimal verbosity: print "compiling M ... done." for each module.
498 2 | equivalent to -dshow-passes
499 3 | equivalent to existing "ghc -v"
500 4 | "ghc -v -ddump-most"
501 5 | "ghc -v -ddump-all"
504 dopt :: DynFlag -> DynFlags -> Bool
505 dopt f dflags = f `elem` (flags dflags)
507 dopt_set :: DynFlags -> DynFlag -> DynFlags
508 dopt_set dfs f = dfs{ flags = f : flags dfs }
510 dopt_unset :: DynFlags -> DynFlag -> DynFlags
511 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
513 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
514 getOpts dflags opts = reverse (opts dflags)
515 -- We add to the options from the front, so we need to reverse the list
517 getVerbFlag :: DynFlags -> String
519 | verbosity dflags >= 3 = "-v"
522 setObjectDir f d = d{ objectDir = f}
523 setHiDir f d = d{ hiDir = f}
524 setStubDir f d = d{ stubDir = f}
526 setObjectSuf f d = d{ objectSuf = f}
527 setHiSuf f d = d{ hiSuf = f}
528 setHcSuf f d = d{ hcSuf = f}
530 setOutputFile f d = d{ outputFile = f}
531 setOutputHi f d = d{ outputHi = f}
533 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
534 -- Config.hs should really use Option.
535 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
537 setPgmL f d = d{ pgm_L = f}
538 setPgmF f d = d{ pgm_F = f}
539 setPgmc f d = d{ pgm_c = (f,[])}
540 setPgmm f d = d{ pgm_m = (f,[])}
541 setPgms f d = d{ pgm_s = (f,[])}
542 setPgma f d = d{ pgm_a = (f,[])}
543 setPgml f d = d{ pgm_l = (f,[])}
544 setPgmdll f d = d{ pgm_dll = (f,[])}
546 addOptL f d = d{ opt_L = f : opt_L d}
547 addOptP f d = d{ opt_P = f : opt_P d}
548 addOptF f d = d{ opt_F = f : opt_F d}
549 addOptc f d = d{ opt_c = f : opt_c d}
550 addOptm f d = d{ opt_m = f : opt_m d}
551 addOpta f d = d{ opt_a = f : opt_a d}
552 addOptl f d = d{ opt_l = f : opt_l d}
553 addOptdll f d = d{ opt_dll = f : opt_dll d}
554 addOptdep f d = d{ opt_dep = f : opt_dep d}
556 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
558 -- -----------------------------------------------------------------------------
559 -- Command-line options
561 -- When invoking external tools as part of the compilation pipeline, we
562 -- pass these a sequence of options on the command-line. Rather than
563 -- just using a list of Strings, we use a type that allows us to distinguish
564 -- between filepaths and 'other stuff'. [The reason being, of course, that
565 -- this type gives us a handle on transforming filenames, and filenames only,
566 -- to whatever format they're expected to be on a particular platform.]
569 = FileOption -- an entry that _contains_ filename(s) / filepaths.
570 String -- a non-filepath prefix that shouldn't be
571 -- transformed (e.g., "/out=")
572 String -- the filepath/filename portion
575 -----------------------------------------------------------------------------
576 -- Setting the optimisation level
578 updOptLevel :: Int -> DynFlags -> DynFlags
579 -- Set dynflags appropriate to the optimisation level
581 = dfs2{ optLevel = final_n }
583 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
584 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
585 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
587 extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
588 remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
590 optLevelFlags :: [([Int], DynFlag)]
592 = [ ([0], Opt_IgnoreInterfacePragmas)
593 , ([0], Opt_OmitInterfacePragmas)
595 , ([1,2], Opt_IgnoreAsserts)
596 , ([1,2], Opt_RewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
598 , ([1,2], Opt_DoEtaReduction)
599 , ([1,2], Opt_CaseMerge)
600 , ([1,2], Opt_Strictness)
602 , ([1,2], Opt_FullLaziness)
604 , ([2], Opt_LiberateCase)
605 , ([2], Opt_SpecConstr)
607 , ([0,1,2], Opt_DoLambdaEtaExpansion)
608 -- This one is important for a tiresome reason:
609 -- we want to make sure that the bindings for data
610 -- constructors are eta-expanded. This is probably
611 -- a good thing anyway, but it seems fragile.
614 -- -----------------------------------------------------------------------------
615 -- Standard sets of warning options
618 = [ Opt_WarnDeprecations,
619 Opt_WarnOverlappingPatterns,
620 Opt_WarnMissingFields,
621 Opt_WarnMissingMethods,
622 Opt_WarnDuplicateExports
626 = standardWarnings ++
627 [ Opt_WarnUnusedBinds,
628 Opt_WarnUnusedMatches,
629 Opt_WarnUnusedImports,
630 Opt_WarnIncompletePatterns,
636 [ Opt_WarnTypeDefaults,
637 Opt_WarnNameShadowing,
643 -- -----------------------------------------------------------------------------
644 -- CoreToDo: abstraction of core-to-core passes to run.
646 data CoreToDo -- These are diff core-to-core passes,
647 -- which may be invoked in any order,
648 -- as many times as you like.
650 = CoreDoSimplify -- The core-to-core simplifier.
653 -- Each run of the simplifier can take a different
654 -- set of simplifier-specific flags.
656 | CoreDoFloatOutwards FloatOutSwitches
661 | CoreDoWorkerWrapper
664 | CoreDoOldStrictness
667 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
668 -- matching this string
669 | CoreDoNothing -- Useful when building up
670 | CoreDoPasses [CoreToDo] -- lists of these things
672 data SimplifierMode -- See comments in SimplMonad
676 data SimplifierSwitch
677 = MaxSimplifierIterations Int
680 data FloatOutSwitches
681 = FloatOutSw Bool -- True <=> float lambdas to top level
682 Bool -- True <=> float constants to top level,
683 -- even if they do not escape a lambda
686 -- The core-to-core pass ordering is derived from the DynFlags:
687 runWhen :: Bool -> CoreToDo -> CoreToDo
688 runWhen True do_this = do_this
689 runWhen False do_this = CoreDoNothing
691 getCoreToDo :: DynFlags -> [CoreToDo]
693 | Just todo <- coreToDo dflags = todo -- set explicitly by user
694 | otherwise = core_todo
696 opt_level = optLevel dflags
697 max_iter = maxSimplIterations dflags
698 strictness = dopt Opt_Strictness dflags
699 full_laziness = dopt Opt_FullLaziness dflags
700 cse = dopt Opt_CSE dflags
701 spec_constr = dopt Opt_SpecConstr dflags
702 liberate_case = dopt Opt_LiberateCase dflags
703 rule_check = ruleCheck dflags
706 if opt_level == 0 then
708 CoreDoSimplify (SimplPhase 0) [
709 MaxSimplifierIterations max_iter
712 else {- opt_level >= 1 -} [
714 -- initial simplify: mk specialiser happy: minimum effort please
715 CoreDoSimplify SimplGently [
717 -- Don't inline anything till full laziness has bitten
718 -- In particular, inlining wrappers inhibits floating
719 -- e.g. ...(case f x of ...)...
720 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
721 -- ==> ...(case x of I# x# -> case fw x# of ...)...
722 -- and now the redex (f x) isn't floatable any more
723 -- Similarly, don't apply any rules until after full
724 -- laziness. Notably, list fusion can prevent floating.
726 NoCaseOfCase, -- Don't do case-of-case transformations.
727 -- This makes full laziness work better
728 MaxSimplifierIterations max_iter
731 -- Specialisation is best done before full laziness
732 -- so that overloaded functions have all their dictionary lambdas manifest
735 runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
739 CoreDoSimplify (SimplPhase 2) [
740 -- Want to run with inline phase 2 after the specialiser to give
741 -- maximum chance for fusion to work before we inline build/augment
742 -- in phase 1. This made a difference in 'ansi' where an
743 -- overloaded function wasn't inlined till too late.
744 MaxSimplifierIterations max_iter
746 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
748 CoreDoSimplify (SimplPhase 1) [
749 -- Need inline-phase2 here so that build/augment get
750 -- inlined. I found that spectral/hartel/genfft lost some useful
751 -- strictness in the function sumcode' if augment is not inlined
752 -- before strictness analysis runs
753 MaxSimplifierIterations max_iter
755 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
757 CoreDoSimplify (SimplPhase 0) [
758 -- Phase 0: allow all Ids to be inlined now
759 -- This gets foldr inlined before strictness analysis
761 MaxSimplifierIterations 3
762 -- At least 3 iterations because otherwise we land up with
763 -- huge dead expressions because of an infelicity in the
765 -- let k = BIG in foldr k z xs
766 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
767 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
771 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
773 #ifdef OLD_STRICTNESS
776 runWhen strictness (CoreDoPasses [
780 CoreDoSimplify (SimplPhase 0) [
781 MaxSimplifierIterations max_iter
784 runWhen full_laziness
785 (CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
786 True)), -- Float constants
787 -- nofib/spectral/hartel/wang doubles in speed if you
788 -- do full laziness late in the day. It only happens
789 -- after fusion and other stuff, so the early pass doesn't
790 -- catch it. For the record, the redex is
791 -- f_el22 (f_el21 r_midblock)
795 -- We want CSE to follow the final full-laziness pass, because it may
796 -- succeed in commoning up things floated out by full laziness.
797 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
801 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
803 -- Case-liberation for -O2. This should be after
804 -- strictness analysis and the simplification which follows it.
805 runWhen liberate_case (CoreDoPasses [
807 CoreDoSimplify (SimplPhase 0) [
808 MaxSimplifierIterations max_iter
809 ] ]), -- Run the simplifier after LiberateCase to vastly
810 -- reduce the possiblility of shadowing
811 -- Reason: see Note [Shadowing] in SpecConstr.lhs
813 runWhen spec_constr CoreDoSpecConstr,
815 -- Final clean-up simplification:
816 CoreDoSimplify (SimplPhase 0) [
817 MaxSimplifierIterations max_iter
821 -- -----------------------------------------------------------------------------
822 -- StgToDo: abstraction of stg-to-stg passes to run.
825 = StgDoMassageForProfiling -- should be (next to) last
826 -- There's also setStgVarInfo, but its absolute "lastness"
827 -- is so critical that it is hardwired in (no flag).
830 getStgToDo :: DynFlags -> [StgToDo]
832 | Just todo <- stgToDo dflags = todo -- set explicitly by user
835 stg_stats = dopt Opt_StgStats dflags
837 todo1 = if stg_stats then [D_stg_stats] else []
839 todo2 | WayProf `elem` wayNames dflags
840 = StgDoMassageForProfiling : todo1
844 -- -----------------------------------------------------------------------------
848 allFlags = map ('-':) $
849 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
850 map ("fno-"++) flags ++
852 where ok (PrefixPred _ _) = False
854 flags = map fst fFlags
856 dynamic_flags :: [(String, OptKind DynP)]
858 ( "n" , NoArg (setDynFlag Opt_DryRun) )
859 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
860 , ( "F" , NoArg (setDynFlag Opt_Pp))
861 , ( "#include" , HasArg (addCmdlineHCInclude) )
862 , ( "v" , OptIntSuffix setVerbosity )
864 ------- Specific phases --------------------------------------------
865 , ( "pgmL" , HasArg (upd . setPgmL) )
866 , ( "pgmP" , HasArg (upd . setPgmP) )
867 , ( "pgmF" , HasArg (upd . setPgmF) )
868 , ( "pgmc" , HasArg (upd . setPgmc) )
869 , ( "pgmm" , HasArg (upd . setPgmm) )
870 , ( "pgms" , HasArg (upd . setPgms) )
871 , ( "pgma" , HasArg (upd . setPgma) )
872 , ( "pgml" , HasArg (upd . setPgml) )
873 , ( "pgmdll" , HasArg (upd . setPgmdll) )
875 , ( "optL" , HasArg (upd . addOptL) )
876 , ( "optP" , HasArg (upd . addOptP) )
877 , ( "optF" , HasArg (upd . addOptF) )
878 , ( "optc" , HasArg (upd . addOptc) )
879 , ( "optm" , HasArg (upd . addOptm) )
880 , ( "opta" , HasArg (upd . addOpta) )
881 , ( "optl" , HasArg (upd . addOptl) )
882 , ( "optdll" , HasArg (upd . addOptdll) )
883 , ( "optdep" , HasArg (upd . addOptdep) )
885 , ( "split-objs" , NoArg (if can_split
886 then setDynFlag Opt_SplitObjs
889 -------- Linking ----------------------------------------------------
890 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
891 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
892 , ( "shared" , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
894 ------- Libraries ---------------------------------------------------
895 , ( "L" , Prefix addLibraryPath )
896 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
899 ------- Frameworks --------------------------------------------------
900 -- -framework-path should really be -F ...
901 , ( "framework-path" , HasArg addFrameworkPath )
902 , ( "framework" , HasArg (upd . addCmdlineFramework) )
904 ------- Output Redirection ------------------------------------------
905 , ( "odir" , HasArg (upd . setObjectDir . Just))
906 , ( "o" , SepArg (upd . setOutputFile . Just))
907 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
908 , ( "osuf" , HasArg (upd . setObjectSuf))
909 , ( "hcsuf" , HasArg (upd . setHcSuf))
910 , ( "hisuf" , HasArg (upd . setHiSuf))
911 , ( "hidir" , HasArg (upd . setHiDir . Just))
912 , ( "tmpdir" , HasArg (upd . setTmpDir))
913 , ( "stubdir" , HasArg (upd . setStubDir . Just))
915 ------- Keeping temporary files -------------------------------------
916 -- These can be singular (think ghc -c) or plural (think ghc --make)
917 , ( "keep-hc-file" , NoArg (setDynFlag Opt_KeepHcFiles))
918 , ( "keep-hc-files" , NoArg (setDynFlag Opt_KeepHcFiles))
919 , ( "keep-s-file" , NoArg (setDynFlag Opt_KeepSFiles))
920 , ( "keep-s-files" , NoArg (setDynFlag Opt_KeepSFiles))
921 , ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
922 , ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
923 -- This only makes sense as plural
924 , ( "keep-tmp-files" , NoArg (setDynFlag Opt_KeepTmpFiles))
926 ------- Miscellaneous ----------------------------------------------
927 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
928 , ( "main-is" , SepArg setMainIs )
929 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
930 , ( "hpcdir" , SepArg setOptHpcDir )
932 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
933 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
934 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
936 ------- Packages ----------------------------------------------------
937 , ( "package-conf" , HasArg extraPkgConf_ )
938 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
939 , ( "package-name" , HasArg (upd . setPackageName) )
940 , ( "package" , HasArg exposePackage )
941 , ( "hide-package" , HasArg hidePackage )
942 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
943 , ( "ignore-package" , HasArg ignorePackage )
944 , ( "syslib" , HasArg exposePackage ) -- for compatibility
946 ------ HsCpp opts ---------------------------------------------------
947 , ( "D", AnySuffix (upd . addOptP) )
948 , ( "U", AnySuffix (upd . addOptP) )
950 ------- Include/Import Paths ----------------------------------------
951 , ( "I" , Prefix addIncludePath)
952 , ( "i" , OptPrefix addImportPath )
954 ------ Debugging ----------------------------------------------------
955 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
957 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
958 , ( "ddump-cps-cmm", setDumpFlag Opt_D_dump_cps_cmm)
959 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
960 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
961 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
962 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
963 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
964 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
965 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
966 , ( "ddump-rule-firings", setDumpFlag Opt_D_dump_rule_firings)
967 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
968 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
969 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
970 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
971 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
972 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
973 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
974 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
975 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
976 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
977 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
978 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
979 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
980 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
981 , ( "ddump-rn-trace", setDumpFlag Opt_D_dump_rn_trace)
982 , ( "ddump-if-trace", setDumpFlag Opt_D_dump_if_trace)
983 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
984 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
985 , ( "ddump-rn-stats", setDumpFlag Opt_D_dump_rn_stats)
986 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
987 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
988 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
989 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
990 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
991 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
992 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
993 , ( "ddump-minimal-imports", setDumpFlag Opt_D_dump_minimal_imports)
994 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
995 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
996 , ( "ddump-mod-cycles", setDumpFlag Opt_D_dump_mod_cycles)
998 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
999 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
1000 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
1001 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
1002 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
1003 setVerbosity (Just 2)) )
1004 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
1006 ------ Machine dependant (-m<blah>) stuff ---------------------------
1008 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
1009 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
1010 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
1012 ------ Warning opts -------------------------------------------------
1013 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
1014 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
1015 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
1016 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
1017 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
1019 ------ Optimisation flags ------------------------------------------
1020 , ( "O" , NoArg (upd (setOptLevel 1)))
1021 , ( "Onot" , NoArg (upd (setOptLevel 0)))
1022 , ( "O" , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1023 -- If the number is missing, use 1
1025 , ( "fmax-simplifier-iterations", IntSuffix (\n ->
1026 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1028 -- liberate-case-threshold is an old flag for '-fspec-threshold'
1029 , ( "fspec-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1030 , ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1032 , ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1033 , ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1035 ------ Compiler flags -----------------------------------------------
1037 , ( "fasm", NoArg (setObjTarget HscAsm) )
1038 , ( "fvia-c", NoArg (setObjTarget HscC) )
1039 , ( "fvia-C", NoArg (setObjTarget HscC) )
1041 , ( "fno-code", NoArg (setTarget HscNothing))
1042 , ( "fbyte-code", NoArg (setTarget HscInterpreted) )
1043 , ( "fobject-code", NoArg (setTarget defaultHscTarget) )
1045 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
1046 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1048 -- the rest of the -f* and -fno-* flags
1049 , ( "f", PrefixPred (isFlag fFlags) (\f -> setDynFlag (getFlag fFlags f)) )
1050 , ( "f", PrefixPred (isNoFlag fFlags) (\f -> unSetDynFlag (getNoFlag fFlags f)) )
1052 -- For now, allow -X flags with -f; ToDo: report this as deprecated
1053 , ( "f", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1054 , ( "f", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1056 -- the rest of the -X* and -Xno-* flags
1057 , ( "X", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1058 , ( "X", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1061 -- these -f<blah> flags can all be reversed with -fno-<blah>
1064 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1065 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1066 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude ),
1067 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1068 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1069 ( "warn-missing-fields", Opt_WarnMissingFields ),
1070 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1071 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1072 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1073 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1074 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1075 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1076 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism ),
1077 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1078 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1079 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1080 ( "warn-deprecations", Opt_WarnDeprecations ),
1081 ( "warn-orphans", Opt_WarnOrphans ),
1082 ( "warn-tabs", Opt_WarnTabs ),
1083 ( "strictness", Opt_Strictness ),
1084 ( "full-laziness", Opt_FullLaziness ),
1085 ( "liberate-case", Opt_LiberateCase ),
1086 ( "spec-constr", Opt_SpecConstr ),
1088 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1089 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1090 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1091 ( "ignore-asserts", Opt_IgnoreAsserts ),
1092 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1093 ( "do-eta-reduction", Opt_DoEtaReduction ),
1094 ( "case-merge", Opt_CaseMerge ),
1095 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1096 ( "dicts-cheap", Opt_DictsCheap ),
1097 ( "excess-precision", Opt_ExcessPrecision ),
1098 ( "asm-mangling", Opt_DoAsmMangling ),
1099 ( "print-bind-result", Opt_PrintBindResult ),
1100 ( "force-recomp", Opt_ForceRecomp ),
1101 ( "hpc-no-auto", Opt_Hpc_No_Auto ),
1102 ( "rewrite-rules", Opt_RewriteRules ),
1103 ( "break-on-exception", Opt_BreakOnException ),
1104 ( "vectorise", Opt_Vectorise )
1108 -- These -X<blah> flags can all be reversed with -Xno-<blah>
1109 xFlags :: [(String, DynFlag)]
1112 ( "PatternGuards", Opt_PatternGuards ),
1113 ( "UnicodeSyntax", Opt_UnicodeSyntax ),
1114 ( "MagicHash", Opt_MagicHash ),
1115 ( "PolymorphicComponents", Opt_PolymorphicComponents ),
1116 ( "ExistentialQuantification", Opt_ExistentialQuantification ),
1117 ( "KindSignatures", Opt_KindSignatures ),
1118 ( "EmptyDataDecls", Opt_EmptyDataDecls ),
1119 ( "ParallelListComp", Opt_ParallelListComp ),
1120 ( "FI", Opt_FFI ), -- support `-ffi'...
1121 ( "FFI", Opt_FFI ), -- ...and also `-fffi'
1122 ( "ForeignFunctionInterface", Opt_FFI ),
1124 ( "Rank2Types", Opt_Rank2Types ),
1125 ( "RankNTypes", Opt_RankNTypes ),
1126 ( "RecursiveDo", Opt_RecursiveDo ),
1127 ( "Arrows", Opt_Arrows ), -- arrow syntax
1128 ( "Parr", Opt_PArr ),
1130 ( "TH", Opt_TH ), -- support -fth
1131 ( "TemplateHaskelll", Opt_TH ),
1133 ( "Generics", Opt_Generics ),
1135 ( "ImplicitPrelude", Opt_ImplicitPrelude ), -- On by default
1137 ( "RecordWildCards", Opt_RecordWildCards ),
1138 ( "RecordPuns", Opt_RecordPuns ),
1139 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields ),
1141 ( "OverloadedStrings", Opt_OverloadedStrings ),
1142 ( "GADTs", Opt_GADTs ),
1143 ( "TypeFamilies", Opt_TypeFamilies ),
1144 ( "BangPatterns", Opt_BangPatterns ),
1145 ( "MonomorphismRestriction", Opt_MonomorphismRestriction ), -- On by default
1146 ( "MonoPatBinds", Opt_MonoPatBinds ), -- On by default (which is not strictly H98)
1147 ( "RelaxedPolyRec", Opt_RelaxedPolyRec),
1148 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules ),
1149 ( "ImplicitParams", Opt_ImplicitParams ),
1150 ( "ScopedTypeVariables", Opt_ScopedTypeVariables ),
1151 ( "TypeSynonymInstances", Opt_TypeSynonymInstances ),
1152 ( "FlexibleInstances", Opt_FlexibleInstances ),
1153 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses ),
1154 ( "FunctionalDependencies", Opt_FunctionalDependencies ),
1155 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving ),
1156 ( "AllowOverlappingInstances", Opt_AllowOverlappingInstances ),
1157 ( "AllowUndecidableInstances", Opt_AllowUndecidableInstances ),
1158 ( "AllowIncoherentInstances", Opt_AllowIncoherentInstances )
1161 impliedFlags :: [(DynFlag, [DynFlag])]
1163 ( Opt_GADTs, [Opt_RelaxedPolyRec] ) -- We want type-sig variables to be completely rigid for GADTs
1166 glasgowExtsFlags = [ Opt_GlasgowExts
1169 , Opt_ImplicitParams
1170 , Opt_ScopedTypeVariables
1171 , Opt_TypeSynonymInstances
1172 , Opt_FlexibleInstances
1173 , Opt_MultiParamTypeClasses
1174 , Opt_FunctionalDependencies
1176 , Opt_PolymorphicComponents
1177 , Opt_ExistentialQuantification
1182 , Opt_ParallelListComp
1183 , Opt_EmptyDataDecls
1184 , Opt_KindSignatures
1185 , Opt_GeneralizedNewtypeDeriving
1186 , Opt_TypeFamilies ]
1189 isNoFlag, isFlag :: [(String,a)] -> String -> Bool
1191 isFlag flags f = is_flag flags (normaliseFlag f)
1194 | Just f <- noFlag_maybe (normaliseFlag no_f) = is_flag flags f
1197 is_flag flags nf = any (\(ff,_) -> normaliseFlag ff == nf) flags
1198 -- nf is normalised alreadly
1201 getFlag, getNoFlag :: [(String,a)] -> String -> a
1203 getFlag flags f = get_flag flags (normaliseFlag f)
1205 getNoFlag flags f = get_flag flags (fromJust (noFlag_maybe (normaliseFlag f)))
1206 -- The flag should be a no-flag already
1208 get_flag flags nf = case [ opt | (ff, opt) <- flags, normaliseFlag ff == nf] of
1210 [] -> panic ("get_flag " ++ nf)
1213 noFlag_maybe :: String -> Maybe String
1214 -- The input is normalised already
1215 noFlag_maybe ('n' : 'o' : f) = Just f
1216 noFlag_maybe other = Nothing
1218 normaliseFlag :: String -> String
1219 -- Normalise a option flag by
1220 -- * map to lower case
1221 -- * removing hyphens
1222 -- Thus: -X=overloaded-strings or -XOverloadedStrings
1223 normaliseFlag [] = []
1224 normaliseFlag ('-':s) = normaliseFlag s
1225 normaliseFlag (c:s) = toLower c : normaliseFlag s
1227 -- -----------------------------------------------------------------------------
1228 -- Parsing the dynamic flags.
1230 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1231 parseDynamicFlags dflags args = do
1232 let ((leftover,errs),dflags')
1233 = runCmdLine (processArgs dynamic_flags args) dflags
1234 when (not (null errs)) $ do
1235 throwDyn (UsageError (unlines errs))
1236 return (dflags', leftover)
1239 type DynP = CmdLineP DynFlags
1241 upd :: (DynFlags -> DynFlags) -> DynP ()
1243 dfs <- getCmdLineState
1244 putCmdLineState $! (f dfs)
1246 --------------------------
1247 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1248 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1250 deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1251 -- When you set f, set the ones it implies
1252 -- When you un-set f, however, we don't un-set the things it implies
1253 -- (except for -fno-glasgow-exts, which is treated specially)
1255 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1257 --------------------------
1258 setDumpFlag :: DynFlag -> OptKind DynP
1259 setDumpFlag dump_flag
1260 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1261 -- Whenver we -ddump, switch off the recompilation checker,
1262 -- else you don't see the dump!
1264 setVerbosity :: Maybe Int -> DynP ()
1265 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1267 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1269 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1272 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1274 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1276 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1279 | Nothing <- unpackPackageId pid
1280 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1282 = \s -> s{ thisPackage = pid }
1284 pid = stringToPackageId p
1286 -- If we're linking a binary, then only targets that produce object
1287 -- code are allowed (requests for other target types are ignored).
1288 setTarget l = upd set
1291 | ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
1294 -- Changes the target only if we're compiling object code. This is
1295 -- used by -fasm and -fvia-C, which switch from one to the other, but
1296 -- not from bytecode to object-code. The idea is that -fasm/-fvia-C
1297 -- can be safely used in an OPTIONS_GHC pragma.
1298 setObjTarget l = upd set
1301 | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1304 setOptLevel :: Int -> DynFlags -> DynFlags
1305 setOptLevel n dflags
1306 | hscTarget dflags == HscInterpreted && n > 0
1308 -- not in IO any more, oh well:
1309 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1311 = updOptLevel n dflags
1314 setMainIs :: String -> DynP ()
1316 | not (null main_fn) -- The arg looked like "Foo.baz"
1317 = upd $ \d -> d{ mainFunIs = Just main_fn,
1318 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1320 | isUpper (head main_mod) -- The arg looked like "Foo"
1321 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1323 | otherwise -- The arg looked like "baz"
1324 = upd $ \d -> d{ mainFunIs = Just main_mod }
1326 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1328 -----------------------------------------------------------------------------
1329 -- Paths & Libraries
1331 -- -i on its own deletes the import paths
1332 addImportPath "" = upd (\s -> s{importPaths = []})
1333 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1337 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1340 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1342 addFrameworkPath p =
1343 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1345 split_marker = ':' -- not configurable (ToDo)
1347 splitPathList :: String -> [String]
1348 splitPathList s = filter notNull (splitUp s)
1349 -- empty paths are ignored: there might be a trailing
1350 -- ':' in the initial list, for example. Empty paths can
1351 -- cause confusion when they are translated into -I options
1352 -- for passing to gcc.
1354 #ifndef mingw32_TARGET_OS
1355 splitUp xs = split split_marker xs
1357 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1359 -- That is, if "foo:bar:baz" is used, this interpreted as
1360 -- consisting of three entries, 'foo', 'bar', 'baz'.
1361 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1362 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1364 -- Notice that no attempt is made to fully replace the 'standard'
1365 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1366 -- that this will cause too much breakage for users & ':' will
1367 -- work fine even with DOS paths, if you're not insisting on being silly.
1370 splitUp (x:':':div:xs) | div `elem` dir_markers
1371 = ((x:':':div:p): splitUp rs)
1373 (p,rs) = findNextPath xs
1374 -- we used to check for existence of the path here, but that
1375 -- required the IO monad to be threaded through the command-line
1376 -- parser which is quite inconvenient. The
1377 splitUp xs = cons p (splitUp rs)
1379 (p,rs) = findNextPath xs
1384 -- will be called either when we've consumed nought or the
1385 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1386 -- finding the next split marker.
1388 case break (`elem` split_markers) xs of
1389 (p, d:ds) -> (p, ds)
1392 split_markers :: [Char]
1393 split_markers = [':', ';']
1395 dir_markers :: [Char]
1396 dir_markers = ['/', '\\']
1399 -- -----------------------------------------------------------------------------
1400 -- tmpDir, where we store temporary files.
1402 setTmpDir :: FilePath -> DynFlags -> DynFlags
1403 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1405 #if !defined(mingw32_HOST_OS)
1406 canonicalise p = normalisePath p
1408 -- Canonicalisation of temp path under win32 is a bit more
1409 -- involved: (a) strip trailing slash,
1410 -- (b) normalise slashes
1411 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1413 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1415 -- if we're operating under cygwin, and TMP/TEMP is of
1416 -- the form "/cygdrive/drive/path", translate this to
1417 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1418 -- understand /cygdrive paths.)
1420 | "/cygdrive/" `isPrefixOf` path =
1421 case drop (length "/cygdrive/") path of
1422 drive:xs@('/':_) -> drive:':':xs
1426 -- strip the trailing backslash (awful, but we only do this once).
1427 removeTrailingSlash path =
1434 -----------------------------------------------------------------------------
1437 setOptHpcDir :: String -> DynP ()
1438 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1440 -----------------------------------------------------------------------------
1441 -- Via-C compilation stuff
1443 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1444 [String]) -- for registerised HC compilations
1445 machdepCCOpts dflags
1446 #if alpha_TARGET_ARCH
1448 #ifdef HAVE_THREADED_RTS_SUPPORT
1452 -- For now, to suppress the gcc warning "call-clobbered
1453 -- register used for global register variable", we simply
1454 -- disable all warnings altogether using the -w flag. Oh well.
1456 #elif hppa_TARGET_ARCH
1457 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1458 -- (very nice, but too bad the HP /usr/include files don't agree.)
1459 = ( ["-D_HPUX_SOURCE"], [] )
1461 #elif m68k_TARGET_ARCH
1462 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1463 -- popping of args to routines to be explicit; if we let things
1464 -- be deferred 'til after an STGJUMP, imminent death is certain!
1466 -- -fomit-frame-pointer : *don't*
1467 -- It's better to have a6 completely tied up being a frame pointer
1468 -- rather than let GCC pick random things to do with it.
1469 -- (If we want to steal a6, then we would try to do things
1470 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1471 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1473 #elif i386_TARGET_ARCH
1474 -- -fno-defer-pop : basically the same game as for m68k
1476 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1477 -- the fp (%ebp) for our register maps.
1478 = let n_regs = stolen_x86_regs dflags
1481 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1482 -- , if "mingw32" `isSuffixOf` cTARGETPLATFORM then "-mno-cygwin" else ""
1485 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1486 -- Some gccs are configured with
1487 -- -momit-leaf-frame-pointer on by default, and it
1488 -- apparently takes precedence over
1489 -- -fomit-frame-pointer, so we disable it first here.
1490 "-mno-omit-leaf-frame-pointer",
1492 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1493 "-fno-unit-at-a-time",
1494 -- unit-at-a-time doesn't do us any good, and screws
1495 -- up -split-objs by moving the split markers around.
1496 -- It's only turned on with -O2, but put it here just
1497 -- in case someone uses -optc-O2.
1499 "-fomit-frame-pointer",
1500 -- we want -fno-builtin, because when gcc inlines
1501 -- built-in functions like memcpy() it tends to
1502 -- run out of registers, requiring -monly-n-regs
1504 "-DSTOLEN_X86_REGS="++show n_regs ]
1507 #elif ia64_TARGET_ARCH
1508 = ( [], ["-fomit-frame-pointer", "-G0"] )
1510 #elif x86_64_TARGET_ARCH
1511 = ( [], ["-fomit-frame-pointer",
1512 "-fno-asynchronous-unwind-tables",
1513 -- the unwind tables are unnecessary for HC code,
1514 -- and get in the way of -split-objs. Another option
1515 -- would be to throw them away in the mangler, but this
1517 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1518 "-fno-unit-at-a-time",
1519 -- unit-at-a-time doesn't do us any good, and screws
1520 -- up -split-objs by moving the split markers around.
1521 -- It's only turned on with -O2, but put it here just
1522 -- in case someone uses -optc-O2.
1525 -- calling builtins like strlen() using the FFI can
1526 -- cause gcc to run out of regs, so use the external
1530 #elif sparc_TARGET_ARCH
1532 -- For now, to suppress the gcc warning "call-clobbered
1533 -- register used for global register variable", we simply
1534 -- disable all warnings altogether using the -w flag. Oh well.
1536 #elif powerpc_apple_darwin_TARGET
1538 -- Disable Apple's precompiling preprocessor. It's a great thing
1539 -- for "normal" programs, but it doesn't support register variable
1541 = ( [], ["-no-cpp-precomp"] )
1546 picCCOpts :: DynFlags -> [String]
1548 #if darwin_TARGET_OS
1549 -- Apple prefers to do things the other way round.
1550 -- PIC is on by default.
1551 -- -mdynamic-no-pic:
1552 -- Turn off PIC code generation.
1554 -- Don't generate "common" symbols - these are unwanted
1555 -- in dynamic libraries.
1560 = ["-mdynamic-no-pic"]
1561 #elif mingw32_TARGET_OS
1562 -- no -fPIC for Windows
1571 -- -----------------------------------------------------------------------------
1576 #if defined(i386_TARGET_ARCH) \
1577 || defined(x86_64_TARGET_ARCH) \
1578 || defined(alpha_TARGET_ARCH) \
1579 || defined(hppa_TARGET_ARCH) \
1580 || defined(m68k_TARGET_ARCH) \
1581 || defined(mips_TARGET_ARCH) \
1582 || defined(powerpc_TARGET_ARCH) \
1583 || defined(rs6000_TARGET_ARCH) \
1584 || defined(sparc_TARGET_ARCH)