64ec8be612b837641e48d7dcbd38651687864403
[ghc.git] / compiler / main / DynFlags.hs
1 -------------------------------------------------------------------------------
2 --
3 -- | Dynamic flags
4 --
5 -- Most flags are dynamic flags, which means they can change from compilation
6 -- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each
7 -- session can be using different dynamic flags. Dynamic flags can also be set
8 -- at the prompt in GHCi.
9 --
10 -- (c) The University of Glasgow 2005
11 --
12 -------------------------------------------------------------------------------
13
14 {-# OPTIONS -fno-cse #-}
15 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
16
17 module DynFlags (
18 -- * Dynamic flags and associated configuration types
19 DumpFlag(..),
20 GeneralFlag(..),
21 WarningFlag(..),
22 ExtensionFlag(..),
23 Language(..),
24 PlatformConstants(..),
25 FatalMessager, LogAction, FlushOut(..), FlushErr(..),
26 ProfAuto(..),
27 glasgowExtsFlags,
28 dopt, dopt_set, dopt_unset,
29 gopt, gopt_set, gopt_unset,
30 wopt, wopt_set, wopt_unset,
31 xopt, xopt_set, xopt_unset,
32 lang_set,
33 whenGeneratingDynamicToo, ifGeneratingDynamicToo,
34 whenCannotGenerateDynamicToo,
35 dynamicTooMkDynamicDynFlags,
36 DynFlags(..),
37 HasDynFlags(..), ContainsDynFlags(..),
38 RtsOptsEnabled(..),
39 HscTarget(..), isObjectTarget, defaultObjectTarget,
40 targetRetainsAllBindings,
41 GhcMode(..), isOneShot,
42 GhcLink(..), isNoLink,
43 PackageFlag(..),
44 PkgConfRef(..),
45 Option(..), showOpt,
46 DynLibLoader(..),
47 fFlags, fWarningFlags, fLangFlags, xFlags,
48 dynFlagDependencies,
49 tablesNextToCode, mkTablesNextToCode,
50
51 printOutputForUser, printInfoForUser,
52
53 Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays,
54 wayGeneralFlags, wayUnsetGeneralFlags,
55
56 -- ** Safe Haskell
57 SafeHaskellMode(..),
58 safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn,
59 packageTrustOn,
60 safeDirectImpsReq, safeImplicitImpsReq,
61 unsafeFlags,
62
63 -- ** System tool settings and locations
64 Settings(..),
65 targetPlatform,
66 ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings,
67 extraGccViaCFlags, systemPackageConfig,
68 pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T,
69 pgm_sysman, pgm_windres, pgm_lo, pgm_lc,
70 opt_L, opt_P, opt_F, opt_c, opt_a, opt_l,
71 opt_windres, opt_lo, opt_lc,
72
73
74 -- ** Manipulating DynFlags
75 defaultDynFlags, -- Settings -> DynFlags
76 defaultWays,
77 interpWays,
78 initDynFlags, -- DynFlags -> IO DynFlags
79 defaultFatalMessager,
80 defaultLogAction,
81 defaultLogActionHPrintDoc,
82 defaultLogActionHPutStrDoc,
83 defaultFlushOut,
84 defaultFlushErr,
85
86 getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a]
87 getVerbFlags,
88 updOptLevel,
89 setTmpDir,
90 setPackageName,
91
92 -- ** Parsing DynFlags
93 parseDynamicFlagsCmdLine,
94 parseDynamicFilePragma,
95 parseDynamicFlagsFull,
96
97 -- ** Available DynFlags
98 allFlags,
99 flagsAll,
100 flagsDynamic,
101 flagsPackage,
102
103 supportedLanguagesAndExtensions,
104
105 -- ** DynFlags C compiler options
106 picCCOpts, picPOpts,
107
108 -- * Configuration of the stg-to-stg passes
109 StgToDo(..),
110 getStgToDo,
111
112 -- * Compiler configuration suitable for display to the user
113 compilerInfo,
114
115 #ifdef GHCI
116 -- Only in stage 2 can we be sure that the RTS
117 -- exposes the appropriate runtime boolean
118 rtsIsProfiled,
119 #endif
120
121 #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellExports.hs"
122 bLOCK_SIZE_W,
123 wORD_SIZE_IN_BITS,
124 tAG_MASK,
125 mAX_PTR_TAG,
126 tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD,
127
128 unsafeGlobalDynFlags, setUnsafeGlobalDynFlags,
129
130 -- * SSE
131 isSse2Enabled,
132 isSse4_2Enabled,
133
134 -- * Linker information
135 LinkerInfo(..),
136 ) where
137
138 #include "HsVersions.h"
139
140 import Platform
141 import PlatformConstants
142 import Module
143 import PackageConfig
144 import {-# SOURCE #-} PrelNames ( mAIN )
145 import {-# SOURCE #-} Packages (PackageState)
146 import DriverPhases ( Phase(..), phaseInputExt )
147 import Config
148 import CmdLineParser
149 import Constants
150 import Panic
151 import Util
152 import Maybes ( orElse )
153 import MonadUtils
154 import qualified Pretty
155 import SrcLoc
156 import FastString
157 import Outputable
158 #ifdef GHCI
159 import Foreign.C ( CInt(..) )
160 #endif
161 import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessage )
162
163 import System.IO.Unsafe ( unsafePerformIO )
164 import Data.IORef
165 import Control.Monad
166
167 import Data.Bits
168 import Data.Char
169 import Data.Int
170 import Data.List
171 import Data.Map (Map)
172 import qualified Data.Map as Map
173 import Data.Maybe
174 import Data.Set (Set)
175 import qualified Data.Set as Set
176 import Data.Word
177 import System.FilePath
178 import System.IO
179 import System.IO.Error
180
181 import Data.IntSet (IntSet)
182 import qualified Data.IntSet as IntSet
183
184 import GHC.Foreign (withCString, peekCString)
185
186 -- -----------------------------------------------------------------------------
187 -- DynFlags
188
189 data DumpFlag
190
191 -- debugging flags
192 = Opt_D_dump_cmm
193 | Opt_D_dump_cmm_raw
194 -- All of the cmm subflags (there are a lot!) Automatically
195 -- enabled if you run -ddump-cmm
196 | Opt_D_dump_cmm_cfg
197 | Opt_D_dump_cmm_cbe
198 | Opt_D_dump_cmm_proc
199 | Opt_D_dump_cmm_rewrite
200 | Opt_D_dump_cmm_sp
201 | Opt_D_dump_cmm_procmap
202 | Opt_D_dump_cmm_split
203 | Opt_D_dump_cmm_info
204 | Opt_D_dump_cmm_cps
205 -- end cmm subflags
206 | Opt_D_dump_asm
207 | Opt_D_dump_asm_native
208 | Opt_D_dump_asm_liveness
209 | Opt_D_dump_asm_regalloc
210 | Opt_D_dump_asm_regalloc_stages
211 | Opt_D_dump_asm_conflicts
212 | Opt_D_dump_asm_stats
213 | Opt_D_dump_asm_expanded
214 | Opt_D_dump_llvm
215 | Opt_D_dump_core_stats
216 | Opt_D_dump_deriv
217 | Opt_D_dump_ds
218 | Opt_D_dump_foreign
219 | Opt_D_dump_inlinings
220 | Opt_D_dump_rule_firings
221 | Opt_D_dump_rule_rewrites
222 | Opt_D_dump_simpl_trace
223 | Opt_D_dump_occur_anal
224 | Opt_D_dump_parsed
225 | Opt_D_dump_rn
226 | Opt_D_dump_core_pipeline -- TODO FIXME: dump after simplifier stats
227 | Opt_D_dump_simpl
228 | Opt_D_dump_simpl_iterations
229 | Opt_D_dump_simpl_phases
230 | Opt_D_dump_spec
231 | Opt_D_dump_prep
232 | Opt_D_dump_stg
233 | Opt_D_dump_stranal
234 | Opt_D_dump_tc
235 | Opt_D_dump_types
236 | Opt_D_dump_rules
237 | Opt_D_dump_cse
238 | Opt_D_dump_worker_wrapper
239 | Opt_D_dump_rn_trace
240 | Opt_D_dump_rn_stats
241 | Opt_D_dump_opt_cmm
242 | Opt_D_dump_simpl_stats
243 | Opt_D_dump_cs_trace -- Constraint solver in type checker
244 | Opt_D_dump_tc_trace
245 | Opt_D_dump_if_trace
246 | Opt_D_dump_vt_trace
247 | Opt_D_dump_splices
248 | Opt_D_dump_BCOs
249 | Opt_D_dump_vect
250 | Opt_D_dump_ticked
251 | Opt_D_dump_rtti
252 | Opt_D_source_stats
253 | Opt_D_verbose_stg2stg
254 | Opt_D_dump_hi
255 | Opt_D_dump_hi_diffs
256 | Opt_D_dump_mod_cycles
257 | Opt_D_dump_view_pattern_commoning
258 | Opt_D_verbose_core2core
259
260 deriving (Eq, Show, Enum)
261
262 -- | Enumerates the simple on-or-off dynamic flags
263 data GeneralFlag
264
265 = Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
266 | Opt_D_faststring_stats
267 | Opt_D_dump_minimal_imports
268 | Opt_DoCoreLinting
269 | Opt_DoStgLinting
270 | Opt_DoCmmLinting
271 | Opt_DoAsmLinting
272 | Opt_NoLlvmMangler -- hidden flag
273
274 | Opt_WarnIsError -- -Werror; makes warnings fatal
275
276 | Opt_PrintExplicitForalls
277
278 -- optimisation opts
279 | Opt_Strictness
280 | Opt_KillAbsence
281 | Opt_KillOneShot
282 | Opt_FullLaziness
283 | Opt_FloatIn
284 | Opt_Specialise
285 | Opt_StaticArgumentTransformation
286 | Opt_CSE
287 | Opt_LiberateCase
288 | Opt_SpecConstr
289 | Opt_DoLambdaEtaExpansion
290 | Opt_IgnoreAsserts
291 | Opt_DoEtaReduction
292 | Opt_CaseMerge
293 | Opt_UnboxStrictFields
294 | Opt_UnboxSmallStrictFields
295 | Opt_DictsCheap
296 | Opt_EnableRewriteRules -- Apply rewrite rules during simplification
297 | Opt_Vectorise
298 | Opt_VectorisationAvoidance
299 | Opt_RegsGraph -- do graph coloring register allocation
300 | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
301 | Opt_PedanticBottoms -- Be picky about how we treat bottom
302 | Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag)
303 | Opt_IrrefutableTuples
304 | Opt_CmmSink
305 | Opt_CmmElimCommonBlocks
306 | Opt_OmitYields
307 | Opt_SimpleListLiterals
308 | Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas
309
310 -- Interface files
311 | Opt_IgnoreInterfacePragmas
312 | Opt_OmitInterfacePragmas
313 | Opt_ExposeAllUnfoldings
314
315 -- profiling opts
316 | Opt_AutoSccsOnIndividualCafs
317 | Opt_ProfCountEntries
318
319 -- misc opts
320 | Opt_Pp
321 | Opt_ForceRecomp
322 | Opt_ExcessPrecision
323 | Opt_EagerBlackHoling
324 | Opt_NoHsMain
325 | Opt_SplitObjs
326 | Opt_StgStats
327 | Opt_HideAllPackages
328 | Opt_PrintBindResult
329 | Opt_Haddock
330 | Opt_HaddockOptions
331 | Opt_Hpc_No_Auto
332 | Opt_BreakOnException
333 | Opt_BreakOnError
334 | Opt_PrintEvldWithShow
335 | Opt_PrintBindContents
336 | Opt_GenManifest
337 | Opt_EmbedManifest
338 | Opt_EmitExternalCore
339 | Opt_SharedImplib
340 | Opt_BuildingCabalPackage
341 | Opt_IgnoreDotGhci
342 | Opt_GhciSandbox
343 | Opt_GhciHistory
344 | Opt_HelpfulErrors
345 | Opt_DeferTypeErrors
346 | Opt_Parallel
347 | Opt_GranMacros
348 | Opt_PIC
349 | Opt_SccProfilingOn
350 | Opt_Ticky
351 | Opt_Ticky_Allocd
352 | Opt_Ticky_LNE
353 | Opt_Ticky_Dyn_Thunk
354 | Opt_Static
355 | Opt_RPath
356 | Opt_RelativeDynlibPaths
357 | Opt_Hpc
358 | Opt_FlatCache
359
360 -- PreInlining is on by default. The option is there just to see how
361 -- bad things get if you turn it off!
362 | Opt_SimplPreInlining
363
364 -- output style opts
365 | Opt_ErrorSpans -- Include full span info in error messages,
366 -- instead of just the start position.
367 | Opt_PprCaseAsLet
368
369 -- Suppress all coercions, them replacing with '...'
370 | Opt_SuppressCoercions
371 | Opt_SuppressVarKinds
372 -- Suppress module id prefixes on variables.
373 | Opt_SuppressModulePrefixes
374 -- Suppress type applications.
375 | Opt_SuppressTypeApplications
376 -- Suppress info such as arity and unfoldings on identifiers.
377 | Opt_SuppressIdInfo
378 -- Suppress separate type signatures in core, but leave types on
379 -- lambda bound vars
380 | Opt_SuppressTypeSignatures
381 -- Suppress unique ids on variables.
382 -- Except for uniques, as some simplifier phases introduce new
383 -- variables that have otherwise identical names.
384 | Opt_SuppressUniques
385
386 -- temporary flags
387 | Opt_RunCPS
388 | Opt_RunCPSZ
389 | Opt_AutoLinkPackages
390 | Opt_ImplicitImportQualified
391
392 -- keeping stuff
393 | Opt_KeepHiDiffs
394 | Opt_KeepHcFiles
395 | Opt_KeepSFiles
396 | Opt_KeepTmpFiles
397 | Opt_KeepRawTokenStream
398 | Opt_KeepLlvmFiles
399
400 | Opt_BuildDynamicToo
401
402 -- safe haskell flags
403 | Opt_DistrustAllPackages
404 | Opt_PackageTrust
405
406 deriving (Eq, Show, Enum)
407
408 data WarningFlag =
409 Opt_WarnDuplicateExports
410 | Opt_WarnDuplicateConstraints
411 | Opt_WarnHiShadows
412 | Opt_WarnImplicitPrelude
413 | Opt_WarnIncompletePatterns
414 | Opt_WarnIncompleteUniPatterns
415 | Opt_WarnIncompletePatternsRecUpd
416 | Opt_WarnOverflowedLiterals
417 | Opt_WarnEmptyEnumerations
418 | Opt_WarnMissingFields
419 | Opt_WarnMissingImportList
420 | Opt_WarnMissingMethods
421 | Opt_WarnMissingSigs
422 | Opt_WarnMissingLocalSigs
423 | Opt_WarnNameShadowing
424 | Opt_WarnOverlappingPatterns
425 | Opt_WarnTypeDefaults
426 | Opt_WarnMonomorphism
427 | Opt_WarnUnusedBinds
428 | Opt_WarnUnusedImports
429 | Opt_WarnUnusedMatches
430 | Opt_WarnWarningsDeprecations
431 | Opt_WarnDeprecatedFlags
432 | Opt_WarnDodgyExports
433 | Opt_WarnDodgyImports
434 | Opt_WarnOrphans
435 | Opt_WarnAutoOrphans
436 | Opt_WarnIdentities
437 | Opt_WarnTabs
438 | Opt_WarnUnrecognisedPragmas
439 | Opt_WarnDodgyForeignImports
440 | Opt_WarnLazyUnliftedBindings
441 | Opt_WarnUnusedDoBind
442 | Opt_WarnWrongDoBind
443 | Opt_WarnAlternativeLayoutRuleTransitional
444 | Opt_WarnUnsafe
445 | Opt_WarnSafe
446 | Opt_WarnPointlessPragmas
447 | Opt_WarnUnsupportedCallingConventions
448 | Opt_WarnUnsupportedLlvmVersion
449 | Opt_WarnInlineRuleShadowing
450 | Opt_WarnTypeableInstances
451 deriving (Eq, Show, Enum)
452
453 data Language = Haskell98 | Haskell2010
454 deriving Enum
455
456 -- | The various Safe Haskell modes
457 data SafeHaskellMode
458 = Sf_None
459 | Sf_Unsafe
460 | Sf_Trustworthy
461 | Sf_Safe
462 | Sf_SafeInferred
463 deriving (Eq)
464
465 instance Show SafeHaskellMode where
466 show Sf_None = "None"
467 show Sf_Unsafe = "Unsafe"
468 show Sf_Trustworthy = "Trustworthy"
469 show Sf_Safe = "Safe"
470 show Sf_SafeInferred = "Safe-Inferred"
471
472 instance Outputable SafeHaskellMode where
473 ppr = text . show
474
475 data ExtensionFlag
476 = Opt_Cpp
477 | Opt_OverlappingInstances
478 | Opt_UndecidableInstances
479 | Opt_IncoherentInstances
480 | Opt_MonomorphismRestriction
481 | Opt_MonoPatBinds
482 | Opt_MonoLocalBinds
483 | Opt_RelaxedPolyRec -- Deprecated
484 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
485 | Opt_ForeignFunctionInterface
486 | Opt_UnliftedFFITypes
487 | Opt_InterruptibleFFI
488 | Opt_CApiFFI
489 | Opt_GHCForeignImportPrim
490 | Opt_ParallelArrays -- Syntactic support for parallel arrays
491 | Opt_Arrows -- Arrow-notation syntax
492 | Opt_TemplateHaskell
493 | Opt_QuasiQuotes
494 | Opt_ImplicitParams
495 | Opt_ImplicitPrelude
496 | Opt_ScopedTypeVariables
497 | Opt_AllowAmbiguousTypes
498 | Opt_UnboxedTuples
499 | Opt_BangPatterns
500 | Opt_TypeFamilies
501 | Opt_OverloadedStrings
502 | Opt_OverloadedLists
503 | Opt_DisambiguateRecordFields
504 | Opt_RecordWildCards
505 | Opt_RecordPuns
506 | Opt_ViewPatterns
507 | Opt_GADTs
508 | Opt_GADTSyntax
509 | Opt_NPlusKPatterns
510 | Opt_DoAndIfThenElse
511 | Opt_RebindableSyntax
512 | Opt_ConstraintKinds
513 | Opt_PolyKinds -- Kind polymorphism
514 | Opt_DataKinds -- Datatype promotion
515 | Opt_InstanceSigs
516
517 | Opt_StandaloneDeriving
518 | Opt_DeriveDataTypeable
519 | Opt_AutoDeriveTypeable -- Automatic derivation of Typeable
520 | Opt_DeriveFunctor
521 | Opt_DeriveTraversable
522 | Opt_DeriveFoldable
523 | Opt_DeriveGeneric -- Allow deriving Generic/1
524 | Opt_DefaultSignatures -- Allow extra signatures for defmeths
525
526 | Opt_TypeSynonymInstances
527 | Opt_FlexibleContexts
528 | Opt_FlexibleInstances
529 | Opt_ConstrainedClassMethods
530 | Opt_MultiParamTypeClasses
531 | Opt_NullaryTypeClasses
532 | Opt_FunctionalDependencies
533 | Opt_UnicodeSyntax
534 | Opt_ExistentialQuantification
535 | Opt_MagicHash
536 | Opt_EmptyDataDecls
537 | Opt_KindSignatures
538 | Opt_RoleAnnotations
539 | Opt_ParallelListComp
540 | Opt_TransformListComp
541 | Opt_MonadComprehensions
542 | Opt_GeneralizedNewtypeDeriving
543 | Opt_RecursiveDo
544 | Opt_PostfixOperators
545 | Opt_TupleSections
546 | Opt_PatternGuards
547 | Opt_LiberalTypeSynonyms
548 | Opt_RankNTypes
549 | Opt_ImpredicativeTypes
550 | Opt_TypeOperators
551 | Opt_ExplicitNamespaces
552 | Opt_PackageImports
553 | Opt_ExplicitForAll
554 | Opt_AlternativeLayoutRule
555 | Opt_AlternativeLayoutRuleTransitional
556 | Opt_DatatypeContexts
557 | Opt_NondecreasingIndentation
558 | Opt_RelaxedLayout
559 | Opt_TraditionalRecordSyntax
560 | Opt_LambdaCase
561 | Opt_MultiWayIf
562 | Opt_TypeHoles
563 | Opt_NegativeLiterals
564 | Opt_EmptyCase
565 deriving (Eq, Enum, Show)
566
567 -- | Contains not only a collection of 'GeneralFlag's but also a plethora of
568 -- information relating to the compilation of a single file or GHC session
569 data DynFlags = DynFlags {
570 ghcMode :: GhcMode,
571 ghcLink :: GhcLink,
572 hscTarget :: HscTarget,
573 settings :: Settings,
574 verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
575 optLevel :: Int, -- ^ Optimisation level
576 simplPhases :: Int, -- ^ Number of simplifier phases
577 maxSimplIterations :: Int, -- ^ Max simplifier iterations
578 shouldDumpSimplPhase :: Maybe String,
579 ruleCheck :: Maybe String,
580 strictnessBefore :: [Int], -- ^ Additional demand analysis
581
582 simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
583 specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
584 specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
585 specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types
586 -- Not optional; otherwise ForceSpecConstr can diverge.
587 liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
588 floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
589 -- See CoreMonad.FloatOutSwitches
590 historySize :: Int,
591
592 cmdlineHcIncludes :: [String], -- ^ @\-\#includes@
593 importPaths :: [FilePath],
594 mainModIs :: Module,
595 mainFunIs :: Maybe String,
596 ctxtStkDepth :: Int, -- ^ Typechecker context stack depth
597
598 thisPackage :: PackageId, -- ^ name of package currently being compiled
599
600 -- ways
601 ways :: [Way], -- ^ Way flags from the command line
602 buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
603 rtsBuildTag :: String, -- ^ The RTS \"way\"
604
605 -- For object splitting
606 splitInfo :: Maybe (String,Int),
607
608 -- paths etc.
609 objectDir :: Maybe String,
610 dylibInstallName :: Maybe String,
611 hiDir :: Maybe String,
612 stubDir :: Maybe String,
613 dumpDir :: Maybe String,
614
615 objectSuf :: String,
616 hcSuf :: String,
617 hiSuf :: String,
618
619 canGenerateDynamicToo :: IORef Bool,
620 dynObjectSuf :: String,
621 dynHiSuf :: String,
622
623 -- Packages.isDllName needs to know whether a call is within a
624 -- single DLL or not. Normally it does this by seeing if the call
625 -- is to the same package, but for the ghc package, we split the
626 -- package between 2 DLLs. The dllSplit tells us which sets of
627 -- modules are in which package.
628 dllSplitFile :: Maybe FilePath,
629 dllSplit :: Maybe [Set String],
630
631 outputFile :: Maybe String,
632 dynOutputFile :: Maybe String,
633 outputHi :: Maybe String,
634 dynLibLoader :: DynLibLoader,
635
636 -- | This is set by 'DriverPipeline.runPipeline' based on where
637 -- its output is going.
638 dumpPrefix :: Maybe FilePath,
639
640 -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
641 -- Set by @-ddump-file-prefix@
642 dumpPrefixForce :: Maybe FilePath,
643
644 ldInputs :: [Option],
645
646 includePaths :: [String],
647 libraryPaths :: [String],
648 frameworkPaths :: [String], -- used on darwin only
649 cmdlineFrameworks :: [String], -- ditto
650
651 rtsOpts :: Maybe String,
652 rtsOptsEnabled :: RtsOptsEnabled,
653
654 hpcDir :: String, -- ^ Path to store the .mix files
655
656 -- Plugins
657 pluginModNames :: [ModuleName],
658 pluginModNameOpts :: [(ModuleName,String)],
659
660 -- For ghc -M
661 depMakefile :: FilePath,
662 depIncludePkgDeps :: Bool,
663 depExcludeMods :: [ModuleName],
664 depSuffixes :: [String],
665
666 -- Package flags
667 extraPkgConfs :: [PkgConfRef] -> [PkgConfRef],
668 -- ^ The @-package-db@ flags given on the command line, in the order
669 -- they appeared.
670
671 packageFlags :: [PackageFlag],
672 -- ^ The @-package@ and @-hide-package@ flags from the command-line
673
674 -- Package state
675 -- NB. do not modify this field, it is calculated by
676 -- Packages.initPackages and Packages.updatePackages.
677 pkgDatabase :: Maybe [PackageConfig],
678 pkgState :: PackageState,
679
680 -- Temporary files
681 -- These have to be IORefs, because the defaultCleanupHandler needs to
682 -- know what to clean when an exception happens
683 filesToClean :: IORef [FilePath],
684 dirsToClean :: IORef (Map FilePath FilePath),
685 filesToNotIntermediateClean :: IORef [FilePath],
686
687
688 -- Names of files which were generated from -ddump-to-file; used to
689 -- track which ones we need to truncate because it's our first run
690 -- through
691 generatedDumps :: IORef (Set FilePath),
692
693 -- hsc dynamic flags
694 dumpFlags :: IntSet,
695 generalFlags :: IntSet,
696 warningFlags :: IntSet,
697 -- Don't change this without updating extensionFlags:
698 language :: Maybe Language,
699 -- | Safe Haskell mode
700 safeHaskell :: SafeHaskellMode,
701 -- We store the location of where some extension and flags were turned on so
702 -- we can produce accurate error messages when Safe Haskell fails due to
703 -- them.
704 thOnLoc :: SrcSpan,
705 newDerivOnLoc :: SrcSpan,
706 pkgTrustOnLoc :: SrcSpan,
707 warnSafeOnLoc :: SrcSpan,
708 warnUnsafeOnLoc :: SrcSpan,
709 -- Don't change this without updating extensionFlags:
710 extensions :: [OnOff ExtensionFlag],
711 -- extensionFlags should always be equal to
712 -- flattenExtensionFlags language extensions
713 extensionFlags :: IntSet,
714
715 -- Unfolding control
716 -- See Note [Discounts and thresholds] in CoreUnfold
717 ufCreationThreshold :: Int,
718 ufUseThreshold :: Int,
719 ufFunAppDiscount :: Int,
720 ufDictDiscount :: Int,
721 ufKeenessFactor :: Float,
722 ufDearOp :: Int,
723
724 maxWorkerArgs :: Int,
725
726 ghciHistSize :: Int,
727
728 -- | MsgDoc output action: use "ErrUtils" instead of this if you can
729 log_action :: LogAction,
730 flushOut :: FlushOut,
731 flushErr :: FlushErr,
732
733 haddockOptions :: Maybe String,
734 ghciScripts :: [String],
735
736 -- Output style options
737 pprUserLength :: Int,
738 pprCols :: Int,
739 traceLevel :: Int, -- Standard level is 1. Less verbose is 0.
740
741 useUnicodeQuotes :: Bool,
742
743 -- | what kind of {-# SCC #-} to add automatically
744 profAuto :: ProfAuto,
745
746 interactivePrint :: Maybe String,
747
748 llvmVersion :: IORef Int,
749
750 nextWrapperNum :: IORef Int,
751
752 -- | Machine dependant flags (-m<blah> stuff)
753 sseVersion :: Maybe (Int, Int), -- (major, minor)
754
755 -- | Run-time linker information (what options we need, etc.)
756 rtldFlags :: IORef (Maybe LinkerInfo)
757 }
758
759 class HasDynFlags m where
760 getDynFlags :: m DynFlags
761
762 class ContainsDynFlags t where
763 extractDynFlags :: t -> DynFlags
764 replaceDynFlags :: t -> DynFlags -> t
765
766 data ProfAuto
767 = NoProfAuto -- ^ no SCC annotations added
768 | ProfAutoAll -- ^ top-level and nested functions are annotated
769 | ProfAutoTop -- ^ top-level functions annotated only
770 | ProfAutoExports -- ^ exported functions annotated only
771 | ProfAutoCalls -- ^ annotate call-sites
772 deriving (Enum)
773
774 data Settings = Settings {
775 sTargetPlatform :: Platform, -- Filled in by SysTools
776 sGhcUsagePath :: FilePath, -- Filled in by SysTools
777 sGhciUsagePath :: FilePath, -- ditto
778 sTopDir :: FilePath,
779 sTmpDir :: String, -- no trailing '/'
780 -- You shouldn't need to look things up in rawSettings directly.
781 -- They should have their own fields instead.
782 sRawSettings :: [(String, String)],
783 sExtraGccViaCFlags :: [String],
784 sSystemPackageConfig :: FilePath,
785 sLdSupportsCompactUnwind :: Bool,
786 sLdSupportsBuildId :: Bool,
787 sLdSupportsFilelist :: Bool,
788 sLdIsGnuLd :: Bool,
789 -- commands for particular phases
790 sPgm_L :: String,
791 sPgm_P :: (String,[Option]),
792 sPgm_F :: String,
793 sPgm_c :: (String,[Option]),
794 sPgm_s :: (String,[Option]),
795 sPgm_a :: (String,[Option]),
796 sPgm_l :: (String,[Option]),
797 sPgm_dll :: (String,[Option]),
798 sPgm_T :: String,
799 sPgm_sysman :: String,
800 sPgm_windres :: String,
801 sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
802 sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
803 -- options for particular phases
804 sOpt_L :: [String],
805 sOpt_P :: [String],
806 sOpt_F :: [String],
807 sOpt_c :: [String],
808 sOpt_a :: [String],
809 sOpt_l :: [String],
810 sOpt_windres :: [String],
811 sOpt_lo :: [String], -- LLVM: llvm optimiser
812 sOpt_lc :: [String], -- LLVM: llc static compiler
813
814 sPlatformConstants :: PlatformConstants
815 }
816
817 targetPlatform :: DynFlags -> Platform
818 targetPlatform dflags = sTargetPlatform (settings dflags)
819
820 ghcUsagePath :: DynFlags -> FilePath
821 ghcUsagePath dflags = sGhcUsagePath (settings dflags)
822 ghciUsagePath :: DynFlags -> FilePath
823 ghciUsagePath dflags = sGhciUsagePath (settings dflags)
824 topDir :: DynFlags -> FilePath
825 topDir dflags = sTopDir (settings dflags)
826 tmpDir :: DynFlags -> String
827 tmpDir dflags = sTmpDir (settings dflags)
828 rawSettings :: DynFlags -> [(String, String)]
829 rawSettings dflags = sRawSettings (settings dflags)
830 extraGccViaCFlags :: DynFlags -> [String]
831 extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
832 systemPackageConfig :: DynFlags -> FilePath
833 systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
834 pgm_L :: DynFlags -> String
835 pgm_L dflags = sPgm_L (settings dflags)
836 pgm_P :: DynFlags -> (String,[Option])
837 pgm_P dflags = sPgm_P (settings dflags)
838 pgm_F :: DynFlags -> String
839 pgm_F dflags = sPgm_F (settings dflags)
840 pgm_c :: DynFlags -> (String,[Option])
841 pgm_c dflags = sPgm_c (settings dflags)
842 pgm_s :: DynFlags -> (String,[Option])
843 pgm_s dflags = sPgm_s (settings dflags)
844 pgm_a :: DynFlags -> (String,[Option])
845 pgm_a dflags = sPgm_a (settings dflags)
846 pgm_l :: DynFlags -> (String,[Option])
847 pgm_l dflags = sPgm_l (settings dflags)
848 pgm_dll :: DynFlags -> (String,[Option])
849 pgm_dll dflags = sPgm_dll (settings dflags)
850 pgm_T :: DynFlags -> String
851 pgm_T dflags = sPgm_T (settings dflags)
852 pgm_sysman :: DynFlags -> String
853 pgm_sysman dflags = sPgm_sysman (settings dflags)
854 pgm_windres :: DynFlags -> String
855 pgm_windres dflags = sPgm_windres (settings dflags)
856 pgm_lo :: DynFlags -> (String,[Option])
857 pgm_lo dflags = sPgm_lo (settings dflags)
858 pgm_lc :: DynFlags -> (String,[Option])
859 pgm_lc dflags = sPgm_lc (settings dflags)
860 opt_L :: DynFlags -> [String]
861 opt_L dflags = sOpt_L (settings dflags)
862 opt_P :: DynFlags -> [String]
863 opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
864 ++ sOpt_P (settings dflags)
865 opt_F :: DynFlags -> [String]
866 opt_F dflags = sOpt_F (settings dflags)
867 opt_c :: DynFlags -> [String]
868 opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags)
869 ++ sOpt_c (settings dflags)
870 opt_a :: DynFlags -> [String]
871 opt_a dflags = sOpt_a (settings dflags)
872 opt_l :: DynFlags -> [String]
873 opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags)
874 ++ sOpt_l (settings dflags)
875 opt_windres :: DynFlags -> [String]
876 opt_windres dflags = sOpt_windres (settings dflags)
877 opt_lo :: DynFlags -> [String]
878 opt_lo dflags = sOpt_lo (settings dflags)
879 opt_lc :: DynFlags -> [String]
880 opt_lc dflags = sOpt_lc (settings dflags)
881
882 -- | The target code type of the compilation (if any).
883 --
884 -- Whenever you change the target, also make sure to set 'ghcLink' to
885 -- something sensible.
886 --
887 -- 'HscNothing' can be used to avoid generating any output, however, note
888 -- that:
889 --
890 -- * If a program uses Template Haskell the typechecker may try to run code
891 -- from an imported module. This will fail if no code has been generated
892 -- for this module. You can use 'GHC.needsTemplateHaskell' to detect
893 -- whether this might be the case and choose to either switch to a
894 -- different target or avoid typechecking such modules. (The latter may be
895 -- preferable for security reasons.)
896 --
897 data HscTarget
898 = HscC -- ^ Generate C code.
899 | HscAsm -- ^ Generate assembly using the native code generator.
900 | HscLlvm -- ^ Generate assembly using the llvm code generator.
901 | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
902 | HscNothing -- ^ Don't generate any code. See notes above.
903 deriving (Eq, Show)
904
905 -- | Will this target result in an object file on the disk?
906 isObjectTarget :: HscTarget -> Bool
907 isObjectTarget HscC = True
908 isObjectTarget HscAsm = True
909 isObjectTarget HscLlvm = True
910 isObjectTarget _ = False
911
912 -- | Does this target retain *all* top-level bindings for a module,
913 -- rather than just the exported bindings, in the TypeEnv and compiled
914 -- code (if any)? In interpreted mode we do this, so that GHCi can
915 -- call functions inside a module. In HscNothing mode we also do it,
916 -- so that Haddock can get access to the GlobalRdrEnv for a module
917 -- after typechecking it.
918 targetRetainsAllBindings :: HscTarget -> Bool
919 targetRetainsAllBindings HscInterpreted = True
920 targetRetainsAllBindings HscNothing = True
921 targetRetainsAllBindings _ = False
922
923 -- | The 'GhcMode' tells us whether we're doing multi-module
924 -- compilation (controlled via the "GHC" API) or one-shot
925 -- (single-module) compilation. This makes a difference primarily to
926 -- the "Finder": in one-shot mode we look for interface files for
927 -- imported modules, but in multi-module mode we look for source files
928 -- in order to check whether they need to be recompiled.
929 data GhcMode
930 = CompManager -- ^ @\-\-make@, GHCi, etc.
931 | OneShot -- ^ @ghc -c Foo.hs@
932 | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
933 deriving Eq
934
935 instance Outputable GhcMode where
936 ppr CompManager = ptext (sLit "CompManager")
937 ppr OneShot = ptext (sLit "OneShot")
938 ppr MkDepend = ptext (sLit "MkDepend")
939
940 isOneShot :: GhcMode -> Bool
941 isOneShot OneShot = True
942 isOneShot _other = False
943
944 -- | What to do in the link step, if there is one.
945 data GhcLink
946 = NoLink -- ^ Don't link at all
947 | LinkBinary -- ^ Link object code into a binary
948 | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
949 -- bytecode and object code).
950 | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
951 deriving (Eq, Show)
952
953 isNoLink :: GhcLink -> Bool
954 isNoLink NoLink = True
955 isNoLink _ = False
956
957 data PackageFlag
958 = ExposePackage String
959 | ExposePackageId String
960 | HidePackage String
961 | IgnorePackage String
962 | TrustPackage String
963 | DistrustPackage String
964 deriving (Eq, Show)
965
966 defaultHscTarget :: Platform -> HscTarget
967 defaultHscTarget = defaultObjectTarget
968
969 -- | The 'HscTarget' value corresponding to the default way to create
970 -- object files on the current platform.
971 defaultObjectTarget :: Platform -> HscTarget
972 defaultObjectTarget platform
973 | platformUnregisterised platform = HscC
974 | cGhcWithNativeCodeGen == "YES" = HscAsm
975 | otherwise = HscLlvm
976
977 tablesNextToCode :: DynFlags -> Bool
978 tablesNextToCode dflags
979 = mkTablesNextToCode (platformUnregisterised (targetPlatform dflags))
980
981 -- Determines whether we will be compiling
982 -- info tables that reside just before the entry code, or with an
983 -- indirection to the entry code. See TABLES_NEXT_TO_CODE in
984 -- includes/rts/storage/InfoTables.h.
985 mkTablesNextToCode :: Bool -> Bool
986 mkTablesNextToCode unregisterised
987 = not unregisterised && cGhcEnableTablesNextToCode == "YES"
988
989 data DynLibLoader
990 = Deployable
991 | SystemDependent
992 deriving Eq
993
994 data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll
995 deriving (Show)
996
997 -----------------------------------------------------------------------------
998 -- Ways
999
1000 -- The central concept of a "way" is that all objects in a given
1001 -- program must be compiled in the same "way". Certain options change
1002 -- parameters of the virtual machine, eg. profiling adds an extra word
1003 -- to the object header, so profiling objects cannot be linked with
1004 -- non-profiling objects.
1005
1006 -- After parsing the command-line options, we determine which "way" we
1007 -- are building - this might be a combination way, eg. profiling+threaded.
1008
1009 -- We then find the "build-tag" associated with this way, and this
1010 -- becomes the suffix used to find .hi files and libraries used in
1011 -- this compilation.
1012
1013 data Way
1014 = WayThreaded
1015 | WayDebug
1016 | WayProf
1017 | WayEventLog
1018 | WayPar
1019 | WayGran
1020 | WayNDP
1021 | WayDyn
1022 deriving (Eq, Ord, Show)
1023
1024 allowed_combination :: [Way] -> Bool
1025 allowed_combination way = and [ x `allowedWith` y
1026 | x <- way, y <- way, x < y ]
1027 where
1028 -- Note ordering in these tests: the left argument is
1029 -- <= the right argument, according to the Ord instance
1030 -- on Way above.
1031
1032 -- dyn is allowed with everything
1033 _ `allowedWith` WayDyn = True
1034 WayDyn `allowedWith` _ = True
1035
1036 -- debug is allowed with everything
1037 _ `allowedWith` WayDebug = True
1038 WayDebug `allowedWith` _ = True
1039
1040 WayProf `allowedWith` WayNDP = True
1041 WayThreaded `allowedWith` WayProf = True
1042 WayThreaded `allowedWith` WayEventLog = True
1043 _ `allowedWith` _ = False
1044
1045 mkBuildTag :: [Way] -> String
1046 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
1047
1048 wayTag :: Way -> String
1049 wayTag WayThreaded = "thr"
1050 wayTag WayDebug = "debug"
1051 wayTag WayDyn = "dyn"
1052 wayTag WayProf = "p"
1053 wayTag WayEventLog = "l"
1054 wayTag WayPar = "mp"
1055 wayTag WayGran = "mg"
1056 wayTag WayNDP = "ndp"
1057
1058 wayRTSOnly :: Way -> Bool
1059 wayRTSOnly WayThreaded = True
1060 wayRTSOnly WayDebug = True
1061 wayRTSOnly WayDyn = False
1062 wayRTSOnly WayProf = False
1063 wayRTSOnly WayEventLog = True
1064 wayRTSOnly WayPar = False
1065 wayRTSOnly WayGran = False
1066 wayRTSOnly WayNDP = False
1067
1068 wayDesc :: Way -> String
1069 wayDesc WayThreaded = "Threaded"
1070 wayDesc WayDebug = "Debug"
1071 wayDesc WayDyn = "Dynamic"
1072 wayDesc WayProf = "Profiling"
1073 wayDesc WayEventLog = "RTS Event Logging"
1074 wayDesc WayPar = "Parallel"
1075 wayDesc WayGran = "GranSim"
1076 wayDesc WayNDP = "Nested data parallelism"
1077
1078 -- Turn these flags on when enabling this way
1079 wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
1080 wayGeneralFlags _ WayThreaded = []
1081 wayGeneralFlags _ WayDebug = []
1082 wayGeneralFlags _ WayDyn = [Opt_PIC]
1083 wayGeneralFlags _ WayProf = [Opt_SccProfilingOn]
1084 wayGeneralFlags _ WayEventLog = []
1085 wayGeneralFlags _ WayPar = [Opt_Parallel]
1086 wayGeneralFlags _ WayGran = [Opt_GranMacros]
1087 wayGeneralFlags _ WayNDP = []
1088
1089 -- Turn these flags off when enabling this way
1090 wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
1091 wayUnsetGeneralFlags _ WayThreaded = []
1092 wayUnsetGeneralFlags _ WayDebug = []
1093 wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects
1094 -- when we're going to be dynamically
1095 -- linking. Plus it breaks compilation
1096 -- on OSX x86.
1097 Opt_SplitObjs]
1098 wayUnsetGeneralFlags _ WayProf = []
1099 wayUnsetGeneralFlags _ WayEventLog = []
1100 wayUnsetGeneralFlags _ WayPar = []
1101 wayUnsetGeneralFlags _ WayGran = []
1102 wayUnsetGeneralFlags _ WayNDP = []
1103
1104 wayExtras :: Platform -> Way -> DynFlags -> DynFlags
1105 wayExtras _ WayThreaded dflags = dflags
1106 wayExtras _ WayDebug dflags = dflags
1107 wayExtras _ WayDyn dflags = dflags
1108 wayExtras _ WayProf dflags = dflags
1109 wayExtras _ WayEventLog dflags = dflags
1110 wayExtras _ WayPar dflags = exposePackage' "concurrent" dflags
1111 wayExtras _ WayGran dflags = exposePackage' "concurrent" dflags
1112 wayExtras _ WayNDP dflags = setExtensionFlag' Opt_ParallelArrays
1113 $ setGeneralFlag' Opt_Vectorise dflags
1114
1115 wayOptc :: Platform -> Way -> [String]
1116 wayOptc platform WayThreaded = case platformOS platform of
1117 OSOpenBSD -> ["-pthread"]
1118 OSNetBSD -> ["-pthread"]
1119 _ -> []
1120 wayOptc _ WayDebug = []
1121 wayOptc _ WayDyn = []
1122 wayOptc _ WayProf = ["-DPROFILING"]
1123 wayOptc _ WayEventLog = ["-DTRACING"]
1124 wayOptc _ WayPar = ["-DPAR", "-w"]
1125 wayOptc _ WayGran = ["-DGRAN"]
1126 wayOptc _ WayNDP = []
1127
1128 wayOptl :: Platform -> Way -> [String]
1129 wayOptl platform WayThreaded =
1130 case platformOS platform of
1131 -- FreeBSD's default threading library is the KSE-based M:N libpthread,
1132 -- which GHC has some problems with. It's currently not clear whether
1133 -- the problems are our fault or theirs, but it seems that using the
1134 -- alternative 1:1 threading library libthr works around it:
1135 OSFreeBSD -> ["-lthr"]
1136 OSSolaris2 -> ["-lrt"]
1137 OSOpenBSD -> ["-pthread"]
1138 OSNetBSD -> ["-pthread"]
1139 _ -> []
1140 wayOptl _ WayDebug = []
1141 wayOptl _ WayDyn = []
1142 wayOptl _ WayProf = []
1143 wayOptl _ WayEventLog = []
1144 wayOptl _ WayPar = ["-L${PVM_ROOT}/lib/${PVM_ARCH}",
1145 "-lpvm3",
1146 "-lgpvm3"]
1147 wayOptl _ WayGran = []
1148 wayOptl _ WayNDP = []
1149
1150 wayOptP :: Platform -> Way -> [String]
1151 wayOptP _ WayThreaded = []
1152 wayOptP _ WayDebug = []
1153 wayOptP _ WayDyn = []
1154 wayOptP _ WayProf = ["-DPROFILING"]
1155 wayOptP _ WayEventLog = ["-DTRACING"]
1156 wayOptP _ WayPar = ["-D__PARALLEL_HASKELL__"]
1157 wayOptP _ WayGran = ["-D__GRANSIM__"]
1158 wayOptP _ WayNDP = []
1159
1160 whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1161 whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ())
1162
1163 ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1164 ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g
1165
1166 whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1167 whenCannotGenerateDynamicToo dflags f
1168 = ifCannotGenerateDynamicToo dflags f (return ())
1169
1170 ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1171 ifCannotGenerateDynamicToo dflags f g
1172 = generateDynamicTooConditional dflags g f g
1173
1174 generateDynamicTooConditional :: MonadIO m
1175 => DynFlags -> m a -> m a -> m a -> m a
1176 generateDynamicTooConditional dflags canGen cannotGen notTryingToGen
1177 = if gopt Opt_BuildDynamicToo dflags
1178 then do let ref = canGenerateDynamicToo dflags
1179 b <- liftIO $ readIORef ref
1180 if b then canGen else cannotGen
1181 else notTryingToGen
1182
1183 dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags
1184 dynamicTooMkDynamicDynFlags dflags0
1185 = let dflags1 = addWay' WayDyn dflags0
1186 dflags2 = dflags1 {
1187 outputFile = dynOutputFile dflags1,
1188 hiSuf = dynHiSuf dflags1,
1189 objectSuf = dynObjectSuf dflags1
1190 }
1191 dflags3 = updateWays dflags2
1192 dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo
1193 in dflags4
1194
1195 -----------------------------------------------------------------------------
1196
1197 -- | Used by 'GHC.newSession' to partially initialize a new 'DynFlags' value
1198 initDynFlags :: DynFlags -> IO DynFlags
1199 initDynFlags dflags = do
1200 let -- We can't build with dynamic-too on Windows, as labels before
1201 -- the fork point are different depending on whether we are
1202 -- building dynamically or not.
1203 platformCanGenerateDynamicToo
1204 = platformOS (targetPlatform dflags) /= OSMinGW32
1205 refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo
1206 refFilesToClean <- newIORef []
1207 refDirsToClean <- newIORef Map.empty
1208 refFilesToNotIntermediateClean <- newIORef []
1209 refGeneratedDumps <- newIORef Set.empty
1210 refLlvmVersion <- newIORef 28
1211 refRtldFlags <- newIORef Nothing
1212 wrapperNum <- newIORef 0
1213 canUseUnicodeQuotes <- do let enc = localeEncoding
1214 str = "‛’"
1215 (withCString enc str $ \cstr ->
1216 do str' <- peekCString enc cstr
1217 return (str == str'))
1218 `catchIOError` \_ -> return False
1219 return dflags{
1220 canGenerateDynamicToo = refCanGenerateDynamicToo,
1221 filesToClean = refFilesToClean,
1222 dirsToClean = refDirsToClean,
1223 filesToNotIntermediateClean = refFilesToNotIntermediateClean,
1224 generatedDumps = refGeneratedDumps,
1225 llvmVersion = refLlvmVersion,
1226 nextWrapperNum = wrapperNum,
1227 useUnicodeQuotes = canUseUnicodeQuotes,
1228 rtldFlags = refRtldFlags
1229 }
1230
1231 -- | The normal 'DynFlags'. Note that they is not suitable for use in this form
1232 -- and must be fully initialized by 'GHC.newSession' first.
1233 defaultDynFlags :: Settings -> DynFlags
1234 defaultDynFlags mySettings =
1235 DynFlags {
1236 ghcMode = CompManager,
1237 ghcLink = LinkBinary,
1238 hscTarget = defaultHscTarget (sTargetPlatform mySettings),
1239 verbosity = 0,
1240 optLevel = 0,
1241 simplPhases = 2,
1242 maxSimplIterations = 4,
1243 shouldDumpSimplPhase = Nothing,
1244 ruleCheck = Nothing,
1245 simplTickFactor = 100,
1246 specConstrThreshold = Just 2000,
1247 specConstrCount = Just 3,
1248 specConstrRecursive = 3,
1249 liberateCaseThreshold = Just 2000,
1250 floatLamArgs = Just 0, -- Default: float only if no fvs
1251 historySize = 20,
1252 strictnessBefore = [],
1253
1254 cmdlineHcIncludes = [],
1255 importPaths = ["."],
1256 mainModIs = mAIN,
1257 mainFunIs = Nothing,
1258 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
1259
1260 thisPackage = mainPackageId,
1261
1262 objectDir = Nothing,
1263 dylibInstallName = Nothing,
1264 hiDir = Nothing,
1265 stubDir = Nothing,
1266 dumpDir = Nothing,
1267
1268 objectSuf = phaseInputExt StopLn,
1269 hcSuf = phaseInputExt HCc,
1270 hiSuf = "hi",
1271
1272 canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo",
1273 dynObjectSuf = "dyn_" ++ phaseInputExt StopLn,
1274 dynHiSuf = "dyn_hi",
1275
1276 dllSplitFile = Nothing,
1277 dllSplit = Nothing,
1278
1279 pluginModNames = [],
1280 pluginModNameOpts = [],
1281
1282 outputFile = Nothing,
1283 dynOutputFile = Nothing,
1284 outputHi = Nothing,
1285 dynLibLoader = SystemDependent,
1286 dumpPrefix = Nothing,
1287 dumpPrefixForce = Nothing,
1288 ldInputs = [],
1289 includePaths = [],
1290 libraryPaths = [],
1291 frameworkPaths = [],
1292 cmdlineFrameworks = [],
1293 rtsOpts = Nothing,
1294 rtsOptsEnabled = RtsOptsSafeOnly,
1295
1296 hpcDir = ".hpc",
1297
1298 extraPkgConfs = id,
1299 packageFlags = [],
1300 pkgDatabase = Nothing,
1301 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
1302 ways = defaultWays mySettings,
1303 buildTag = mkBuildTag (defaultWays mySettings),
1304 rtsBuildTag = mkBuildTag (defaultWays mySettings),
1305 splitInfo = Nothing,
1306 settings = mySettings,
1307 -- ghc -M values
1308 depMakefile = "Makefile",
1309 depIncludePkgDeps = False,
1310 depExcludeMods = [],
1311 depSuffixes = [],
1312 -- end of ghc -M values
1313 filesToClean = panic "defaultDynFlags: No filesToClean",
1314 dirsToClean = panic "defaultDynFlags: No dirsToClean",
1315 filesToNotIntermediateClean = panic "defaultDynFlags: No filesToNotIntermediateClean",
1316 generatedDumps = panic "defaultDynFlags: No generatedDumps",
1317 haddockOptions = Nothing,
1318 dumpFlags = IntSet.empty,
1319 generalFlags = IntSet.fromList (map fromEnum (defaultFlags mySettings)),
1320 warningFlags = IntSet.fromList (map fromEnum standardWarnings),
1321 ghciScripts = [],
1322 language = Nothing,
1323 safeHaskell = Sf_SafeInferred,
1324 thOnLoc = noSrcSpan,
1325 newDerivOnLoc = noSrcSpan,
1326 pkgTrustOnLoc = noSrcSpan,
1327 warnSafeOnLoc = noSrcSpan,
1328 warnUnsafeOnLoc = noSrcSpan,
1329 extensions = [],
1330 extensionFlags = flattenExtensionFlags Nothing [],
1331
1332 -- The ufCreationThreshold threshold must be reasonably high to
1333 -- take account of possible discounts.
1334 -- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline
1335 -- into Csg.calc (The unfolding for sqr never makes it into the
1336 -- interface file.)
1337 ufCreationThreshold = 750,
1338 ufUseThreshold = 60,
1339 ufFunAppDiscount = 60,
1340 -- Be fairly keen to inline a fuction if that means
1341 -- we'll be able to pick the right method from a dictionary
1342 ufDictDiscount = 30,
1343 ufKeenessFactor = 1.5,
1344 ufDearOp = 40,
1345
1346 maxWorkerArgs = 10,
1347
1348 ghciHistSize = 50, -- keep a log of length 50 by default
1349
1350 log_action = defaultLogAction,
1351 flushOut = defaultFlushOut,
1352 flushErr = defaultFlushErr,
1353 pprUserLength = 5,
1354 pprCols = 100,
1355 useUnicodeQuotes = False,
1356 traceLevel = 1,
1357 profAuto = NoProfAuto,
1358 llvmVersion = panic "defaultDynFlags: No llvmVersion",
1359 interactivePrint = Nothing,
1360 nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum",
1361 sseVersion = Nothing,
1362 rtldFlags = panic "defaultDynFlags: no rtldFlags"
1363 }
1364
1365 defaultWays :: Settings -> [Way]
1366 defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
1367 then [WayDyn]
1368 else []
1369
1370 interpWays :: [Way]
1371 interpWays = if cDYNAMIC_GHC_PROGRAMS
1372 then [WayDyn]
1373 else []
1374
1375 --------------------------------------------------------------------------
1376
1377 type FatalMessager = String -> IO ()
1378 type LogAction = DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO ()
1379
1380 defaultFatalMessager :: FatalMessager
1381 defaultFatalMessager = hPutStrLn stderr
1382
1383 defaultLogAction :: LogAction
1384 defaultLogAction dflags severity srcSpan style msg
1385 = case severity of
1386 SevOutput -> printSDoc msg style
1387 SevDump -> printSDoc (msg $$ blankLine) style
1388 SevInteractive -> putStrSDoc msg style
1389 SevInfo -> printErrs msg style
1390 SevFatal -> printErrs msg style
1391 _ -> do hPutChar stderr '\n'
1392 printErrs (mkLocMessage severity srcSpan msg) style
1393 -- careful (#2302): printErrs prints in UTF-8,
1394 -- whereas converting to string first and using
1395 -- hPutStr would just emit the low 8 bits of
1396 -- each unicode char.
1397 where printSDoc = defaultLogActionHPrintDoc dflags stdout
1398 printErrs = defaultLogActionHPrintDoc dflags stderr
1399 putStrSDoc = defaultLogActionHPutStrDoc dflags stdout
1400
1401 defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
1402 defaultLogActionHPrintDoc dflags h d sty
1403 = do let doc = runSDoc d (initSDocContext dflags sty)
1404 Pretty.printDoc Pretty.PageMode (pprCols dflags) h doc
1405 hFlush h
1406
1407 defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
1408 defaultLogActionHPutStrDoc dflags h d sty
1409 = do let doc = runSDoc d (initSDocContext dflags sty)
1410 hPutStr h (Pretty.render doc)
1411 hFlush h
1412
1413 newtype FlushOut = FlushOut (IO ())
1414
1415 defaultFlushOut :: FlushOut
1416 defaultFlushOut = FlushOut $ hFlush stdout
1417
1418 newtype FlushErr = FlushErr (IO ())
1419
1420 defaultFlushErr :: FlushErr
1421 defaultFlushErr = FlushErr $ hFlush stderr
1422
1423 printOutputForUser :: DynFlags -> PrintUnqualified -> SDoc -> IO ()
1424 printOutputForUser = printSevForUser SevOutput
1425
1426 printInfoForUser :: DynFlags -> PrintUnqualified -> SDoc -> IO ()
1427 printInfoForUser = printSevForUser SevInfo
1428
1429 printSevForUser :: Severity -> DynFlags -> PrintUnqualified -> SDoc -> IO ()
1430 printSevForUser sev dflags unqual doc
1431 = log_action dflags dflags sev noSrcSpan (mkUserStyle unqual AllTheWay) doc
1432
1433 {-
1434 Note [Verbosity levels]
1435 ~~~~~~~~~~~~~~~~~~~~~~~
1436 0 | print errors & warnings only
1437 1 | minimal verbosity: print "compiling M ... done." for each module.
1438 2 | equivalent to -dshow-passes
1439 3 | equivalent to existing "ghc -v"
1440 4 | "ghc -v -ddump-most"
1441 5 | "ghc -v -ddump-all"
1442 -}
1443
1444 data OnOff a = On a
1445 | Off a
1446
1447 -- OnOffs accumulate in reverse order, so we use foldr in order to
1448 -- process them in the right order
1449 flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet
1450 flattenExtensionFlags ml = foldr f defaultExtensionFlags
1451 where f (On f) flags = IntSet.insert (fromEnum f) flags
1452 f (Off f) flags = IntSet.delete (fromEnum f) flags
1453 defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml))
1454
1455 languageExtensions :: Maybe Language -> [ExtensionFlag]
1456
1457 languageExtensions Nothing
1458 -- Nothing => the default case
1459 = Opt_NondecreasingIndentation -- This has been on by default for some time
1460 : delete Opt_DatatypeContexts -- The Haskell' committee decided to
1461 -- remove datatype contexts from the
1462 -- language:
1463 -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
1464 (languageExtensions (Just Haskell2010))
1465
1466 -- NB: MonoPatBinds is no longer the default
1467
1468 languageExtensions (Just Haskell98)
1469 = [Opt_ImplicitPrelude,
1470 Opt_MonomorphismRestriction,
1471 Opt_NPlusKPatterns,
1472 Opt_DatatypeContexts,
1473 Opt_TraditionalRecordSyntax,
1474 Opt_NondecreasingIndentation
1475 -- strictly speaking non-standard, but we always had this
1476 -- on implicitly before the option was added in 7.1, and
1477 -- turning it off breaks code, so we're keeping it on for
1478 -- backwards compatibility. Cabal uses -XHaskell98 by
1479 -- default unless you specify another language.
1480 ]
1481
1482 languageExtensions (Just Haskell2010)
1483 = [Opt_ImplicitPrelude,
1484 Opt_MonomorphismRestriction,
1485 Opt_DatatypeContexts,
1486 Opt_TraditionalRecordSyntax,
1487 Opt_EmptyDataDecls,
1488 Opt_ForeignFunctionInterface,
1489 Opt_PatternGuards,
1490 Opt_DoAndIfThenElse,
1491 Opt_RelaxedPolyRec]
1492
1493 -- | Test whether a 'DumpFlag' is set
1494 dopt :: DumpFlag -> DynFlags -> Bool
1495 dopt f dflags = (fromEnum f `IntSet.member` dumpFlags dflags)
1496 || (verbosity dflags >= 4 && enableIfVerbose f)
1497 where enableIfVerbose Opt_D_dump_tc_trace = False
1498 enableIfVerbose Opt_D_dump_rn_trace = False
1499 enableIfVerbose Opt_D_dump_cs_trace = False
1500 enableIfVerbose Opt_D_dump_if_trace = False
1501 enableIfVerbose Opt_D_dump_vt_trace = False
1502 enableIfVerbose Opt_D_dump_tc = False
1503 enableIfVerbose Opt_D_dump_rn = False
1504 enableIfVerbose Opt_D_dump_rn_stats = False
1505 enableIfVerbose Opt_D_dump_hi_diffs = False
1506 enableIfVerbose Opt_D_verbose_core2core = False
1507 enableIfVerbose Opt_D_verbose_stg2stg = False
1508 enableIfVerbose Opt_D_dump_splices = False
1509 enableIfVerbose Opt_D_dump_rule_firings = False
1510 enableIfVerbose Opt_D_dump_rule_rewrites = False
1511 enableIfVerbose Opt_D_dump_simpl_trace = False
1512 enableIfVerbose Opt_D_dump_rtti = False
1513 enableIfVerbose Opt_D_dump_inlinings = False
1514 enableIfVerbose Opt_D_dump_core_stats = False
1515 enableIfVerbose Opt_D_dump_asm_stats = False
1516 enableIfVerbose Opt_D_dump_types = False
1517 enableIfVerbose Opt_D_dump_simpl_iterations = False
1518 enableIfVerbose Opt_D_dump_ticked = False
1519 enableIfVerbose Opt_D_dump_view_pattern_commoning = False
1520 enableIfVerbose Opt_D_dump_mod_cycles = False
1521 enableIfVerbose _ = True
1522
1523 -- | Set a 'DumpFlag'
1524 dopt_set :: DynFlags -> DumpFlag -> DynFlags
1525 dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) }
1526
1527 -- | Unset a 'DumpFlag'
1528 dopt_unset :: DynFlags -> DumpFlag -> DynFlags
1529 dopt_unset dfs f = dfs{ dumpFlags = IntSet.delete (fromEnum f) (dumpFlags dfs) }
1530
1531 -- | Test whether a 'GeneralFlag' is set
1532 gopt :: GeneralFlag -> DynFlags -> Bool
1533 gopt f dflags = fromEnum f `IntSet.member` generalFlags dflags
1534
1535 -- | Set a 'GeneralFlag'
1536 gopt_set :: DynFlags -> GeneralFlag -> DynFlags
1537 gopt_set dfs f = dfs{ generalFlags = IntSet.insert (fromEnum f) (generalFlags dfs) }
1538
1539 -- | Unset a 'GeneralFlag'
1540 gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
1541 gopt_unset dfs f = dfs{ generalFlags = IntSet.delete (fromEnum f) (generalFlags dfs) }
1542
1543 -- | Test whether a 'WarningFlag' is set
1544 wopt :: WarningFlag -> DynFlags -> Bool
1545 wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags
1546
1547 -- | Set a 'WarningFlag'
1548 wopt_set :: DynFlags -> WarningFlag -> DynFlags
1549 wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) }
1550
1551 -- | Unset a 'WarningFlag'
1552 wopt_unset :: DynFlags -> WarningFlag -> DynFlags
1553 wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) }
1554
1555 -- | Test whether a 'ExtensionFlag' is set
1556 xopt :: ExtensionFlag -> DynFlags -> Bool
1557 xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags
1558
1559 -- | Set a 'ExtensionFlag'
1560 xopt_set :: DynFlags -> ExtensionFlag -> DynFlags
1561 xopt_set dfs f
1562 = let onoffs = On f : extensions dfs
1563 in dfs { extensions = onoffs,
1564 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1565
1566 -- | Unset a 'ExtensionFlag'
1567 xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags
1568 xopt_unset dfs f
1569 = let onoffs = Off f : extensions dfs
1570 in dfs { extensions = onoffs,
1571 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1572
1573 lang_set :: DynFlags -> Maybe Language -> DynFlags
1574 lang_set dflags lang =
1575 dflags {
1576 language = lang,
1577 extensionFlags = flattenExtensionFlags lang (extensions dflags)
1578 }
1579
1580 -- | Set the Haskell language standard to use
1581 setLanguage :: Language -> DynP ()
1582 setLanguage l = upd (`lang_set` Just l)
1583
1584 -- | Some modules have dependencies on others through the DynFlags rather than textual imports
1585 dynFlagDependencies :: DynFlags -> [ModuleName]
1586 dynFlagDependencies = pluginModNames
1587
1588 -- | Is the -fpackage-trust mode on
1589 packageTrustOn :: DynFlags -> Bool
1590 packageTrustOn = gopt Opt_PackageTrust
1591
1592 -- | Is Safe Haskell on in some way (including inference mode)
1593 safeHaskellOn :: DynFlags -> Bool
1594 safeHaskellOn dflags = safeHaskell dflags /= Sf_None
1595
1596 -- | Is the Safe Haskell safe language in use
1597 safeLanguageOn :: DynFlags -> Bool
1598 safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
1599
1600 -- | Is the Safe Haskell safe inference mode active
1601 safeInferOn :: DynFlags -> Bool
1602 safeInferOn dflags = safeHaskell dflags == Sf_SafeInferred
1603
1604 -- | Test if Safe Imports are on in some form
1605 safeImportsOn :: DynFlags -> Bool
1606 safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
1607 safeHaskell dflags == Sf_Trustworthy ||
1608 safeHaskell dflags == Sf_Safe
1609
1610 -- | Set a 'Safe Haskell' flag
1611 setSafeHaskell :: SafeHaskellMode -> DynP ()
1612 setSafeHaskell s = updM f
1613 where f dfs = do
1614 let sf = safeHaskell dfs
1615 safeM <- combineSafeFlags sf s
1616 return $ dfs { safeHaskell = safeM }
1617
1618 -- | Are all direct imports required to be safe for this Safe Haskell mode?
1619 -- Direct imports are when the code explicitly imports a module
1620 safeDirectImpsReq :: DynFlags -> Bool
1621 safeDirectImpsReq d = safeLanguageOn d
1622
1623 -- | Are all implicit imports required to be safe for this Safe Haskell mode?
1624 -- Implicit imports are things in the prelude. e.g System.IO when print is used.
1625 safeImplicitImpsReq :: DynFlags -> Bool
1626 safeImplicitImpsReq d = safeLanguageOn d
1627
1628 -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
1629 -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
1630 -- want to export this functionality from the module but do want to export the
1631 -- type constructors.
1632 combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
1633 combineSafeFlags a b | a == Sf_SafeInferred = return b
1634 | b == Sf_SafeInferred = return a
1635 | a == Sf_None = return b
1636 | b == Sf_None = return a
1637 | a == b = return a
1638 | otherwise = addErr errm >> return (panic errm)
1639 where errm = "Incompatible Safe Haskell flags! ("
1640 ++ show a ++ ", " ++ show b ++ ")"
1641
1642 -- | A list of unsafe flags under Safe Haskell. Tuple elements are:
1643 -- * name of the flag
1644 -- * function to get srcspan that enabled the flag
1645 -- * function to test if the flag is on
1646 -- * function to turn the flag off
1647 unsafeFlags :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
1648 unsafeFlags = [("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
1649 xopt Opt_GeneralizedNewtypeDeriving,
1650 flip xopt_unset Opt_GeneralizedNewtypeDeriving),
1651 ("-XTemplateHaskell", thOnLoc,
1652 xopt Opt_TemplateHaskell,
1653 flip xopt_unset Opt_TemplateHaskell)]
1654
1655 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
1656 getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
1657 -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
1658 -> [a] -- ^ Correctly ordered extracted options
1659 getOpts dflags opts = reverse (opts dflags)
1660 -- We add to the options from the front, so we need to reverse the list
1661
1662 -- | Gets the verbosity flag for the current verbosity level. This is fed to
1663 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
1664 getVerbFlags :: DynFlags -> [String]
1665 getVerbFlags dflags
1666 | verbosity dflags >= 4 = ["-v"]
1667 | otherwise = []
1668
1669 setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir,
1670 setDynObjectSuf, setDynHiSuf,
1671 setDylibInstallName,
1672 setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
1673 setPgmP, addOptl, addOptc, addOptP,
1674 addCmdlineFramework, addHaddockOpts, addGhciScript,
1675 setInteractivePrint
1676 :: String -> DynFlags -> DynFlags
1677 setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce
1678 :: Maybe String -> DynFlags -> DynFlags
1679
1680 setObjectDir f d = d{ objectDir = Just f}
1681 setHiDir f d = d{ hiDir = Just f}
1682 setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
1683 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
1684 -- \#included from the .hc file when compiling via C (i.e. unregisterised
1685 -- builds).
1686 setDumpDir f d = d{ dumpDir = Just f}
1687 setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f
1688 setDylibInstallName f d = d{ dylibInstallName = Just f}
1689
1690 setObjectSuf f d = d{ objectSuf = f}
1691 setDynObjectSuf f d = d{ dynObjectSuf = f}
1692 setHiSuf f d = d{ hiSuf = f}
1693 setDynHiSuf f d = d{ dynHiSuf = f}
1694 setHcSuf f d = d{ hcSuf = f}
1695
1696 setOutputFile f d = d{ outputFile = f}
1697 setDynOutputFile f d = d{ dynOutputFile = f}
1698 setOutputHi f d = d{ outputHi = f}
1699
1700 addPluginModuleName :: String -> DynFlags -> DynFlags
1701 addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
1702
1703 addPluginModuleNameOption :: String -> DynFlags -> DynFlags
1704 addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
1705 where (m, rest) = break (== ':') optflag
1706 option = case rest of
1707 [] -> "" -- should probably signal an error
1708 (_:plug_opt) -> plug_opt -- ignore the ':' from break
1709
1710 parseDynLibLoaderMode f d =
1711 case splitAt 8 f of
1712 ("deploy", "") -> d{ dynLibLoader = Deployable }
1713 ("sysdep", "") -> d{ dynLibLoader = SystemDependent }
1714 _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f))
1715
1716 setDumpPrefixForce f d = d { dumpPrefixForce = f}
1717
1718 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
1719 -- Config.hs should really use Option.
1720 setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
1721 addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
1722 addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s})
1723 addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s})
1724
1725
1726 setDepMakefile :: FilePath -> DynFlags -> DynFlags
1727 setDepMakefile f d = d { depMakefile = deOptDep f }
1728
1729 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
1730 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
1731
1732 addDepExcludeMod :: String -> DynFlags -> DynFlags
1733 addDepExcludeMod m d
1734 = d { depExcludeMods = mkModuleName (deOptDep m) : depExcludeMods d }
1735
1736 addDepSuffix :: FilePath -> DynFlags -> DynFlags
1737 addDepSuffix s d = d { depSuffixes = deOptDep s : depSuffixes d }
1738
1739 -- XXX Legacy code:
1740 -- We used to use "-optdep-flag -optdeparg", so for legacy applications
1741 -- we need to strip the "-optdep" off of the arg
1742 deOptDep :: String -> String
1743 deOptDep x = case stripPrefix "-optdep" x of
1744 Just rest -> rest
1745 Nothing -> x
1746
1747 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
1748
1749 addHaddockOpts f d = d{ haddockOptions = Just f}
1750
1751 addGhciScript f d = d{ ghciScripts = f : ghciScripts d}
1752
1753 setInteractivePrint f d = d{ interactivePrint = Just f}
1754
1755 -- -----------------------------------------------------------------------------
1756 -- Command-line options
1757
1758 -- | When invoking external tools as part of the compilation pipeline, we
1759 -- pass these a sequence of options on the command-line. Rather than
1760 -- just using a list of Strings, we use a type that allows us to distinguish
1761 -- between filepaths and 'other stuff'. The reason for this is that
1762 -- this type gives us a handle on transforming filenames, and filenames only,
1763 -- to whatever format they're expected to be on a particular platform.
1764 data Option
1765 = FileOption -- an entry that _contains_ filename(s) / filepaths.
1766 String -- a non-filepath prefix that shouldn't be
1767 -- transformed (e.g., "/out=")
1768 String -- the filepath/filename portion
1769 | Option String
1770 deriving ( Eq )
1771
1772 showOpt :: Option -> String
1773 showOpt (FileOption pre f) = pre ++ f
1774 showOpt (Option s) = s
1775
1776 -----------------------------------------------------------------------------
1777 -- Setting the optimisation level
1778
1779 updOptLevel :: Int -> DynFlags -> DynFlags
1780 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
1781 updOptLevel n dfs
1782 = dfs2{ optLevel = final_n }
1783 where
1784 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
1785 dfs1 = foldr (flip gopt_unset) dfs remove_gopts
1786 dfs2 = foldr (flip gopt_set) dfs1 extra_gopts
1787
1788 extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
1789 remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
1790
1791 -- -----------------------------------------------------------------------------
1792 -- StgToDo: abstraction of stg-to-stg passes to run.
1793
1794 data StgToDo
1795 = StgDoMassageForProfiling -- should be (next to) last
1796 -- There's also setStgVarInfo, but its absolute "lastness"
1797 -- is so critical that it is hardwired in (no flag).
1798 | D_stg_stats
1799
1800 getStgToDo :: DynFlags -> [StgToDo]
1801 getStgToDo dflags
1802 = todo2
1803 where
1804 stg_stats = gopt Opt_StgStats dflags
1805
1806 todo1 = if stg_stats then [D_stg_stats] else []
1807
1808 todo2 | WayProf `elem` ways dflags
1809 = StgDoMassageForProfiling : todo1
1810 | otherwise
1811 = todo1
1812
1813 {- **********************************************************************
1814 %* *
1815 DynFlags parser
1816 %* *
1817 %********************************************************************* -}
1818
1819 -- -----------------------------------------------------------------------------
1820 -- Parsing the dynamic flags.
1821
1822
1823 -- | Parse dynamic flags from a list of command line arguments. Returns the
1824 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
1825 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
1826 -- flags or missing arguments).
1827 parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String]
1828 -> m (DynFlags, [Located String], [Located String])
1829 -- ^ Updated 'DynFlags', left-over arguments, and
1830 -- list of warnings.
1831 parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True
1832
1833
1834 -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
1835 -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
1836 -- Used to parse flags set in a modules pragma.
1837 parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String]
1838 -> m (DynFlags, [Located String], [Located String])
1839 -- ^ Updated 'DynFlags', left-over arguments, and
1840 -- list of warnings.
1841 parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False
1842
1843
1844 -- | Parses the dynamically set flags for GHC. This is the most general form of
1845 -- the dynamic flag parser that the other methods simply wrap. It allows
1846 -- saying which flags are valid flags and indicating if we are parsing
1847 -- arguments from the command line or from a file pragma.
1848 parseDynamicFlagsFull :: MonadIO m
1849 => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against
1850 -> Bool -- ^ are the arguments from the command line?
1851 -> DynFlags -- ^ current dynamic flags
1852 -> [Located String] -- ^ arguments to parse
1853 -> m (DynFlags, [Located String], [Located String])
1854 parseDynamicFlagsFull activeFlags cmdline dflags0 args = do
1855 -- XXX Legacy support code
1856 -- We used to accept things like
1857 -- optdep-f -optdepdepend
1858 -- optdep-f -optdep depend
1859 -- optdep -f -optdepdepend
1860 -- optdep -f -optdep depend
1861 -- but the spaces trip up proper argument handling. So get rid of them.
1862 let f (L p "-optdep" : L _ x : xs) = (L p ("-optdep" ++ x)) : f xs
1863 f (x : xs) = x : f xs
1864 f xs = xs
1865 args' = f args
1866
1867 let ((leftover, errs, warns), dflags1)
1868 = runCmdLine (processArgs activeFlags args') dflags0
1869 when (not (null errs)) $ liftIO $
1870 throwGhcExceptionIO $ errorsToGhcException errs
1871
1872 -- check for disabled flags in safe haskell
1873 let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
1874 dflags3 = updateWays dflags2
1875 theWays = ways dflags3
1876
1877 unless (allowed_combination theWays) $ liftIO $
1878 throwGhcExceptionIO (CmdLineError ("combination not supported: " ++
1879 intercalate "/" (map wayDesc theWays)))
1880
1881 whenGeneratingDynamicToo dflags3 $
1882 unless (isJust (outputFile dflags3) == isJust (dynOutputFile dflags3)) $
1883 liftIO $ throwGhcExceptionIO $ CmdLineError
1884 "With -dynamic-too, must give -dyno iff giving -o"
1885
1886 let (dflags4, consistency_warnings) = makeDynFlagsConsistent dflags3
1887
1888 dflags5 <- case dllSplitFile dflags4 of
1889 Nothing -> return (dflags4 { dllSplit = Nothing })
1890 Just f ->
1891 case dllSplit dflags4 of
1892 Just _ ->
1893 -- If dllSplit is out of date then it would have
1894 -- been set to Nothing. As it's a Just, it must be
1895 -- up-to-date.
1896 return dflags4
1897 Nothing ->
1898 do xs <- liftIO $ readFile f
1899 let ss = map (Set.fromList . words) (lines xs)
1900 return $ dflags4 { dllSplit = Just ss }
1901
1902 liftIO $ setUnsafeGlobalDynFlags dflags5
1903
1904 return (dflags5, leftover, consistency_warnings ++ sh_warns ++ warns)
1905
1906 updateWays :: DynFlags -> DynFlags
1907 updateWays dflags
1908 = let theWays = sort $ nub $ ways dflags
1909 f = if WayDyn `elem` theWays then unSetGeneralFlag'
1910 else setGeneralFlag'
1911 in f Opt_Static
1912 $ dflags {
1913 ways = theWays,
1914 buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays),
1915 rtsBuildTag = mkBuildTag theWays
1916 }
1917
1918 -- | Check (and potentially disable) any extensions that aren't allowed
1919 -- in safe mode.
1920 --
1921 -- The bool is to indicate if we are parsing command line flags (false means
1922 -- file pragma). This allows us to generate better warnings.
1923 safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
1924 safeFlagCheck _ dflags | not (safeLanguageOn dflags || safeInferOn dflags)
1925 = (dflags, [])
1926
1927 -- safe or safe-infer ON
1928 safeFlagCheck cmdl dflags =
1929 case safeLanguageOn dflags of
1930 True -> (dflags', warns)
1931
1932 -- throw error if -fpackage-trust by itself with no safe haskell flag
1933 False | not cmdl && packageTrustOn dflags
1934 -> (gopt_unset dflags' Opt_PackageTrust,
1935 [L (pkgTrustOnLoc dflags') $
1936 "-fpackage-trust ignored;" ++
1937 " must be specified with a Safe Haskell flag"]
1938 )
1939
1940 False | null warns && safeInfOk
1941 -> (dflags', [])
1942
1943 | otherwise
1944 -> (dflags' { safeHaskell = Sf_None }, [])
1945 -- Have we inferred Unsafe?
1946 -- See Note [HscMain . Safe Haskell Inference]
1947 where
1948 -- TODO: Can we do better than this for inference?
1949 safeInfOk = not $ xopt Opt_OverlappingInstances dflags
1950
1951 (dflags', warns) = foldl check_method (dflags, []) unsafeFlags
1952
1953 check_method (df, warns) (str,loc,test,fix)
1954 | test df = (apFix fix df, warns ++ safeFailure (loc dflags) str)
1955 | otherwise = (df, warns)
1956
1957 apFix f = if safeInferOn dflags then id else f
1958
1959 safeFailure loc str
1960 = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring " ++ str]
1961
1962 {- **********************************************************************
1963 %* *
1964 DynFlags specifications
1965 %* *
1966 %********************************************************************* -}
1967
1968 -- | All dynamic flags option strings. These are the user facing strings for
1969 -- enabling and disabling options.
1970 allFlags :: [String]
1971 allFlags = map ('-':) $
1972 [ flagName flag | flag <- dynamic_flags ++ package_flags, ok (flagOptKind flag) ] ++
1973 map ("fno-"++) fflags ++
1974 map ("f"++) fflags ++
1975 map ("X"++) supportedExtensions
1976 where ok (PrefixPred _ _) = False
1977 ok _ = True
1978 fflags = fflags0 ++ fflags1 ++ fflags2
1979 fflags0 = [ name | (name, _, _) <- fFlags ]
1980 fflags1 = [ name | (name, _, _) <- fWarningFlags ]
1981 fflags2 = [ name | (name, _, _) <- fLangFlags ]
1982
1983 {-
1984 - Below we export user facing symbols for GHC dynamic flags for use with the
1985 - GHC API.
1986 -}
1987
1988 -- All dynamic flags present in GHC.
1989 flagsAll :: [Flag (CmdLineP DynFlags)]
1990 flagsAll = package_flags ++ dynamic_flags
1991
1992 -- All dynamic flags, minus package flags, present in GHC.
1993 flagsDynamic :: [Flag (CmdLineP DynFlags)]
1994 flagsDynamic = dynamic_flags
1995
1996 -- ALl package flags present in GHC.
1997 flagsPackage :: [Flag (CmdLineP DynFlags)]
1998 flagsPackage = package_flags
1999
2000 --------------- The main flags themselves ------------------
2001 dynamic_flags :: [Flag (CmdLineP DynFlags)]
2002 dynamic_flags = [
2003 Flag "n" (NoArg (addWarn "The -n flag is deprecated and no longer has any effect"))
2004 , Flag "cpp" (NoArg (setExtensionFlag Opt_Cpp))
2005 , Flag "F" (NoArg (setGeneralFlag Opt_Pp))
2006 , Flag "#include"
2007 (HasArg (\s -> do addCmdlineHCInclude s
2008 addWarn "-#include and INCLUDE pragmas are deprecated: They no longer have any effect"))
2009 , Flag "v" (OptIntSuffix setVerbosity)
2010
2011 ------- ways --------------------------------------------------------
2012 , Flag "prof" (NoArg (addWay WayProf))
2013 , Flag "eventlog" (NoArg (addWay WayEventLog))
2014 , Flag "parallel" (NoArg (addWay WayPar))
2015 , Flag "gransim" (NoArg (addWay WayGran))
2016 , Flag "smp" (NoArg (addWay WayThreaded >> deprecate "Use -threaded instead"))
2017 , Flag "debug" (NoArg (addWay WayDebug))
2018 , Flag "ndp" (NoArg (addWay WayNDP))
2019 , Flag "threaded" (NoArg (addWay WayThreaded))
2020
2021 , Flag "ticky" (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
2022
2023 -- -ticky enables ticky-ticky code generation, and also implies -debug which
2024 -- is required to get the RTS ticky support.
2025
2026 ----- Linker --------------------------------------------------------
2027 , Flag "static" (NoArg removeWayDyn)
2028 , Flag "dynamic" (NoArg (addWay WayDyn))
2029 -- ignored for compat w/ gcc:
2030 , Flag "rdynamic" (NoArg (return ()))
2031 , Flag "relative-dynlib-paths" (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
2032
2033 ------- Specific phases --------------------------------------------
2034 -- need to appear before -pgmL to be parsed as LLVM flags.
2035 , Flag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
2036 , Flag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
2037 , Flag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
2038 , Flag "pgmP" (hasArg setPgmP)
2039 , Flag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
2040 , Flag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
2041 , Flag "pgmm" (HasArg (\_ -> addWarn "The -pgmm flag does nothing; it will be removed in a future GHC release"))
2042 , Flag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
2043 , Flag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
2044 , Flag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
2045 , Flag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
2046 , Flag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
2047
2048 -- need to appear before -optl/-opta to be parsed as LLVM flags.
2049 , Flag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
2050 , Flag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
2051 , Flag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
2052 , Flag "optP" (hasArg addOptP)
2053 , Flag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
2054 , Flag "optc" (hasArg addOptc)
2055 , Flag "optm" (HasArg (\_ -> addWarn "The -optm flag does nothing; it will be removed in a future GHC release"))
2056 , Flag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
2057 , Flag "optl" (hasArg addOptl)
2058 , Flag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
2059
2060 , Flag "split-objs"
2061 (NoArg (if can_split
2062 then setGeneralFlag Opt_SplitObjs
2063 else addWarn "ignoring -fsplit-objs"))
2064
2065 -------- ghc -M -----------------------------------------------------
2066 , Flag "dep-suffix" (hasArg addDepSuffix)
2067 , Flag "optdep-s" (hasArgDF addDepSuffix "Use -dep-suffix instead")
2068 , Flag "dep-makefile" (hasArg setDepMakefile)
2069 , Flag "optdep-f" (hasArgDF setDepMakefile "Use -dep-makefile instead")
2070 , Flag "optdep-w" (NoArg (deprecate "doesn't do anything"))
2071 , Flag "include-pkg-deps" (noArg (setDepIncludePkgDeps True))
2072 , Flag "optdep--include-prelude" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
2073 , Flag "optdep--include-pkg-deps" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
2074 , Flag "exclude-module" (hasArg addDepExcludeMod)
2075 , Flag "optdep--exclude-module" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
2076 , Flag "optdep-x" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
2077
2078 -------- Linking ----------------------------------------------------
2079 , Flag "no-link" (noArg (\d -> d{ ghcLink=NoLink }))
2080 , Flag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib }))
2081 , Flag "dynload" (hasArg parseDynLibLoaderMode)
2082 , Flag "dylib-install-name" (hasArg setDylibInstallName)
2083 -- -dll-split is an internal flag, used only during the GHC build
2084 , Flag "dll-split" (hasArg (\f d -> d{ dllSplitFile = Just f, dllSplit = Nothing }))
2085
2086 ------- Libraries ---------------------------------------------------
2087 , Flag "L" (Prefix addLibraryPath)
2088 , Flag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
2089
2090 ------- Frameworks --------------------------------------------------
2091 -- -framework-path should really be -F ...
2092 , Flag "framework-path" (HasArg addFrameworkPath)
2093 , Flag "framework" (hasArg addCmdlineFramework)
2094
2095 ------- Output Redirection ------------------------------------------
2096 , Flag "odir" (hasArg setObjectDir)
2097 , Flag "o" (sepArg (setOutputFile . Just))
2098 , Flag "dyno" (sepArg (setDynOutputFile . Just))
2099 , Flag "ohi" (hasArg (setOutputHi . Just ))
2100 , Flag "osuf" (hasArg setObjectSuf)
2101 , Flag "dynosuf" (hasArg setDynObjectSuf)
2102 , Flag "hcsuf" (hasArg setHcSuf)
2103 , Flag "hisuf" (hasArg setHiSuf)
2104 , Flag "dynhisuf" (hasArg setDynHiSuf)
2105 , Flag "hidir" (hasArg setHiDir)
2106 , Flag "tmpdir" (hasArg setTmpDir)
2107 , Flag "stubdir" (hasArg setStubDir)
2108 , Flag "dumpdir" (hasArg setDumpDir)
2109 , Flag "outputdir" (hasArg setOutputDir)
2110 , Flag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just))
2111
2112 , Flag "dynamic-too" (NoArg (setGeneralFlag Opt_BuildDynamicToo))
2113
2114 ------- Keeping temporary files -------------------------------------
2115 -- These can be singular (think ghc -c) or plural (think ghc --make)
2116 , Flag "keep-hc-file" (NoArg (setGeneralFlag Opt_KeepHcFiles))
2117 , Flag "keep-hc-files" (NoArg (setGeneralFlag Opt_KeepHcFiles))
2118 , Flag "keep-s-file" (NoArg (setGeneralFlag Opt_KeepSFiles))
2119 , Flag "keep-s-files" (NoArg (setGeneralFlag Opt_KeepSFiles))
2120 , Flag "keep-raw-s-file" (NoArg (addWarn "The -keep-raw-s-file flag does nothing; it will be removed in a future GHC release"))
2121 , Flag "keep-raw-s-files" (NoArg (addWarn "The -keep-raw-s-files flag does nothing; it will be removed in a future GHC release"))
2122 , Flag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm
2123 setGeneralFlag Opt_KeepLlvmFiles))
2124 , Flag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm
2125 setGeneralFlag Opt_KeepLlvmFiles))
2126 -- This only makes sense as plural
2127 , Flag "keep-tmp-files" (NoArg (setGeneralFlag Opt_KeepTmpFiles))
2128
2129 ------- Miscellaneous ----------------------------------------------
2130 , Flag "no-auto-link-packages" (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
2131 , Flag "no-hs-main" (NoArg (setGeneralFlag Opt_NoHsMain))
2132 , Flag "with-rtsopts" (HasArg setRtsOpts)
2133 , Flag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll))
2134 , Flag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll))
2135 , Flag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
2136 , Flag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone))
2137 , Flag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone))
2138 , Flag "main-is" (SepArg setMainIs)
2139 , Flag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
2140 , Flag "haddock-opts" (hasArg addHaddockOpts)
2141 , Flag "hpcdir" (SepArg setOptHpcDir)
2142 , Flag "ghci-script" (hasArg addGhciScript)
2143 , Flag "interactive-print" (hasArg setInteractivePrint)
2144 , Flag "ticky-allocd" (NoArg (setGeneralFlag Opt_Ticky_Allocd))
2145 , Flag "ticky-LNE" (NoArg (setGeneralFlag Opt_Ticky_LNE))
2146 , Flag "ticky-dyn-thunk" (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
2147 ------- recompilation checker --------------------------------------
2148 , Flag "recomp" (NoArg (do unSetGeneralFlag Opt_ForceRecomp
2149 deprecate "Use -fno-force-recomp instead"))
2150 , Flag "no-recomp" (NoArg (do setGeneralFlag Opt_ForceRecomp
2151 deprecate "Use -fforce-recomp instead"))
2152
2153 ------ HsCpp opts ---------------------------------------------------
2154 , Flag "D" (AnySuffix (upd . addOptP))
2155 , Flag "U" (AnySuffix (upd . addOptP))
2156
2157 ------- Include/Import Paths ----------------------------------------
2158 , Flag "I" (Prefix addIncludePath)
2159 , Flag "i" (OptPrefix addImportPath)
2160
2161 ------ Output style options -----------------------------------------
2162 , Flag "dppr-user-length" (intSuffix (\n d -> d{ pprUserLength = n }))
2163 , Flag "dppr-cols" (intSuffix (\n d -> d{ pprCols = n }))
2164 , Flag "dtrace-level" (intSuffix (\n d -> d{ traceLevel = n }))
2165 -- Suppress all that is suppressable in core dumps.
2166 -- Except for uniques, as some simplifier phases introduce new varibles that
2167 -- have otherwise identical names.
2168 , Flag "dsuppress-all" (NoArg $ do setGeneralFlag Opt_SuppressCoercions
2169 setGeneralFlag Opt_SuppressVarKinds
2170 setGeneralFlag Opt_SuppressModulePrefixes
2171 setGeneralFlag Opt_SuppressTypeApplications
2172 setGeneralFlag Opt_SuppressIdInfo
2173 setGeneralFlag Opt_SuppressTypeSignatures)
2174
2175 ------ Debugging ----------------------------------------------------
2176 , Flag "dstg-stats" (NoArg (setGeneralFlag Opt_StgStats))
2177
2178 , Flag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm)
2179 , Flag "ddump-cmm-raw" (setDumpFlag Opt_D_dump_cmm_raw)
2180 , Flag "ddump-cmm-cfg" (setDumpFlag Opt_D_dump_cmm_cfg)
2181 , Flag "ddump-cmm-cbe" (setDumpFlag Opt_D_dump_cmm_cbe)
2182 , Flag "ddump-cmm-proc" (setDumpFlag Opt_D_dump_cmm_proc)
2183 , Flag "ddump-cmm-rewrite" (setDumpFlag Opt_D_dump_cmm_rewrite)
2184 , Flag "ddump-cmm-sp" (setDumpFlag Opt_D_dump_cmm_sp)
2185 , Flag "ddump-cmm-procmap" (setDumpFlag Opt_D_dump_cmm_procmap)
2186 , Flag "ddump-cmm-split" (setDumpFlag Opt_D_dump_cmm_split)
2187 , Flag "ddump-cmm-info" (setDumpFlag Opt_D_dump_cmm_info)
2188 , Flag "ddump-cmm-cps" (setDumpFlag Opt_D_dump_cmm_cps)
2189 , Flag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats)
2190 , Flag "ddump-asm" (setDumpFlag Opt_D_dump_asm)
2191 , Flag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native)
2192 , Flag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness)
2193 , Flag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc)
2194 , Flag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts)
2195 , Flag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages)
2196 , Flag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats)
2197 , Flag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded)
2198 , Flag "ddump-llvm" (NoArg (do setObjTarget HscLlvm
2199 setDumpFlag' Opt_D_dump_llvm))
2200 , Flag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv)
2201 , Flag "ddump-ds" (setDumpFlag Opt_D_dump_ds)
2202 , Flag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign)
2203 , Flag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings)
2204 , Flag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings)
2205 , Flag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites)
2206 , Flag "ddump-simpl-trace" (setDumpFlag Opt_D_dump_simpl_trace)
2207 , Flag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal)
2208 , Flag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed)
2209 , Flag "ddump-rn" (setDumpFlag Opt_D_dump_rn)
2210 , Flag "ddump-core-pipeline" (setDumpFlag Opt_D_dump_core_pipeline)
2211 , Flag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl)
2212 , Flag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations)
2213 , Flag "ddump-simpl-phases" (OptPrefix setDumpSimplPhases)
2214 , Flag "ddump-spec" (setDumpFlag Opt_D_dump_spec)
2215 , Flag "ddump-prep" (setDumpFlag Opt_D_dump_prep)
2216 , Flag "ddump-stg" (setDumpFlag Opt_D_dump_stg)
2217 , Flag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal)
2218 , Flag "ddump-tc" (setDumpFlag Opt_D_dump_tc)
2219 , Flag "ddump-types" (setDumpFlag Opt_D_dump_types)
2220 , Flag "ddump-rules" (setDumpFlag Opt_D_dump_rules)
2221 , Flag "ddump-cse" (setDumpFlag Opt_D_dump_cse)
2222 , Flag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper)
2223 , Flag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace)
2224 , Flag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace)
2225 , Flag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace)
2226 , Flag "ddump-tc-trace" (setDumpFlag Opt_D_dump_tc_trace)
2227 , Flag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace)
2228 , Flag "ddump-splices" (setDumpFlag Opt_D_dump_splices)
2229 , Flag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats)
2230 , Flag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm)
2231 , Flag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats)
2232 , Flag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs)
2233 , Flag "dsource-stats" (setDumpFlag Opt_D_source_stats)
2234 , Flag "dverbose-core2core" (NoArg (do setVerbosity (Just 2)
2235 setVerboseCore2Core))
2236 , Flag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg)
2237 , Flag "ddump-hi" (setDumpFlag Opt_D_dump_hi)
2238 , Flag "ddump-minimal-imports" (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
2239 , Flag "ddump-vect" (setDumpFlag Opt_D_dump_vect)
2240 , Flag "ddump-hpc" (setDumpFlag Opt_D_dump_ticked) -- back compat
2241 , Flag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked)
2242 , Flag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles)
2243 , Flag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning)
2244 , Flag "ddump-to-file" (NoArg (setGeneralFlag Opt_DumpToFile))
2245 , Flag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs)
2246 , Flag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti)
2247 , Flag "dcore-lint" (NoArg (setGeneralFlag Opt_DoCoreLinting))
2248 , Flag "dstg-lint" (NoArg (setGeneralFlag Opt_DoStgLinting))
2249 , Flag "dcmm-lint" (NoArg (setGeneralFlag Opt_DoCmmLinting))
2250 , Flag "dasm-lint" (NoArg (setGeneralFlag Opt_DoAsmLinting))
2251 , Flag "dshow-passes" (NoArg (do forceRecompile
2252 setVerbosity $ Just 2))
2253 , Flag "dfaststring-stats" (NoArg (setGeneralFlag Opt_D_faststring_stats))
2254 , Flag "dno-llvm-mangler" (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
2255
2256 ------ Machine dependant (-m<blah>) stuff ---------------------------
2257
2258 , Flag "monly-2-regs" (NoArg (addWarn "The -monly-2-regs flag does nothing; it will be removed in a future GHC release"))
2259 , Flag "monly-3-regs" (NoArg (addWarn "The -monly-3-regs flag does nothing; it will be removed in a future GHC release"))
2260 , Flag "monly-4-regs" (NoArg (addWarn "The -monly-4-regs flag does nothing; it will be removed in a future GHC release"))
2261 , Flag "msse" (versionSuffix (\maj min d -> d{ sseVersion = Just (maj, min) }))
2262
2263 ------ Warning opts -------------------------------------------------
2264 , Flag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
2265 , Flag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError))
2266 , Flag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError))
2267 , Flag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts))
2268 , Flag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty})
2269 deprecate "Use -w instead"))
2270 , Flag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty})))
2271
2272 ------ Plugin flags ------------------------------------------------
2273 , Flag "fplugin-opt" (hasArg addPluginModuleNameOption)
2274 , Flag "fplugin" (hasArg addPluginModuleName)
2275
2276 ------ Optimisation flags ------------------------------------------
2277 , Flag "O" (noArgM (setOptLevel 1))
2278 , Flag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead"
2279 setOptLevel 0 dflags))
2280 , Flag "Odph" (noArgM setDPHOpt)
2281 , Flag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1)))
2282 -- If the number is missing, use 1
2283
2284 , Flag "fsimplifier-phases" (intSuffix (\n d -> d{ simplPhases = n }))
2285 , Flag "fmax-simplifier-iterations" (intSuffix (\n d -> d{ maxSimplIterations = n }))
2286 , Flag "fsimpl-tick-factor" (intSuffix (\n d -> d{ simplTickFactor = n }))
2287 , Flag "fspec-constr-threshold" (intSuffix (\n d -> d{ specConstrThreshold = Just n }))
2288 , Flag "fno-spec-constr-threshold" (noArg (\d -> d{ specConstrThreshold = Nothing }))
2289 , Flag "fspec-constr-count" (intSuffix (\n d -> d{ specConstrCount = Just n }))
2290 , Flag "fno-spec-constr-count" (noArg (\d -> d{ specConstrCount = Nothing }))
2291 , Flag "fspec-constr-recursive" (intSuffix (\n d -> d{ specConstrRecursive = n }))
2292 , Flag "fliberate-case-threshold" (intSuffix (\n d -> d{ liberateCaseThreshold = Just n }))
2293 , Flag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing }))
2294 , Flag "frule-check" (sepArg (\s d -> d{ ruleCheck = Just s }))
2295 , Flag "fcontext-stack" (intSuffix (\n d -> d{ ctxtStkDepth = n }))
2296 , Flag "fstrictness-before" (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d }))
2297 , Flag "ffloat-lam-args" (intSuffix (\n d -> d{ floatLamArgs = Just n }))
2298 , Flag "ffloat-all-lams" (noArg (\d -> d{ floatLamArgs = Nothing }))
2299 , Flag "fhistory-size" (intSuffix (\n d -> d{ historySize = n }))
2300
2301 , Flag "funfolding-creation-threshold" (intSuffix (\n d -> d {ufCreationThreshold = n}))
2302 , Flag "funfolding-use-threshold" (intSuffix (\n d -> d {ufUseThreshold = n}))
2303 , Flag "funfolding-fun-discount" (intSuffix (\n d -> d {ufFunAppDiscount = n}))
2304 , Flag "funfolding-dict-discount" (intSuffix (\n d -> d {ufDictDiscount = n}))
2305 , Flag "funfolding-keeness-factor" (floatSuffix (\n d -> d {ufKeenessFactor = n}))
2306
2307 , Flag "fmax-worker-args" (intSuffix (\n d -> d {maxWorkerArgs = n}))
2308
2309 , Flag "fghci-hist-size" (intSuffix (\n d -> d {ghciHistSize = n}))
2310
2311 ------ Profiling ----------------------------------------------------
2312
2313 -- OLD profiling flags
2314 , Flag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } ))
2315 , Flag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } ))
2316 , Flag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } ))
2317 , Flag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
2318 , Flag "caf-all" (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
2319 , Flag "no-caf-all" (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
2320
2321 -- NEW profiling flags
2322 , Flag "fprof-auto" (noArg (\d -> d { profAuto = ProfAutoAll } ))
2323 , Flag "fprof-auto-top" (noArg (\d -> d { profAuto = ProfAutoTop } ))
2324 , Flag "fprof-auto-exported" (noArg (\d -> d { profAuto = ProfAutoExports } ))
2325 , Flag "fprof-auto-calls" (noArg (\d -> d { profAuto = ProfAutoCalls } ))
2326 , Flag "fno-prof-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
2327
2328 ------ Compiler flags -----------------------------------------------
2329
2330 , Flag "fasm" (NoArg (setObjTarget HscAsm))
2331 , Flag "fvia-c" (NoArg
2332 (addWarn "The -fvia-c flag does nothing; it will be removed in a future GHC release"))
2333 , Flag "fvia-C" (NoArg
2334 (addWarn "The -fvia-C flag does nothing; it will be removed in a future GHC release"))
2335 , Flag "fllvm" (NoArg (setObjTarget HscLlvm))
2336
2337 , Flag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink }
2338 setTarget HscNothing))
2339 , Flag "fbyte-code" (NoArg (setTarget HscInterpreted))
2340 , Flag "fobject-code" (NoArg (setTargetWithPlatform defaultHscTarget))
2341 , Flag "fglasgow-exts" (NoArg (enableGlasgowExts >> deprecate "Use individual extensions instead"))
2342 , Flag "fno-glasgow-exts" (NoArg (disableGlasgowExts >> deprecate "Use individual extensions instead"))
2343
2344 ------ Safe Haskell flags -------------------------------------------
2345 , Flag "fpackage-trust" (NoArg setPackageTrust)
2346 , Flag "fno-safe-infer" (NoArg (setSafeHaskell Sf_None))
2347 , Flag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
2348 , Flag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
2349 ]
2350 ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlags
2351 ++ map (mkFlag turnOff "no-" unSetGeneralFlag) negatableFlags
2352 ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlags
2353 ++ map (mkFlag turnOff "dno-" unSetGeneralFlag) dFlags
2354 ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlags
2355 ++ map (mkFlag turnOff "fno-" unSetGeneralFlag) fFlags
2356 ++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags
2357 ++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags
2358 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags
2359 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags
2360 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags
2361 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags
2362 ++ map (mkFlag turnOn "X" setLanguage) languageFlags
2363 ++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags
2364 ++ [ Flag "XGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support."))
2365 , Flag "XNoGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support.")) ]
2366
2367 package_flags :: [Flag (CmdLineP DynFlags)]
2368 package_flags = [
2369 ------- Packages ----------------------------------------------------
2370 Flag "package-db" (HasArg (addPkgConfRef . PkgConfFile))
2371 , Flag "clear-package-db" (NoArg clearPkgConf)
2372 , Flag "no-global-package-db" (NoArg removeGlobalPkgConf)
2373 , Flag "no-user-package-db" (NoArg removeUserPkgConf)
2374 , Flag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf))
2375 , Flag "user-package-db" (NoArg (addPkgConfRef UserPkgConf))
2376
2377 -- backwards compat with GHC<=7.4 :
2378 , Flag "package-conf" (HasArg $ \path -> do
2379 addPkgConfRef (PkgConfFile path)
2380 deprecate "Use -package-db instead")
2381 , Flag "no-user-package-conf" (NoArg $ do
2382 removeUserPkgConf
2383 deprecate "Use -no-user-package-db instead")
2384
2385 , Flag "package-name" (hasArg setPackageName)
2386 , Flag "package-id" (HasArg exposePackageId)
2387 , Flag "package" (HasArg exposePackage)
2388 , Flag "hide-package" (HasArg hidePackage)
2389 , Flag "hide-all-packages" (NoArg (setGeneralFlag Opt_HideAllPackages))
2390 , Flag "ignore-package" (HasArg ignorePackage)
2391 , Flag "syslib" (HasArg (\s -> do exposePackage s
2392 deprecate "Use -package instead"))
2393 , Flag "distrust-all-packages" (NoArg (setGeneralFlag Opt_DistrustAllPackages))
2394 , Flag "trust" (HasArg trustPackage)
2395 , Flag "distrust" (HasArg distrustPackage)
2396 ]
2397
2398 type TurnOnFlag = Bool -- True <=> we are turning the flag on
2399 -- False <=> we are turning the flag off
2400 turnOn :: TurnOnFlag; turnOn = True
2401 turnOff :: TurnOnFlag; turnOff = False
2402
2403 type FlagSpec flag
2404 = ( String -- Flag in string form
2405 , flag -- Flag in internal form
2406 , TurnOnFlag -> DynP ()) -- Extra action to run when the flag is found
2407 -- Typically, emit a warning or error
2408
2409 mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
2410 -> String -- ^ The flag prefix
2411 -> (flag -> DynP ()) -- ^ What to do when the flag is found
2412 -> FlagSpec flag -- ^ Specification of this particular flag
2413 -> Flag (CmdLineP DynFlags)
2414 mkFlag turn_on flagPrefix f (name, flag, extra_action)
2415 = Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on))
2416
2417 deprecatedForExtension :: String -> TurnOnFlag -> DynP ()
2418 deprecatedForExtension lang turn_on
2419 = deprecate ("use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead")
2420 where
2421 flag | turn_on = lang
2422 | otherwise = "No"++lang
2423
2424 useInstead :: String -> TurnOnFlag -> DynP ()
2425 useInstead flag turn_on
2426 = deprecate ("Use -f" ++ no ++ flag ++ " instead")
2427 where
2428 no = if turn_on then "" else "no-"
2429
2430 nop :: TurnOnFlag -> DynP ()
2431 nop _ = return ()
2432
2433 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2434 fWarningFlags :: [FlagSpec WarningFlag]
2435 fWarningFlags = [
2436 ( "warn-dodgy-foreign-imports", Opt_WarnDodgyForeignImports, nop ),
2437 ( "warn-dodgy-exports", Opt_WarnDodgyExports, nop ),
2438 ( "warn-dodgy-imports", Opt_WarnDodgyImports, nop ),
2439 ( "warn-overflowed-literals", Opt_WarnOverflowedLiterals, nop ),
2440 ( "warn-empty-enumerations", Opt_WarnEmptyEnumerations, nop ),
2441 ( "warn-duplicate-exports", Opt_WarnDuplicateExports, nop ),
2442 ( "warn-duplicate-constraints", Opt_WarnDuplicateConstraints, nop ),
2443 ( "warn-hi-shadowing", Opt_WarnHiShadows, nop ),
2444 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude, nop ),
2445 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns, nop ),
2446 ( "warn-incomplete-uni-patterns", Opt_WarnIncompleteUniPatterns, nop ),
2447 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd, nop ),
2448 ( "warn-missing-fields", Opt_WarnMissingFields, nop ),
2449 ( "warn-missing-import-lists", Opt_WarnMissingImportList, nop ),
2450 ( "warn-missing-methods", Opt_WarnMissingMethods, nop ),
2451 ( "warn-missing-signatures", Opt_WarnMissingSigs, nop ),
2452 ( "warn-missing-local-sigs", Opt_WarnMissingLocalSigs, nop ),
2453 ( "warn-name-shadowing", Opt_WarnNameShadowing, nop ),
2454 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns, nop ),
2455 ( "warn-type-defaults", Opt_WarnTypeDefaults, nop ),
2456 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism, nop ),
2457 ( "warn-unused-binds", Opt_WarnUnusedBinds, nop ),
2458 ( "warn-unused-imports", Opt_WarnUnusedImports, nop ),
2459 ( "warn-unused-matches", Opt_WarnUnusedMatches, nop ),
2460 ( "warn-warnings-deprecations", Opt_WarnWarningsDeprecations, nop ),
2461 ( "warn-deprecations", Opt_WarnWarningsDeprecations, nop ),
2462 ( "warn-deprecated-flags", Opt_WarnDeprecatedFlags, nop ),
2463 ( "warn-orphans", Opt_WarnOrphans, nop ),
2464 ( "warn-identities", Opt_WarnIdentities, nop ),
2465 ( "warn-auto-orphans", Opt_WarnAutoOrphans, nop ),
2466 ( "warn-tabs", Opt_WarnTabs, nop ),
2467 ( "warn-unrecognised-pragmas", Opt_WarnUnrecognisedPragmas, nop ),
2468 ( "warn-lazy-unlifted-bindings", Opt_WarnLazyUnliftedBindings, nop ),
2469 ( "warn-unused-do-bind", Opt_WarnUnusedDoBind, nop ),
2470 ( "warn-wrong-do-bind", Opt_WarnWrongDoBind, nop ),
2471 ( "warn-alternative-layout-rule-transitional", Opt_WarnAlternativeLayoutRuleTransitional, nop ),
2472 ( "warn-unsafe", Opt_WarnUnsafe, setWarnUnsafe ),
2473 ( "warn-safe", Opt_WarnSafe, setWarnSafe ),
2474 ( "warn-pointless-pragmas", Opt_WarnPointlessPragmas, nop ),
2475 ( "warn-unsupported-calling-conventions", Opt_WarnUnsupportedCallingConventions, nop ),
2476 ( "warn-inline-rule-shadowing", Opt_WarnInlineRuleShadowing, nop ),
2477 ( "warn-unsupported-llvm-version", Opt_WarnUnsupportedLlvmVersion, nop ),
2478 ( "warn-typeable-instances", Opt_WarnTypeableInstances, nop ) ]
2479
2480 -- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@
2481 negatableFlags :: [FlagSpec GeneralFlag]
2482 negatableFlags = [
2483 ( "ignore-dot-ghci", Opt_IgnoreDotGhci, nop ) ]
2484
2485 -- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@
2486 dFlags :: [FlagSpec GeneralFlag]
2487 dFlags = [
2488 ( "suppress-coercions", Opt_SuppressCoercions, nop),
2489 ( "suppress-var-kinds", Opt_SuppressVarKinds, nop),
2490 ( "suppress-module-prefixes", Opt_SuppressModulePrefixes, nop),
2491 ( "suppress-type-applications", Opt_SuppressTypeApplications, nop),
2492 ( "suppress-idinfo", Opt_SuppressIdInfo, nop),
2493 ( "suppress-type-signatures", Opt_SuppressTypeSignatures, nop),
2494 ( "suppress-uniques", Opt_SuppressUniques, nop),
2495 ( "ppr-case-as-let", Opt_PprCaseAsLet, nop)]
2496
2497 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2498 fFlags :: [FlagSpec GeneralFlag]
2499 fFlags = [
2500 ( "error-spans", Opt_ErrorSpans, nop ),
2501 ( "print-explicit-foralls", Opt_PrintExplicitForalls, nop ),
2502 ( "strictness", Opt_Strictness, nop ),
2503 ( "specialise", Opt_Specialise, nop ),
2504 ( "float-in", Opt_FloatIn, nop ),
2505 ( "static-argument-transformation", Opt_StaticArgumentTransformation, nop ),
2506 ( "full-laziness", Opt_FullLaziness, nop ),
2507 ( "liberate-case", Opt_LiberateCase, nop ),
2508 ( "spec-constr", Opt_SpecConstr, nop ),
2509 ( "cse", Opt_CSE, nop ),
2510 ( "pedantic-bottoms", Opt_PedanticBottoms, nop ),
2511 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas, nop ),
2512 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas, nop ),
2513 ( "expose-all-unfoldings", Opt_ExposeAllUnfoldings, nop ),
2514 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion, nop ),
2515 ( "ignore-asserts", Opt_IgnoreAsserts, nop ),
2516 ( "do-eta-reduction", Opt_DoEtaReduction, nop ),
2517 ( "case-merge", Opt_CaseMerge, nop ),
2518 ( "unbox-strict-fields", Opt_UnboxStrictFields, nop ),
2519 ( "unbox-small-strict-fields", Opt_UnboxSmallStrictFields, nop ),
2520 ( "dicts-cheap", Opt_DictsCheap, nop ),
2521 ( "excess-precision", Opt_ExcessPrecision, nop ),
2522 ( "eager-blackholing", Opt_EagerBlackHoling, nop ),
2523 ( "print-bind-result", Opt_PrintBindResult, nop ),
2524 ( "force-recomp", Opt_ForceRecomp, nop ),
2525 ( "hpc-no-auto", Opt_Hpc_No_Auto, nop ),
2526 ( "rewrite-rules", Opt_EnableRewriteRules, useInstead "enable-rewrite-rules" ),
2527 ( "enable-rewrite-rules", Opt_EnableRewriteRules, nop ),
2528 ( "break-on-exception", Opt_BreakOnException, nop ),
2529 ( "break-on-error", Opt_BreakOnError, nop ),
2530 ( "print-evld-with-show", Opt_PrintEvldWithShow, nop ),
2531 ( "print-bind-contents", Opt_PrintBindContents, nop ),
2532 ( "run-cps", Opt_RunCPS, nop ),
2533 ( "run-cpsz", Opt_RunCPSZ, nop ),
2534 ( "vectorise", Opt_Vectorise, nop ),
2535 ( "vectorisation-avoidance", Opt_VectorisationAvoidance, nop ),
2536 ( "regs-graph", Opt_RegsGraph, nop ),
2537 ( "regs-iterative", Opt_RegsIterative, nop ),
2538 ( "llvm-tbaa", Opt_LlvmTBAA, nop), -- hidden flag
2539 ( "irrefutable-tuples", Opt_IrrefutableTuples, nop ),
2540 ( "cmm-sink", Opt_CmmSink, nop ),
2541 ( "cmm-elim-common-blocks", Opt_CmmElimCommonBlocks, nop ),
2542 ( "omit-yields", Opt_OmitYields, nop ),
2543 ( "simple-list-literals", Opt_SimpleListLiterals, nop ),
2544 ( "fun-to-thunk", Opt_FunToThunk, nop ),
2545 ( "gen-manifest", Opt_GenManifest, nop ),
2546 ( "embed-manifest", Opt_EmbedManifest, nop ),
2547 ( "ext-core", Opt_EmitExternalCore, nop ),
2548 ( "shared-implib", Opt_SharedImplib, nop ),
2549 ( "ghci-sandbox", Opt_GhciSandbox, nop ),
2550 ( "ghci-history", Opt_GhciHistory, nop ),
2551 ( "helpful-errors", Opt_HelpfulErrors, nop ),
2552 ( "defer-type-errors", Opt_DeferTypeErrors, nop ),
2553 ( "building-cabal-package", Opt_BuildingCabalPackage, nop ),
2554 ( "implicit-import-qualified", Opt_ImplicitImportQualified, nop ),
2555 ( "prof-count-entries", Opt_ProfCountEntries, nop ),
2556 ( "prof-cafs", Opt_AutoSccsOnIndividualCafs, nop ),
2557 ( "hpc", Opt_Hpc, nop ),
2558 ( "pre-inlining", Opt_SimplPreInlining, nop ),
2559 ( "flat-cache", Opt_FlatCache, nop ),
2560 ( "use-rpaths", Opt_RPath, nop ),
2561 ( "kill-absence", Opt_KillAbsence, nop),
2562 ( "kill-one-shot", Opt_KillOneShot, nop)
2563 ]
2564
2565 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2566 fLangFlags :: [FlagSpec ExtensionFlag]
2567 fLangFlags = [
2568 ( "th", Opt_TemplateHaskell,
2569 \on -> deprecatedForExtension "TemplateHaskell" on
2570 >> checkTemplateHaskellOk on ),
2571 ( "fi", Opt_ForeignFunctionInterface,
2572 deprecatedForExtension "ForeignFunctionInterface" ),
2573 ( "ffi", Opt_ForeignFunctionInterface,
2574 deprecatedForExtension "ForeignFunctionInterface" ),
2575 ( "arrows", Opt_Arrows,
2576 deprecatedForExtension "Arrows" ),
2577 ( "implicit-prelude", Opt_ImplicitPrelude,
2578 deprecatedForExtension "ImplicitPrelude" ),
2579 ( "bang-patterns", Opt_BangPatterns,
2580 deprecatedForExtension "BangPatterns" ),
2581 ( "monomorphism-restriction", Opt_MonomorphismRestriction,
2582 deprecatedForExtension "MonomorphismRestriction" ),
2583 ( "mono-pat-binds", Opt_MonoPatBinds,
2584 deprecatedForExtension "MonoPatBinds" ),
2585 ( "extended-default-rules", Opt_ExtendedDefaultRules,
2586 deprecatedForExtension "ExtendedDefaultRules" ),
2587 ( "implicit-params", Opt_ImplicitParams,
2588 deprecatedForExtension "ImplicitParams" ),
2589 ( "scoped-type-variables", Opt_ScopedTypeVariables,
2590 deprecatedForExtension "ScopedTypeVariables" ),
2591 ( "parr", Opt_ParallelArrays,
2592 deprecatedForExtension "ParallelArrays" ),
2593 ( "PArr", Opt_ParallelArrays,
2594 deprecatedForExtension "ParallelArrays" ),
2595 ( "allow-overlapping-instances", Opt_OverlappingInstances,
2596 deprecatedForExtension "OverlappingInstances" ),
2597 ( "allow-undecidable-instances", Opt_UndecidableInstances,
2598 deprecatedForExtension "UndecidableInstances" ),
2599 ( "allow-incoherent-instances", Opt_IncoherentInstances,
2600 deprecatedForExtension "IncoherentInstances" )
2601 ]
2602
2603 supportedLanguages :: [String]
2604 supportedLanguages = [ name | (name, _, _) <- languageFlags ]
2605
2606 supportedLanguageOverlays :: [String]
2607 supportedLanguageOverlays = [ name | (name, _, _) <- safeHaskellFlags ]
2608
2609 supportedExtensions :: [String]
2610 supportedExtensions = [ name' | (name, _, _) <- xFlags, name' <- [name, "No" ++ name] ]
2611
2612 supportedLanguagesAndExtensions :: [String]
2613 supportedLanguagesAndExtensions =
2614 supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions
2615
2616 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
2617 languageFlags :: [FlagSpec Language]
2618 languageFlags = [
2619 ( "Haskell98", Haskell98, nop ),
2620 ( "Haskell2010", Haskell2010, nop )
2621 ]
2622
2623 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
2624 -- They are used to place hard requirements on what GHC Haskell language
2625 -- features can be used.
2626 safeHaskellFlags :: [FlagSpec SafeHaskellMode]
2627 safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe]
2628 where mkF flag = (show flag, flag, nop)
2629
2630 -- | These -X<blah> flags can all be reversed with -XNo<blah>
2631 xFlags :: [FlagSpec ExtensionFlag]
2632 xFlags = [
2633 ( "CPP", Opt_Cpp, nop ),
2634 ( "PostfixOperators", Opt_PostfixOperators, nop ),
2635 ( "TupleSections", Opt_TupleSections, nop ),
2636 ( "PatternGuards", Opt_PatternGuards, nop ),
2637 ( "UnicodeSyntax", Opt_UnicodeSyntax, nop ),
2638 ( "MagicHash", Opt_MagicHash, nop ),
2639 ( "ExistentialQuantification", Opt_ExistentialQuantification, nop ),
2640 ( "KindSignatures", Opt_KindSignatures, nop ),
2641 ( "RoleAnnotations", Opt_RoleAnnotations, nop ),
2642 ( "EmptyDataDecls", Opt_EmptyDataDecls, nop ),
2643 ( "ParallelListComp", Opt_ParallelListComp, nop ),
2644 ( "TransformListComp", Opt_TransformListComp, nop ),
2645 ( "MonadComprehensions", Opt_MonadComprehensions, nop),
2646 ( "ForeignFunctionInterface", Opt_ForeignFunctionInterface, nop ),
2647 ( "UnliftedFFITypes", Opt_UnliftedFFITypes, nop ),
2648 ( "InterruptibleFFI", Opt_InterruptibleFFI, nop ),
2649 ( "CApiFFI", Opt_CApiFFI, nop ),
2650 ( "GHCForeignImportPrim", Opt_GHCForeignImportPrim, nop ),
2651 ( "LiberalTypeSynonyms", Opt_LiberalTypeSynonyms, nop ),
2652
2653 ( "PolymorphicComponents", Opt_RankNTypes, nop),
2654 ( "Rank2Types", Opt_RankNTypes, nop),
2655 ( "RankNTypes", Opt_RankNTypes, nop ),
2656
2657 ( "ImpredicativeTypes", Opt_ImpredicativeTypes, nop),
2658 ( "TypeOperators", Opt_TypeOperators, nop ),
2659 ( "ExplicitNamespaces", Opt_ExplicitNamespaces, nop ),
2660 ( "RecursiveDo", Opt_RecursiveDo, nop ), -- Enables 'mdo' and 'rec'
2661 ( "DoRec", Opt_RecursiveDo,
2662 deprecatedForExtension "RecursiveDo" ),
2663 ( "Arrows", Opt_Arrows, nop ),
2664 ( "ParallelArrays", Opt_ParallelArrays, nop ),
2665 ( "TemplateHaskell", Opt_TemplateHaskell, checkTemplateHaskellOk ),
2666 ( "QuasiQuotes", Opt_QuasiQuotes, nop ),
2667 ( "ImplicitPrelude", Opt_ImplicitPrelude, nop ),
2668 ( "RecordWildCards", Opt_RecordWildCards, nop ),
2669 ( "NamedFieldPuns", Opt_RecordPuns, nop ),
2670 ( "RecordPuns", Opt_RecordPuns,
2671 deprecatedForExtension "NamedFieldPuns" ),
2672 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields, nop ),
2673 ( "OverloadedStrings", Opt_OverloadedStrings, nop ),
2674 ( "OverloadedLists", Opt_OverloadedLists, nop),
2675 ( "GADTs", Opt_GADTs, nop ),
2676 ( "GADTSyntax", Opt_GADTSyntax, nop ),
2677 ( "ViewPatterns", Opt_ViewPatterns, nop ),
2678 ( "TypeFamilies", Opt_TypeFamilies, nop ),
2679 ( "BangPatterns", Opt_BangPatterns, nop ),
2680 ( "MonomorphismRestriction", Opt_MonomorphismRestriction, nop ),
2681 ( "NPlusKPatterns", Opt_NPlusKPatterns, nop ),
2682 ( "DoAndIfThenElse", Opt_DoAndIfThenElse, nop ),
2683 ( "RebindableSyntax", Opt_RebindableSyntax, nop ),
2684 ( "ConstraintKinds", Opt_ConstraintKinds, nop ),
2685 ( "PolyKinds", Opt_PolyKinds, nop ),
2686 ( "DataKinds", Opt_DataKinds, nop ),
2687 ( "InstanceSigs", Opt_InstanceSigs, nop ),
2688 ( "MonoPatBinds", Opt_MonoPatBinds,
2689 \ turn_on -> when turn_on $ deprecate "Experimental feature now removed; has no effect" ),
2690 ( "ExplicitForAll", Opt_ExplicitForAll, nop ),
2691 ( "AlternativeLayoutRule", Opt_AlternativeLayoutRule, nop ),
2692 ( "AlternativeLayoutRuleTransitional",Opt_AlternativeLayoutRuleTransitional, nop ),
2693 ( "DatatypeContexts", Opt_DatatypeContexts,
2694 \ turn_on -> when turn_on $ deprecate "It was widely considered a misfeature, and has been removed from the Haskell language." ),
2695 ( "NondecreasingIndentation", Opt_NondecreasingIndentation, nop ),
2696 ( "RelaxedLayout", Opt_RelaxedLayout, nop ),
2697 ( "TraditionalRecordSyntax", Opt_TraditionalRecordSyntax, nop ),
2698 ( "LambdaCase", Opt_LambdaCase, nop ),
2699 ( "MultiWayIf", Opt_MultiWayIf, nop ),
2700 ( "MonoLocalBinds", Opt_MonoLocalBinds, nop ),
2701 ( "RelaxedPolyRec", Opt_RelaxedPolyRec,
2702 \ turn_on -> unless turn_on
2703 $ deprecate "You can't turn off RelaxedPolyRec any more" ),
2704 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules, nop ),
2705 ( "ImplicitParams", Opt_ImplicitParams, nop ),
2706 ( "ScopedTypeVariables", Opt_ScopedTypeVariables, nop ),
2707 ( "AllowAmbiguousTypes", Opt_AllowAmbiguousTypes, nop),
2708
2709 ( "PatternSignatures", Opt_ScopedTypeVariables,
2710 deprecatedForExtension "ScopedTypeVariables" ),
2711
2712 ( "UnboxedTuples", Opt_UnboxedTuples, nop ),
2713 ( "StandaloneDeriving", Opt_StandaloneDeriving, nop ),
2714 ( "DeriveDataTypeable", Opt_DeriveDataTypeable, nop ),
2715 ( "AutoDeriveTypeable", Opt_AutoDeriveTypeable, nop ),
2716 ( "DeriveFunctor", Opt_DeriveFunctor, nop ),
2717 ( "DeriveTraversable", Opt_DeriveTraversable, nop ),
2718 ( "DeriveFoldable", Opt_DeriveFoldable, nop ),
2719 ( "DeriveGeneric", Opt_DeriveGeneric, nop ),
2720 ( "DefaultSignatures", Opt_DefaultSignatures, nop ),
2721 ( "TypeSynonymInstances", Opt_TypeSynonymInstances, nop ),
2722 ( "FlexibleContexts", Opt_FlexibleContexts, nop ),
2723 ( "FlexibleInstances", Opt_FlexibleInstances, nop ),
2724 ( "ConstrainedClassMethods", Opt_ConstrainedClassMethods, nop ),
2725 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses, nop ),
2726 ( "NullaryTypeClasses", Opt_NullaryTypeClasses, nop ),
2727 ( "FunctionalDependencies", Opt_FunctionalDependencies, nop ),
2728 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving, setGenDeriving ),
2729 ( "OverlappingInstances", Opt_OverlappingInstances, nop ),
2730 ( "UndecidableInstances", Opt_UndecidableInstances, nop ),
2731 ( "IncoherentInstances", Opt_IncoherentInstances, nop ),
2732 ( "PackageImports", Opt_PackageImports, nop ),
2733 ( "TypeHoles", Opt_TypeHoles, nop ),
2734 ( "NegativeLiterals", Opt_NegativeLiterals, nop ),
2735 ( "EmptyCase", Opt_EmptyCase, nop )
2736 ]
2737
2738 defaultFlags :: Settings -> [GeneralFlag]
2739 defaultFlags settings
2740 = [ Opt_AutoLinkPackages,
2741
2742 Opt_SharedImplib,
2743
2744 Opt_OmitYields,
2745
2746 Opt_GenManifest,
2747 Opt_EmbedManifest,
2748 Opt_PrintBindContents,
2749 Opt_GhciSandbox,
2750 Opt_GhciHistory,
2751 Opt_HelpfulErrors,
2752 Opt_ProfCountEntries,
2753 Opt_SimplPreInlining,
2754 Opt_FlatCache,
2755 Opt_RPath
2756 ]
2757
2758 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
2759 -- The default -O0 options
2760
2761 ++ default_PIC platform
2762
2763 ++ (if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
2764 then wayGeneralFlags platform WayDyn
2765 else [])
2766
2767 where platform = sTargetPlatform settings
2768
2769 default_PIC :: Platform -> [GeneralFlag]
2770 default_PIC platform =
2771 case (platformOS platform, platformArch platform) of
2772 (OSDarwin, ArchX86_64) -> [Opt_PIC]
2773 _ -> []
2774
2775 impliedFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)]
2776 impliedFlags
2777 = [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll)
2778 , (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll)
2779 , (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll)
2780 , (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll)
2781 , (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances)
2782 , (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses)
2783
2784 , (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off!
2785
2786 , (Opt_GADTs, turnOn, Opt_GADTSyntax)
2787 , (Opt_GADTs, turnOn, Opt_MonoLocalBinds)
2788 , (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds)
2789
2790 , (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures
2791 , (Opt_PolyKinds, turnOn, Opt_KindSignatures) -- Ditto polymorphic kinds
2792
2793 -- AutoDeriveTypeable is not very useful without DeriveDataTypeable
2794 , (Opt_AutoDeriveTypeable, turnOn, Opt_DeriveDataTypeable)
2795
2796 -- We turn this on so that we can export associated type
2797 -- type synonyms in subordinates (e.g. MyClass(type AssocType))
2798 , (Opt_TypeFamilies, turnOn, Opt_ExplicitNamespaces)
2799 , (Opt_TypeOperators, turnOn, Opt_ExplicitNamespaces)
2800
2801 , (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes)
2802
2803 -- Record wild-cards implies field disambiguation
2804 -- Otherwise if you write (C {..}) you may well get
2805 -- stuff like " 'a' not in scope ", which is a bit silly
2806 -- if the compiler has just filled in field 'a' of constructor 'C'
2807 , (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields)
2808
2809 , (Opt_ParallelArrays, turnOn, Opt_ParallelListComp)
2810
2811 -- An implicit parameter constraint, `?x::Int`, is desugared into
2812 -- `IP "x" Int`, which requires a flexible context/instance.
2813 , (Opt_ImplicitParams, turnOn, Opt_FlexibleContexts)
2814 , (Opt_ImplicitParams, turnOn, Opt_FlexibleInstances)
2815 ]
2816
2817 optLevelFlags :: [([Int], GeneralFlag)]
2818 optLevelFlags
2819 = [ ([0], Opt_IgnoreInterfacePragmas)
2820 , ([0], Opt_OmitInterfacePragmas)
2821
2822 , ([1,2], Opt_IgnoreAsserts)
2823 , ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
2824 -- in PrelRules
2825 , ([1,2], Opt_DoEtaReduction)
2826 , ([1,2], Opt_CaseMerge)
2827 , ([1,2], Opt_Strictness)
2828 , ([1,2], Opt_CSE)
2829 , ([1,2], Opt_FullLaziness)
2830 , ([1,2], Opt_Specialise)
2831 , ([1,2], Opt_FloatIn)
2832 , ([1,2], Opt_UnboxSmallStrictFields)
2833
2834 , ([2], Opt_LiberateCase)
2835 , ([2], Opt_SpecConstr)
2836 -- XXX disabled, see #7192
2837 -- , ([2], Opt_RegsGraph)
2838 , ([0,1,2], Opt_LlvmTBAA)
2839 , ([1,2], Opt_CmmSink)
2840 , ([1,2], Opt_CmmElimCommonBlocks)
2841
2842 -- , ([2], Opt_StaticArgumentTransformation)
2843 -- Max writes: I think it's probably best not to enable SAT with -O2 for the
2844 -- 6.10 release. The version of SAT in HEAD at the moment doesn't incorporate
2845 -- several improvements to the heuristics, and I'm concerned that without
2846 -- those changes SAT will interfere with some attempts to write "high
2847 -- performance Haskell", as we saw in some posts on Haskell-Cafe earlier
2848 -- this year. In particular, the version in HEAD lacks the tail call
2849 -- criterion, so many things that look like reasonable loops will be
2850 -- turned into functions with extra (unneccesary) thunk creation.
2851
2852 , ([0,1,2], Opt_DoLambdaEtaExpansion)
2853 -- This one is important for a tiresome reason:
2854 -- we want to make sure that the bindings for data
2855 -- constructors are eta-expanded. This is probably
2856 -- a good thing anyway, but it seems fragile.
2857 , ([0,1,2], Opt_VectorisationAvoidance)
2858 ]
2859
2860 -- -----------------------------------------------------------------------------
2861 -- Standard sets of warning options
2862
2863 standardWarnings :: [WarningFlag]
2864 standardWarnings
2865 = [ Opt_WarnOverlappingPatterns,
2866 Opt_WarnWarningsDeprecations,
2867 Opt_WarnDeprecatedFlags,
2868 Opt_WarnUnrecognisedPragmas,
2869 Opt_WarnPointlessPragmas,
2870 Opt_WarnDuplicateConstraints,
2871 Opt_WarnDuplicateExports,
2872 Opt_WarnOverflowedLiterals,
2873 Opt_WarnEmptyEnumerations,
2874 Opt_WarnMissingFields,
2875 Opt_WarnMissingMethods,
2876 Opt_WarnLazyUnliftedBindings,
2877 Opt_WarnWrongDoBind,
2878 Opt_WarnUnsupportedCallingConventions,
2879 Opt_WarnDodgyForeignImports,
2880 Opt_WarnTypeableInstances,
2881 Opt_WarnInlineRuleShadowing,
2882 Opt_WarnAlternativeLayoutRuleTransitional,
2883 Opt_WarnUnsupportedLlvmVersion
2884 ]
2885
2886 minusWOpts :: [WarningFlag]
2887 -- Things you get with -W
2888 minusWOpts
2889 = standardWarnings ++
2890 [ Opt_WarnUnusedBinds,
2891 Opt_WarnUnusedMatches,
2892 Opt_WarnUnusedImports,
2893 Opt_WarnIncompletePatterns,
2894 Opt_WarnDodgyExports,
2895 Opt_WarnDodgyImports
2896 ]
2897
2898 minusWallOpts :: [WarningFlag]
2899 -- Things you get with -Wall
2900 minusWallOpts
2901 = minusWOpts ++
2902 [ Opt_WarnTypeDefaults,
2903 Opt_WarnNameShadowing,
2904 Opt_WarnMissingSigs,
2905 Opt_WarnHiShadows,
2906 Opt_WarnOrphans,
2907 Opt_WarnUnusedDoBind
2908 ]
2909
2910 enableGlasgowExts :: DynP ()
2911 enableGlasgowExts = do setGeneralFlag Opt_PrintExplicitForalls
2912 mapM_ setExtensionFlag glasgowExtsFlags
2913
2914 disableGlasgowExts :: DynP ()
2915 disableGlasgowExts = do unSetGeneralFlag Opt_PrintExplicitForalls
2916 mapM_ unSetExtensionFlag glasgowExtsFlags
2917
2918 glasgowExtsFlags :: [ExtensionFlag]
2919 glasgowExtsFlags = [
2920 Opt_ForeignFunctionInterface
2921 , Opt_UnliftedFFITypes
2922 , Opt_ImplicitParams
2923 , Opt_ScopedTypeVariables
2924 , Opt_UnboxedTuples
2925 , Opt_TypeSynonymInstances
2926 , Opt_StandaloneDeriving
2927 , Opt_DeriveDataTypeable
2928 , Opt_DeriveFunctor
2929 , Opt_DeriveFoldable
2930 , Opt_DeriveTraversable
2931 , Opt_DeriveGeneric
2932 , Opt_FlexibleContexts
2933 , Opt_FlexibleInstances
2934 , Opt_ConstrainedClassMethods
2935 , Opt_MultiParamTypeClasses
2936 , Opt_FunctionalDependencies
2937 , Opt_MagicHash
2938 , Opt_ExistentialQuantification
2939 , Opt_UnicodeSyntax
2940 , Opt_PostfixOperators
2941 , Opt_PatternGuards
2942 , Opt_LiberalTypeSynonyms
2943 , Opt_RankNTypes
2944 , Opt_TypeOperators
2945 , Opt_ExplicitNamespaces
2946 , Opt_RecursiveDo
2947 , Opt_ParallelListComp
2948 , Opt_EmptyDataDecls
2949 , Opt_KindSignatures
2950 , Opt_GeneralizedNewtypeDeriving ]
2951
2952 #ifdef GHCI
2953 -- Consult the RTS to find whether GHC itself has been built profiled
2954 -- If so, you can't use Template Haskell
2955 foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt
2956
2957 rtsIsProfiled :: Bool
2958 rtsIsProfiled = unsafePerformIO rtsIsProfiledIO /= 0
2959 #endif
2960
2961 setWarnSafe :: Bool -> DynP ()
2962 setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l })
2963 setWarnSafe False = return ()
2964
2965 setWarnUnsafe :: Bool -> DynP ()
2966 setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l })
2967 setWarnUnsafe False = return ()
2968
2969 setPackageTrust :: DynP ()
2970 setPackageTrust = do
2971 setGeneralFlag Opt_PackageTrust
2972 l <- getCurLoc
2973 upd $ \d -> d { pkgTrustOnLoc = l }
2974
2975 setGenDeriving :: TurnOnFlag -> DynP ()
2976 setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l })
2977 setGenDeriving False = return ()
2978
2979 checkTemplateHaskellOk :: TurnOnFlag -> DynP ()
2980 #ifdef GHCI
2981 checkTemplateHaskellOk turn_on
2982 | turn_on && rtsIsProfiled
2983 = addErr "You can't use Template Haskell with a profiled compiler"
2984 | otherwise
2985 = getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l })
2986 #else
2987 -- In stage 1 we don't know that the RTS has rts_isProfiled,
2988 -- so we simply say "ok". It doesn't matter because TH isn't
2989 -- available in stage 1 anyway.
2990 checkTemplateHaskellOk _ = return ()
2991 #endif
2992
2993 {- **********************************************************************
2994 %* *
2995 DynFlags constructors
2996 %* *
2997 %********************************************************************* -}
2998
2999 type DynP = EwM (CmdLineP DynFlags)
3000
3001 upd :: (DynFlags -> DynFlags) -> DynP ()
3002 upd f = liftEwM (do dflags <- getCmdLineState
3003 putCmdLineState $! f dflags)
3004
3005 updM :: (DynFlags -> DynP DynFlags) -> DynP ()
3006 updM f = do dflags <- liftEwM getCmdLineState
3007 dflags' <- f dflags
3008 liftEwM $ putCmdLineState $! dflags'
3009
3010 --------------- Constructor functions for OptKind -----------------
3011 noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3012 noArg fn = NoArg (upd fn)
3013
3014 noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
3015 noArgM fn = NoArg (updM fn)
3016
3017 noArgDF :: (DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
3018 noArgDF fn deprec = NoArg (upd fn >> deprecate deprec)
3019
3020 hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3021 hasArg fn = HasArg (upd . fn)
3022
3023 hasArgDF :: (String -> DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
3024 hasArgDF fn deprec = HasArg (\s -> do upd (fn s)
3025 deprecate deprec)
3026
3027 sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3028 sepArg fn = SepArg (upd . fn)
3029
3030 intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3031 intSuffix fn = IntSuffix (\n -> upd (fn n))
3032
3033 floatSuffix :: (Float -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3034 floatSuffix fn = FloatSuffix (\n -> upd (fn n))
3035
3036 optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags)
3037 -> OptKind (CmdLineP DynFlags)
3038 optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi))
3039
3040 versionSuffix :: (Int -> Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3041 versionSuffix fn = VersionSuffix (\maj min -> upd (fn maj min))
3042
3043 setDumpFlag :: DumpFlag -> OptKind (CmdLineP DynFlags)
3044 setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
3045
3046 --------------------------
3047 addWay :: Way -> DynP ()
3048 addWay w = upd (addWay' w)
3049
3050 addWay' :: Way -> DynFlags -> DynFlags
3051 addWay' w dflags0 = let platform = targetPlatform dflags0
3052 dflags1 = dflags0 { ways = w : ways dflags0 }
3053 dflags2 = wayExtras platform w dflags1
3054 dflags3 = foldr setGeneralFlag' dflags2
3055 (wayGeneralFlags platform w)
3056 dflags4 = foldr unSetGeneralFlag' dflags3
3057 (wayUnsetGeneralFlags platform w)
3058 in dflags4
3059
3060 removeWayDyn :: DynP ()
3061 removeWayDyn = upd (\dfs -> dfs { ways = filter (WayDyn /=) (ways dfs) })
3062
3063 --------------------------
3064 setGeneralFlag, unSetGeneralFlag :: GeneralFlag -> DynP ()
3065 setGeneralFlag f = upd (setGeneralFlag' f)
3066 unSetGeneralFlag f = upd (unSetGeneralFlag' f)
3067
3068 setGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
3069 setGeneralFlag' f dflags = gopt_set dflags f
3070 unSetGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
3071 unSetGeneralFlag' f dflags = gopt_unset dflags f
3072
3073 --------------------------
3074 setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP ()
3075 setWarningFlag f = upd (\dfs -> wopt_set dfs f)
3076 unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f)
3077
3078 --------------------------
3079 setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP ()
3080 setExtensionFlag f = upd (setExtensionFlag' f)
3081 unSetExtensionFlag f = upd (unSetExtensionFlag' f)
3082
3083 setExtensionFlag', unSetExtensionFlag' :: ExtensionFlag -> DynFlags -> DynFlags
3084 setExtensionFlag' f dflags = foldr ($) (xopt_set dflags f) deps
3085 where
3086 deps = [ if turn_on then setExtensionFlag' d
3087 else unSetExtensionFlag' d
3088 | (f', turn_on, d) <- impliedFlags, f' == f ]
3089 -- When you set f, set the ones it implies
3090 -- NB: use setExtensionFlag recursively, in case the implied flags
3091 -- implies further flags
3092
3093 unSetExtensionFlag' f dflags = xopt_unset dflags f
3094 -- When you un-set f, however, we don't un-set the things it implies
3095 -- (except for -fno-glasgow-exts, which is treated specially)
3096
3097 --------------------------
3098 alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags
3099 alterSettings f dflags = dflags { settings = f (settings dflags) }
3100
3101 --------------------------
3102 setDumpFlag' :: DumpFlag -> DynP ()
3103 setDumpFlag' dump_flag
3104 = do upd (\dfs -> dopt_set dfs dump_flag)
3105 when want_recomp forceRecompile
3106 where -- Certain dumpy-things are really interested in what's going
3107 -- on during recompilation checking, so in those cases we
3108 -- don't want to turn it off.
3109 want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace,
3110 Opt_D_dump_hi_diffs]
3111
3112 forceRecompile :: DynP ()
3113 -- Whenver we -ddump, force recompilation (by switching off the
3114 -- recompilation checker), else you don't see the dump! However,
3115 -- don't switch it off in --make mode, else *everything* gets
3116 -- recompiled which probably isn't what you want
3117 forceRecompile = do dfs <- liftEwM getCmdLineState
3118 when (force_recomp dfs) (setGeneralFlag Opt_ForceRecomp)
3119 where
3120 force_recomp dfs = isOneShot (ghcMode dfs)
3121
3122 setVerboseCore2Core :: DynP ()
3123 setVerboseCore2Core = do setDumpFlag' Opt_D_verbose_core2core
3124 upd (\dfs -> dfs { shouldDumpSimplPhase = Nothing })
3125
3126 setDumpSimplPhases :: String -> DynP ()
3127 setDumpSimplPhases s = do forceRecompile
3128 upd (\dfs -> dfs { shouldDumpSimplPhase = Just spec })
3129 where
3130 spec = case s of { ('=' : s') -> s'; _ -> s }
3131
3132 setVerbosity :: Maybe Int -> DynP ()
3133 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
3134
3135 addCmdlineHCInclude :: String -> DynP ()
3136 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
3137
3138 data PkgConfRef
3139 = GlobalPkgConf
3140 | UserPkgConf
3141 | PkgConfFile FilePath
3142
3143 addPkgConfRef :: PkgConfRef -> DynP ()
3144 addPkgConfRef p = upd $ \s -> s { extraPkgConfs = (p:) . extraPkgConfs s }
3145
3146 removeUserPkgConf :: DynP ()
3147 removeUserPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotUser . extraPkgConfs s }
3148 where
3149 isNotUser UserPkgConf = False
3150 isNotUser _ = True
3151
3152 removeGlobalPkgConf :: DynP ()
3153 removeGlobalPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotGlobal . extraPkgConfs s }
3154 where
3155 isNotGlobal GlobalPkgConf = False
3156 isNotGlobal _ = True
3157
3158 clearPkgConf :: DynP ()
3159 clearPkgConf = upd $ \s -> s { extraPkgConfs = const [] }
3160
3161 exposePackage, exposePackageId, hidePackage, ignorePackage,
3162 trustPackage, distrustPackage :: String -> DynP ()
3163 exposePackage p = upd (exposePackage' p)
3164 exposePackageId p =
3165 upd (\s -> s{ packageFlags = ExposePackageId p : packageFlags s })
3166 hidePackage p =
3167 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
3168 ignorePackage p =
3169 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
3170 trustPackage p = exposePackage p >> -- both trust and distrust also expose a package
3171 upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s })
3172 distrustPackage p = exposePackage p >>
3173 upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s })
3174
3175 exposePackage' :: String -> DynFlags -> DynFlags
3176 exposePackage' p dflags
3177 = dflags { packageFlags = ExposePackage p : packageFlags dflags }
3178
3179 setPackageName :: String -> DynFlags -> DynFlags
3180 setPackageName p s = s{ thisPackage = stringToPackageId p }
3181
3182 -- If we're linking a binary, then only targets that produce object
3183 -- code are allowed (requests for other target types are ignored).
3184 setTarget :: HscTarget -> DynP ()
3185 setTarget l = setTargetWithPlatform (const l)
3186
3187 setTargetWithPlatform :: (Platform -> HscTarget) -> DynP ()
3188 setTargetWithPlatform f = upd set
3189 where
3190 set dfs = let l = f (targetPlatform dfs)
3191 in if ghcLink dfs /= LinkBinary || isObjectTarget l
3192 then dfs{ hscTarget = l }
3193 else dfs
3194
3195 -- Changes the target only if we're compiling object code. This is
3196 -- used by -fasm and -fllvm, which switch from one to the other, but
3197 -- not from bytecode to object-code. The idea is that -fasm/-fllvm
3198 -- can be safely used in an OPTIONS_GHC pragma.
3199 setObjTarget :: HscTarget -> DynP ()
3200 setObjTarget l = updM set
3201 where
3202 set dflags
3203 | isObjectTarget (hscTarget dflags)
3204 = return $ dflags { hscTarget = l }
3205 | otherwise = return dflags
3206
3207 setOptLevel :: Int -> DynFlags -> DynP DynFlags
3208 setOptLevel n dflags
3209 | hscTarget dflags == HscInterpreted && n > 0
3210 = do addWarn "-O conflicts with --interactive; -O ignored."
3211 return dflags
3212 | otherwise
3213 = return (updOptLevel n dflags)
3214
3215
3216 -- -Odph is equivalent to
3217 --
3218 -- -O2 optimise as much as possible
3219 -- -fmax-simplifier-iterations20 this is necessary sometimes
3220 -- -fsimplifier-phases=3 we use an additional simplifier phase for fusion
3221 --
3222 setDPHOpt :: DynFlags -> DynP DynFlags
3223 setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations = 20
3224 , simplPhases = 3
3225 })
3226
3227 setMainIs :: String -> DynP ()
3228 setMainIs arg
3229 | not (null main_fn) && isLower (head main_fn)
3230 -- The arg looked like "Foo.Bar.baz"
3231 = upd $ \d -> d{ mainFunIs = Just main_fn,
3232 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
3233
3234 | isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar"
3235 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) }
3236
3237 | otherwise -- The arg looked like "baz"
3238 = upd $ \d -> d{ mainFunIs = Just arg }
3239 where
3240 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
3241
3242 addLdInputs :: Option -> DynFlags -> DynFlags
3243 addLdInputs p dflags = dflags{ldInputs = ldInputs dflags ++ [p]}
3244
3245 -----------------------------------------------------------------------------
3246 -- Paths & Libraries
3247
3248 addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP ()
3249
3250 -- -i on its own deletes the import paths
3251 addImportPath "" = upd (\s -> s{importPaths = []})
3252 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
3253
3254 addLibraryPath p =
3255 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
3256
3257 addIncludePath p =
3258 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
3259
3260 addFrameworkPath p =
3261 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
3262
3263 #ifndef mingw32_TARGET_OS
3264 split_marker :: Char
3265 split_marker = ':' -- not configurable (ToDo)
3266 #endif
3267
3268 splitPathList :: String -> [String]
3269 splitPathList s = filter notNull (splitUp s)
3270 -- empty paths are ignored: there might be a trailing
3271 -- ':' in the initial list, for example. Empty paths can
3272 -- cause confusion when they are translated into -I options
3273 -- for passing to gcc.
3274 where
3275 #ifndef mingw32_TARGET_OS
3276 splitUp xs = split split_marker xs
3277 #else
3278 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
3279 --
3280 -- That is, if "foo:bar:baz" is used, this interpreted as
3281 -- consisting of three entries, 'foo', 'bar', 'baz'.
3282 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
3283 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
3284 --
3285 -- Notice that no attempt is made to fully replace the 'standard'
3286 -- split marker ':' with the Windows / DOS one, ';'. The reason being
3287 -- that this will cause too much breakage for users & ':' will
3288 -- work fine even with DOS paths, if you're not insisting on being silly.
3289 -- So, use either.
3290 splitUp [] = []
3291 splitUp (x:':':div:xs) | div `elem` dir_markers
3292 = ((x:':':div:p): splitUp rs)
3293 where
3294 (p,rs) = findNextPath xs
3295 -- we used to check for existence of the path here, but that
3296 -- required the IO monad to be threaded through the command-line
3297 -- parser which is quite inconvenient. The
3298 splitUp xs = cons p (splitUp rs)
3299 where
3300 (p,rs) = findNextPath xs
3301
3302 cons "" xs = xs
3303 cons x xs = x:xs
3304
3305 -- will be called either when we've consumed nought or the
3306 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
3307 -- finding the next split marker.
3308 findNextPath xs =
3309 case break (`elem` split_markers) xs of
3310 (p, _:ds) -> (p, ds)
3311 (p, xs) -> (p, xs)
3312
3313 split_markers :: [Char]
3314 split_markers = [':', ';']
3315
3316 dir_markers :: [Char]
3317 dir_markers = ['/', '\\']
3318 #endif
3319
3320 -- -----------------------------------------------------------------------------
3321 -- tmpDir, where we store temporary files.
3322
3323 setTmpDir :: FilePath -> DynFlags -> DynFlags
3324 setTmpDir dir = alterSettings (\s -> s { sTmpDir = normalise dir })
3325 -- we used to fix /cygdrive/c/.. on Windows, but this doesn't
3326 -- seem necessary now --SDM 7/2/2008
3327
3328 -----------------------------------------------------------------------------
3329 -- RTS opts
3330
3331 setRtsOpts :: String -> DynP ()
3332 setRtsOpts arg = upd $ \ d -> d {rtsOpts = Just arg}
3333
3334 setRtsOptsEnabled :: RtsOptsEnabled -> DynP ()
3335 setRtsOptsEnabled arg = upd $ \ d -> d {rtsOptsEnabled = arg}
3336
3337 -----------------------------------------------------------------------------
3338 -- Hpc stuff
3339
3340 setOptHpcDir :: String -> DynP ()
3341 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
3342
3343 -----------------------------------------------------------------------------
3344 -- Via-C compilation stuff
3345
3346 -- There are some options that we need to pass to gcc when compiling
3347 -- Haskell code via C, but are only supported by recent versions of
3348 -- gcc. The configure script decides which of these options we need,
3349 -- and puts them in the "settings" file in $topdir. The advantage of
3350 -- having these in a separate file is that the file can be created at
3351 -- install-time depending on the available gcc version, and even
3352 -- re-generated later if gcc is upgraded.
3353 --
3354 -- The options below are not dependent on the version of gcc, only the
3355 -- platform.
3356
3357 picCCOpts :: DynFlags -> [String]
3358 picCCOpts dflags
3359 = case platformOS (targetPlatform dflags) of
3360 OSDarwin
3361 -- Apple prefers to do things the other way round.
3362 -- PIC is on by default.
3363 -- -mdynamic-no-pic:
3364 -- Turn off PIC code generation.
3365 -- -fno-common:
3366 -- Don't generate "common" symbols - these are unwanted
3367 -- in dynamic libraries.
3368
3369 | gopt Opt_PIC dflags -> ["-fno-common", "-U __PIC__", "-D__PIC__"]
3370 | otherwise -> ["-mdynamic-no-pic"]
3371 OSMinGW32 -- no -fPIC for Windows
3372 | gopt Opt_PIC dflags -> ["-U __PIC__", "-D__PIC__"]
3373 | otherwise -> []
3374 _
3375 -- we need -fPIC for C files when we are compiling with -dynamic,
3376 -- otherwise things like stub.c files don't get compiled
3377 -- correctly. They need to reference data in the Haskell
3378 -- objects, but can't without -fPIC. See
3379 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode
3380 | gopt Opt_PIC dflags || not (gopt Opt_Static dflags) ->
3381 ["-fPIC", "-U __PIC__", "-D__PIC__"]
3382 | otherwise -> []
3383
3384 picPOpts :: DynFlags -> [String]
3385 picPOpts dflags
3386 | gopt Opt_PIC dflags = ["-U __PIC__", "-D__PIC__"]
3387 | otherwise = []
3388
3389 -- -----------------------------------------------------------------------------
3390 -- Splitting
3391
3392 can_split :: Bool
3393 can_split = cSupportsSplitObjs == "YES"
3394
3395 -- -----------------------------------------------------------------------------
3396 -- Compiler Info
3397
3398 compilerInfo :: DynFlags -> [(String, String)]
3399 compilerInfo dflags
3400 = -- We always make "Project name" be first to keep parsing in
3401 -- other languages simple, i.e. when looking for other fields,
3402 -- you don't have to worry whether there is a leading '[' or not
3403 ("Project name", cProjectName)
3404 -- Next come the settings, so anything else can be overridden
3405 -- in the settings file (as "lookup" uses the first match for the
3406 -- key)
3407 : rawSettings dflags
3408 ++ [("Project version", cProjectVersion),
3409 ("Booter version", cBooterVersion),
3410 ("Stage", cStage),
3411 ("Build platform", cBuildPlatformString),
3412 ("Host platform", cHostPlatformString),
3413 ("Target platform", cTargetPlatformString),
3414 ("Have interpreter", cGhcWithInterpreter),
3415 ("Object splitting supported", cSupportsSplitObjs),
3416 ("Have native code generator", cGhcWithNativeCodeGen),
3417 ("Support SMP", cGhcWithSMP),
3418 ("Tables next to code", cGhcEnableTablesNextToCode),
3419 ("RTS ways", cGhcRTSWays),
3420 ("Support dynamic-too", "YES"),
3421 ("Dynamic by default", if dYNAMIC_BY_DEFAULT dflags
3422 then "YES" else "NO"),
3423 ("GHC Dynamic", if cDYNAMIC_GHC_PROGRAMS
3424 then "YES" else "NO"),
3425 ("Leading underscore", cLeadingUnderscore),
3426 ("Debug on", show debugIsOn),
3427 ("LibDir", topDir dflags),
3428 ("Global Package DB", systemPackageConfig dflags)
3429 ]
3430
3431 #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellWrappers.hs"
3432
3433 bLOCK_SIZE_W :: DynFlags -> Int
3434 bLOCK_SIZE_W dflags = bLOCK_SIZE dflags `quot` wORD_SIZE dflags
3435
3436 wORD_SIZE_IN_BITS :: DynFlags -> Int
3437 wORD_SIZE_IN_BITS dflags = wORD_SIZE dflags * 8
3438
3439 tAG_MASK :: DynFlags -> Int
3440 tAG_MASK dflags = (1 `shiftL` tAG_BITS dflags) - 1
3441
3442 mAX_PTR_TAG :: DynFlags -> Int
3443 mAX_PTR_TAG = tAG_MASK
3444
3445 -- Might be worth caching these in targetPlatform?
3446 tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD :: DynFlags -> Integer
3447 tARGET_MIN_INT dflags
3448 = case platformWordSize (targetPlatform dflags) of
3449 4 -> toInteger (minBound :: Int32)
3450 8 -> toInteger (minBound :: Int64)
3451 w -> panic ("tARGET_MIN_INT: Unknown platformWordSize: " ++ show w)
3452 tARGET_MAX_INT dflags
3453 = case platformWordSize (targetPlatform dflags) of
3454 4 -> toInteger (maxBound :: Int32)
3455 8 -> toInteger (maxBound :: Int64)
3456 w -> panic ("tARGET_MAX_INT: Unknown platformWordSize: " ++ show w)
3457 tARGET_MAX_WORD dflags
3458 = case platformWordSize (targetPlatform dflags) of
3459 4 -> toInteger (maxBound :: Word32)
3460 8 -> toInteger (maxBound :: Word64)
3461 w -> panic ("tARGET_MAX_WORD: Unknown platformWordSize: " ++ show w)
3462
3463 -- Whenever makeDynFlagsConsistent does anything, it starts over, to
3464 -- ensure that a later change doesn't invalidate an earlier check.
3465 -- Be careful not to introduce potential loops!
3466 makeDynFlagsConsistent :: DynFlags -> (DynFlags, [Located String])
3467 makeDynFlagsConsistent dflags
3468 | hscTarget dflags == HscC &&
3469 not (platformUnregisterised (targetPlatform dflags))
3470 = if cGhcWithNativeCodeGen == "YES"
3471 then let dflags' = dflags { hscTarget = HscAsm }
3472 warn = "Compiler not unregisterised, so using native code generator rather than compiling via C"
3473 in loop dflags' warn
3474 else let dflags' = dflags { hscTarget = HscLlvm }
3475 warn = "Compiler not unregisterised, so using LLVM rather than compiling via C"
3476 in loop dflags' warn
3477 | hscTarget dflags == HscAsm &&
3478 platformUnregisterised (targetPlatform dflags)
3479 = loop (dflags { hscTarget = HscC })
3480 "Compiler unregisterised, so compiling via C"
3481 | hscTarget dflags == HscAsm &&
3482 cGhcWithNativeCodeGen /= "YES"
3483 = let dflags' = dflags { hscTarget = HscLlvm }
3484 warn = "No native code generator, so using LLVM"
3485 in loop dflags' warn
3486 | hscTarget dflags == HscLlvm &&
3487 not ((arch == ArchX86_64) && (os == OSLinux || os == OSDarwin)) &&
3488 not ((isARM arch) && (os == OSLinux)) &&
3489 (not (gopt Opt_Static dflags) || gopt Opt_PIC dflags)
3490 = if cGhcWithNativeCodeGen == "YES"
3491 then let dflags' = dflags { hscTarget = HscAsm }
3492 warn = "Using native code generator rather than LLVM, as LLVM is incompatible with -fPIC and -dynamic on this platform"
3493 in loop dflags' warn
3494 else throwGhcException $ CmdLineError "Can't use -fPIC or -dynamic on this platform"
3495 | os == OSDarwin &&
3496 arch == ArchX86_64 &&
3497 not (gopt Opt_PIC dflags)
3498 = loop (gopt_set dflags Opt_PIC)
3499 "Enabling -fPIC as it is always on for this platform"
3500 | otherwise = (dflags, [])
3501 where loc = mkGeneralSrcSpan (fsLit "when making flags consistent")
3502 loop updated_dflags warning
3503 = case makeDynFlagsConsistent updated_dflags of
3504 (dflags', ws) -> (dflags', L loc warning : ws)
3505 platform = targetPlatform dflags
3506 arch = platformArch platform
3507 os = platformOS platform
3508
3509 --------------------------------------------------------------------------
3510 -- Do not use unsafeGlobalDynFlags!
3511 --
3512 -- unsafeGlobalDynFlags is a hack, necessary because we need to be able
3513 -- to show SDocs when tracing, but we don't always have DynFlags
3514 -- available.
3515 --
3516 -- Do not use it if you can help it. You may get the wrong value!
3517
3518 GLOBAL_VAR(v_unsafeGlobalDynFlags, panic "v_unsafeGlobalDynFlags: not initialised", DynFlags)
3519
3520 unsafeGlobalDynFlags :: DynFlags
3521 unsafeGlobalDynFlags = unsafePerformIO $ readIORef v_unsafeGlobalDynFlags
3522
3523 setUnsafeGlobalDynFlags :: DynFlags -> IO ()
3524 setUnsafeGlobalDynFlags = writeIORef v_unsafeGlobalDynFlags
3525
3526 -- -----------------------------------------------------------------------------
3527 -- SSE
3528
3529 -- TODO: Instead of using a separate predicate (i.e. isSse2Enabled) to
3530 -- check if SSE is enabled, we might have x86-64 imply the -msse2
3531 -- flag.
3532
3533 isSse2Enabled :: DynFlags -> Bool
3534 isSse2Enabled dflags = case platformArch (targetPlatform dflags) of
3535 ArchX86_64 -> -- SSE2 is fixed on for x86_64. It would be
3536 -- possible to make it optional, but we'd need to
3537 -- fix at least the foreign call code where the
3538 -- calling convention specifies the use of xmm regs,
3539 -- and possibly other places.
3540 True
3541 ArchX86 -> sseVersion dflags >= Just (2,0)
3542 _ -> False
3543
3544 isSse4_2Enabled :: DynFlags -> Bool
3545 isSse4_2Enabled dflags = sseVersion dflags >= Just (4,2)
3546
3547 -- -----------------------------------------------------------------------------
3548 -- Linker information
3549
3550 -- LinkerInfo contains any extra options needed by the system linker.
3551 data LinkerInfo
3552 = GnuLD [Option]
3553 | GnuGold [Option]
3554 | DarwinLD [Option]
3555 | UnknownLD
3556 deriving Eq