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