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