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