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