forked from ghc/ghc
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDynFlags.hs
More file actions
1639 lines (1402 loc) · 63.9 KB
/
Copy pathDynFlags.hs
File metadata and controls
1639 lines (1402 loc) · 63.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE LambdaCase #-}
module GHC.Driver.DynFlags (
-- * Dynamic flags and associated configuration types
DumpFlag(..),
GeneralFlag(..),
WarningFlag(..), DiagnosticReason(..),
Language(..),
FatalMessager, FlushOut(..),
ProfAuto(..),
hasPprDebug, hasNoDebugOutput, hasNoStateHack, hasNoOptCoercion,
dopt, dopt_set, dopt_unset,
gopt, gopt_set, gopt_unset,
wopt, wopt_set, wopt_unset,
wopt_fatal, wopt_set_fatal, wopt_unset_fatal,
wopt_set_all_custom, wopt_unset_all_custom,
wopt_set_all_fatal_custom, wopt_unset_all_fatal_custom,
wopt_set_custom, wopt_unset_custom,
wopt_set_fatal_custom, wopt_unset_fatal_custom,
wopt_any_custom,
xopt, xopt_set, xopt_unset,
xopt_set_unlessExplSpec,
xopt_DuplicateRecordFields,
xopt_FieldSelectors,
lang_set,
-- Note: DynamicTooState, dynamicTooState, setDynamicNow removed
-- -dynamic-too is deprecated, only dynamic objects are produced
OnOff(..),
DynFlags(..),
ParMakeCount(..),
ways,
HasDynFlags(..), ContainsDynFlags(..),
RtsOptsEnabled(..), haveRtsOptsFlags,
GhcMode(..), isOneShot,
GhcLink(..), isNoLink,
isExecutableLink,
ExecutableLinkMode(..),
PackageFlag(..), PackageArg(..), ModRenaming(..),
packageFlagsChanged,
IgnorePackageFlag(..), TrustFlag(..),
PackageDBFlag(..), PkgDbRef(..),
Option(..), showOpt,
DynLibLoader(..),
positionIndependent,
optimisationFlags,
targetProfile,
ReexportedModule(..),
-- ** Manipulating DynFlags
defaultDynFlags, -- Settings -> DynFlags
initDynFlags, -- DynFlags -> IO DynFlags
defaultFatalMessager,
defaultFlushOut,
optLevelFlags,
languageExtensions,
TurnOnFlag,
turnOn,
turnOff,
-- ** System tool settings and locations
programName, projectVersion,
ghcUsagePath, ghciUsagePath, topDir, toolDir,
versionedAppDir, versionedFilePath,
extraGccViaCFlags, globalPackageDatabasePath,
--
baseUnitId,
rtsWayUnitId',
rtsWayUnitId,
-- * Include specifications
IncludeSpecs(..), addGlobalInclude, addQuoteInclude, flattenIncludes,
addImplicitQuoteInclude,
-- * SDoc
initSDocContext, initDefaultSDocContext,
initPromotionTickContext,
-- * Platform features
isSse3Enabled,
isSsse3Enabled,
isSse4_1Enabled,
isSse4_2Enabled,
isAvxEnabled,
isAvx2Enabled,
isAvx512cdEnabled,
isAvx512erEnabled,
isAvx512fEnabled,
isAvx512pfEnabled,
isFmaEnabled,
isBmiEnabled,
isBmi2Enabled
) where
import GHC.Prelude
import GHC.Platform
import GHC.Platform.Ways
import GHC.Platform.Profile
import GHC.CmmToAsm.CFG.Weight
import GHC.Core.Unfold
import GHC.Data.Bool
import GHC.Data.EnumSet (EnumSet)
import GHC.Data.Maybe
import GHC.Builtin.Names ( mAIN_NAME )
import GHC.Driver.Backend
import GHC.Driver.Flags
import GHC.Driver.IncludeSpecs
import GHC.Driver.Phases ( Phase(..), phaseInputExt )
import GHC.Driver.Plugins.External
import GHC.Settings
import GHC.Settings.Constants
import GHC.Types.Basic ( IntWithInf, treatZeroAsInf )
import GHC.Types.Error (DiagnosticReason(..))
import GHC.Types.ProfAuto
import GHC.Types.SafeHaskell
import GHC.Types.SrcLoc
import GHC.Unit.Module
import GHC.Unit.Module.Warnings
import GHC.Utils.CliOption
import GHC.SysTools.Terminal ( stderrSupportsAnsiColors )
import GHC.UniqueSubdir (uniqueSubdir)
import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Utils.TmpFs
import qualified GHC.Types.FieldLabel as FieldLabel
import qualified GHC.Utils.Ppr.Colour as Col
import qualified GHC.Data.EnumSet as EnumSet
import GHC.Core.Opt.CallerCC.Types
import Control.Monad (msum, (<=<))
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Except (ExceptT)
import Control.Monad.Trans.Reader (ReaderT)
import Control.Monad.Trans.Writer (WriterT)
import Data.Word
import System.IO
import System.IO.Error (catchIOError)
import System.Environment (lookupEnv)
import System.FilePath (normalise, (</>))
import System.Directory
import GHC.Foreign (withCString, peekCString)
import qualified Data.Set as Set
import qualified GHC.LanguageExtensions as LangExt
-- -----------------------------------------------------------------------------
-- DynFlags
-- | Contains not only a collection of 'GeneralFlag's but also a plethora of
-- information relating to the compilation of a single file or GHC session
data DynFlags = DynFlags {
ghcMode :: GhcMode,
ghcLink :: GhcLink,
backend :: !Backend,
-- ^ The backend to use (if any).
--
-- Whenever you change the backend, also make sure to set 'ghcLink' to
-- something sensible.
--
-- 'NoBackend' can be used to avoid generating any output, however, note that:
--
-- * If a program uses Template Haskell the typechecker may need to run code
-- from an imported module. To facilitate this, code generation is enabled
-- for modules imported by modules that use template haskell, using the
-- default backend for the platform.
-- See Note [-fno-code mode].
-- formerly Settings
ghcNameVersion :: {-# UNPACK #-} !GhcNameVersion,
fileSettings :: {-# UNPACK #-} !FileSettings,
unitSettings :: {-# UNPACK #-} !UnitSettings,
targetPlatform :: Platform, -- Filled in by SysTools
toolSettings :: {-# UNPACK #-} !ToolSettings,
platformMisc :: {-# UNPACK #-} !PlatformMisc,
rawSettings :: [(String, String)],
tmpDir :: TempDir,
llvmOptLevel :: Int, -- ^ LLVM optimisation level
verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
debugLevel :: Int, -- ^ How much debug information to produce
simplPhases :: Int, -- ^ Number of simplifier phases
maxSimplIterations :: Int, -- ^ Max simplifier iterations
ruleCheck :: Maybe String,
strictnessBefore :: [Int], -- ^ Additional demand analysis
parMakeCount :: Maybe ParMakeCount,
-- ^ The number of modules to compile in parallel
-- If unspecified, compile with a single job.
enableTimeStats :: Bool, -- ^ Enable RTS timing statistics?
ghcHeapSize :: Maybe Int, -- ^ The heap size to set.
maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt
-- to show in type error messages
maxValidHoleFits :: Maybe Int, -- ^ Maximum number of hole fits to show
-- in typed hole error messages
maxRefHoleFits :: Maybe Int, -- ^ Maximum number of refinement hole
-- fits to show in typed hole error
-- messages
refLevelHoleFits :: Maybe Int, -- ^ Maximum level of refinement for
-- refinement hole fits in typed hole
-- error messages
maxUncoveredPatterns :: Int, -- ^ Maximum number of unmatched patterns to show
-- in non-exhaustiveness warnings
maxPmCheckModels :: Int, -- ^ Soft limit on the number of models
-- the pattern match checker checks
-- a pattern against. A safe guard
-- against exponential blow-up.
simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
dmdUnboxWidth :: !Int, -- ^ Whether DmdAnal should optimistically put an
-- Unboxed demand on returned products with at most
-- this number of fields
ifCompression :: Int,
specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types
-- Not optional; otherwise ForceSpecConstr can diverge.
binBlobThreshold :: Maybe Word, -- ^ Binary literals (e.g. strings) whose size is above
-- this threshold will be dumped in a binary file
-- by the assembler code generator. 0 and Nothing disables
-- this feature. See 'GHC.StgToCmm.Config'.
liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
-- See 'GHC.Core.Opt.Monad.FloatOutSwitches'
liftLamsRecArgs :: Maybe Int, -- ^ Maximum number of arguments after lambda lifting a
-- recursive function.
liftLamsNonRecArgs :: Maybe Int, -- ^ Maximum number of arguments after lambda lifting a
-- non-recursive function.
liftLamsKnown :: Bool, -- ^ Lambda lift even when this turns a known call
-- into an unknown call.
cmmProcAlignment :: Maybe Int, -- ^ Align Cmm functions at this boundary or use default.
historySize :: Int, -- ^ Simplification history size
importPaths :: [FilePath],
mainModuleNameIs :: ModuleName,
mainFunIs :: Maybe String,
reductionDepth :: IntWithInf, -- ^ Typechecker maximum stack depth
solverIterations :: IntWithInf, -- ^ Number of iterations in the constraints solver
-- Typically only 1 is needed
givensFuel :: Int, -- ^ Number of layers of superclass expansion for givens
-- Should be < solverIterations
-- See Note [Expanding Recursive Superclasses and ExpansionFuel]
wantedsFuel :: Int, -- ^ Number of layers of superclass expansion for wanteds
-- Should be < givensFuel
-- See Note [Expanding Recursive Superclasses and ExpansionFuel]
qcsFuel :: Int, -- ^ Number of layers of superclass expansion for quantified constraints
-- Should be < givensFuel
-- See Note [Expanding Recursive Superclasses and ExpansionFuel]
homeUnitId_ :: UnitId, -- ^ Target home unit-id
homeUnitInstanceOf_ :: Maybe UnitId, -- ^ Id of the unit to instantiate
homeUnitInstantiations_ :: [(ModuleName, Module)], -- ^ Module instantiations
-- Note [Filepaths and Multiple Home Units]
workingDirectory :: Maybe FilePath,
thisPackageName :: Maybe String, -- ^ What the package is called, use with multiple home units
hiddenModules :: Set.Set ModuleName,
reexportedModules :: [ReexportedModule],
-- ways
targetWays_ :: Ways, -- ^ Target way flags from the command line
-- For object splitting
splitInfo :: Maybe (String,Int),
-- paths etc.
objectDir :: Maybe String,
dylibInstallName :: Maybe String,
hiDir :: Maybe String,
hieDir :: Maybe String,
stubDir :: Maybe String,
dumpDir :: Maybe String,
objectSuf_ :: String,
hcSuf :: String,
hiSuf_ :: String,
hieSuf :: String,
dynObjectSuf_ :: String,
dynHiSuf_ :: String,
outputFile_ :: Maybe String,
dynOutputFile_ :: Maybe String,
outputHi :: Maybe String,
dynOutputHi :: Maybe String,
dynLibLoader :: DynLibLoader,
-- Note: dynamicNow field removed - -dynamic-too is deprecated
-- | This defaults to 'non-module'. It can be set by
-- 'GHC.Driver.Pipeline.setDumpPrefix' or 'ghc.GHCi.UI.runStmt' based on
-- where its output is going.
dumpPrefix :: FilePath,
-- | Override the 'dumpPrefix' set by 'GHC.Driver.Pipeline.setDumpPrefix'
-- or 'ghc.GHCi.UI.runStmt'.
-- Set by @-ddump-file-prefix@
dumpPrefixForce :: Maybe FilePath,
ldInputs :: [Option],
includePaths :: IncludeSpecs,
libraryPaths :: [String],
frameworkPaths :: [String], -- used on darwin only
cmdlineFrameworks :: [String], -- ditto
rtsOpts :: Maybe String,
rtsOptsEnabled :: RtsOptsEnabled,
rtsOptsSuggestions :: Bool,
hpcDir :: String, -- ^ Path to store the .mix files
-- Plugins
pluginModNames :: [ModuleName],
-- ^ the @-fplugin@ flags given on the command line, in *reverse*
-- order that they're specified on the command line.
pluginModNameOpts :: [(ModuleName,String)],
frontendPluginOpts :: [String],
-- ^ the @-ffrontend-opt@ flags given on the command line, in *reverse*
-- order that they're specified on the command line.
externalPluginSpecs :: [ExternalPluginSpec],
-- ^ External plugins loaded from shared libraries
-- For ghc -M
depMakefile :: FilePath,
depIncludePkgDeps :: Bool,
depIncludeCppDeps :: Bool,
depExcludeMods :: [ModuleName],
depSuffixes :: [String],
-- Package flags
packageDBFlags :: [PackageDBFlag],
-- ^ The @-package-db@ flags given on the command line, In
-- *reverse* order that they're specified on the command line.
-- This is intended to be applied with the list of "initial"
-- package databases derived from @GHC_PACKAGE_PATH@; see
-- 'getUnitDbRefs'.
ignorePackageFlags :: [IgnorePackageFlag],
-- ^ The @-ignore-package@ flags from the command line.
-- In *reverse* order that they're specified on the command line.
packageFlags :: [PackageFlag],
-- ^ The @-package@ and @-hide-package@ flags from the command-line.
-- In *reverse* order that they're specified on the command line.
pluginPackageFlags :: [PackageFlag],
-- ^ The @-plugin-package-id@ flags from command line.
-- In *reverse* order that they're specified on the command line.
trustFlags :: [TrustFlag],
-- ^ The @-trust@ and @-distrust@ flags.
-- In *reverse* order that they're specified on the command line.
packageEnv :: Maybe FilePath,
-- ^ Filepath to the package environment file (if overriding default)
-- hsc dynamic flags
dumpFlags :: EnumSet DumpFlag,
generalFlags :: EnumSet GeneralFlag,
warningFlags :: EnumSet WarningFlag,
fatalWarningFlags :: EnumSet WarningFlag,
customWarningCategories :: WarningCategorySet, -- See Note [Warning categories]
fatalCustomWarningCategories :: WarningCategorySet, -- in GHC.Unit.Module.Warnings
-- Don't change this without updating extensionFlags:
language :: Maybe Language,
-- | Safe Haskell mode
safeHaskell :: SafeHaskellMode,
safeInfer :: Bool,
safeInferred :: Bool,
-- We store the location of where some extension and flags were turned on so
-- we can produce accurate error messages when Safe Haskell fails due to
-- them.
thOnLoc :: SrcSpan,
newDerivOnLoc :: SrcSpan,
deriveViaOnLoc :: SrcSpan,
overlapInstLoc :: SrcSpan,
incoherentOnLoc :: SrcSpan,
pkgTrustOnLoc :: SrcSpan,
warnSafeOnLoc :: SrcSpan,
warnUnsafeOnLoc :: SrcSpan,
trustworthyOnLoc :: SrcSpan,
-- Don't change this without updating extensionFlags:
-- Here we collect the settings of the language extensions
-- from the command line, the ghci config file and
-- from interactive :set / :seti commands.
extensions :: [OnOff LangExt.Extension],
-- extensionFlags should always be equal to
-- flattenExtensionFlags language extensions
-- LangExt.Extension is defined in libraries/ghc-boot so that it can be used
-- by template-haskell
extensionFlags :: EnumSet LangExt.Extension,
-- | Unfolding control
-- See Note [Discounts and thresholds] in GHC.Core.Unfold
unfoldingOpts :: !UnfoldingOpts,
maxWorkerArgs :: Int,
maxForcedSpecArgs :: Int,
ghciHistSize :: Int,
-- wasm ghci browser mode
ghciBrowserHost :: !String,
ghciBrowserPort :: !Int,
ghciBrowserPuppeteerLaunchOpts :: !(Maybe String),
ghciBrowserPlaywrightBrowserType :: !(Maybe String),
ghciBrowserPlaywrightLaunchOpts :: !(Maybe String),
flushOut :: FlushOut,
ghcVersionFile :: Maybe FilePath,
haddockOptions :: Maybe String,
-- | GHCi scripts specified by -ghci-script, in reverse order
ghciScripts :: [String],
-- Output style options
pprUserLength :: Int,
pprCols :: Int,
useUnicode :: Bool,
useColor :: OverridingBool,
canUseColor :: Bool,
useErrorLinks :: OverridingBool,
canUseErrorLinks :: Bool,
colScheme :: Col.Scheme,
-- | what kind of {-# SCC #-} to add automatically
profAuto :: ProfAuto,
callerCcFilters :: [CallerCcFilter],
interactivePrint :: Maybe String,
-- | Machine dependent flags (-m\<blah> stuff)
sseVersion :: Maybe SseVersion,
bmiVersion :: Maybe BmiVersion,
avx :: Bool,
avx2 :: Bool,
avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions.
avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions.
avx512f :: Bool, -- Enable AVX-512 instructions.
avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions.
fma :: Bool, -- ^ Enable FMA instructions.
-- Constants used to control the amount of optimization done.
-- | Max size, in bytes, of inline array allocations.
maxInlineAllocSize :: Int,
-- | Only inline memcpy if it generates no more than this many
-- pseudo (roughly: Cmm) instructions.
maxInlineMemcpyInsns :: Int,
-- | Only inline memset if it generates no more than this many
-- pseudo (roughly: Cmm) instructions.
maxInlineMemsetInsns :: Int,
-- | Reverse the order of error messages in GHC/GHCi
reverseErrors :: Bool,
-- | Limit the maximum number of errors to show
maxErrors :: Maybe Int,
-- | Unique supply configuration for testing build determinism
initialUnique :: Word64,
uniqueIncrement :: Int,
-- 'Int' because it can be used to test uniques in decreasing order.
-- | Temporary: CFG Edge weights for fast iterations
cfgWeights :: Weights,
-- | Archive prelinking configuration
-- See Note [Archive Prelinking]
prelinkArchiveThreshold :: Maybe Word64,
-- ^ Size threshold in bytes for prelinking archives.
-- Nothing = prelinking disabled
-- Just n = prelink archives larger than n bytes
prelinkCacheDir :: Maybe FilePath
-- ^ Persistent cache directory for prelinked objects.
-- Nothing = use per-session temp files only
-- Just dir = store prelinked objects in dir for reuse across sessions
}
-- Note [Archive Prelinking]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~
-- Historically, GHC generated prelinked objects (.o files) at build time
-- for use with GHCi. This was slow and disk-intensive. Instead, we now
-- create prelinked objects on-demand when the internal linker loads large
-- static archives.
--
-- When loading an archive (.a file), instead of loading each member object
-- individually, we use 'ld -r' to merge all members into a single object.
-- This provides several benefits:
--
-- 1. Faster loading: Fewer objects for the RTS linker to process
-- 2. Fewer system calls: Single loadObj instead of many
-- 3. Better relocation handling: 'ld -r' resolves internal relocations
-- 4. On-demand: Only prelink when actually needed
-- 5. Cacheable: Optional persistent cache for reuse across sessions
--
-- Configuration:
-- - prelinkArchiveThreshold: Size threshold (default 5MB). Archives larger
-- than this are prelinked on first load. Set to Nothing to disable.
-- - prelinkCacheDir: Optional persistent cache directory. If set, prelinked
-- objects are cached here for reuse across GHC sessions. If Nothing, temp
-- files are used and discarded after the session.
--
-- See also: GHC.Linker.ArchivePrelink
class HasDynFlags m where
getDynFlags :: m DynFlags
{- It would be desirable to have the more generalised
instance (MonadTrans t, Monad m, HasDynFlags m) => HasDynFlags (t m) where
getDynFlags = lift getDynFlags
instance definition. However, that definition would overlap with the
`HasDynFlags (GhcT m)` instance. Instead we define instances for a
couple of common Monad transformers explicitly. -}
instance (Monoid a, Monad m, HasDynFlags m) => HasDynFlags (WriterT a m) where
getDynFlags = lift getDynFlags
instance (Monad m, HasDynFlags m) => HasDynFlags (ReaderT a m) where
getDynFlags = lift getDynFlags
instance (Monad m, HasDynFlags m) => HasDynFlags (MaybeT m) where
getDynFlags = lift getDynFlags
instance (Monad m, HasDynFlags m) => HasDynFlags (ExceptT e m) where
getDynFlags = lift getDynFlags
class ContainsDynFlags t where
extractDynFlags :: t -> DynFlags
-----------------------------------------------------------------------------
-- | Used by 'GHC.runGhc' to partially initialize a new 'DynFlags' value
initDynFlags :: DynFlags -> IO DynFlags
initDynFlags dflags = do
let
-- This is not bulletproof: we test that 'localeEncoding' is Unicode-capable,
-- but potentially 'hGetEncoding' 'stdout' might be different. Still good enough.
canUseUnicode <- do let enc = localeEncoding
str = "‘’"
(withCString enc str $ \cstr ->
do str' <- peekCString enc cstr
return (str == str'))
`catchIOError` \_ -> return False
ghcNoUnicodeEnv <- lookupEnv "GHC_NO_UNICODE"
let useUnicode' = isNothing ghcNoUnicodeEnv && canUseUnicode
maybeGhcColorsEnv <- lookupEnv "GHC_COLORS"
maybeGhcColoursEnv <- lookupEnv "GHC_COLOURS"
let adjustCols (Just env) = Col.parseScheme env
adjustCols Nothing = id
let (useColor', colScheme') =
(adjustCols maybeGhcColoursEnv . adjustCols maybeGhcColorsEnv)
(useColor dflags, colScheme dflags)
tmp_dir <- normalise <$> getTemporaryDirectory
return dflags{
useUnicode = useUnicode',
useColor = useColor',
canUseColor = stderrSupportsAnsiColors,
-- if the terminal supports color, we assume it supports links as well
canUseErrorLinks = stderrSupportsAnsiColors,
colScheme = colScheme',
tmpDir = TempDir tmp_dir
}
-- | The normal 'DynFlags'. Note that they are not suitable for use in this form
-- and must be fully initialized by 'GHC.runGhc' first.
defaultDynFlags :: Settings -> DynFlags
defaultDynFlags mySettings =
-- See Note [Updating flag description in the User's Guide]
DynFlags {
ghcMode = CompManager,
ghcLink = LinkExecutable Dynamic,
backend = platformDefaultBackend (sTargetPlatform mySettings),
verbosity = 0,
debugLevel = 0,
simplPhases = 2,
maxSimplIterations = 4,
ruleCheck = Nothing,
binBlobThreshold = Just 500000, -- 500K is a good default (see #16190)
maxRelevantBinds = Just 6,
maxValidHoleFits = Just 6,
maxRefHoleFits = Just 6,
refLevelHoleFits = Nothing,
maxUncoveredPatterns = 4,
maxPmCheckModels = 30,
simplTickFactor = 100,
dmdUnboxWidth = 3, -- Default: Assume an unboxed demand on function bodies returning a triple
ifCompression = 2, -- Default: Apply safe compressions
specConstrThreshold = Just 2000,
specConstrCount = Just 3,
specConstrRecursive = 3,
liberateCaseThreshold = Just 2000,
floatLamArgs = Just 0, -- Default: float only if no fvs
liftLamsRecArgs = Just 5, -- Default: the number of available argument hardware registers on x86_64
liftLamsNonRecArgs = Just 5, -- Default: the number of available argument hardware registers on x86_64
liftLamsKnown = False, -- Default: don't turn known calls into unknown ones
cmmProcAlignment = Nothing,
historySize = 20,
strictnessBefore = [],
parMakeCount = Nothing,
enableTimeStats = False,
ghcHeapSize = Nothing,
importPaths = ["."],
mainModuleNameIs = mAIN_NAME,
mainFunIs = Nothing,
reductionDepth = treatZeroAsInf mAX_REDUCTION_DEPTH,
solverIterations = treatZeroAsInf mAX_SOLVER_ITERATIONS,
givensFuel = mAX_GIVENS_FUEL,
wantedsFuel = mAX_WANTEDS_FUEL,
qcsFuel = mAX_QC_FUEL,
homeUnitId_ = mainUnitId,
homeUnitInstanceOf_ = Nothing,
homeUnitInstantiations_ = [],
workingDirectory = Nothing,
thisPackageName = Nothing,
hiddenModules = Set.empty,
reexportedModules = [],
objectDir = Nothing,
dylibInstallName = Nothing,
hiDir = Nothing,
hieDir = Nothing,
stubDir = Nothing,
dumpDir = Nothing,
objectSuf_ = phaseInputExt StopLn,
hcSuf = phaseInputExt HCc,
hiSuf_ = "hi",
hieSuf = "hie",
dynObjectSuf_ = "dyn_" ++ phaseInputExt StopLn,
dynHiSuf_ = "dyn_hi",
pluginModNames = [],
pluginModNameOpts = [],
frontendPluginOpts = [],
externalPluginSpecs = [],
outputFile_ = Nothing,
dynOutputFile_ = Nothing,
outputHi = Nothing,
dynOutputHi = Nothing,
dynLibLoader = SystemDependent,
dumpPrefix = "non-module.",
dumpPrefixForce = Nothing,
ldInputs = [],
includePaths = IncludeSpecs [] [] [],
libraryPaths = [],
frameworkPaths = [],
cmdlineFrameworks = [],
rtsOpts = Nothing,
rtsOptsEnabled = RtsOptsSafeOnly,
rtsOptsSuggestions = True,
hpcDir = ".hpc",
packageDBFlags = [],
packageFlags = [],
pluginPackageFlags = [],
ignorePackageFlags = [],
trustFlags = [],
packageEnv = Nothing,
targetWays_ = Set.empty,
splitInfo = Nothing,
ghcNameVersion = sGhcNameVersion mySettings,
unitSettings = sUnitSettings mySettings,
fileSettings = sFileSettings mySettings,
toolSettings = sToolSettings mySettings,
targetPlatform = sTargetPlatform mySettings,
platformMisc = sPlatformMisc mySettings,
rawSettings = sRawSettings mySettings,
tmpDir = panic "defaultDynFlags: uninitialized tmpDir",
llvmOptLevel = 0,
-- ghc -M values
depMakefile = "Makefile",
depIncludePkgDeps = False,
depIncludeCppDeps = False,
depExcludeMods = [],
depSuffixes = [],
-- end of ghc -M values
ghcVersionFile = Nothing,
haddockOptions = Nothing,
dumpFlags = EnumSet.empty,
generalFlags = EnumSet.fromList (defaultFlags mySettings),
warningFlags = EnumSet.fromList standardWarnings,
fatalWarningFlags = EnumSet.empty,
customWarningCategories = completeWarningCategorySet,
fatalCustomWarningCategories = emptyWarningCategorySet,
ghciScripts = [],
language = Nothing,
safeHaskell = Sf_None,
safeInfer = True,
safeInferred = True,
thOnLoc = noSrcSpan,
newDerivOnLoc = noSrcSpan,
deriveViaOnLoc = noSrcSpan,
overlapInstLoc = noSrcSpan,
incoherentOnLoc = noSrcSpan,
pkgTrustOnLoc = noSrcSpan,
warnSafeOnLoc = noSrcSpan,
warnUnsafeOnLoc = noSrcSpan,
trustworthyOnLoc = noSrcSpan,
extensions = [],
extensionFlags = flattenExtensionFlags Nothing [],
unfoldingOpts = defaultUnfoldingOpts,
maxWorkerArgs = 10,
maxForcedSpecArgs = 333,
-- 333 is fairly arbitrary, see Note [Forcing specialisation]:FS5
ghciHistSize = 50, -- keep a log of length 50 by default
ghciBrowserHost = "127.0.0.1",
ghciBrowserPort = 0,
ghciBrowserPuppeteerLaunchOpts = Nothing,
ghciBrowserPlaywrightBrowserType = Nothing,
ghciBrowserPlaywrightLaunchOpts = Nothing,
flushOut = defaultFlushOut,
pprUserLength = 5,
pprCols = 100,
useUnicode = False,
useColor = Auto,
canUseColor = False,
useErrorLinks = Auto,
canUseErrorLinks = False,
colScheme = Col.defaultScheme,
profAuto = NoProfAuto,
callerCcFilters = [],
interactivePrint = Nothing,
sseVersion = Nothing,
bmiVersion = Nothing,
avx = False,
avx2 = False,
avx512cd = False,
avx512er = False,
avx512f = False,
avx512pf = False,
-- Use FMA by default on AArch64
fma = (platformArch . sTargetPlatform $ mySettings) == ArchAArch64,
maxInlineAllocSize = 128,
maxInlineMemcpyInsns = 32,
maxInlineMemsetInsns = 32,
initialUnique = 0,
uniqueIncrement = 1,
reverseErrors = False,
maxErrors = Nothing,
cfgWeights = defaultWeights,
-- Archive prelinking defaults
-- Default threshold: 5MB (5 * 1024 * 1024 bytes)
-- This avoids prelinking overhead for small archives while fixing
-- "strange closure type" crashes for large archives in DYNAMIC=1 builds
prelinkArchiveThreshold = Just (5 * 1024 * 1024),
prelinkCacheDir = Nothing -- No persistent cache by default
}
type FatalMessager = String -> IO ()
defaultFatalMessager :: FatalMessager
defaultFatalMessager = hPutStrLn stderr
newtype FlushOut = FlushOut (IO ())
defaultFlushOut :: FlushOut
defaultFlushOut = FlushOut $ hFlush stdout
-- OnOffs accumulate in reverse order, so we use foldr in order to
-- process them in the right order
flattenExtensionFlags :: Maybe Language -> [OnOff LangExt.Extension] -> EnumSet LangExt.Extension
flattenExtensionFlags ml = foldr g defaultExtensionFlags
where g (On f) flags = EnumSet.insert f flags
g (Off f) flags = EnumSet.delete f flags
defaultExtensionFlags = EnumSet.fromList (languageExtensions ml)
-- -----------------------------------------------------------------------------
-- -jN
-- | The type for the -jN argument, specifying that -j on its own represents
-- using the number of machine processors.
data ParMakeCount
-- | Use this many processors (@-j<n>@ flag).
= ParMakeThisMany Int
-- | Use parallelism with as many processors as possible (@-j@ flag without an argument).
| ParMakeNumProcessors
-- | Use the specific semaphore @<sem>@ to control parallelism (@-jsem <sem>@ flag).
| ParMakeSemaphore FilePath
-- | The 'GhcMode' tells us whether we're doing multi-module
-- compilation (controlled via the "GHC" API) or one-shot
-- (single-module) compilation. This makes a difference primarily to
-- the "GHC.Unit.Finder": in one-shot mode we look for interface files for
-- imported modules, but in multi-module mode we look for source files
-- in order to check whether they need to be recompiled.
data GhcMode
= CompManager -- ^ @\-\-make@, GHCi, etc.
| OneShot -- ^ @ghc -c Foo.hs@
| MkDepend -- ^ @ghc -M@, see "GHC.Unit.Finder" for why we need this
deriving Eq
instance Outputable GhcMode where
ppr CompManager = text "CompManager"
ppr OneShot = text "OneShot"
ppr MkDepend = text "MkDepend"
isOneShot :: GhcMode -> Bool
isOneShot OneShot = True
isOneShot _other = False
-- | What to do in the link step, if there is one.
data GhcLink
= NoLink -- ^ Don't link at all
| LinkExecutable ExecutableLinkMode -- ^ Link object code into an executable
| LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
-- bytecode and object code).
| LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
| LinkStaticLib -- ^ Link objects into a static lib
| LinkMergedObj -- ^ Link objects into a merged "GHCi object"
deriving (Eq, Show)
isExecutableLink :: GhcLink -> Bool
isExecutableLink (LinkExecutable _) = True
isExecutableLink _ = False
-- | How we link the binary.
--
-- This mostly deals with how external system dependencies are treated.
-- The 'Ways' determine how Haskell libraries are linked.
data ExecutableLinkMode
= FullyStatic -- ^ fully static binary (incompatible with 'WayDyn')
| MostlyStatic [String] -- ^ we link system libraries statically, except the ones provided
| Dynamic -- ^ default
deriving (Eq, Show)
isNoLink :: GhcLink -> Bool
isNoLink NoLink = True
isNoLink _ = False
-- | We accept flags which make packages visible, but how they select
-- the package varies; this data type reflects what selection criterion
-- is used.
data PackageArg =
PackageArg String -- ^ @-package@, by 'PackageName'
| UnitIdArg Unit -- ^ @-package-id@, by 'Unit'
deriving (Eq, Show)
instance Outputable PackageArg where
ppr (PackageArg pn) = text "package" <+> text pn
ppr (UnitIdArg uid) = text "unit" <+> ppr uid
-- | Represents the renaming that may be associated with an exposed
-- package, e.g. the @rns@ part of @-package "foo (rns)"@.
--
-- Here are some example parsings of the package flags (where
-- a string literal is punned to be a 'ModuleName':
--
-- * @-package foo@ is @ModRenaming True []@
-- * @-package foo ()@ is @ModRenaming False []@
-- * @-package foo (A)@ is @ModRenaming False [("A", "A")]@
-- * @-package foo (A as B)@ is @ModRenaming False [("A", "B")]@
-- * @-package foo with (A as B)@ is @ModRenaming True [("A", "B")]@
data ModRenaming = ModRenaming {
modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope?
modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope
-- under name @n@.
} deriving (Eq)
instance Outputable ModRenaming where
ppr (ModRenaming b rns) = ppr b <+> parens (ppr rns)
-- | Flags for manipulating the set of non-broken packages.
newtype IgnorePackageFlag = IgnorePackage String -- ^ @-ignore-package@
deriving (Eq)
-- | Flags for manipulating package trust.
data TrustFlag
= TrustPackage String -- ^ @-trust@
| DistrustPackage String -- ^ @-distrust@
deriving (Eq)
-- | Flags for manipulating packages visibility.
data PackageFlag
= ExposePackage String PackageArg ModRenaming -- ^ @-package@, @-package-id@
| HidePackage String -- ^ @-hide-package@
deriving (Eq) -- NB: equality instance is used by packageFlagsChanged
data PackageDBFlag
= PackageDB PkgDbRef
| NoUserPackageDB
| NoGlobalPackageDB
| ClearPackageDBs
deriving (Eq)
packageFlagsChanged :: DynFlags -> DynFlags -> Bool
packageFlagsChanged idflags1 idflags0 =
packageFlags idflags1 /= packageFlags idflags0 ||
ignorePackageFlags idflags1 /= ignorePackageFlags idflags0 ||
pluginPackageFlags idflags1 /= pluginPackageFlags idflags0 ||
trustFlags idflags1 /= trustFlags idflags0 ||
packageDBFlags idflags1 /= packageDBFlags idflags0 ||
packageGFlags idflags1 /= packageGFlags idflags0
where
packageGFlags dflags = map (`gopt` dflags)
[ Opt_HideAllPackages
, Opt_HideAllPluginPackages
, Opt_AutoLinkPackages
, Opt_NoRts
, Opt_NoGhcInternal ]
instance Outputable PackageFlag where
ppr (ExposePackage n arg rn) = text n <> braces (ppr arg <+> ppr rn)
ppr (HidePackage str) = text "-hide-package" <+> text str
data DynLibLoader
= Deployable
| SystemDependent
deriving Eq
data RtsOptsEnabled
= RtsOptsNone | RtsOptsIgnore | RtsOptsIgnoreAll | RtsOptsSafeOnly
| RtsOptsAll
deriving (Show)
haveRtsOptsFlags :: DynFlags -> Bool
haveRtsOptsFlags dflags =
isJust (rtsOpts dflags) || case rtsOptsEnabled dflags of
RtsOptsSafeOnly -> False
_ -> True
-- | Are we building with @-fPIE@ or @-fPIC@ enabled?
positionIndependent :: DynFlags -> Bool
positionIndependent dflags = gopt Opt_PIC dflags || gopt Opt_PIE dflags
-- Note [-dynamic-too business]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- With -dynamic-too flag, we try to build both the non-dynamic and dynamic
-- objects in a single run of the compiler: the pipeline is the same down to
-- Core optimisation, then the backend (from Core to object code) is executed
-- twice.
--
-- The implementation is currently rather hacky, for example, we don't clearly separate non-dynamic
-- and dynamic loaded interfaces (#9176).
--
-- To make matters worse, we automatically enable -dynamic-too when some modules
-- need Template-Haskell and GHC is dynamically linked (cf
-- GHC.Driver.Pipeline.compileOne').
--
-- Note: DynamicTooState type and dynamicTooState/setDynamicNow functions removed
-- -dynamic-too is deprecated - only dynamic objects are produced now
data PkgDbRef
= GlobalPkgDb
| UserPkgDb
| PkgDbPath FilePath
deriving Eq
-- An argument to --reexported-module which can optionally specify a module renaming.
data ReexportedModule = ReexportedModule { reexportFrom :: ModuleName
, reexportTo :: ModuleName
}
instance Outputable ReexportedModule where
ppr (ReexportedModule from to) =
if from == to then ppr from