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