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