Include CPP preprocessor dependencies in -M output
[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 depIncludeCppDeps :: Bool,
1026 depExcludeMods :: [ModuleName],
1027 depSuffixes :: [String],
1028
1029 -- Package flags
1030 packageDBFlags :: [PackageDBFlag],
1031 -- ^ The @-package-db@ flags given on the command line, In
1032 -- *reverse* order that they're specified on the command line.
1033 -- This is intended to be applied with the list of "initial"
1034 -- package databases derived from @GHC_PACKAGE_PATH@; see
1035 -- 'getPackageConfRefs'.
1036
1037 ignorePackageFlags :: [IgnorePackageFlag],
1038 -- ^ The @-ignore-package@ flags from the command line.
1039 -- In *reverse* order that they're specified on the command line.
1040 packageFlags :: [PackageFlag],
1041 -- ^ The @-package@ and @-hide-package@ flags from the command-line.
1042 -- In *reverse* order that they're specified on the command line.
1043 pluginPackageFlags :: [PackageFlag],
1044 -- ^ The @-plugin-package-id@ flags from command line.
1045 -- In *reverse* order that they're specified on the command line.
1046 trustFlags :: [TrustFlag],
1047 -- ^ The @-trust@ and @-distrust@ flags.
1048 -- In *reverse* order that they're specified on the command line.
1049 packageEnv :: Maybe FilePath,
1050 -- ^ Filepath to the package environment file (if overriding default)
1051
1052 -- Package state
1053 -- NB. do not modify this field, it is calculated by
1054 -- Packages.initPackages
1055 pkgDatabase :: Maybe [(FilePath, [PackageConfig])],
1056 pkgState :: PackageState,
1057
1058 -- Temporary files
1059 -- These have to be IORefs, because the defaultCleanupHandler needs to
1060 -- know what to clean when an exception happens
1061 filesToClean :: IORef FilesToClean,
1062 dirsToClean :: IORef (Map FilePath FilePath),
1063 -- The next available suffix to uniquely name a temp file, updated atomically
1064 nextTempSuffix :: IORef Int,
1065
1066 -- Names of files which were generated from -ddump-to-file; used to
1067 -- track which ones we need to truncate because it's our first run
1068 -- through
1069 generatedDumps :: IORef (Set FilePath),
1070
1071 -- hsc dynamic flags
1072 dumpFlags :: EnumSet DumpFlag,
1073 generalFlags :: EnumSet GeneralFlag,
1074 warningFlags :: EnumSet WarningFlag,
1075 fatalWarningFlags :: EnumSet WarningFlag,
1076 -- Don't change this without updating extensionFlags:
1077 language :: Maybe Language,
1078 -- | Safe Haskell mode
1079 safeHaskell :: SafeHaskellMode,
1080 safeInfer :: Bool,
1081 safeInferred :: Bool,
1082 -- We store the location of where some extension and flags were turned on so
1083 -- we can produce accurate error messages when Safe Haskell fails due to
1084 -- them.
1085 thOnLoc :: SrcSpan,
1086 newDerivOnLoc :: SrcSpan,
1087 overlapInstLoc :: SrcSpan,
1088 incoherentOnLoc :: SrcSpan,
1089 pkgTrustOnLoc :: SrcSpan,
1090 warnSafeOnLoc :: SrcSpan,
1091 warnUnsafeOnLoc :: SrcSpan,
1092 trustworthyOnLoc :: SrcSpan,
1093 -- Don't change this without updating extensionFlags:
1094 -- Here we collect the settings of the language extensions
1095 -- from the command line, the ghci config file and
1096 -- from interactive :set / :seti commands.
1097 extensions :: [OnOff LangExt.Extension],
1098 -- extensionFlags should always be equal to
1099 -- flattenExtensionFlags language extensions
1100 -- LangExt.Extension is defined in libraries/ghc-boot so that it can be used
1101 -- by template-haskell
1102 extensionFlags :: EnumSet LangExt.Extension,
1103
1104 -- Unfolding control
1105 -- See Note [Discounts and thresholds] in CoreUnfold
1106 ufCreationThreshold :: Int,
1107 ufUseThreshold :: Int,
1108 ufFunAppDiscount :: Int,
1109 ufDictDiscount :: Int,
1110 ufKeenessFactor :: Float,
1111 ufDearOp :: Int,
1112 ufVeryAggressive :: Bool,
1113
1114 maxWorkerArgs :: Int,
1115
1116 ghciHistSize :: Int,
1117
1118 -- | MsgDoc output action: use "ErrUtils" instead of this if you can
1119 log_action :: LogAction,
1120 flushOut :: FlushOut,
1121 flushErr :: FlushErr,
1122
1123 ghcVersionFile :: Maybe FilePath,
1124 haddockOptions :: Maybe String,
1125
1126 -- | GHCi scripts specified by -ghci-script, in reverse order
1127 ghciScripts :: [String],
1128
1129 -- Output style options
1130 pprUserLength :: Int,
1131 pprCols :: Int,
1132
1133 useUnicode :: Bool,
1134 useColor :: OverridingBool,
1135 canUseColor :: Bool,
1136 colScheme :: Col.Scheme,
1137
1138 -- | what kind of {-# SCC #-} to add automatically
1139 profAuto :: ProfAuto,
1140
1141 interactivePrint :: Maybe String,
1142
1143 nextWrapperNum :: IORef (ModuleEnv Int),
1144
1145 -- | Machine dependent flags (-m<blah> stuff)
1146 sseVersion :: Maybe SseVersion,
1147 bmiVersion :: Maybe BmiVersion,
1148 avx :: Bool,
1149 avx2 :: Bool,
1150 avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions.
1151 avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions.
1152 avx512f :: Bool, -- Enable AVX-512 instructions.
1153 avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions.
1154
1155 -- | Run-time linker information (what options we need, etc.)
1156 rtldInfo :: IORef (Maybe LinkerInfo),
1157
1158 -- | Run-time compiler information
1159 rtccInfo :: IORef (Maybe CompilerInfo),
1160
1161 -- Constants used to control the amount of optimization done.
1162
1163 -- | Max size, in bytes, of inline array allocations.
1164 maxInlineAllocSize :: Int,
1165
1166 -- | Only inline memcpy if it generates no more than this many
1167 -- pseudo (roughly: Cmm) instructions.
1168 maxInlineMemcpyInsns :: Int,
1169
1170 -- | Only inline memset if it generates no more than this many
1171 -- pseudo (roughly: Cmm) instructions.
1172 maxInlineMemsetInsns :: Int,
1173
1174 -- | Reverse the order of error messages in GHC/GHCi
1175 reverseErrors :: Bool,
1176
1177 -- | Limit the maximum number of errors to show
1178 maxErrors :: Maybe Int,
1179
1180 -- | Unique supply configuration for testing build determinism
1181 initialUnique :: Int,
1182 uniqueIncrement :: Int,
1183
1184 -- | Temporary: CFG Edge weights for fast iterations
1185 cfgWeightInfo :: CfgWeights
1186 }
1187
1188 -- | Edge weights to use when generating a CFG from CMM
1189 data CfgWeights
1190 = CFGWeights
1191 { uncondWeight :: Int
1192 , condBranchWeight :: Int
1193 , switchWeight :: Int
1194 , callWeight :: Int
1195 , likelyCondWeight :: Int
1196 , unlikelyCondWeight :: Int
1197 , infoTablePenalty :: Int
1198 , backEdgeBonus :: Int
1199 }
1200
1201 defaultCfgWeights :: CfgWeights
1202 defaultCfgWeights
1203 = CFGWeights
1204 { uncondWeight = 1000
1205 , condBranchWeight = 800
1206 , switchWeight = 1
1207 , callWeight = -10
1208 , likelyCondWeight = 900
1209 , unlikelyCondWeight = 300
1210 , infoTablePenalty = 300
1211 , backEdgeBonus = 400
1212 }
1213
1214 parseCfgWeights :: String -> CfgWeights -> CfgWeights
1215 parseCfgWeights s oldWeights =
1216 foldl' (\cfg (n,v) -> update n v cfg) oldWeights assignments
1217 where
1218 assignments = map assignment $ settings s
1219 update "uncondWeight" n w =
1220 w {uncondWeight = n}
1221 update "condBranchWeight" n w =
1222 w {condBranchWeight = n}
1223 update "switchWeight" n w =
1224 w {switchWeight = n}
1225 update "callWeight" n w =
1226 w {callWeight = n}
1227 update "likelyCondWeight" n w =
1228 w {likelyCondWeight = n}
1229 update "unlikelyCondWeight" n w =
1230 w {unlikelyCondWeight = n}
1231 update "infoTablePenalty" n w =
1232 w {infoTablePenalty = n}
1233 update "backEdgeBonus" n w =
1234 w {backEdgeBonus = n}
1235 update other _ _
1236 = panic $ other ++
1237 " is not a cfg weight parameter. " ++
1238 exampleString
1239 settings s
1240 | (s1,rest) <- break (== ',') s
1241 , null rest
1242 = [s1]
1243 | (s1,rest) <- break (== ',') s
1244 = [s1] ++ settings (drop 1 rest)
1245 | otherwise = panic $ "Invalid cfg parameters." ++ exampleString
1246 assignment as
1247 | (name, _:val) <- break (== '=') as
1248 = (name,read val)
1249 | otherwise
1250 = panic $ "Invalid cfg parameters." ++ exampleString
1251 exampleString = "Example parameters: uncondWeight=1000," ++
1252 "condBranchWeight=800,switchWeight=0,callWeight=300" ++
1253 ",likelyCondWeight=900,unlikelyCondWeight=300" ++
1254 ",infoTablePenalty=300,backEdgeBonus=400"
1255
1256 backendMaintainsCfg :: DynFlags -> Bool
1257 backendMaintainsCfg dflags = case (platformArch $ targetPlatform dflags) of
1258 -- ArchX86 -- Should work but not tested so disabled currently.
1259 ArchX86_64 -> True
1260 _otherwise -> False
1261
1262 class HasDynFlags m where
1263 getDynFlags :: m DynFlags
1264
1265 {- It would be desirable to have the more generalised
1266
1267 instance (MonadTrans t, Monad m, HasDynFlags m) => HasDynFlags (t m) where
1268 getDynFlags = lift getDynFlags
1269
1270 instance definition. However, that definition would overlap with the
1271 `HasDynFlags (GhcT m)` instance. Instead we define instances for a
1272 couple of common Monad transformers explicitly. -}
1273
1274 instance (Monoid a, Monad m, HasDynFlags m) => HasDynFlags (WriterT a m) where
1275 getDynFlags = lift getDynFlags
1276
1277 instance (Monad m, HasDynFlags m) => HasDynFlags (ReaderT a m) where
1278 getDynFlags = lift getDynFlags
1279
1280 instance (Monad m, HasDynFlags m) => HasDynFlags (MaybeT m) where
1281 getDynFlags = lift getDynFlags
1282
1283 instance (Monad m, HasDynFlags m) => HasDynFlags (ExceptT e m) where
1284 getDynFlags = lift getDynFlags
1285
1286 class ContainsDynFlags t where
1287 extractDynFlags :: t -> DynFlags
1288
1289 data ProfAuto
1290 = NoProfAuto -- ^ no SCC annotations added
1291 | ProfAutoAll -- ^ top-level and nested functions are annotated
1292 | ProfAutoTop -- ^ top-level functions annotated only
1293 | ProfAutoExports -- ^ exported functions annotated only
1294 | ProfAutoCalls -- ^ annotate call-sites
1295 deriving (Eq,Enum)
1296
1297 data LlvmTarget = LlvmTarget
1298 { lDataLayout :: String
1299 , lCPU :: String
1300 , lAttributes :: [String]
1301 }
1302
1303 type LlvmTargets = [(String, LlvmTarget)]
1304 type LlvmPasses = [(Int, String)]
1305 type LlvmConfig = (LlvmTargets, LlvmPasses)
1306
1307 data IntegerLibrary
1308 = IntegerGMP
1309 | IntegerSimple
1310 deriving (Read, Show, Eq)
1311
1312 data Settings = Settings {
1313 sTargetPlatform :: Platform, -- Filled in by SysTools
1314 sGhcUsagePath :: FilePath, -- ditto
1315 sGhciUsagePath :: FilePath, -- ditto
1316 sToolDir :: Maybe FilePath, -- ditto
1317 sTopDir :: FilePath, -- ditto
1318 sTmpDir :: String, -- no trailing '/'
1319 sProgramName :: String,
1320 sProjectVersion :: String,
1321 -- You shouldn't need to look things up in rawSettings directly.
1322 -- They should have their own fields instead.
1323 sRawSettings :: [(String, String)],
1324 sExtraGccViaCFlags :: [String],
1325 sSystemPackageConfig :: FilePath,
1326 sLdSupportsCompactUnwind :: Bool,
1327 sLdSupportsBuildId :: Bool,
1328 sLdSupportsFilelist :: Bool,
1329 sLdIsGnuLd :: Bool,
1330 sGccSupportsNoPie :: Bool,
1331 -- commands for particular phases
1332 sPgm_L :: String,
1333 sPgm_P :: (String,[Option]),
1334 sPgm_F :: String,
1335 sPgm_c :: (String,[Option]),
1336 sPgm_a :: (String,[Option]),
1337 sPgm_l :: (String,[Option]),
1338 sPgm_dll :: (String,[Option]),
1339 sPgm_T :: String,
1340 sPgm_windres :: String,
1341 sPgm_libtool :: String,
1342 sPgm_ar :: String,
1343 sPgm_ranlib :: String,
1344 sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
1345 sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
1346 sPgm_lcc :: (String,[Option]), -- LLVM: c compiler
1347 sPgm_i :: String,
1348 -- options for particular phases
1349 sOpt_L :: [String],
1350 sOpt_P :: [String],
1351 sOpt_P_fingerprint :: Fingerprint, -- cached Fingerprint of sOpt_P
1352 -- See Note [Repeated -optP hashing]
1353 sOpt_F :: [String],
1354 sOpt_c :: [String],
1355 sOpt_cxx :: [String],
1356 sOpt_a :: [String],
1357 sOpt_l :: [String],
1358 sOpt_windres :: [String],
1359 sOpt_lo :: [String], -- LLVM: llvm optimiser
1360 sOpt_lc :: [String], -- LLVM: llc static compiler
1361 sOpt_lcc :: [String], -- LLVM: c compiler
1362 sOpt_i :: [String], -- iserv options
1363
1364 sPlatformConstants :: PlatformConstants,
1365
1366 -- Formerly Config.hs, target specific
1367 sTargetPlatformString :: String, -- TODO Recalculate string from richer info?
1368 sIntegerLibrary :: String,
1369 sIntegerLibraryType :: IntegerLibrary,
1370 sGhcWithInterpreter :: Bool,
1371 sGhcWithNativeCodeGen :: Bool,
1372 sGhcWithSMP :: Bool,
1373 sGhcRTSWays :: String,
1374 sTablesNextToCode :: Bool,
1375 sLeadingUnderscore :: Bool,
1376 sLibFFI :: Bool,
1377 sGhcThreaded :: Bool,
1378 sGhcDebugged :: Bool,
1379 sGhcRtsWithLibdw :: Bool
1380 }
1381
1382 targetPlatform :: DynFlags -> Platform
1383 targetPlatform dflags = sTargetPlatform (settings dflags)
1384 programName :: DynFlags -> String
1385 programName dflags = sProgramName (settings dflags)
1386 projectVersion :: DynFlags -> String
1387 projectVersion dflags = sProjectVersion (settings dflags)
1388 ghcUsagePath :: DynFlags -> FilePath
1389 ghcUsagePath dflags = sGhcUsagePath (settings dflags)
1390 ghciUsagePath :: DynFlags -> FilePath
1391 ghciUsagePath dflags = sGhciUsagePath (settings dflags)
1392 toolDir :: DynFlags -> Maybe FilePath
1393 toolDir dflags = sToolDir (settings dflags)
1394 topDir :: DynFlags -> FilePath
1395 topDir dflags = sTopDir (settings dflags)
1396 tmpDir :: DynFlags -> String
1397 tmpDir dflags = sTmpDir (settings dflags)
1398 rawSettings :: DynFlags -> [(String, String)]
1399 rawSettings dflags = sRawSettings (settings dflags)
1400 extraGccViaCFlags :: DynFlags -> [String]
1401 extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
1402 systemPackageConfig :: DynFlags -> FilePath
1403 systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
1404 pgm_L :: DynFlags -> String
1405 pgm_L dflags = sPgm_L (settings dflags)
1406 pgm_P :: DynFlags -> (String,[Option])
1407 pgm_P dflags = sPgm_P (settings dflags)
1408 pgm_F :: DynFlags -> String
1409 pgm_F dflags = sPgm_F (settings dflags)
1410 pgm_c :: DynFlags -> (String,[Option])
1411 pgm_c dflags = sPgm_c (settings dflags)
1412 pgm_a :: DynFlags -> (String,[Option])
1413 pgm_a dflags = sPgm_a (settings dflags)
1414 pgm_l :: DynFlags -> (String,[Option])
1415 pgm_l dflags = sPgm_l (settings dflags)
1416 pgm_dll :: DynFlags -> (String,[Option])
1417 pgm_dll dflags = sPgm_dll (settings dflags)
1418 pgm_T :: DynFlags -> String
1419 pgm_T dflags = sPgm_T (settings dflags)
1420 pgm_windres :: DynFlags -> String
1421 pgm_windres dflags = sPgm_windres (settings dflags)
1422 pgm_libtool :: DynFlags -> String
1423 pgm_libtool dflags = sPgm_libtool (settings dflags)
1424 pgm_lcc :: DynFlags -> (String,[Option])
1425 pgm_lcc dflags = sPgm_lcc (settings dflags)
1426 pgm_ar :: DynFlags -> String
1427 pgm_ar dflags = sPgm_ar (settings dflags)
1428 pgm_ranlib :: DynFlags -> String
1429 pgm_ranlib dflags = sPgm_ranlib (settings dflags)
1430 pgm_lo :: DynFlags -> (String,[Option])
1431 pgm_lo dflags = sPgm_lo (settings dflags)
1432 pgm_lc :: DynFlags -> (String,[Option])
1433 pgm_lc dflags = sPgm_lc (settings dflags)
1434 pgm_i :: DynFlags -> String
1435 pgm_i dflags = sPgm_i (settings dflags)
1436 opt_L :: DynFlags -> [String]
1437 opt_L dflags = sOpt_L (settings dflags)
1438 opt_P :: DynFlags -> [String]
1439 opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
1440 ++ sOpt_P (settings dflags)
1441
1442 -- This function packages everything that's needed to fingerprint opt_P
1443 -- flags. See Note [Repeated -optP hashing].
1444 opt_P_signature :: DynFlags -> ([String], Fingerprint)
1445 opt_P_signature dflags =
1446 ( concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
1447 , sOpt_P_fingerprint (settings dflags))
1448
1449 opt_F :: DynFlags -> [String]
1450 opt_F dflags = sOpt_F (settings dflags)
1451 opt_c :: DynFlags -> [String]
1452 opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags)
1453 ++ sOpt_c (settings dflags)
1454 opt_cxx :: DynFlags -> [String]
1455 opt_cxx dflags = sOpt_cxx (settings dflags)
1456 opt_a :: DynFlags -> [String]
1457 opt_a dflags = sOpt_a (settings dflags)
1458 opt_l :: DynFlags -> [String]
1459 opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags)
1460 ++ sOpt_l (settings dflags)
1461 opt_windres :: DynFlags -> [String]
1462 opt_windres dflags = sOpt_windres (settings dflags)
1463 opt_lcc :: DynFlags -> [String]
1464 opt_lcc dflags = sOpt_lcc (settings dflags)
1465 opt_lo :: DynFlags -> [String]
1466 opt_lo dflags = sOpt_lo (settings dflags)
1467 opt_lc :: DynFlags -> [String]
1468 opt_lc dflags = sOpt_lc (settings dflags)
1469 opt_i :: DynFlags -> [String]
1470 opt_i dflags = sOpt_i (settings dflags)
1471
1472 -- | The directory for this version of ghc in the user's app directory
1473 -- (typically something like @~/.ghc/x86_64-linux-7.6.3@)
1474 --
1475 versionedAppDir :: DynFlags -> MaybeT IO FilePath
1476 versionedAppDir dflags = do
1477 -- Make sure we handle the case the HOME isn't set (see #11678)
1478 appdir <- tryMaybeT $ getAppUserDataDirectory (programName dflags)
1479 return $ appdir </> versionedFilePath dflags
1480
1481 -- | A filepath like @x86_64-linux-7.6.3@ with the platform string to use when
1482 -- constructing platform-version-dependent files that need to co-exist.
1483 --
1484 versionedFilePath :: DynFlags -> FilePath
1485 versionedFilePath dflags = TARGET_ARCH
1486 ++ '-':TARGET_OS
1487 ++ '-':projectVersion dflags
1488 -- NB: This functionality is reimplemented in Cabal, so if you
1489 -- change it, be sure to update Cabal.
1490
1491 -- | The target code type of the compilation (if any).
1492 --
1493 -- Whenever you change the target, also make sure to set 'ghcLink' to
1494 -- something sensible.
1495 --
1496 -- 'HscNothing' can be used to avoid generating any output, however, note
1497 -- that:
1498 --
1499 -- * If a program uses Template Haskell the typechecker may need to run code
1500 -- from an imported module. To facilitate this, code generation is enabled
1501 -- for modules imported by modules that use template haskell.
1502 -- See Note [-fno-code mode].
1503 --
1504 data HscTarget
1505 = HscC -- ^ Generate C code.
1506 | HscAsm -- ^ Generate assembly using the native code generator.
1507 | HscLlvm -- ^ Generate assembly using the llvm code generator.
1508 | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
1509 | HscNothing -- ^ Don't generate any code. See notes above.
1510 deriving (Eq, Show)
1511
1512 -- | Will this target result in an object file on the disk?
1513 isObjectTarget :: HscTarget -> Bool
1514 isObjectTarget HscC = True
1515 isObjectTarget HscAsm = True
1516 isObjectTarget HscLlvm = True
1517 isObjectTarget _ = False
1518
1519 -- | Does this target retain *all* top-level bindings for a module,
1520 -- rather than just the exported bindings, in the TypeEnv and compiled
1521 -- code (if any)? In interpreted mode we do this, so that GHCi can
1522 -- call functions inside a module. In HscNothing mode we also do it,
1523 -- so that Haddock can get access to the GlobalRdrEnv for a module
1524 -- after typechecking it.
1525 targetRetainsAllBindings :: HscTarget -> Bool
1526 targetRetainsAllBindings HscInterpreted = True
1527 targetRetainsAllBindings HscNothing = True
1528 targetRetainsAllBindings _ = False
1529
1530 -- | The 'GhcMode' tells us whether we're doing multi-module
1531 -- compilation (controlled via the "GHC" API) or one-shot
1532 -- (single-module) compilation. This makes a difference primarily to
1533 -- the "Finder": in one-shot mode we look for interface files for
1534 -- imported modules, but in multi-module mode we look for source files
1535 -- in order to check whether they need to be recompiled.
1536 data GhcMode
1537 = CompManager -- ^ @\-\-make@, GHCi, etc.
1538 | OneShot -- ^ @ghc -c Foo.hs@
1539 | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
1540 deriving Eq
1541
1542 instance Outputable GhcMode where
1543 ppr CompManager = text "CompManager"
1544 ppr OneShot = text "OneShot"
1545 ppr MkDepend = text "MkDepend"
1546
1547 isOneShot :: GhcMode -> Bool
1548 isOneShot OneShot = True
1549 isOneShot _other = False
1550
1551 -- | What to do in the link step, if there is one.
1552 data GhcLink
1553 = NoLink -- ^ Don't link at all
1554 | LinkBinary -- ^ Link object code into a binary
1555 | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
1556 -- bytecode and object code).
1557 | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
1558 | LinkStaticLib -- ^ Link objects into a static lib
1559 deriving (Eq, Show)
1560
1561 isNoLink :: GhcLink -> Bool
1562 isNoLink NoLink = True
1563 isNoLink _ = False
1564
1565 -- | We accept flags which make packages visible, but how they select
1566 -- the package varies; this data type reflects what selection criterion
1567 -- is used.
1568 data PackageArg =
1569 PackageArg String -- ^ @-package@, by 'PackageName'
1570 | UnitIdArg UnitId -- ^ @-package-id@, by 'UnitId'
1571 deriving (Eq, Show)
1572 instance Outputable PackageArg where
1573 ppr (PackageArg pn) = text "package" <+> text pn
1574 ppr (UnitIdArg uid) = text "unit" <+> ppr uid
1575
1576 -- | Represents the renaming that may be associated with an exposed
1577 -- package, e.g. the @rns@ part of @-package "foo (rns)"@.
1578 --
1579 -- Here are some example parsings of the package flags (where
1580 -- a string literal is punned to be a 'ModuleName':
1581 --
1582 -- * @-package foo@ is @ModRenaming True []@
1583 -- * @-package foo ()@ is @ModRenaming False []@
1584 -- * @-package foo (A)@ is @ModRenaming False [("A", "A")]@
1585 -- * @-package foo (A as B)@ is @ModRenaming False [("A", "B")]@
1586 -- * @-package foo with (A as B)@ is @ModRenaming True [("A", "B")]@
1587 data ModRenaming = ModRenaming {
1588 modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope?
1589 modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope
1590 -- under name @n@.
1591 } deriving (Eq)
1592 instance Outputable ModRenaming where
1593 ppr (ModRenaming b rns) = ppr b <+> parens (ppr rns)
1594
1595 -- | Flags for manipulating the set of non-broken packages.
1596 newtype IgnorePackageFlag = IgnorePackage String -- ^ @-ignore-package@
1597 deriving (Eq)
1598
1599 -- | Flags for manipulating package trust.
1600 data TrustFlag
1601 = TrustPackage String -- ^ @-trust@
1602 | DistrustPackage String -- ^ @-distrust@
1603 deriving (Eq)
1604
1605 -- | Flags for manipulating packages visibility.
1606 data PackageFlag
1607 = ExposePackage String PackageArg ModRenaming -- ^ @-package@, @-package-id@
1608 | HidePackage String -- ^ @-hide-package@
1609 deriving (Eq) -- NB: equality instance is used by packageFlagsChanged
1610
1611 data PackageDBFlag
1612 = PackageDB PkgConfRef
1613 | NoUserPackageDB
1614 | NoGlobalPackageDB
1615 | ClearPackageDBs
1616 deriving (Eq)
1617
1618 packageFlagsChanged :: DynFlags -> DynFlags -> Bool
1619 packageFlagsChanged idflags1 idflags0 =
1620 packageFlags idflags1 /= packageFlags idflags0 ||
1621 ignorePackageFlags idflags1 /= ignorePackageFlags idflags0 ||
1622 pluginPackageFlags idflags1 /= pluginPackageFlags idflags0 ||
1623 trustFlags idflags1 /= trustFlags idflags0 ||
1624 packageDBFlags idflags1 /= packageDBFlags idflags0 ||
1625 packageGFlags idflags1 /= packageGFlags idflags0
1626 where
1627 packageGFlags dflags = map (`gopt` dflags)
1628 [ Opt_HideAllPackages
1629 , Opt_HideAllPluginPackages
1630 , Opt_AutoLinkPackages ]
1631
1632 instance Outputable PackageFlag where
1633 ppr (ExposePackage n arg rn) = text n <> braces (ppr arg <+> ppr rn)
1634 ppr (HidePackage str) = text "-hide-package" <+> text str
1635
1636 defaultHscTarget :: Settings -> HscTarget
1637 defaultHscTarget = defaultObjectTarget
1638
1639 -- | The 'HscTarget' value corresponding to the default way to create
1640 -- object files on the current platform.
1641 defaultObjectTarget :: Settings -> HscTarget
1642 defaultObjectTarget settings
1643 | platformUnregisterised platform = HscC
1644 | sGhcWithNativeCodeGen settings = HscAsm
1645 | otherwise = HscLlvm
1646 where
1647 platform = sTargetPlatform settings
1648
1649 -- Determines whether we will be compiling
1650 -- info tables that reside just before the entry code, or with an
1651 -- indirection to the entry code. See TABLES_NEXT_TO_CODE in
1652 -- includes/rts/storage/InfoTables.h.
1653 tablesNextToCode :: DynFlags -> Bool
1654 tablesNextToCode dflags =
1655 not (platformUnregisterised $ targetPlatform dflags) &&
1656 sTablesNextToCode (settings dflags)
1657
1658 data DynLibLoader
1659 = Deployable
1660 | SystemDependent
1661 deriving Eq
1662
1663 data RtsOptsEnabled
1664 = RtsOptsNone | RtsOptsIgnore | RtsOptsIgnoreAll | RtsOptsSafeOnly
1665 | RtsOptsAll
1666 deriving (Show)
1667
1668 shouldUseColor :: DynFlags -> Bool
1669 shouldUseColor dflags = overrideWith (canUseColor dflags) (useColor dflags)
1670
1671 shouldUseHexWordLiterals :: DynFlags -> Bool
1672 shouldUseHexWordLiterals dflags =
1673 Opt_HexWordLiterals `EnumSet.member` generalFlags dflags
1674
1675 -- | Are we building with @-fPIE@ or @-fPIC@ enabled?
1676 positionIndependent :: DynFlags -> Bool
1677 positionIndependent dflags = gopt Opt_PIC dflags || gopt Opt_PIE dflags
1678
1679 -----------------------------------------------------------------------------
1680 -- Ways
1681
1682 -- The central concept of a "way" is that all objects in a given
1683 -- program must be compiled in the same "way". Certain options change
1684 -- parameters of the virtual machine, eg. profiling adds an extra word
1685 -- to the object header, so profiling objects cannot be linked with
1686 -- non-profiling objects.
1687
1688 -- After parsing the command-line options, we determine which "way" we
1689 -- are building - this might be a combination way, eg. profiling+threaded.
1690
1691 -- We then find the "build-tag" associated with this way, and this
1692 -- becomes the suffix used to find .hi files and libraries used in
1693 -- this compilation.
1694
1695 data Way
1696 = WayCustom String -- for GHC API clients building custom variants
1697 | WayThreaded
1698 | WayDebug
1699 | WayProf
1700 | WayEventLog
1701 | WayDyn
1702 deriving (Eq, Ord, Show)
1703
1704 allowed_combination :: [Way] -> Bool
1705 allowed_combination way = and [ x `allowedWith` y
1706 | x <- way, y <- way, x < y ]
1707 where
1708 -- Note ordering in these tests: the left argument is
1709 -- <= the right argument, according to the Ord instance
1710 -- on Way above.
1711
1712 -- dyn is allowed with everything
1713 _ `allowedWith` WayDyn = True
1714 WayDyn `allowedWith` _ = True
1715
1716 -- debug is allowed with everything
1717 _ `allowedWith` WayDebug = True
1718 WayDebug `allowedWith` _ = True
1719
1720 (WayCustom {}) `allowedWith` _ = True
1721 WayThreaded `allowedWith` WayProf = True
1722 WayThreaded `allowedWith` WayEventLog = True
1723 WayProf `allowedWith` WayEventLog = True
1724 _ `allowedWith` _ = False
1725
1726 mkBuildTag :: [Way] -> String
1727 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
1728
1729 wayTag :: Way -> String
1730 wayTag (WayCustom xs) = xs
1731 wayTag WayThreaded = "thr"
1732 wayTag WayDebug = "debug"
1733 wayTag WayDyn = "dyn"
1734 wayTag WayProf = "p"
1735 wayTag WayEventLog = "l"
1736
1737 wayRTSOnly :: Way -> Bool
1738 wayRTSOnly (WayCustom {}) = False
1739 wayRTSOnly WayThreaded = True
1740 wayRTSOnly WayDebug = True
1741 wayRTSOnly WayDyn = False
1742 wayRTSOnly WayProf = False
1743 wayRTSOnly WayEventLog = True
1744
1745 wayDesc :: Way -> String
1746 wayDesc (WayCustom xs) = xs
1747 wayDesc WayThreaded = "Threaded"
1748 wayDesc WayDebug = "Debug"
1749 wayDesc WayDyn = "Dynamic"
1750 wayDesc WayProf = "Profiling"
1751 wayDesc WayEventLog = "RTS Event Logging"
1752
1753 -- Turn these flags on when enabling this way
1754 wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
1755 wayGeneralFlags _ (WayCustom {}) = []
1756 wayGeneralFlags _ WayThreaded = []
1757 wayGeneralFlags _ WayDebug = []
1758 wayGeneralFlags _ WayDyn = [Opt_PIC, Opt_ExternalDynamicRefs]
1759 -- We could get away without adding -fPIC when compiling the
1760 -- modules of a program that is to be linked with -dynamic; the
1761 -- program itself does not need to be position-independent, only
1762 -- the libraries need to be. HOWEVER, GHCi links objects into a
1763 -- .so before loading the .so using the system linker. Since only
1764 -- PIC objects can be linked into a .so, we have to compile even
1765 -- modules of the main program with -fPIC when using -dynamic.
1766 wayGeneralFlags _ WayProf = [Opt_SccProfilingOn]
1767 wayGeneralFlags _ WayEventLog = []
1768
1769 -- Turn these flags off when enabling this way
1770 wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
1771 wayUnsetGeneralFlags _ (WayCustom {}) = []
1772 wayUnsetGeneralFlags _ WayThreaded = []
1773 wayUnsetGeneralFlags _ WayDebug = []
1774 wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting
1775 -- when we're going to be dynamically
1776 -- linking. Plus it breaks compilation
1777 -- on OSX x86.
1778 Opt_SplitSections]
1779 wayUnsetGeneralFlags _ WayProf = []
1780 wayUnsetGeneralFlags _ WayEventLog = []
1781
1782 wayOptc :: Platform -> Way -> [String]
1783 wayOptc _ (WayCustom {}) = []
1784 wayOptc platform WayThreaded = case platformOS platform of
1785 OSOpenBSD -> ["-pthread"]
1786 OSNetBSD -> ["-pthread"]
1787 _ -> []
1788 wayOptc _ WayDebug = []
1789 wayOptc _ WayDyn = []
1790 wayOptc _ WayProf = ["-DPROFILING"]
1791 wayOptc _ WayEventLog = ["-DTRACING"]
1792
1793 wayOptl :: Platform -> Way -> [String]
1794 wayOptl _ (WayCustom {}) = []
1795 wayOptl platform WayThreaded =
1796 case platformOS platform of
1797 OSFreeBSD -> ["-pthread"]
1798 OSOpenBSD -> ["-pthread"]
1799 OSNetBSD -> ["-pthread"]
1800 _ -> []
1801 wayOptl _ WayDebug = []
1802 wayOptl _ WayDyn = []
1803 wayOptl _ WayProf = []
1804 wayOptl _ WayEventLog = []
1805
1806 wayOptP :: Platform -> Way -> [String]
1807 wayOptP _ (WayCustom {}) = []
1808 wayOptP _ WayThreaded = []
1809 wayOptP _ WayDebug = []
1810 wayOptP _ WayDyn = []
1811 wayOptP _ WayProf = ["-DPROFILING"]
1812 wayOptP _ WayEventLog = ["-DTRACING"]
1813
1814 whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1815 whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ())
1816
1817 ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1818 ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g
1819
1820 whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1821 whenCannotGenerateDynamicToo dflags f
1822 = ifCannotGenerateDynamicToo dflags f (return ())
1823
1824 ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1825 ifCannotGenerateDynamicToo dflags f g
1826 = generateDynamicTooConditional dflags g f g
1827
1828 generateDynamicTooConditional :: MonadIO m
1829 => DynFlags -> m a -> m a -> m a -> m a
1830 generateDynamicTooConditional dflags canGen cannotGen notTryingToGen
1831 = if gopt Opt_BuildDynamicToo dflags
1832 then do let ref = canGenerateDynamicToo dflags
1833 b <- liftIO $ readIORef ref
1834 if b then canGen else cannotGen
1835 else notTryingToGen
1836
1837 dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags
1838 dynamicTooMkDynamicDynFlags dflags0
1839 = let dflags1 = addWay' WayDyn dflags0
1840 dflags2 = dflags1 {
1841 outputFile = dynOutputFile dflags1,
1842 hiSuf = dynHiSuf dflags1,
1843 objectSuf = dynObjectSuf dflags1
1844 }
1845 dflags3 = updateWays dflags2
1846 dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo
1847 in dflags4
1848
1849 -- | Compute the path of the dynamic object corresponding to an object file.
1850 dynamicOutputFile :: DynFlags -> FilePath -> FilePath
1851 dynamicOutputFile dflags outputFile = dynOut outputFile
1852 where
1853 dynOut = flip addExtension (dynObjectSuf dflags) . dropExtension
1854
1855 -----------------------------------------------------------------------------
1856
1857 -- | Used by 'GHC.runGhc' to partially initialize a new 'DynFlags' value
1858 initDynFlags :: DynFlags -> IO DynFlags
1859 initDynFlags dflags = do
1860 let -- We can't build with dynamic-too on Windows, as labels before
1861 -- the fork point are different depending on whether we are
1862 -- building dynamically or not.
1863 platformCanGenerateDynamicToo
1864 = platformOS (targetPlatform dflags) /= OSMinGW32
1865 refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo
1866 refNextTempSuffix <- newIORef 0
1867 refFilesToClean <- newIORef emptyFilesToClean
1868 refDirsToClean <- newIORef Map.empty
1869 refGeneratedDumps <- newIORef Set.empty
1870 refRtldInfo <- newIORef Nothing
1871 refRtccInfo <- newIORef Nothing
1872 wrapperNum <- newIORef emptyModuleEnv
1873 canUseUnicode <- do let enc = localeEncoding
1874 str = "‘’"
1875 (withCString enc str $ \cstr ->
1876 do str' <- peekCString enc cstr
1877 return (str == str'))
1878 `catchIOError` \_ -> return False
1879 canUseColor <- stderrSupportsAnsiColors
1880 maybeGhcColorsEnv <- lookupEnv "GHC_COLORS"
1881 maybeGhcColoursEnv <- lookupEnv "GHC_COLOURS"
1882 let adjustCols (Just env) = Col.parseScheme env
1883 adjustCols Nothing = id
1884 let (useColor', colScheme') =
1885 (adjustCols maybeGhcColoursEnv . adjustCols maybeGhcColorsEnv)
1886 (useColor dflags, colScheme dflags)
1887 return dflags{
1888 canGenerateDynamicToo = refCanGenerateDynamicToo,
1889 nextTempSuffix = refNextTempSuffix,
1890 filesToClean = refFilesToClean,
1891 dirsToClean = refDirsToClean,
1892 generatedDumps = refGeneratedDumps,
1893 nextWrapperNum = wrapperNum,
1894 useUnicode = canUseUnicode,
1895 useColor = useColor',
1896 canUseColor = canUseColor,
1897 colScheme = colScheme',
1898 rtldInfo = refRtldInfo,
1899 rtccInfo = refRtccInfo
1900 }
1901
1902 -- | The normal 'DynFlags'. Note that they are not suitable for use in this form
1903 -- and must be fully initialized by 'GHC.runGhc' first.
1904 defaultDynFlags :: Settings -> LlvmConfig -> DynFlags
1905 defaultDynFlags mySettings (myLlvmTargets, myLlvmPasses) =
1906 -- See Note [Updating flag description in the User's Guide]
1907 DynFlags {
1908 ghcMode = CompManager,
1909 ghcLink = LinkBinary,
1910 hscTarget = defaultHscTarget mySettings,
1911 integerLibrary = sIntegerLibraryType mySettings,
1912 verbosity = 0,
1913 optLevel = 0,
1914 debugLevel = 0,
1915 simplPhases = 2,
1916 maxSimplIterations = 4,
1917 maxPmCheckIterations = 2000000,
1918 ruleCheck = Nothing,
1919 inlineCheck = Nothing,
1920 binBlobThreshold = 500000, -- 500K is a good default (see #16190)
1921 maxRelevantBinds = Just 6,
1922 maxValidHoleFits = Just 6,
1923 maxRefHoleFits = Just 6,
1924 refLevelHoleFits = Nothing,
1925 maxUncoveredPatterns = 4,
1926 simplTickFactor = 100,
1927 specConstrThreshold = Just 2000,
1928 specConstrCount = Just 3,
1929 specConstrRecursive = 3,
1930 liberateCaseThreshold = Just 2000,
1931 floatLamArgs = Just 0, -- Default: float only if no fvs
1932 liftLamsRecArgs = Just 5, -- Default: the number of available argument hardware registers on x86_64
1933 liftLamsNonRecArgs = Just 5, -- Default: the number of available argument hardware registers on x86_64
1934 liftLamsKnown = False, -- Default: don't turn known calls into unknown ones
1935 cmmProcAlignment = Nothing,
1936
1937 historySize = 20,
1938 strictnessBefore = [],
1939
1940 parMakeCount = Just 1,
1941
1942 enableTimeStats = False,
1943 ghcHeapSize = Nothing,
1944
1945 importPaths = ["."],
1946 mainModIs = mAIN,
1947 mainFunIs = Nothing,
1948 reductionDepth = treatZeroAsInf mAX_REDUCTION_DEPTH,
1949 solverIterations = treatZeroAsInf mAX_SOLVER_ITERATIONS,
1950
1951 thisInstalledUnitId = toInstalledUnitId mainUnitId,
1952 thisUnitIdInsts_ = Nothing,
1953 thisComponentId_ = Nothing,
1954
1955 objectDir = Nothing,
1956 dylibInstallName = Nothing,
1957 hiDir = Nothing,
1958 hieDir = Nothing,
1959 stubDir = Nothing,
1960 dumpDir = Nothing,
1961
1962 objectSuf = phaseInputExt StopLn,
1963 hcSuf = phaseInputExt HCc,
1964 hiSuf = "hi",
1965 hieSuf = "hie",
1966
1967 canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo",
1968 dynObjectSuf = "dyn_" ++ phaseInputExt StopLn,
1969 dynHiSuf = "dyn_hi",
1970
1971 pluginModNames = [],
1972 pluginModNameOpts = [],
1973 frontendPluginOpts = [],
1974 cachedPlugins = [],
1975 staticPlugins = [],
1976 hooks = emptyHooks,
1977
1978 outputFile = Nothing,
1979 dynOutputFile = Nothing,
1980 outputHi = Nothing,
1981 dynLibLoader = SystemDependent,
1982 dumpPrefix = Nothing,
1983 dumpPrefixForce = Nothing,
1984 ldInputs = [],
1985 includePaths = IncludeSpecs [] [],
1986 libraryPaths = [],
1987 frameworkPaths = [],
1988 cmdlineFrameworks = [],
1989 rtsOpts = Nothing,
1990 rtsOptsEnabled = RtsOptsSafeOnly,
1991 rtsOptsSuggestions = True,
1992
1993 hpcDir = ".hpc",
1994
1995 packageDBFlags = [],
1996 packageFlags = [],
1997 pluginPackageFlags = [],
1998 ignorePackageFlags = [],
1999 trustFlags = [],
2000 packageEnv = Nothing,
2001 pkgDatabase = Nothing,
2002 -- This gets filled in with GHC.setSessionDynFlags
2003 pkgState = emptyPackageState,
2004 ways = defaultWays mySettings,
2005 buildTag = mkBuildTag (defaultWays mySettings),
2006 splitInfo = Nothing,
2007 settings = mySettings,
2008 llvmTargets = myLlvmTargets,
2009 llvmPasses = myLlvmPasses,
2010
2011 -- ghc -M values
2012 depMakefile = "Makefile",
2013 depIncludePkgDeps = False,
2014 depIncludeCppDeps = False,
2015 depExcludeMods = [],
2016 depSuffixes = [],
2017 -- end of ghc -M values
2018 nextTempSuffix = panic "defaultDynFlags: No nextTempSuffix",
2019 filesToClean = panic "defaultDynFlags: No filesToClean",
2020 dirsToClean = panic "defaultDynFlags: No dirsToClean",
2021 generatedDumps = panic "defaultDynFlags: No generatedDumps",
2022 ghcVersionFile = Nothing,
2023 haddockOptions = Nothing,
2024 dumpFlags = EnumSet.empty,
2025 generalFlags = EnumSet.fromList (defaultFlags mySettings),
2026 warningFlags = EnumSet.fromList standardWarnings,
2027 fatalWarningFlags = EnumSet.empty,
2028 ghciScripts = [],
2029 language = Nothing,
2030 safeHaskell = Sf_None,
2031 safeInfer = True,
2032 safeInferred = True,
2033 thOnLoc = noSrcSpan,
2034 newDerivOnLoc = noSrcSpan,
2035 overlapInstLoc = noSrcSpan,
2036 incoherentOnLoc = noSrcSpan,
2037 pkgTrustOnLoc = noSrcSpan,
2038 warnSafeOnLoc = noSrcSpan,
2039 warnUnsafeOnLoc = noSrcSpan,
2040 trustworthyOnLoc = noSrcSpan,
2041 extensions = [],
2042 extensionFlags = flattenExtensionFlags Nothing [],
2043
2044 -- The ufCreationThreshold threshold must be reasonably high to
2045 -- take account of possible discounts.
2046 -- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline
2047 -- into Csg.calc (The unfolding for sqr never makes it into the
2048 -- interface file.)
2049 ufCreationThreshold = 750,
2050 ufUseThreshold = 60,
2051 ufFunAppDiscount = 60,
2052 -- Be fairly keen to inline a function if that means
2053 -- we'll be able to pick the right method from a dictionary
2054 ufDictDiscount = 30,
2055 ufKeenessFactor = 1.5,
2056 ufDearOp = 40,
2057 ufVeryAggressive = False,
2058
2059 maxWorkerArgs = 10,
2060
2061 ghciHistSize = 50, -- keep a log of length 50 by default
2062
2063 -- Logging
2064
2065 log_action = defaultLogAction,
2066
2067 flushOut = defaultFlushOut,
2068 flushErr = defaultFlushErr,
2069 pprUserLength = 5,
2070 pprCols = 100,
2071 useUnicode = False,
2072 useColor = Auto,
2073 canUseColor = False,
2074 colScheme = Col.defaultScheme,
2075 profAuto = NoProfAuto,
2076 interactivePrint = Nothing,
2077 nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum",
2078 sseVersion = Nothing,
2079 bmiVersion = Nothing,
2080 avx = False,
2081 avx2 = False,
2082 avx512cd = False,
2083 avx512er = False,
2084 avx512f = False,
2085 avx512pf = False,
2086 rtldInfo = panic "defaultDynFlags: no rtldInfo",
2087 rtccInfo = panic "defaultDynFlags: no rtccInfo",
2088
2089 maxInlineAllocSize = 128,
2090 maxInlineMemcpyInsns = 32,
2091 maxInlineMemsetInsns = 32,
2092
2093 initialUnique = 0,
2094 uniqueIncrement = 1,
2095
2096 reverseErrors = False,
2097 maxErrors = Nothing,
2098 cfgWeightInfo = defaultCfgWeights
2099 }
2100
2101 defaultWays :: Settings -> [Way]
2102 defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
2103 then [WayDyn]
2104 else []
2105
2106 interpWays :: [Way]
2107 interpWays
2108 | dynamicGhc = [WayDyn]
2109 | rtsIsProfiled = [WayProf]
2110 | otherwise = []
2111
2112 interpreterProfiled :: DynFlags -> Bool
2113 interpreterProfiled dflags
2114 | gopt Opt_ExternalInterpreter dflags = gopt Opt_SccProfilingOn dflags
2115 | otherwise = rtsIsProfiled
2116
2117 interpreterDynamic :: DynFlags -> Bool
2118 interpreterDynamic dflags
2119 | gopt Opt_ExternalInterpreter dflags = WayDyn `elem` ways dflags
2120 | otherwise = dynamicGhc
2121
2122 --------------------------------------------------------------------------
2123 --
2124 -- Note [JSON Error Messages]
2125 --
2126 -- When the user requests the compiler output to be dumped as json
2127 -- we used to collect them all in an IORef and then print them at the end.
2128 -- This doesn't work very well with GHCi. (See #14078) So instead we now
2129 -- use the simpler method of just outputting a JSON document inplace to
2130 -- stdout.
2131 --
2132 -- Before the compiler calls log_action, it has already turned the `ErrMsg`
2133 -- into a formatted message. This means that we lose some possible
2134 -- information to provide to the user but refactoring log_action is quite
2135 -- invasive as it is called in many places. So, for now I left it alone
2136 -- and we can refine its behaviour as users request different output.
2137
2138 type FatalMessager = String -> IO ()
2139
2140 type LogAction = DynFlags
2141 -> WarnReason
2142 -> Severity
2143 -> SrcSpan
2144 -> PprStyle
2145 -> MsgDoc
2146 -> IO ()
2147
2148 defaultFatalMessager :: FatalMessager
2149 defaultFatalMessager = hPutStrLn stderr
2150
2151
2152 -- See Note [JSON Error Messages]
2153 --
2154 jsonLogAction :: LogAction
2155 jsonLogAction dflags reason severity srcSpan _style msg
2156 = do
2157 defaultLogActionHPutStrDoc dflags stdout (doc $$ text "")
2158 (mkCodeStyle CStyle)
2159 where
2160 doc = renderJSON $
2161 JSObject [ ( "span", json srcSpan )
2162 , ( "doc" , JSString (showSDoc dflags msg) )
2163 , ( "severity", json severity )
2164 , ( "reason" , json reason )
2165 ]
2166
2167
2168 defaultLogAction :: LogAction
2169 defaultLogAction dflags reason severity srcSpan style msg
2170 = case severity of
2171 SevOutput -> printOut msg style
2172 SevDump -> printOut (msg $$ blankLine) style
2173 SevInteractive -> putStrSDoc msg style
2174 SevInfo -> printErrs msg style
2175 SevFatal -> printErrs msg style
2176 SevWarning -> printWarns
2177 SevError -> printWarns
2178 where
2179 printOut = defaultLogActionHPrintDoc dflags stdout
2180 printErrs = defaultLogActionHPrintDoc dflags stderr
2181 putStrSDoc = defaultLogActionHPutStrDoc dflags stdout
2182 -- Pretty print the warning flag, if any (#10752)
2183 message = mkLocMessageAnn flagMsg severity srcSpan msg
2184
2185 printWarns = do
2186 hPutChar stderr '\n'
2187 caretDiagnostic <-
2188 if gopt Opt_DiagnosticsShowCaret dflags
2189 then getCaretDiagnostic severity srcSpan
2190 else pure empty
2191 printErrs (message $+$ caretDiagnostic)
2192 (setStyleColoured True style)
2193 -- careful (#2302): printErrs prints in UTF-8,
2194 -- whereas converting to string first and using
2195 -- hPutStr would just emit the low 8 bits of
2196 -- each unicode char.
2197
2198 flagMsg =
2199 case reason of
2200 NoReason -> Nothing
2201 Reason wflag -> do
2202 spec <- flagSpecOf wflag
2203 return ("-W" ++ flagSpecName spec ++ warnFlagGrp wflag)
2204 ErrReason Nothing ->
2205 return "-Werror"
2206 ErrReason (Just wflag) -> do
2207 spec <- flagSpecOf wflag
2208 return $
2209 "-W" ++ flagSpecName spec ++ warnFlagGrp wflag ++
2210 ", -Werror=" ++ flagSpecName spec
2211
2212 warnFlagGrp flag
2213 | gopt Opt_ShowWarnGroups dflags =
2214 case smallestGroups flag of
2215 [] -> ""
2216 groups -> " (in " ++ intercalate ", " (map ("-W"++) groups) ++ ")"
2217 | otherwise = ""
2218
2219 -- | Like 'defaultLogActionHPutStrDoc' but appends an extra newline.
2220 defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
2221 defaultLogActionHPrintDoc dflags h d sty
2222 = defaultLogActionHPutStrDoc dflags h (d $$ text "") sty
2223
2224 defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
2225 defaultLogActionHPutStrDoc dflags h d sty
2226 -- Don't add a newline at the end, so that successive
2227 -- calls to this log-action can output all on the same line
2228 = printSDoc Pretty.PageMode dflags h sty d
2229
2230 newtype FlushOut = FlushOut (IO ())
2231
2232 defaultFlushOut :: FlushOut
2233 defaultFlushOut = FlushOut $ hFlush stdout
2234
2235 newtype FlushErr = FlushErr (IO ())
2236
2237 defaultFlushErr :: FlushErr
2238 defaultFlushErr = FlushErr $ hFlush stderr
2239
2240 {-
2241 Note [Verbosity levels]
2242 ~~~~~~~~~~~~~~~~~~~~~~~
2243 0 | print errors & warnings only
2244 1 | minimal verbosity: print "compiling M ... done." for each module.
2245 2 | equivalent to -dshow-passes
2246 3 | equivalent to existing "ghc -v"
2247 4 | "ghc -v -ddump-most"
2248 5 | "ghc -v -ddump-all"
2249 -}
2250
2251 data OnOff a = On a
2252 | Off a
2253 deriving (Eq, Show)
2254
2255 instance Outputable a => Outputable (OnOff a) where
2256 ppr (On x) = text "On" <+> ppr x
2257 ppr (Off x) = text "Off" <+> ppr x
2258
2259 -- OnOffs accumulate in reverse order, so we use foldr in order to
2260 -- process them in the right order
2261 flattenExtensionFlags :: Maybe Language -> [OnOff LangExt.Extension] -> EnumSet LangExt.Extension
2262 flattenExtensionFlags ml = foldr f defaultExtensionFlags
2263 where f (On f) flags = EnumSet.insert f flags
2264 f (Off f) flags = EnumSet.delete f flags
2265 defaultExtensionFlags = EnumSet.fromList (languageExtensions ml)
2266
2267 languageExtensions :: Maybe Language -> [LangExt.Extension]
2268
2269 languageExtensions Nothing
2270 -- Nothing => the default case
2271 = LangExt.NondecreasingIndentation -- This has been on by default for some time
2272 : delete LangExt.DatatypeContexts -- The Haskell' committee decided to
2273 -- remove datatype contexts from the
2274 -- language:
2275 -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
2276 (languageExtensions (Just Haskell2010))
2277
2278 -- NB: MonoPatBinds is no longer the default
2279
2280 languageExtensions (Just Haskell98)
2281 = [LangExt.ImplicitPrelude,
2282 -- See Note [When is StarIsType enabled]
2283 LangExt.StarIsType,
2284 LangExt.CUSKs,
2285 LangExt.MonomorphismRestriction,
2286 LangExt.NPlusKPatterns,
2287 LangExt.DatatypeContexts,
2288 LangExt.TraditionalRecordSyntax,
2289 LangExt.NondecreasingIndentation
2290 -- strictly speaking non-standard, but we always had this
2291 -- on implicitly before the option was added in 7.1, and
2292 -- turning it off breaks code, so we're keeping it on for
2293 -- backwards compatibility. Cabal uses -XHaskell98 by
2294 -- default unless you specify another language.
2295 ]
2296
2297 languageExtensions (Just Haskell2010)
2298 = [LangExt.ImplicitPrelude,
2299 -- See Note [When is StarIsType enabled]
2300 LangExt.StarIsType,
2301 LangExt.CUSKs,
2302 LangExt.MonomorphismRestriction,
2303 LangExt.DatatypeContexts,
2304 LangExt.TraditionalRecordSyntax,
2305 LangExt.EmptyDataDecls,
2306 LangExt.ForeignFunctionInterface,
2307 LangExt.PatternGuards,
2308 LangExt.DoAndIfThenElse,
2309 LangExt.RelaxedPolyRec]
2310
2311 hasPprDebug :: DynFlags -> Bool
2312 hasPprDebug = dopt Opt_D_ppr_debug
2313
2314 hasNoDebugOutput :: DynFlags -> Bool
2315 hasNoDebugOutput = dopt Opt_D_no_debug_output
2316
2317 hasNoStateHack :: DynFlags -> Bool
2318 hasNoStateHack = gopt Opt_G_NoStateHack
2319
2320 hasNoOptCoercion :: DynFlags -> Bool
2321 hasNoOptCoercion = gopt Opt_G_NoOptCoercion
2322
2323
2324 -- | Test whether a 'DumpFlag' is set
2325 dopt :: DumpFlag -> DynFlags -> Bool
2326 dopt f dflags = (f `EnumSet.member` dumpFlags dflags)
2327 || (verbosity dflags >= 4 && enableIfVerbose f)
2328 where enableIfVerbose Opt_D_dump_tc_trace = False
2329 enableIfVerbose Opt_D_dump_rn_trace = False
2330 enableIfVerbose Opt_D_dump_cs_trace = False
2331 enableIfVerbose Opt_D_dump_if_trace = False
2332 enableIfVerbose Opt_D_dump_vt_trace = False
2333 enableIfVerbose Opt_D_dump_tc = False
2334 enableIfVerbose Opt_D_dump_rn = False
2335 enableIfVerbose Opt_D_dump_shape = False
2336 enableIfVerbose Opt_D_dump_rn_stats = False
2337 enableIfVerbose Opt_D_dump_hi_diffs = False
2338 enableIfVerbose Opt_D_verbose_core2core = False
2339 enableIfVerbose Opt_D_verbose_stg2stg = False
2340 enableIfVerbose Opt_D_dump_splices = False
2341 enableIfVerbose Opt_D_th_dec_file = False
2342 enableIfVerbose Opt_D_dump_rule_firings = False
2343 enableIfVerbose Opt_D_dump_rule_rewrites = False
2344 enableIfVerbose Opt_D_dump_simpl_trace = False
2345 enableIfVerbose Opt_D_dump_rtti = False
2346 enableIfVerbose Opt_D_dump_inlinings = False
2347 enableIfVerbose Opt_D_dump_core_stats = False
2348 enableIfVerbose Opt_D_dump_asm_stats = False
2349 enableIfVerbose Opt_D_dump_types = False
2350 enableIfVerbose Opt_D_dump_simpl_iterations = False
2351 enableIfVerbose Opt_D_dump_ticked = False
2352 enableIfVerbose Opt_D_dump_view_pattern_commoning = False
2353 enableIfVerbose Opt_D_dump_mod_cycles = False
2354 enableIfVerbose Opt_D_dump_mod_map = False
2355 enableIfVerbose Opt_D_dump_ec_trace = False
2356 enableIfVerbose _ = True
2357
2358 -- | Set a 'DumpFlag'
2359 dopt_set :: DynFlags -> DumpFlag -> DynFlags
2360 dopt_set dfs f = dfs{ dumpFlags = EnumSet.insert f (dumpFlags dfs) }
2361
2362 -- | Unset a 'DumpFlag'
2363 dopt_unset :: DynFlags -> DumpFlag -> DynFlags
2364 dopt_unset dfs f = dfs{ dumpFlags = EnumSet.delete f (dumpFlags dfs) }
2365
2366 -- | Test whether a 'GeneralFlag' is set
2367 gopt :: GeneralFlag -> DynFlags -> Bool
2368 gopt f dflags = f `EnumSet.member` generalFlags dflags
2369
2370 -- | Set a 'GeneralFlag'
2371 gopt_set :: DynFlags -> GeneralFlag -> DynFlags
2372 gopt_set dfs f = dfs{ generalFlags = EnumSet.insert f (generalFlags dfs) }
2373
2374 -- | Unset a 'GeneralFlag'
2375 gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
2376 gopt_unset dfs f = dfs{ generalFlags = EnumSet.delete f (generalFlags dfs) }
2377
2378 -- | Test whether a 'WarningFlag' is set
2379 wopt :: WarningFlag -> DynFlags -> Bool
2380 wopt f dflags = f `EnumSet.member` warningFlags dflags
2381
2382 -- | Set a 'WarningFlag'
2383 wopt_set :: DynFlags -> WarningFlag -> DynFlags
2384 wopt_set dfs f = dfs{ warningFlags = EnumSet.insert f (warningFlags dfs) }
2385
2386 -- | Unset a 'WarningFlag'
2387 wopt_unset :: DynFlags -> WarningFlag -> DynFlags
2388 wopt_unset dfs f = dfs{ warningFlags = EnumSet.delete f (warningFlags dfs) }
2389
2390 -- | Test whether a 'WarningFlag' is set as fatal
2391 wopt_fatal :: WarningFlag -> DynFlags -> Bool
2392 wopt_fatal f dflags = f `EnumSet.member` fatalWarningFlags dflags
2393
2394 -- | Mark a 'WarningFlag' as fatal (do not set the flag)
2395 wopt_set_fatal :: DynFlags -> WarningFlag -> DynFlags
2396 wopt_set_fatal dfs f
2397 = dfs { fatalWarningFlags = EnumSet.insert f (fatalWarningFlags dfs) }
2398
2399 -- | Mark a 'WarningFlag' as not fatal
2400 wopt_unset_fatal :: DynFlags -> WarningFlag -> DynFlags
2401 wopt_unset_fatal dfs f
2402 = dfs { fatalWarningFlags = EnumSet.delete f (fatalWarningFlags dfs) }
2403
2404 -- | Test whether a 'LangExt.Extension' is set
2405 xopt :: LangExt.Extension -> DynFlags -> Bool
2406 xopt f dflags = f `EnumSet.member` extensionFlags dflags
2407
2408 -- | Set a 'LangExt.Extension'
2409 xopt_set :: DynFlags -> LangExt.Extension -> DynFlags
2410 xopt_set dfs f
2411 = let onoffs = On f : extensions dfs
2412 in dfs { extensions = onoffs,
2413 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
2414
2415 -- | Unset a 'LangExt.Extension'
2416 xopt_unset :: DynFlags -> LangExt.Extension -> DynFlags
2417 xopt_unset dfs f
2418 = let onoffs = Off f : extensions dfs
2419 in dfs { extensions = onoffs,
2420 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
2421
2422 -- | Set or unset a 'LangExt.Extension', unless it has been explicitly
2423 -- set or unset before.
2424 xopt_set_unlessExplSpec
2425 :: LangExt.Extension
2426 -> (DynFlags -> LangExt.Extension -> DynFlags)
2427 -> DynFlags -> DynFlags
2428 xopt_set_unlessExplSpec ext setUnset dflags =
2429 let referedExts = stripOnOff <$> extensions dflags
2430 stripOnOff (On x) = x
2431 stripOnOff (Off x) = x
2432 in
2433 if ext `elem` referedExts then dflags else setUnset dflags ext
2434
2435 lang_set :: DynFlags -> Maybe Language -> DynFlags
2436 lang_set dflags lang =
2437 dflags {
2438 language = lang,
2439 extensionFlags = flattenExtensionFlags lang (extensions dflags)
2440 }
2441
2442 -- | An internal helper to check whether to use unicode syntax for output.
2443 --
2444 -- Note: You should very likely be using 'Outputable.unicodeSyntax' instead
2445 -- of this function.
2446 useUnicodeSyntax :: DynFlags -> Bool
2447 useUnicodeSyntax = gopt Opt_PrintUnicodeSyntax
2448
2449 useStarIsType :: DynFlags -> Bool
2450 useStarIsType = xopt LangExt.StarIsType
2451
2452 -- | Set the Haskell language standard to use
2453 setLanguage :: Language -> DynP ()
2454 setLanguage l = upd (`lang_set` Just l)
2455
2456 -- | Some modules have dependencies on others through the DynFlags rather than textual imports
2457 dynFlagDependencies :: DynFlags -> [ModuleName]
2458 dynFlagDependencies = pluginModNames
2459
2460 -- | Is the -fpackage-trust mode on
2461 packageTrustOn :: DynFlags -> Bool
2462 packageTrustOn = gopt Opt_PackageTrust
2463
2464 -- | Is Safe Haskell on in some way (including inference mode)
2465 safeHaskellOn :: DynFlags -> Bool
2466 safeHaskellOn dflags = safeHaskellModeEnabled dflags || safeInferOn dflags
2467
2468 safeHaskellModeEnabled :: DynFlags -> Bool
2469 safeHaskellModeEnabled dflags = safeHaskell dflags `elem` [Sf_Unsafe, Sf_Trustworthy
2470 , Sf_Safe ]
2471
2472
2473 -- | Is the Safe Haskell safe language in use
2474 safeLanguageOn :: DynFlags -> Bool
2475 safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
2476
2477 -- | Is the Safe Haskell safe inference mode active
2478 safeInferOn :: DynFlags -> Bool
2479 safeInferOn = safeInfer
2480
2481 -- | Test if Safe Imports are on in some form
2482 safeImportsOn :: DynFlags -> Bool
2483 safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
2484 safeHaskell dflags == Sf_Trustworthy ||
2485 safeHaskell dflags == Sf_Safe
2486
2487 -- | Set a 'Safe Haskell' flag
2488 setSafeHaskell :: SafeHaskellMode -> DynP ()
2489 setSafeHaskell s = updM f
2490 where f dfs = do
2491 let sf = safeHaskell dfs
2492 safeM <- combineSafeFlags sf s
2493 case s of
2494 Sf_Safe -> return $ dfs { safeHaskell = safeM, safeInfer = False }
2495 -- leave safe inferrence on in Trustworthy mode so we can warn
2496 -- if it could have been inferred safe.
2497 Sf_Trustworthy -> do
2498 l <- getCurLoc
2499 return $ dfs { safeHaskell = safeM, trustworthyOnLoc = l }
2500 -- leave safe inference on in Unsafe mode as well.
2501 _ -> return $ dfs { safeHaskell = safeM }
2502
2503 -- | Are all direct imports required to be safe for this Safe Haskell mode?
2504 -- Direct imports are when the code explicitly imports a module
2505 safeDirectImpsReq :: DynFlags -> Bool
2506 safeDirectImpsReq d = safeLanguageOn d
2507
2508 -- | Are all implicit imports required to be safe for this Safe Haskell mode?
2509 -- Implicit imports are things in the prelude. e.g System.IO when print is used.
2510 safeImplicitImpsReq :: DynFlags -> Bool
2511 safeImplicitImpsReq d = safeLanguageOn d
2512
2513 -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
2514 -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
2515 -- want to export this functionality from the module but do want to export the
2516 -- type constructors.
2517 combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
2518 combineSafeFlags a b | a == Sf_None = return b
2519 | b == Sf_None = return a
2520 | a == Sf_Ignore || b == Sf_Ignore = return Sf_Ignore
2521 | a == b = return a
2522 | otherwise = addErr errm >> pure a
2523 where errm = "Incompatible Safe Haskell flags! ("
2524 ++ show a ++ ", " ++ show b ++ ")"
2525
2526 -- | A list of unsafe flags under Safe Haskell. Tuple elements are:
2527 -- * name of the flag
2528 -- * function to get srcspan that enabled the flag
2529 -- * function to test if the flag is on
2530 -- * function to turn the flag off
2531 unsafeFlags, unsafeFlagsForInfer
2532 :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
2533 unsafeFlags = [ ("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
2534 xopt LangExt.GeneralizedNewtypeDeriving,
2535 flip xopt_unset LangExt.GeneralizedNewtypeDeriving)
2536 , ("-XTemplateHaskell", thOnLoc,
2537 xopt LangExt.TemplateHaskell,
2538 flip xopt_unset LangExt.TemplateHaskell)
2539 ]
2540 unsafeFlagsForInfer = unsafeFlags
2541
2542
2543 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
2544 getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
2545 -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
2546 -> [a] -- ^ Correctly ordered extracted options
2547 getOpts dflags opts = reverse (opts dflags)
2548 -- We add to the options from the front, so we need to reverse the list
2549
2550 -- | Gets the verbosity flag for the current verbosity level. This is fed to
2551 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
2552 getVerbFlags :: DynFlags -> [String]
2553 getVerbFlags dflags
2554 | verbosity dflags >= 4 = ["-v"]
2555 | otherwise = []
2556
2557 setObjectDir, setHiDir, setHieDir, setStubDir, setDumpDir, setOutputDir,
2558 setDynObjectSuf, setDynHiSuf,
2559 setDylibInstallName,
2560 setObjectSuf, setHiSuf, setHieSuf, setHcSuf, parseDynLibLoaderMode,
2561 setPgmP, addOptl, addOptc, addOptcxx, addOptP,
2562 addCmdlineFramework, addHaddockOpts, addGhciScript,
2563 setInteractivePrint
2564 :: String -> DynFlags -> DynFlags
2565 setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce
2566 :: Maybe String -> DynFlags -> DynFlags
2567
2568 setObjectDir f d = d { objectDir = Just f}
2569 setHiDir f d = d { hiDir = Just f}
2570 setHieDir f d = d { hieDir = Just f}
2571 setStubDir f d = d { stubDir = Just f
2572 , includePaths = addGlobalInclude (includePaths d) [f] }
2573 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
2574 -- \#included from the .hc file when compiling via C (i.e. unregisterised
2575 -- builds).
2576 setDumpDir f d = d { dumpDir = Just f}
2577 setOutputDir f = setObjectDir f
2578 . setHieDir f
2579 . setHiDir f
2580 . setStubDir f
2581 . setDumpDir f
2582 setDylibInstallName f d = d { dylibInstallName = Just f}
2583
2584 setObjectSuf f d = d { objectSuf = f}
2585 setDynObjectSuf f d = d { dynObjectSuf = f}
2586 setHiSuf f d = d { hiSuf = f}
2587 setHieSuf f d = d { hieSuf = f}
2588 setDynHiSuf f d = d { dynHiSuf = f}
2589 setHcSuf f d = d { hcSuf = f}
2590
2591 setOutputFile f d = d { outputFile = f}
2592 setDynOutputFile f d = d { dynOutputFile = f}
2593 setOutputHi f d = d { outputHi = f}
2594
2595 setJsonLogAction :: DynFlags -> DynFlags
2596 setJsonLogAction d = d { log_action = jsonLogAction }
2597
2598 thisComponentId :: DynFlags -> ComponentId
2599 thisComponentId dflags =
2600 case thisComponentId_ dflags of
2601 Just cid -> cid
2602 Nothing ->
2603 case thisUnitIdInsts_ dflags of
2604 Just _ ->
2605 throwGhcException $ CmdLineError ("Use of -instantiated-with requires -this-component-id")
2606 Nothing -> ComponentId (unitIdFS (thisPackage dflags))
2607
2608 thisUnitIdInsts :: DynFlags -> [(ModuleName, Module)]
2609 thisUnitIdInsts dflags =
2610 case thisUnitIdInsts_ dflags of
2611 Just insts -> insts
2612 Nothing -> []
2613
2614 thisPackage :: DynFlags -> UnitId
2615 thisPackage dflags =
2616 case thisUnitIdInsts_ dflags of
2617 Nothing -> default_uid
2618 Just insts
2619 | all (\(x,y) -> mkHoleModule x == y) insts
2620 -> newUnitId (thisComponentId dflags) insts
2621 | otherwise
2622 -> default_uid
2623 where
2624 default_uid = DefiniteUnitId (DefUnitId (thisInstalledUnitId dflags))
2625
2626 parseUnitIdInsts :: String -> [(ModuleName, Module)]
2627 parseUnitIdInsts str = case filter ((=="").snd) (readP_to_S parse str) of
2628 [(r, "")] -> r
2629 _ -> throwGhcException $ CmdLineError ("Can't parse -instantiated-with: " ++ str)
2630 where parse = sepBy parseEntry (R.char ',')
2631 parseEntry = do
2632 n <- parseModuleName
2633 _ <- R.char '='
2634 m <- parseModuleId
2635 return (n, m)
2636
2637 setUnitIdInsts :: String -> DynFlags -> DynFlags
2638 setUnitIdInsts s d =
2639 d { thisUnitIdInsts_ = Just (parseUnitIdInsts s) }
2640
2641 setComponentId :: String -> DynFlags -> DynFlags
2642 setComponentId s d =
2643 d { thisComponentId_ = Just (ComponentId (fsLit s)) }
2644
2645 addPluginModuleName :: String -> DynFlags -> DynFlags
2646 addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
2647
2648 clearPluginModuleNames :: DynFlags -> DynFlags
2649 clearPluginModuleNames d =
2650 d { pluginModNames = []
2651 , pluginModNameOpts = []
2652 , cachedPlugins = [] }
2653
2654 addPluginModuleNameOption :: String -> DynFlags -> DynFlags
2655 addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
2656 where (m, rest) = break (== ':') optflag
2657 option = case rest of
2658 [] -> "" -- should probably signal an error
2659 (_:plug_opt) -> plug_opt -- ignore the ':' from break
2660
2661 addFrontendPluginOption :: String -> DynFlags -> DynFlags
2662 addFrontendPluginOption s d = d { frontendPluginOpts = s : frontendPluginOpts d }
2663
2664 parseDynLibLoaderMode f d =
2665 case splitAt 8 f of
2666 ("deploy", "") -> d { dynLibLoader = Deployable }
2667 ("sysdep", "") -> d { dynLibLoader = SystemDependent }
2668 _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f))
2669
2670 setDumpPrefixForce f d = d { dumpPrefixForce = f}
2671
2672 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
2673 -- Config.hs should really use Option.
2674 setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
2675 addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
2676 addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s})
2677 addOptcxx f = alterSettings (\s -> s { sOpt_cxx = f : sOpt_cxx s})
2678 addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s
2679 , sOpt_P_fingerprint = fingerprintStrings (f : sOpt_P s)
2680 })
2681 -- See Note [Repeated -optP hashing]
2682 where
2683 fingerprintStrings ss = fingerprintFingerprints $ map fingerprintString ss
2684
2685
2686 setDepMakefile :: FilePath -> DynFlags -> DynFlags
2687 setDepMakefile f d = d { depMakefile = f }
2688
2689 setDepIncludeCppDeps :: Bool -> DynFlags -> DynFlags
2690 setDepIncludeCppDeps b d = d { depIncludeCppDeps = b }
2691
2692 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
2693 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
2694
2695 addDepExcludeMod :: String -> DynFlags -> DynFlags
2696 addDepExcludeMod m d
2697 = d { depExcludeMods = mkModuleName m : depExcludeMods d }
2698
2699 addDepSuffix :: FilePath -> DynFlags -> DynFlags
2700 addDepSuffix s d = d { depSuffixes = s : depSuffixes d }
2701
2702 addCmdlineFramework f d = d { cmdlineFrameworks = f : cmdlineFrameworks d}
2703
2704 addGhcVersionFile :: FilePath -> DynFlags -> DynFlags
2705 addGhcVersionFile f d = d { ghcVersionFile = Just f }
2706
2707 addHaddockOpts f d = d { haddockOptions = Just f}
2708
2709 addGhciScript f d = d { ghciScripts = f : ghciScripts d}
2710
2711 setInteractivePrint f d = d { interactivePrint = Just f}
2712
2713 -- -----------------------------------------------------------------------------
2714 -- Command-line options
2715
2716 -- | When invoking external tools as part of the compilation pipeline, we
2717 -- pass these a sequence of options on the command-line. Rather than
2718 -- just using a list of Strings, we use a type that allows us to distinguish
2719 -- between filepaths and 'other stuff'. The reason for this is that
2720 -- this type gives us a handle on transforming filenames, and filenames only,
2721 -- to whatever format they're expected to be on a particular platform.
2722 data Option
2723 = FileOption -- an entry that _contains_ filename(s) / filepaths.
2724 String -- a non-filepath prefix that shouldn't be
2725 -- transformed (e.g., "/out=")
2726 String -- the filepath/filename portion
2727 | Option String
2728 deriving ( Eq )
2729
2730 showOpt :: Option -> String
2731 showOpt (FileOption pre f) = pre ++ f
2732 showOpt (Option s) = s
2733
2734 -----------------------------------------------------------------------------
2735 -- Setting the optimisation level
2736
2737 updOptLevel :: Int -> DynFlags -> DynFlags
2738 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
2739 updOptLevel n dfs
2740 = dfs2{ optLevel = final_n }
2741 where
2742 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
2743 dfs1 = foldr (flip gopt_unset) dfs remove_gopts
2744 dfs2 = foldr (flip gopt_set) dfs1 extra_gopts
2745
2746 extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
2747 remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
2748
2749 {- **********************************************************************
2750 %* *
2751 DynFlags parser
2752 %* *
2753 %********************************************************************* -}
2754
2755 -- -----------------------------------------------------------------------------
2756 -- Parsing the dynamic flags.
2757
2758
2759 -- | Parse dynamic flags from a list of command line arguments. Returns the
2760 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
2761 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
2762 -- flags or missing arguments).
2763 parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String]
2764 -> m (DynFlags, [Located String], [Warn])
2765 -- ^ Updated 'DynFlags', left-over arguments, and
2766 -- list of warnings.
2767 parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True
2768
2769
2770 -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
2771 -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
2772 -- Used to parse flags set in a modules pragma.
2773 parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String]
2774 -> m (DynFlags, [Located String], [Warn])
2775 -- ^ Updated 'DynFlags', left-over arguments, and
2776 -- list of warnings.
2777 parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False
2778
2779
2780 -- | Parses the dynamically set flags for GHC. This is the most general form of
2781 -- the dynamic flag parser that the other methods simply wrap. It allows
2782 -- saying which flags are valid flags and indicating if we are parsing
2783 -- arguments from the command line or from a file pragma.
2784 parseDynamicFlagsFull :: MonadIO m
2785 => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against
2786 -> Bool -- ^ are the arguments from the command line?
2787 -> DynFlags -- ^ current dynamic flags
2788 -> [Located String] -- ^ arguments to parse
2789 -> m (DynFlags, [Located String], [Warn])
2790 parseDynamicFlagsFull activeFlags cmdline dflags0 args = do
2791 let ((leftover, errs, warns), dflags1)
2792 = runCmdLine (processArgs activeFlags args) dflags0
2793
2794 -- See Note [Handling errors when parsing commandline flags]
2795 unless (null errs) $ liftIO $ throwGhcExceptionIO $ errorsToGhcException $
2796 map ((showPpr dflags0 . getLoc &&& unLoc) . errMsg) $ errs
2797
2798 -- check for disabled flags in safe haskell
2799 let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
2800 dflags3 = updateWays dflags2
2801 theWays = ways dflags3
2802
2803 unless (allowed_combination theWays) $ liftIO $
2804 throwGhcExceptionIO (CmdLineError ("combination not supported: " ++
2805 intercalate "/" (map wayDesc theWays)))
2806
2807 let chooseOutput
2808 | isJust (outputFile dflags3) -- Only iff user specified -o ...
2809 , not (isJust (dynOutputFile dflags3)) -- but not -dyno
2810 = return $ dflags3 { dynOutputFile = Just $ dynamicOutputFile dflags3 outFile }
2811 | otherwise
2812 = return dflags3
2813 where
2814 outFile = fromJust $ outputFile dflags3
2815 dflags4 <- ifGeneratingDynamicToo dflags3 chooseOutput (return dflags3)
2816
2817 let (dflags5, consistency_warnings) = makeDynFlagsConsistent dflags4
2818
2819 -- Set timer stats & heap size
2820 when (enableTimeStats dflags5) $ liftIO enableTimingStats
2821 case (ghcHeapSize dflags5) of
2822 Just x -> liftIO (setHeapSize x)
2823 _ -> return ()
2824
2825 liftIO $ setUnsafeGlobalDynFlags dflags5
2826
2827 let warns' = map (Warn Cmd.NoReason) (consistency_warnings ++ sh_warns)
2828
2829 return (dflags5, leftover, warns' ++ warns)
2830
2831 -- | Write an error or warning to the 'LogOutput'.
2832 putLogMsg :: DynFlags -> WarnReason -> Severity -> SrcSpan -> PprStyle
2833 -> MsgDoc -> IO ()
2834 putLogMsg dflags = log_action dflags dflags
2835
2836 updateWays :: DynFlags -> DynFlags
2837 updateWays dflags
2838 = let theWays = sort $ nub $ ways dflags
2839 in dflags {
2840 ways = theWays,
2841 buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays)
2842 }
2843
2844 -- | Check (and potentially disable) any extensions that aren't allowed
2845 -- in safe mode.
2846 --
2847 -- The bool is to indicate if we are parsing command line flags (false means
2848 -- file pragma). This allows us to generate better warnings.
2849 safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
2850 safeFlagCheck _ dflags | safeLanguageOn dflags = (dflagsUnset, warns)
2851 where
2852 -- Handle illegal flags under safe language.
2853 (dflagsUnset, warns) = foldl' check_method (dflags, []) unsafeFlags
2854
2855 check_method (df, warns) (str,loc,test,fix)
2856 | test df = (fix df, warns ++ safeFailure (loc df) str)
2857 | otherwise = (df, warns)
2858
2859 safeFailure loc str
2860 = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring "
2861 ++ str]
2862
2863 safeFlagCheck cmdl dflags =
2864 case (safeInferOn dflags) of
2865 True | safeFlags -> (dflags', warn)
2866 True -> (dflags' { safeInferred = False }, warn)
2867 False -> (dflags', warn)
2868
2869 where
2870 -- dynflags and warn for when -fpackage-trust by itself with no safe
2871 -- haskell flag
2872 (dflags', warn)
2873 | not (safeHaskellModeEnabled dflags) && not cmdl && packageTrustOn dflags
2874 = (gopt_unset dflags Opt_PackageTrust, pkgWarnMsg)
2875 | otherwise = (dflags, [])
2876
2877 pkgWarnMsg = [L (pkgTrustOnLoc dflags') $
2878 "-fpackage-trust ignored;" ++
2879 " must be specified with a Safe Haskell flag"]
2880
2881 -- Have we inferred Unsafe? See Note [HscMain . Safe Haskell Inference]
2882 safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer
2883
2884
2885 {- **********************************************************************
2886 %* *
2887 DynFlags specifications
2888 %* *
2889 %********************************************************************* -}
2890
2891 -- | All dynamic flags option strings without the deprecated ones.
2892 -- These are the user facing strings for enabling and disabling options.
2893 allNonDeprecatedFlags :: [String]
2894 allNonDeprecatedFlags = allFlagsDeps False
2895
2896 -- | All flags with possibility to filter deprecated ones
2897 allFlagsDeps :: Bool -> [String]
2898 allFlagsDeps keepDeprecated = [ '-':flagName flag
2899 | (deprecated, flag) <- flagsAllDeps
2900 , keepDeprecated || not (isDeprecated deprecated)]
2901 where isDeprecated Deprecated = True
2902 isDeprecated _ = False
2903
2904 {-
2905 - Below we export user facing symbols for GHC dynamic flags for use with the
2906 - GHC API.
2907 -}
2908
2909 -- All dynamic flags present in GHC.
2910 flagsAll :: [Flag (CmdLineP DynFlags)]
2911 flagsAll = map snd flagsAllDeps
2912
2913 -- All dynamic flags present in GHC with deprecation information.
2914 flagsAllDeps :: [(Deprecation, Flag (CmdLineP DynFlags))]
2915 flagsAllDeps = package_flags_deps ++ dynamic_flags_deps
2916
2917
2918 -- All dynamic flags, minus package flags, present in GHC.
2919 flagsDynamic :: [Flag (CmdLineP DynFlags)]
2920 flagsDynamic = map snd dynamic_flags_deps
2921
2922 -- ALl package flags present in GHC.
2923 flagsPackage :: [Flag (CmdLineP DynFlags)]
2924 flagsPackage = map snd package_flags_deps
2925
2926 ----------------Helpers to make flags and keep deprecation information----------
2927
2928 type FlagMaker m = String -> OptKind m -> Flag m
2929 type DynFlagMaker = FlagMaker (CmdLineP DynFlags)
2930 data Deprecation = NotDeprecated | Deprecated deriving (Eq, Ord)
2931
2932 -- Make a non-deprecated flag
2933 make_ord_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags)
2934 -> (Deprecation, Flag (CmdLineP DynFlags))
2935 make_ord_flag fm name kind = (NotDeprecated, fm name kind)
2936
2937 -- Make a deprecated flag
2938 make_dep_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags) -> String
2939 -> (Deprecation, Flag (CmdLineP DynFlags))
2940 make_dep_flag fm name kind message = (Deprecated,
2941 fm name $ add_dep_message kind message)
2942
2943 add_dep_message :: OptKind (CmdLineP DynFlags) -> String
2944 -> OptKind (CmdLineP DynFlags)
2945 add_dep_message (NoArg f) message = NoArg $ f >> deprecate message
2946 add_dep_message (HasArg f) message = HasArg $ \s -> f s >> deprecate message
2947 add_dep_message (SepArg f) message = SepArg $ \s -> f s >> deprecate message
2948 add_dep_message (Prefix f) message = Prefix $ \s -> f s >> deprecate message
2949 add_dep_message (OptPrefix f) message =
2950 OptPrefix $ \s -> f s >> deprecate message
2951 add_dep_message (OptIntSuffix f) message =
2952 OptIntSuffix $ \oi -> f oi >> deprecate message
2953 add_dep_message (IntSuffix f) message =
2954 IntSuffix $ \i -> f i >> deprecate message
2955 add_dep_message (FloatSuffix f) message =
2956 FloatSuffix $ \fl -> f fl >> deprecate message
2957 add_dep_message (PassFlag f) message =
2958 PassFlag $ \s -> f s >> deprecate message
2959 add_dep_message (AnySuffix f) message =
2960 AnySuffix $ \s -> f s >> deprecate message
2961
2962 ----------------------- The main flags themselves ------------------------------
2963 -- See Note [Updating flag description in the User's Guide]
2964 -- See Note [Supporting CLI completion]
2965 dynamic_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))]
2966 dynamic_flags_deps = [
2967 make_dep_flag defFlag "n" (NoArg $ return ())
2968 "The -n flag is deprecated and no longer has any effect"
2969 , make_ord_flag defFlag "cpp" (NoArg (setExtensionFlag LangExt.Cpp))
2970 , make_ord_flag defFlag "F" (NoArg (setGeneralFlag Opt_Pp))
2971 , (Deprecated, defFlag "#include"
2972 (HasArg (\_s ->
2973 deprecate ("-#include and INCLUDE pragmas are " ++
2974 "deprecated: They no longer have any effect"))))
2975 , make_ord_flag defFlag "v" (OptIntSuffix setVerbosity)
2976
2977 , make_ord_flag defGhcFlag "j" (OptIntSuffix
2978 (\n -> case n of
2979 Just n
2980 | n > 0 -> upd (\d -> d { parMakeCount = Just n })
2981 | otherwise -> addErr "Syntax: -j[n] where n > 0"
2982 Nothing -> upd (\d -> d { parMakeCount = Nothing })))
2983 -- When the number of parallel builds
2984 -- is omitted, it is the same
2985 -- as specifing that the number of
2986 -- parallel builds is equal to the
2987 -- result of getNumProcessors
2988 , make_ord_flag defFlag "instantiated-with" (sepArg setUnitIdInsts)
2989 , make_ord_flag defFlag "this-component-id" (sepArg setComponentId)
2990
2991 -- RTS options -------------------------------------------------------------
2992 , make_ord_flag defFlag "H" (HasArg (\s -> upd (\d ->
2993 d { ghcHeapSize = Just $ fromIntegral (decodeSize s)})))
2994
2995 , make_ord_flag defFlag "Rghc-timing" (NoArg (upd (\d ->
2996 d { enableTimeStats = True })))
2997
2998 ------- ways ---------------------------------------------------------------
2999 , make_ord_flag defGhcFlag "prof" (NoArg (addWay WayProf))
3000 , make_ord_flag defGhcFlag "eventlog" (NoArg (addWay WayEventLog))
3001 , make_dep_flag defGhcFlag "smp"
3002 (NoArg $ addWay WayThreaded) "Use -threaded instead"
3003 , make_ord_flag defGhcFlag "debug" (NoArg (addWay WayDebug))
3004 , make_ord_flag defGhcFlag "threaded" (NoArg (addWay WayThreaded))
3005
3006 , make_ord_flag defGhcFlag "ticky"
3007 (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
3008
3009 -- -ticky enables ticky-ticky code generation, and also implies -debug which
3010 -- is required to get the RTS ticky support.
3011
3012 ----- Linker --------------------------------------------------------
3013 , make_ord_flag defGhcFlag "static" (NoArg removeWayDyn)
3014 , make_ord_flag defGhcFlag "dynamic" (NoArg (addWay WayDyn))
3015 , make_ord_flag defGhcFlag "rdynamic" $ noArg $
3016 #if defined(linux_HOST_OS)
3017 addOptl "-rdynamic"
3018 #elif defined (mingw32_HOST_OS)
3019 addOptl "-Wl,--export-all-symbols"
3020 #else
3021 -- ignored for compat w/ gcc:
3022 id
3023 #endif
3024 , make_ord_flag defGhcFlag "relative-dynlib-paths"
3025 (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
3026 , make_ord_flag defGhcFlag "copy-libs-when-linking"
3027 (NoArg (setGeneralFlag Opt_SingleLibFolder))
3028 , make_ord_flag defGhcFlag "pie" (NoArg (setGeneralFlag Opt_PICExecutable))
3029 , make_ord_flag defGhcFlag "no-pie" (NoArg (unSetGeneralFlag Opt_PICExecutable))
3030
3031 ------- Specific phases --------------------------------------------
3032 -- need to appear before -pgmL to be parsed as LLVM flags.
3033 , make_ord_flag defFlag "pgmlo"
3034 (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
3035 , make_ord_flag defFlag "pgmlc"
3036 (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
3037 , make_ord_flag defFlag "pgmi"
3038 (hasArg (\f -> alterSettings (\s -> s { sPgm_i = f})))
3039 , make_ord_flag defFlag "pgmL"
3040 (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
3041 , make_ord_flag defFlag "pgmP"
3042 (hasArg setPgmP)
3043 , make_ord_flag defFlag "pgmF"
3044 (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
3045 , make_ord_flag defFlag "pgmc"
3046 (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[]),
3047 -- Don't pass -no-pie with -pgmc
3048 -- (see #15319)
3049 sGccSupportsNoPie = False})))
3050 , make_ord_flag defFlag "pgms"
3051 (HasArg (\_ -> addWarn "Object splitting was removed in GHC 8.8"))
3052 , make_ord_flag defFlag "pgma"
3053 (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
3054 , make_ord_flag defFlag "pgml"
3055 (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
3056 , make_ord_flag defFlag "pgmdll"
3057 (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
3058 , make_ord_flag defFlag "pgmwindres"
3059 (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
3060 , make_ord_flag defFlag "pgmlibtool"
3061 (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f})))
3062 , make_ord_flag defFlag "pgmar"
3063 (hasArg (\f -> alterSettings (\s -> s { sPgm_ar = f})))
3064 , make_ord_flag defFlag "pgmranlib"
3065 (hasArg (\f -> alterSettings (\s -> s { sPgm_ranlib = f})))
3066
3067
3068 -- need to appear before -optl/-opta to be parsed as LLVM flags.
3069 , make_ord_flag defFlag "optlo"
3070 (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
3071 , make_ord_flag defFlag "optlc"
3072 (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
3073 , make_ord_flag defFlag "opti"
3074 (hasArg (\f -> alterSettings (\s -> s { sOpt_i = f : sOpt_i s})))
3075 , make_ord_flag defFlag "optL"
3076 (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
3077 , make_ord_flag defFlag "optP"
3078 (hasArg addOptP)
3079 , make_ord_flag defFlag "optF"
3080 (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
3081 , make_ord_flag defFlag "optc"
3082 (hasArg addOptc)
3083 , make_ord_flag defFlag "optcxx"
3084 (hasArg addOptcxx)
3085 , make_ord_flag defFlag "opta"
3086 (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
3087 , make_ord_flag defFlag "optl"
3088 (hasArg addOptl)
3089 , make_ord_flag defFlag "optwindres"
3090 (hasArg (\f ->
3091 alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
3092
3093 , make_ord_flag defGhcFlag "split-objs"
3094 (NoArg $ addWarn "ignoring -split-objs")
3095
3096 , make_ord_flag defGhcFlag "split-sections"
3097 (noArgM (\dflags -> do
3098 if platformHasSubsectionsViaSymbols (targetPlatform dflags)
3099 then do addErr $
3100 "-split-sections is not useful on this platform " ++
3101 "since it always uses subsections via symbols."
3102 return dflags
3103 else return (gopt_set dflags Opt_SplitSections)))
3104
3105 -------- ghc -M -----------------------------------------------------
3106 , make_ord_flag defGhcFlag "dep-suffix" (hasArg addDepSuffix)
3107 , make_ord_flag defGhcFlag "dep-makefile" (hasArg setDepMakefile)
3108 , make_ord_flag defGhcFlag "include-cpp-deps"
3109 (noArg (setDepIncludeCppDeps True))
3110 , make_ord_flag defGhcFlag "include-pkg-deps"
3111 (noArg (setDepIncludePkgDeps True))
3112 , make_ord_flag defGhcFlag "exclude-module" (hasArg addDepExcludeMod)
3113
3114 -------- Linking ----------------------------------------------------
3115 , make_ord_flag defGhcFlag "no-link"
3116 (noArg (\d -> d { ghcLink=NoLink }))
3117 , make_ord_flag defGhcFlag "shared"
3118 (noArg (\d -> d { ghcLink=LinkDynLib }))
3119 , make_ord_flag defGhcFlag "staticlib"
3120 (noArg (\d -> d { ghcLink=LinkStaticLib }))
3121 , make_ord_flag defGhcFlag "dynload" (hasArg parseDynLibLoaderMode)
3122 , make_ord_flag defGhcFlag "dylib-install-name" (hasArg setDylibInstallName)
3123
3124 ------- Libraries ---------------------------------------------------
3125 , make_ord_flag defFlag "L" (Prefix addLibraryPath)
3126 , make_ord_flag defFlag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
3127
3128 ------- Frameworks --------------------------------------------------
3129 -- -framework-path should really be -F ...
3130 , make_ord_flag defFlag "framework-path" (HasArg addFrameworkPath)
3131 , make_ord_flag defFlag "framework" (hasArg addCmdlineFramework)
3132
3133 ------- Output Redirection ------------------------------------------
3134 , make_ord_flag defGhcFlag "odir" (hasArg setObjectDir)
3135 , make_ord_flag defGhcFlag "o" (sepArg (setOutputFile . Just))
3136 , make_ord_flag defGhcFlag "dyno"
3137 (sepArg (setDynOutputFile . Just))
3138 , make_ord_flag defGhcFlag "ohi"
3139 (hasArg (setOutputHi . Just ))
3140 , make_ord_flag defGhcFlag "osuf" (hasArg setObjectSuf)
3141 , make_ord_flag defGhcFlag "dynosuf" (hasArg setDynObjectSuf)
3142 , make_ord_flag defGhcFlag "hcsuf" (hasArg setHcSuf)
3143 , make_ord_flag defGhcFlag "hisuf" (hasArg setHiSuf)
3144 , make_ord_flag defGhcFlag "hiesuf" (hasArg setHieSuf)
3145 , make_ord_flag defGhcFlag "dynhisuf" (hasArg setDynHiSuf)
3146 , make_ord_flag defGhcFlag "hidir" (hasArg setHiDir)
3147 , make_ord_flag defGhcFlag "hiedir" (hasArg setHieDir)
3148 , make_ord_flag defGhcFlag "tmpdir" (hasArg setTmpDir)
3149 , make_ord_flag defGhcFlag "stubdir" (hasArg setStubDir)
3150 , make_ord_flag defGhcFlag "dumpdir" (hasArg setDumpDir)
3151 , make_ord_flag defGhcFlag "outputdir" (hasArg setOutputDir)
3152 , make_ord_flag defGhcFlag "ddump-file-prefix"
3153 (hasArg (setDumpPrefixForce . Just))
3154
3155 , make_ord_flag defGhcFlag "dynamic-too"
3156 (NoArg (setGeneralFlag Opt_BuildDynamicToo))
3157
3158 ------- Keeping temporary files -------------------------------------
3159 -- These can be singular (think ghc -c) or plural (think ghc --make)
3160 , make_ord_flag defGhcFlag "keep-hc-file"
3161 (NoArg (setGeneralFlag Opt_KeepHcFiles))
3162 , make_ord_flag defGhcFlag "keep-hc-files"
3163 (NoArg (setGeneralFlag Opt_KeepHcFiles))
3164 , make_ord_flag defGhcFlag "keep-hscpp-file"
3165 (NoArg (setGeneralFlag Opt_KeepHscppFiles))
3166 , make_ord_flag defGhcFlag "keep-hscpp-files"
3167 (NoArg (setGeneralFlag Opt_KeepHscppFiles))
3168 , make_ord_flag defGhcFlag "keep-s-file"
3169 (NoArg (setGeneralFlag Opt_KeepSFiles))
3170 , make_ord_flag defGhcFlag "keep-s-files"
3171 (NoArg (setGeneralFlag Opt_KeepSFiles))
3172 , make_ord_flag defGhcFlag "keep-llvm-file"
3173 (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles)
3174 , make_ord_flag defGhcFlag "keep-llvm-files"
3175 (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles)
3176 -- This only makes sense as plural
3177 , make_ord_flag defGhcFlag "keep-tmp-files"
3178 (NoArg (setGeneralFlag Opt_KeepTmpFiles))
3179 , make_ord_flag defGhcFlag "keep-hi-file"
3180 (NoArg (setGeneralFlag Opt_KeepHiFiles))
3181 , make_ord_flag defGhcFlag "no-keep-hi-file"
3182 (NoArg (unSetGeneralFlag Opt_KeepHiFiles))
3183 , make_ord_flag defGhcFlag "keep-hi-files"
3184 (NoArg (setGeneralFlag Opt_KeepHiFiles))
3185 , make_ord_flag defGhcFlag "no-keep-hi-files"
3186 (NoArg (unSetGeneralFlag Opt_KeepHiFiles))
3187 , make_ord_flag defGhcFlag "keep-o-file"
3188 (NoArg (setGeneralFlag Opt_KeepOFiles))
3189 , make_ord_flag defGhcFlag "no-keep-o-file"
3190 (NoArg (unSetGeneralFlag Opt_KeepOFiles))
3191 , make_ord_flag defGhcFlag "keep-o-files"
3192 (NoArg (setGeneralFlag Opt_KeepOFiles))
3193 , make_ord_flag defGhcFlag "no-keep-o-files"
3194 (NoArg (unSetGeneralFlag Opt_KeepOFiles))
3195
3196 ------- Miscellaneous ----------------------------------------------
3197 , make_ord_flag defGhcFlag "no-auto-link-packages"
3198 (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
3199 , make_ord_flag defGhcFlag "no-hs-main"
3200 (NoArg (setGeneralFlag Opt_NoHsMain))
3201 , make_ord_flag defGhcFlag "fno-state-hack"
3202 (NoArg (setGeneralFlag Opt_G_NoStateHack))
3203 , make_ord_flag defGhcFlag "fno-opt-coercion"
3204 (NoArg (setGeneralFlag Opt_G_NoOptCoercion))
3205 , make_ord_flag defGhcFlag "with-rtsopts"
3206 (HasArg setRtsOpts)
3207 , make_ord_flag defGhcFlag "rtsopts"
3208 (NoArg (setRtsOptsEnabled RtsOptsAll))
3209 , make_ord_flag defGhcFlag "rtsopts=all"
3210 (NoArg (setRtsOptsEnabled RtsOptsAll))
3211 , make_ord_flag defGhcFlag "rtsopts=some"
3212 (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
3213 , make_ord_flag defGhcFlag "rtsopts=none"
3214 (NoArg (setRtsOptsEnabled RtsOptsNone))
3215 , make_ord_flag defGhcFlag "rtsopts=ignore"
3216 (NoArg (setRtsOptsEnabled RtsOptsIgnore))
3217 , make_ord_flag defGhcFlag "rtsopts=ignoreAll"
3218 (NoArg (setRtsOptsEnabled RtsOptsIgnoreAll))
3219 , make_ord_flag defGhcFlag "no-rtsopts"
3220 (NoArg (setRtsOptsEnabled RtsOptsNone))
3221 , make_ord_flag defGhcFlag "no-rtsopts-suggestions"
3222 (noArg (\d -> d {rtsOptsSuggestions = False}))
3223 , make_ord_flag defGhcFlag "dhex-word-literals"
3224 (NoArg (setGeneralFlag Opt_HexWordLiterals))
3225
3226 , make_ord_flag defGhcFlag "ghcversion-file" (hasArg addGhcVersionFile)
3227 , make_ord_flag defGhcFlag "main-is" (SepArg setMainIs)
3228 , make_ord_flag defGhcFlag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
3229 , make_ord_flag defGhcFlag "haddock-opts" (hasArg addHaddockOpts)
3230 , make_ord_flag defGhcFlag "hpcdir" (SepArg setOptHpcDir)
3231 , make_ord_flag defGhciFlag "ghci-script" (hasArg addGhciScript)
3232 , make_ord_flag defGhciFlag "interactive-print" (hasArg setInteractivePrint)
3233 , make_ord_flag defGhcFlag "ticky-allocd"
3234 (NoArg (setGeneralFlag Opt_Ticky_Allocd))
3235 , make_ord_flag defGhcFlag "ticky-LNE"
3236 (NoArg (setGeneralFlag Opt_Ticky_LNE))
3237 , make_ord_flag defGhcFlag "ticky-dyn-thunk"
3238 (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
3239 ------- recompilation checker --------------------------------------
3240 , make_dep_flag defGhcFlag "recomp"
3241 (NoArg $ unSetGeneralFlag Opt_ForceRecomp)
3242 "Use -fno-force-recomp instead"
3243 , make_dep_flag defGhcFlag "no-recomp"
3244 (NoArg $ setGeneralFlag Opt_ForceRecomp) "Use -fforce-recomp instead"
3245 , make_ord_flag defFlag "fmax-errors"
3246 (intSuffix (\n d -> d { maxErrors = Just (max 1 n) }))
3247 , make_ord_flag defFlag "fno-max-errors"
3248 (noArg (\d -> d { maxErrors = Nothing }))
3249 , make_ord_flag defFlag "freverse-errors"
3250 (noArg (\d -> d {reverseErrors = True} ))
3251 , make_ord_flag defFlag "fno-reverse-errors"
3252 (noArg (\d -> d {reverseErrors = False} ))
3253
3254 ------ HsCpp opts ---------------------------------------------------
3255 , make_ord_flag defFlag "D" (AnySuffix (upd . addOptP))
3256 , make_ord_flag defFlag "U" (AnySuffix (upd . addOptP))
3257
3258 ------- Include/Import Paths ----------------------------------------
3259 , make_ord_flag defFlag "I" (Prefix addIncludePath)
3260 , make_ord_flag defFlag "i" (OptPrefix addImportPath)
3261
3262 ------ Output style options -----------------------------------------
3263 , make_ord_flag defFlag "dppr-user-length" (intSuffix (\n d ->
3264 d { pprUserLength = n }))
3265 , make_ord_flag defFlag "dppr-cols" (intSuffix (\n d ->
3266 d { pprCols = n }))
3267 , make_ord_flag defFlag "fdiagnostics-color=auto"
3268 (NoArg (upd (\d -> d { useColor = Auto })))
3269 , make_ord_flag defFlag "fdiagnostics-color=always"
3270 (NoArg (upd (\d -> d { useColor = Always })))
3271 , make_ord_flag defFlag "fdiagnostics-color=never"
3272 (NoArg (upd (\d -> d { useColor = Never })))
3273
3274 -- Suppress all that is suppressable in core dumps.
3275 -- Except for uniques, as some simplifier phases introduce new variables that
3276 -- have otherwise identical names.
3277 , make_ord_flag defGhcFlag "dsuppress-all"
3278 (NoArg $ do setGeneralFlag Opt_SuppressCoercions
3279 setGeneralFlag Opt_SuppressVarKinds
3280 setGeneralFlag Opt_SuppressModulePrefixes
3281 setGeneralFlag Opt_SuppressTypeApplications
3282 setGeneralFlag Opt_SuppressIdInfo
3283 setGeneralFlag Opt_SuppressTicks
3284 setGeneralFlag Opt_SuppressStgExts
3285 setGeneralFlag Opt_SuppressTypeSignatures
3286 setGeneralFlag Opt_SuppressTimestamps)
3287
3288 ------ Debugging ----------------------------------------------------
3289 , make_ord_flag defGhcFlag "dstg-stats"
3290 (NoArg (setGeneralFlag Opt_StgStats))
3291
3292 , make_ord_flag defGhcFlag "ddump-cmm"
3293 (setDumpFlag Opt_D_dump_cmm)
3294 , make_ord_flag defGhcFlag "ddump-cmm-from-stg"
3295 (setDumpFlag Opt_D_dump_cmm_from_stg)
3296 , make_ord_flag defGhcFlag "ddump-cmm-raw"
3297 (setDumpFlag Opt_D_dump_cmm_raw)
3298 , make_ord_flag defGhcFlag "ddump-cmm-verbose"
3299 (setDumpFlag Opt_D_dump_cmm_verbose)
3300 , make_ord_flag defGhcFlag "ddump-cmm-cfg"
3301 (setDumpFlag Opt_D_dump_cmm_cfg)
3302 , make_ord_flag defGhcFlag "ddump-cmm-cbe"
3303 (setDumpFlag Opt_D_dump_cmm_cbe)
3304 , make_ord_flag defGhcFlag "ddump-cmm-switch"
3305 (setDumpFlag Opt_D_dump_cmm_switch)
3306 , make_ord_flag defGhcFlag "ddump-cmm-proc"
3307 (setDumpFlag Opt_D_dump_cmm_proc)
3308 , make_ord_flag defGhcFlag "ddump-cmm-sp"
3309 (setDumpFlag Opt_D_dump_cmm_sp)
3310 , make_ord_flag defGhcFlag "ddump-cmm-sink"
3311 (setDumpFlag Opt_D_dump_cmm_sink)
3312 , make_ord_flag defGhcFlag "ddump-cmm-caf"
3313 (setDumpFlag Opt_D_dump_cmm_caf)
3314 , make_ord_flag defGhcFlag "ddump-cmm-procmap"
3315 (setDumpFlag Opt_D_dump_cmm_procmap)
3316 , make_ord_flag defGhcFlag "ddump-cmm-split"
3317 (setDumpFlag Opt_D_dump_cmm_split)
3318 , make_ord_flag defGhcFlag "ddump-cmm-info"
3319 (setDumpFlag Opt_D_dump_cmm_info)
3320 , make_ord_flag defGhcFlag "ddump-cmm-cps"
3321 (setDumpFlag Opt_D_dump_cmm_cps)
3322 , make_ord_flag defGhcFlag "ddump-cfg-weights"
3323 (setDumpFlag Opt_D_dump_cfg_weights)
3324 , make_ord_flag defGhcFlag "ddump-core-stats"
3325 (setDumpFlag Opt_D_dump_core_stats)
3326 , make_ord_flag defGhcFlag "ddump-asm"
3327 (setDumpFlag Opt_D_dump_asm)
3328 , make_ord_flag defGhcFlag "ddump-asm-native"
3329 (setDumpFlag Opt_D_dump_asm_native)
3330 , make_ord_flag defGhcFlag "ddump-asm-liveness"
3331 (setDumpFlag Opt_D_dump_asm_liveness)
3332 , make_ord_flag defGhcFlag "ddump-asm-regalloc"
3333 (setDumpFlag Opt_D_dump_asm_regalloc)
3334 , make_ord_flag defGhcFlag "ddump-asm-conflicts"
3335 (setDumpFlag Opt_D_dump_asm_conflicts)
3336 , make_ord_flag defGhcFlag "ddump-asm-regalloc-stages"
3337 (setDumpFlag Opt_D_dump_asm_regalloc_stages)
3338 , make_ord_flag defGhcFlag "ddump-asm-stats"
3339 (setDumpFlag Opt_D_dump_asm_stats)
3340 , make_ord_flag defGhcFlag "ddump-asm-expanded"
3341 (setDumpFlag Opt_D_dump_asm_expanded)
3342 , make_ord_flag defGhcFlag "ddump-llvm"
3343 (NoArg $ setObjTarget HscLlvm >> setDumpFlag' Opt_D_dump_llvm)
3344 , make_ord_flag defGhcFlag "ddump-deriv"
3345 (setDumpFlag Opt_D_dump_deriv)
3346 , make_ord_flag defGhcFlag "ddump-ds"
3347 (setDumpFlag Opt_D_dump_ds)
3348 , make_ord_flag defGhcFlag "ddump-ds-preopt"
3349 (setDumpFlag Opt_D_dump_ds_preopt)
3350 , make_ord_flag defGhcFlag "ddump-foreign"
3351 (setDumpFlag Opt_D_dump_foreign)
3352 , make_ord_flag defGhcFlag "ddump-inlinings"
3353 (setDumpFlag Opt_D_dump_inlinings)
3354 , make_ord_flag defGhcFlag "ddump-rule-firings"
3355 (setDumpFlag Opt_D_dump_rule_firings)
3356 , make_ord_flag defGhcFlag "ddump-rule-rewrites"
3357 (setDumpFlag Opt_D_dump_rule_rewrites)
3358 , make_ord_flag defGhcFlag "ddump-simpl-trace"
3359 (setDumpFlag Opt_D_dump_simpl_trace)
3360 , make_ord_flag defGhcFlag "ddump-occur-anal"
3361 (setDumpFlag Opt_D_dump_occur_anal)
3362 , make_ord_flag defGhcFlag "ddump-parsed"
3363 (setDumpFlag Opt_D_dump_parsed)
3364 , make_ord_flag defGhcFlag "ddump-parsed-ast"
3365 (setDumpFlag Opt_D_dump_parsed_ast)
3366 , make_ord_flag defGhcFlag "ddump-rn"
3367 (setDumpFlag Opt_D_dump_rn)
3368 , make_ord_flag defGhcFlag "ddump-rn-ast"
3369 (setDumpFlag Opt_D_dump_rn_ast)
3370 , make_ord_flag defGhcFlag "ddump-simpl"
3371 (setDumpFlag Opt_D_dump_simpl)
3372 , make_ord_flag defGhcFlag "ddump-simpl-iterations"
3373 (setDumpFlag Opt_D_dump_simpl_iterations)
3374 , make_ord_flag defGhcFlag "ddump-spec"
3375 (setDumpFlag Opt_D_dump_spec)
3376 , make_ord_flag defGhcFlag "ddump-prep"
3377 (setDumpFlag Opt_D_dump_prep)
3378 , make_ord_flag defGhcFlag "ddump-stg"
3379 (setDumpFlag Opt_D_dump_stg)
3380 , make_ord_flag defGhcFlag "ddump-stg-final"
3381 (setDumpFlag Opt_D_dump_stg_final)
3382 , make_ord_flag defGhcFlag "ddump-call-arity"
3383 (setDumpFlag Opt_D_dump_call_arity)
3384 , make_ord_flag defGhcFlag "ddump-exitify"
3385 (setDumpFlag Opt_D_dump_exitify)
3386 , make_ord_flag defGhcFlag "ddump-stranal"
3387 (setDumpFlag Opt_D_dump_stranal)
3388 , make_ord_flag defGhcFlag "ddump-str-signatures"
3389 (setDumpFlag Opt_D_dump_str_signatures)
3390 , make_ord_flag defGhcFlag "ddump-tc"
3391 (setDumpFlag Opt_D_dump_tc)
3392 , make_ord_flag defGhcFlag "ddump-tc-ast"
3393 (setDumpFlag Opt_D_dump_tc_ast)
3394 , make_ord_flag defGhcFlag "ddump-types"
3395 (setDumpFlag Opt_D_dump_types)
3396 , make_ord_flag defGhcFlag "ddump-rules"
3397 (setDumpFlag Opt_D_dump_rules)
3398 , make_ord_flag defGhcFlag "ddump-cse"
3399 (setDumpFlag Opt_D_dump_cse)
3400 , make_ord_flag defGhcFlag "ddump-worker-wrapper"
3401 (setDumpFlag Opt_D_dump_worker_wrapper)
3402 , make_ord_flag defGhcFlag "ddump-rn-trace"
3403 (setDumpFlag Opt_D_dump_rn_trace)
3404 , make_ord_flag defGhcFlag "ddump-shape"
3405 (setDumpFlag Opt_D_dump_shape)
3406 , make_ord_flag defGhcFlag "ddump-if-trace"
3407 (setDumpFlag Opt_D_dump_if_trace)
3408 , make_ord_flag defGhcFlag "ddump-cs-trace"
3409 (setDumpFlag Opt_D_dump_cs_trace)
3410 , make_ord_flag defGhcFlag "ddump-tc-trace"
3411 (NoArg (do setDumpFlag' Opt_D_dump_tc_trace
3412 setDumpFlag' Opt_D_dump_cs_trace))
3413 , make_ord_flag defGhcFlag "ddump-ec-trace"
3414 (setDumpFlag Opt_D_dump_ec_trace)
3415 , make_ord_flag defGhcFlag "ddump-vt-trace"
3416 (setDumpFlag Opt_D_dump_vt_trace)
3417 , make_ord_flag defGhcFlag "ddump-splices"
3418 (setDumpFlag Opt_D_dump_splices)
3419 , make_ord_flag defGhcFlag "dth-dec-file"
3420 (setDumpFlag Opt_D_th_dec_file)
3421
3422 , make_ord_flag defGhcFlag "ddump-rn-stats"
3423 (setDumpFlag Opt_D_dump_rn_stats)
3424 , make_ord_flag defGhcFlag "ddump-opt-cmm"
3425 (setDumpFlag Opt_D_dump_opt_cmm)
3426 , make_ord_flag defGhcFlag "ddump-simpl-stats"
3427 (setDumpFlag Opt_D_dump_simpl_stats)
3428 , make_ord_flag defGhcFlag "ddump-bcos"
3429 (setDumpFlag Opt_D_dump_BCOs)
3430 , make_ord_flag defGhcFlag "dsource-stats"
3431 (setDumpFlag Opt_D_source_stats)
3432 , make_ord_flag defGhcFlag "dverbose-core2core"
3433 (NoArg $ setVerbosity (Just 2) >> setVerboseCore2Core)
3434 , make_ord_flag defGhcFlag "dverbose-stg2stg"
3435 (setDumpFlag Opt_D_verbose_stg2stg)
3436 , make_ord_flag defGhcFlag "ddump-hi"
3437 (setDumpFlag Opt_D_dump_hi)
3438 , make_ord_flag defGhcFlag "ddump-minimal-imports"
3439 (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
3440 , make_ord_flag defGhcFlag "ddump-hpc"
3441 (setDumpFlag Opt_D_dump_ticked) -- back compat
3442 , make_ord_flag defGhcFlag "ddump-ticked"
3443 (setDumpFlag Opt_D_dump_ticked)
3444 , make_ord_flag defGhcFlag "ddump-mod-cycles"
3445 (setDumpFlag Opt_D_dump_mod_cycles)
3446 , make_ord_flag defGhcFlag "ddump-mod-map"
3447 (setDumpFlag Opt_D_dump_mod_map)
3448 , make_ord_flag defGhcFlag "ddump-timings"
3449 (setDumpFlag Opt_D_dump_timings)
3450 , make_ord_flag defGhcFlag "ddump-view-pattern-commoning"
3451 (setDumpFlag Opt_D_dump_view_pattern_commoning)
3452 , make_ord_flag defGhcFlag "ddump-to-file"
3453 (NoArg (setGeneralFlag Opt_DumpToFile))
3454 , make_ord_flag defGhcFlag "ddump-hi-diffs"
3455 (setDumpFlag Opt_D_dump_hi_diffs)
3456 , make_ord_flag defGhcFlag "ddump-rtti"
3457 (setDumpFlag Opt_D_dump_rtti)
3458 , make_ord_flag defGhcFlag "dcore-lint"
3459 (NoArg (setGeneralFlag Opt_DoCoreLinting))
3460 , make_ord_flag defGhcFlag "dstg-lint"
3461 (NoArg (setGeneralFlag Opt_DoStgLinting))
3462 , make_ord_flag defGhcFlag "dcmm-lint"
3463 (NoArg (setGeneralFlag Opt_DoCmmLinting))
3464 , make_ord_flag defGhcFlag "dasm-lint"
3465 (NoArg (setGeneralFlag Opt_DoAsmLinting))
3466 , make_ord_flag defGhcFlag "dannot-lint"
3467 (NoArg (setGeneralFlag Opt_DoAnnotationLinting))
3468 , make_ord_flag defGhcFlag "dshow-passes"
3469 (NoArg $ forceRecompile >> (setVerbosity $ Just 2))
3470 , make_ord_flag defGhcFlag "dfaststring-stats"
3471 (NoArg (setGeneralFlag Opt_D_faststring_stats))
3472 , make_ord_flag defGhcFlag "dno-llvm-mangler"
3473 (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
3474 , make_ord_flag defGhcFlag "fast-llvm"
3475 (NoArg (setGeneralFlag Opt_FastLlvm)) -- hidden flag
3476 , make_ord_flag defGhcFlag "ddump-debug"
3477 (setDumpFlag Opt_D_dump_debug)
3478 , make_ord_flag defGhcFlag "ddump-json"
3479 (noArg (flip dopt_set Opt_D_dump_json . setJsonLogAction ) )
3480 , make_ord_flag defGhcFlag "dppr-debug"
3481 (setDumpFlag Opt_D_ppr_debug)
3482 , make_ord_flag defGhcFlag "ddebug-output"
3483 (noArg (flip dopt_unset Opt_D_no_debug_output))
3484 , make_ord_flag defGhcFlag "dno-debug-output"
3485 (setDumpFlag Opt_D_no_debug_output)
3486
3487 ------ Machine dependent (-m<blah>) stuff ---------------------------
3488
3489 , make_ord_flag defGhcFlag "msse" (noArg (\d ->
3490 d { sseVersion = Just SSE1 }))
3491 , make_ord_flag defGhcFlag "msse2" (noArg (\d ->
3492 d { sseVersion = Just SSE2 }))
3493 , make_ord_flag defGhcFlag "msse3" (noArg (\d ->
3494 d { sseVersion = Just SSE3 }))
3495 , make_ord_flag defGhcFlag "msse4" (noArg (\d ->
3496 d { sseVersion = Just SSE4 }))
3497 , make_ord_flag defGhcFlag "msse4.2" (noArg (\d ->
3498 d { sseVersion = Just SSE42 }))
3499 , make_ord_flag defGhcFlag "mbmi" (noArg (\d ->
3500 d { bmiVersion = Just BMI1 }))
3501 , make_ord_flag defGhcFlag "mbmi2" (noArg (\d ->
3502 d { bmiVersion = Just BMI2 }))
3503 , make_ord_flag defGhcFlag "mavx" (noArg (\d -> d { avx = True }))
3504 , make_ord_flag defGhcFlag "mavx2" (noArg (\d -> d { avx2 = True }))
3505 , make_ord_flag defGhcFlag "mavx512cd" (noArg (\d ->
3506 d { avx512cd = True }))
3507 , make_ord_flag defGhcFlag "mavx512er" (noArg (\d ->
3508 d { avx512er = True }))
3509 , make_ord_flag defGhcFlag "mavx512f" (noArg (\d -> d { avx512f = True }))
3510 , make_ord_flag defGhcFlag "mavx512pf" (noArg (\d ->
3511 d { avx512pf = True }))
3512
3513 ------ Warning opts -------------------------------------------------
3514 , make_ord_flag defFlag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
3515 , make_ord_flag defFlag "Werror"
3516 (NoArg (do { setGeneralFlag Opt_WarnIsError
3517 ; mapM_ setFatalWarningFlag minusWeverythingOpts }))
3518 , make_ord_flag defFlag "Wwarn"
3519 (NoArg (do { unSetGeneralFlag Opt_WarnIsError
3520 ; mapM_ unSetFatalWarningFlag minusWeverythingOpts }))
3521 -- Opt_WarnIsError is still needed to pass -Werror
3522 -- to CPP; see runCpp in SysTools
3523 , make_dep_flag defFlag "Wnot" (NoArg (upd (\d ->
3524 d {warningFlags = EnumSet.empty})))
3525 "Use -w or -Wno-everything instead"
3526 , make_ord_flag defFlag "w" (NoArg (upd (\d ->
3527 d {warningFlags = EnumSet.empty})))
3528
3529 -- New-style uniform warning sets
3530 --
3531 -- Note that -Weverything > -Wall > -Wextra > -Wdefault > -Wno-everything
3532 , make_ord_flag defFlag "Weverything" (NoArg (mapM_
3533 setWarningFlag minusWeverythingOpts))
3534 , make_ord_flag defFlag "Wno-everything"
3535 (NoArg (upd (\d -> d {warningFlags = EnumSet.empty})))
3536
3537 , make_ord_flag defFlag "Wall" (NoArg (mapM_
3538 setWarningFlag minusWallOpts))
3539 , make_ord_flag defFlag "Wno-all" (NoArg (mapM_
3540 unSetWarningFlag minusWallOpts))
3541
3542 , make_ord_flag defFlag "Wextra" (NoArg (mapM_
3543 setWarningFlag minusWOpts))
3544 , make_ord_flag defFlag "Wno-extra" (NoArg (mapM_
3545 unSetWarningFlag minusWOpts))
3546
3547 , make_ord_flag defFlag "Wdefault" (NoArg (mapM_
3548 setWarningFlag standardWarnings))
3549 , make_ord_flag defFlag "Wno-default" (NoArg (mapM_
3550 unSetWarningFlag standardWarnings))
3551
3552 , make_ord_flag defFlag "Wcompat" (NoArg (mapM_
3553 setWarningFlag minusWcompatOpts))
3554 , make_ord_flag defFlag "Wno-compat" (NoArg (mapM_
3555 unSetWarningFlag minusWcompatOpts))
3556
3557 ------ Plugin flags ------------------------------------------------
3558 , make_ord_flag defGhcFlag "fplugin-opt" (hasArg addPluginModuleNameOption)
3559 , make_ord_flag defGhcFlag "fplugin-trustworthy"
3560 (NoArg (setGeneralFlag Opt_PluginTrustworthy))
3561 , make_ord_flag defGhcFlag "fplugin" (hasArg addPluginModuleName)
3562 , make_ord_flag defGhcFlag "fclear-plugins" (noArg clearPluginModuleNames)
3563 , make_ord_flag defGhcFlag "ffrontend-opt" (hasArg addFrontendPluginOption)
3564
3565 ------ Optimisation flags ------------------------------------------
3566 , make_dep_flag defGhcFlag "Onot" (noArgM $ setOptLevel 0 )
3567 "Use -O0 instead"
3568 , make_ord_flag defGhcFlag "O" (optIntSuffixM (\mb_n ->
3569 setOptLevel (mb_n `orElse` 1)))
3570 -- If the number is missing, use 1
3571
3572 , make_ord_flag defFlag "fbinary-blob-threshold"
3573 (intSuffix (\n d -> d { binBlobThreshold = fromIntegral n }))
3574
3575 , make_ord_flag defFlag "fmax-relevant-binds"
3576 (intSuffix (\n d -> d { maxRelevantBinds = Just n }))
3577 , make_ord_flag defFlag "fno-max-relevant-binds"
3578 (noArg (\d -> d { maxRelevantBinds = Nothing }))
3579
3580 , make_ord_flag defFlag "fmax-valid-hole-fits"
3581 (intSuffix (\n d -> d { maxValidHoleFits = Just n }))
3582 , make_ord_flag defFlag "fno-max-valid-hole-fits"
3583 (noArg (\d -> d { maxValidHoleFits = Nothing }))
3584 , make_ord_flag defFlag "fmax-refinement-hole-fits"
3585 (intSuffix (\n d -> d { maxRefHoleFits = Just n }))
3586 , make_ord_flag defFlag "fno-max-refinement-hole-fits"
3587 (noArg (\d -> d { maxRefHoleFits = Nothing }))
3588 , make_ord_flag defFlag "frefinement-level-hole-fits"
3589 (intSuffix (\n d -> d { refLevelHoleFits = Just n }))
3590 , make_ord_flag defFlag "fno-refinement-level-hole-fits"
3591 (noArg (\d -> d { refLevelHoleFits = Nothing }))
3592
3593 , make_dep_flag defGhcFlag "fllvm-pass-vectors-in-regs"
3594 (noArg id)
3595 "vectors registers are now passed in registers by default."
3596 , make_ord_flag defFlag "fmax-uncovered-patterns"
3597 (intSuffix (\n d -> d { maxUncoveredPatterns = n }))
3598 , make_ord_flag defFlag "fsimplifier-phases"
3599 (intSuffix (\n d -> d { simplPhases = n }))
3600 , make_ord_flag defFlag "fmax-simplifier-iterations"
3601 (intSuffix (\n d -> d { maxSimplIterations = n }))
3602 , make_ord_flag defFlag "fmax-pmcheck-iterations"
3603 (intSuffix (\n d -> d{ maxPmCheckIterations = n }))
3604 , make_ord_flag defFlag "fsimpl-tick-factor"
3605 (intSuffix (\n d -> d { simplTickFactor = n }))
3606 , make_ord_flag defFlag "fspec-constr-threshold"
3607 (intSuffix (\n d -> d { specConstrThreshold = Just n }))
3608 , make_ord_flag defFlag "fno-spec-constr-threshold"
3609 (noArg (\d -> d { specConstrThreshold = Nothing }))
3610 , make_ord_flag defFlag "fspec-constr-count"
3611 (intSuffix (\n d -> d { specConstrCount = Just n }))
3612 , make_ord_flag defFlag "fno-spec-constr-count"
3613 (noArg (\d -> d { specConstrCount = Nothing }))
3614 , make_ord_flag defFlag "fspec-constr-recursive"
3615 (intSuffix (\n d -> d { specConstrRecursive = n }))
3616 , make_ord_flag defFlag "fliberate-case-threshold"
3617 (intSuffix (\n d -> d { liberateCaseThreshold = Just n }))
3618 , make_ord_flag defFlag "fno-liberate-case-threshold"
3619 (noArg (\d -> d { liberateCaseThreshold = Nothing }))
3620 , make_ord_flag defFlag "drule-check"
3621 (sepArg (\s d -> d { ruleCheck = Just s }))
3622 , make_ord_flag defFlag "dinline-check"
3623 (sepArg (\s d -> d { inlineCheck = Just s }))
3624 , make_ord_flag defFlag "freduction-depth"
3625 (intSuffix (\n d -> d { reductionDepth = treatZeroAsInf n }))
3626 , make_ord_flag defFlag "fconstraint-solver-iterations"
3627 (intSuffix (\n d -> d { solverIterations = treatZeroAsInf n }))
3628 , (Deprecated, defFlag "fcontext-stack"
3629 (intSuffixM (\n d ->
3630 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
3631 ; return $ d { reductionDepth = treatZeroAsInf n } })))
3632 , (Deprecated, defFlag "ftype-function-depth"
3633 (intSuffixM (\n d ->
3634 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
3635 ; return $ d { reductionDepth = treatZeroAsInf n } })))
3636 , make_ord_flag defFlag "fstrictness-before"
3637 (intSuffix (\n d -> d { strictnessBefore = n : strictnessBefore d }))
3638 , make_ord_flag defFlag "ffloat-lam-args"
3639 (intSuffix (\n d -> d { floatLamArgs = Just n }))
3640 , make_ord_flag defFlag "ffloat-all-lams"
3641 (noArg (\d -> d { floatLamArgs = Nothing }))
3642 , make_ord_flag defFlag "fstg-lift-lams-rec-args"
3643 (intSuffix (\n d -> d { liftLamsRecArgs = Just n }))
3644 , make_ord_flag defFlag "fstg-lift-lams-rec-args-any"
3645 (noArg (\d -> d { liftLamsRecArgs = Nothing }))
3646 , make_ord_flag defFlag "fstg-lift-lams-non-rec-args"
3647 (intSuffix (\n d -> d { liftLamsRecArgs = Just n }))
3648 , make_ord_flag defFlag "fstg-lift-lams-non-rec-args-any"
3649 (noArg (\d -> d { liftLamsRecArgs = Nothing }))
3650 , make_ord_flag defFlag "fstg-lift-lams-known"
3651 (noArg (\d -> d { liftLamsKnown = True }))
3652 , make_ord_flag defFlag "fno-stg-lift-lams-known"
3653 (noArg (\d -> d { liftLamsKnown = False }))
3654 , make_ord_flag defFlag "fproc-alignment"
3655 (intSuffix (\n d -> d { cmmProcAlignment = Just n }))
3656 , make_ord_flag defFlag "fblock-layout-weights"
3657 (HasArg (\s ->
3658 upd (\d -> d { cfgWeightInfo =
3659 parseCfgWeights s (cfgWeightInfo d)})))
3660 , make_ord_flag defFlag "fhistory-size"
3661 (intSuffix (\n d -> d { historySize = n }))
3662 , make_ord_flag defFlag "funfolding-creation-threshold"
3663 (intSuffix (\n d -> d {ufCreationThreshold = n}))
3664 , make_ord_flag defFlag "funfolding-use-threshold"
3665 (intSuffix (\n d -> d {ufUseThreshold = n}))
3666 , make_ord_flag defFlag "funfolding-fun-discount"
3667 (intSuffix (\n d -> d {ufFunAppDiscount = n}))
3668 , make_ord_flag defFlag "funfolding-dict-discount"
3669 (intSuffix (\n d -> d {ufDictDiscount = n}))
3670 , make_ord_flag defFlag "funfolding-keeness-factor"
3671 (floatSuffix (\n d -> d {ufKeenessFactor = n}))
3672 , make_ord_flag defFlag "fmax-worker-args"
3673 (intSuffix (\n d -> d {maxWorkerArgs = n}))
3674 , make_ord_flag defGhciFlag "fghci-hist-size"
3675 (intSuffix (\n d -> d {ghciHistSize = n}))
3676 , make_ord_flag defGhcFlag "fmax-inline-alloc-size"
3677 (intSuffix (\n d -> d { maxInlineAllocSize = n }))
3678 , make_ord_flag defGhcFlag "fmax-inline-memcpy-insns"
3679 (intSuffix (\n d -> d { maxInlineMemcpyInsns = n }))
3680 , make_ord_flag defGhcFlag "fmax-inline-memset-insns"
3681 (intSuffix (\n d -> d { maxInlineMemsetInsns = n }))
3682 , make_ord_flag defGhcFlag "dinitial-unique"
3683 (intSuffix (\n d -> d { initialUnique = n }))
3684 , make_ord_flag defGhcFlag "dunique-increment"
3685 (intSuffix (\n d -> d { uniqueIncrement = n }))
3686
3687 ------ Profiling ----------------------------------------------------
3688
3689 -- OLD profiling flags
3690 , make_dep_flag defGhcFlag "auto-all"
3691 (noArg (\d -> d { profAuto = ProfAutoAll } ))
3692 "Use -fprof-auto instead"
3693 , make_dep_flag defGhcFlag "no-auto-all"
3694 (noArg (\d -> d { profAuto = NoProfAuto } ))
3695 "Use -fno-prof-auto instead"
3696 , make_dep_flag defGhcFlag "auto"
3697 (noArg (\d -> d { profAuto = ProfAutoExports } ))
3698 "Use -fprof-auto-exported instead"
3699 , make_dep_flag defGhcFlag "no-auto"
3700 (noArg (\d -> d { profAuto = NoProfAuto } ))
3701 "Use -fno-prof-auto instead"
3702 , make_dep_flag defGhcFlag "caf-all"
3703 (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
3704 "Use -fprof-cafs instead"
3705 , make_dep_flag defGhcFlag "no-caf-all"
3706 (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
3707 "Use -fno-prof-cafs instead"
3708
3709 -- NEW profiling flags
3710 , make_ord_flag defGhcFlag "fprof-auto"
3711 (noArg (\d -> d { profAuto = ProfAutoAll } ))
3712 , make_ord_flag defGhcFlag "fprof-auto-top"
3713 (noArg (\d -> d { profAuto = ProfAutoTop } ))
3714 , make_ord_flag defGhcFlag "fprof-auto-exported"
3715 (noArg (\d -> d { profAuto = ProfAutoExports } ))
3716 , make_ord_flag defGhcFlag "fprof-auto-calls"
3717 (noArg (\d -> d { profAuto = ProfAutoCalls } ))
3718 , make_ord_flag defGhcFlag "fno-prof-auto"
3719 (noArg (\d -> d { profAuto = NoProfAuto } ))
3720
3721 ------ Compiler flags -----------------------------------------------
3722
3723 , make_ord_flag defGhcFlag "fasm" (NoArg (setObjTarget HscAsm))
3724 , make_ord_flag defGhcFlag "fvia-c" (NoArg
3725 (deprecate $ "The -fvia-c flag does nothing; " ++
3726 "it will be removed in a future GHC release"))
3727 , make_ord_flag defGhcFlag "fvia-C" (NoArg
3728 (deprecate $ "The -fvia-C flag does nothing; " ++
3729 "it will be removed in a future GHC release"))
3730 , make_ord_flag defGhcFlag "fllvm" (NoArg (setObjTarget HscLlvm))
3731
3732 , make_ord_flag defFlag "fno-code" (NoArg ((upd $ \d ->
3733 d { ghcLink=NoLink }) >> setTarget HscNothing))
3734 , make_ord_flag defFlag "fbyte-code" (NoArg (setTarget HscInterpreted))
3735 , make_ord_flag defFlag "fobject-code" (NoArg (setTargetWithSettings
3736 defaultHscTarget))
3737 , make_dep_flag defFlag "fglasgow-exts"
3738 (NoArg enableGlasgowExts) "Use individual extensions instead"
3739 , make_dep_flag defFlag "fno-glasgow-exts"
3740 (NoArg disableGlasgowExts) "Use individual extensions instead"
3741 , make_ord_flag defFlag "Wunused-binds" (NoArg enableUnusedBinds)
3742 , make_ord_flag defFlag "Wno-unused-binds" (NoArg disableUnusedBinds)
3743 , make_ord_flag defHiddenFlag "fwarn-unused-binds" (NoArg enableUnusedBinds)
3744 , make_ord_flag defHiddenFlag "fno-warn-unused-binds" (NoArg
3745 disableUnusedBinds)
3746
3747 ------ Safe Haskell flags -------------------------------------------
3748 , make_ord_flag defFlag "fpackage-trust" (NoArg setPackageTrust)
3749 , make_ord_flag defFlag "fno-safe-infer" (noArg (\d ->
3750 d { safeInfer = False }))
3751 , make_ord_flag defFlag "fno-safe-haskell" (NoArg (setSafeHaskell Sf_Ignore))
3752 , make_ord_flag defGhcFlag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
3753 , make_ord_flag defGhcFlag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
3754 , make_ord_flag defGhcFlag "fPIE" (NoArg (setGeneralFlag Opt_PIC))
3755 , make_ord_flag defGhcFlag "fno-PIE" (NoArg (unSetGeneralFlag Opt_PIC))
3756
3757 ------ Debugging flags ----------------------------------------------
3758 , make_ord_flag defGhcFlag "g" (OptIntSuffix setDebugLevel)
3759 ]
3760 ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlagsDeps
3761 ++ map (mkFlag turnOff "no-" unSetGeneralFlag ) negatableFlagsDeps
3762 ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlagsDeps
3763 ++ map (mkFlag turnOff "dno-" unSetGeneralFlag ) dFlagsDeps
3764 ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlagsDeps
3765 ++ map (mkFlag turnOff "fno-" unSetGeneralFlag ) fFlagsDeps
3766 ++ map (mkFlag turnOn "W" setWarningFlag ) wWarningFlagsDeps
3767 ++ map (mkFlag turnOff "Wno-" unSetWarningFlag ) wWarningFlagsDeps
3768 ++ map (mkFlag turnOn "Werror=" setWErrorFlag ) wWarningFlagsDeps
3769 ++ map (mkFlag turnOn "Wwarn=" unSetFatalWarningFlag )
3770 wWarningFlagsDeps
3771 ++ map (mkFlag turnOn "Wno-error=" unSetFatalWarningFlag )
3772 wWarningFlagsDeps
3773 ++ map (mkFlag turnOn "fwarn-" setWarningFlag . hideFlag)
3774 wWarningFlagsDeps
3775 ++ map (mkFlag turnOff "fno-warn-" unSetWarningFlag . hideFlag)
3776 wWarningFlagsDeps
3777 ++ [ (NotDeprecated, unrecognisedWarning "W"),
3778 (Deprecated, unrecognisedWarning "fwarn-"),
3779 (Deprecated, unrecognisedWarning "fno-warn-") ]
3780 ++ [ make_ord_flag defFlag "Werror=compat"
3781 (NoArg (mapM_ setWErrorFlag minusWcompatOpts))
3782 , make_ord_flag defFlag "Wno-error=compat"
3783 (NoArg (mapM_ unSetFatalWarningFlag minusWcompatOpts))
3784 , make_ord_flag defFlag "Wwarn=compat"
3785 (NoArg (mapM_ unSetFatalWarningFlag minusWcompatOpts)) ]
3786 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlagsDeps
3787 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlagsDeps
3788 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlagsDeps
3789 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlagsDeps
3790 ++ map (mkFlag turnOn "X" setLanguage ) languageFlagsDeps
3791 ++ map (mkFlag turnOn "X" setSafeHaskell ) safeHaskellFlagsDeps
3792 ++ [ make_dep_flag defFlag "XGenerics"
3793 (NoArg $ return ())
3794 ("it does nothing; look into -XDefaultSignatures " ++
3795 "and -XDeriveGeneric for generic programming support.")
3796 , make_dep_flag defFlag "XNoGenerics"
3797 (NoArg $ return ())
3798 ("it does nothing; look into -XDefaultSignatures and " ++
3799 "-XDeriveGeneric for generic programming support.") ]
3800
3801 -- | This is where we handle unrecognised warning flags. We only issue a warning
3802 -- if -Wunrecognised-warning-flags is set. See #11429 for context.
3803 unrecognisedWarning :: String -> Flag (CmdLineP DynFlags)
3804 unrecognisedWarning prefix = defHiddenFlag prefix (Prefix action)
3805 where
3806 action :: String -> EwM (CmdLineP DynFlags) ()
3807 action flag = do
3808 f <- wopt Opt_WarnUnrecognisedWarningFlags <$> liftEwM getCmdLineState
3809 when f $ addFlagWarn Cmd.ReasonUnrecognisedFlag $
3810 "unrecognised warning flag: -" ++ prefix ++ flag
3811
3812 -- See Note [Supporting CLI completion]
3813 package_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))]
3814 package_flags_deps = [
3815 ------- Packages ----------------------------------------------------
3816 make_ord_flag defFlag "package-db"
3817 (HasArg (addPkgConfRef . PkgConfFile))
3818 , make_ord_flag defFlag "clear-package-db" (NoArg clearPkgConf)
3819 , make_ord_flag defFlag "no-global-package-db" (NoArg removeGlobalPkgConf)
3820 , make_ord_flag defFlag "no-user-package-db" (NoArg removeUserPkgConf)
3821 , make_ord_flag defFlag "global-package-db"
3822 (NoArg (addPkgConfRef GlobalPkgConf))
3823 , make_ord_flag defFlag "user-package-db"
3824 (NoArg (addPkgConfRef UserPkgConf))
3825 -- backwards compat with GHC<=7.4 :
3826 , make_dep_flag defFlag "package-conf"
3827 (HasArg $ addPkgConfRef . PkgConfFile) "Use -package-db instead"
3828 , make_dep_flag defFlag "no-user-package-conf"
3829 (NoArg removeUserPkgConf) "Use -no-user-package-db instead"
3830 , make_ord_flag defGhcFlag "package-name" (HasArg $ \name -> do
3831 upd (setUnitId name))
3832 -- TODO: Since we JUST deprecated
3833 -- -this-package-key, let's keep this
3834 -- undeprecated for another cycle.
3835 -- Deprecate this eventually.
3836 -- deprecate "Use -this-unit-id instead")
3837 , make_dep_flag defGhcFlag "this-package-key" (HasArg $ upd . setUnitId)
3838 "Use -this-unit-id instead"
3839 , make_ord_flag defGhcFlag "this-unit-id" (hasArg setUnitId)
3840 , make_ord_flag defFlag "package" (HasArg exposePackage)
3841 , make_ord_flag defFlag "plugin-package-id" (HasArg exposePluginPackageId)
3842