1//===- LangOptions.h - C Language Family Language Options -------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the clang::LangOptions interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_BASIC_LANGOPTIONS_H
15#define LLVM_CLANG_BASIC_LANGOPTIONS_H
16
17#include "clang/Basic/CommentOptions.h"
18#include "clang/Basic/LLVM.h"
19#include "clang/Basic/LangStandard.h"
20#include "clang/Basic/ObjCRuntime.h"
21#include "clang/Basic/Sanitizers.h"
22#include "clang/Basic/TargetCXXABI.h"
23#include "clang/Basic/Visibility.h"
24#include "llvm/ADT/FloatingPointMode.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/TargetParser/Triple.h"
27#include <optional>
28#include <string>
29#include <vector>
30
31namespace clang {
32
33/// In the Microsoft ABI, this controls the placement of virtual displacement
34/// members used to implement virtual inheritance.
35enum class MSVtorDispMode { Never, ForVBaseOverride, ForVFTable };
36
37/// Shader programs run in specific pipeline stages.
38/// The order of these values matters, and must be kept in sync with the
39/// Triple Environment enum in llvm::Triple. The ordering is enforced in
40/// static_asserts in Triple.cpp and in clang/Basic/HLSLRuntime.h.
41enum class ShaderStage {
42 Pixel = 0,
43 Vertex,
44 Geometry,
45 Hull,
46 Domain,
47 Compute,
48 Library,
49 RayGeneration,
50 Intersection,
51 AnyHit,
52 ClosestHit,
53 Miss,
54 Callable,
55 Mesh,
56 Amplification,
57 Invalid,
58};
59
60/// Bitfields of LangOptions, split out from LangOptions in order to ensure that
61/// this large collection of bitfields is a trivial class type.
62class LangOptionsBase {
63 friend class CompilerInvocation;
64 friend class CompilerInvocationBase;
65
66public:
67 using Visibility = clang::Visibility;
68 using RoundingMode = llvm::RoundingMode;
69
70 enum GCMode { NonGC, GCOnly, HybridGC };
71 enum StackProtectorMode { SSPOff, SSPOn, SSPStrong, SSPReq };
72
73 // Automatic variables live on the stack, and when trivial they're usually
74 // uninitialized because it's undefined behavior to use them without
75 // initializing them.
76 enum class TrivialAutoVarInitKind { Uninitialized, Zero, Pattern };
77
78 enum SignedOverflowBehaviorTy {
79 // Default C standard behavior.
80 SOB_Undefined,
81
82 // -fwrapv
83 SOB_Defined,
84
85 // -ftrapv
86 SOB_Trapping
87 };
88
89 // FIXME: Unify with TUKind.
90 enum CompilingModuleKind {
91 /// Not compiling a module interface at all.
92 CMK_None,
93
94 /// Compiling a module from a module map.
95 CMK_ModuleMap,
96
97 /// Compiling a module header unit.
98 CMK_HeaderUnit,
99
100 /// Compiling a C++ modules interface unit.
101 CMK_ModuleInterface,
102 };
103
104 enum PragmaMSPointersToMembersKind {
105 PPTMK_BestCase,
106 PPTMK_FullGeneralitySingleInheritance,
107 PPTMK_FullGeneralityMultipleInheritance,
108 PPTMK_FullGeneralityVirtualInheritance
109 };
110
111 using MSVtorDispMode = clang::MSVtorDispMode;
112
113 enum DefaultCallingConvention {
114 DCC_None,
115 DCC_CDecl,
116 DCC_FastCall,
117 DCC_StdCall,
118 DCC_VectorCall,
119 DCC_RegCall,
120 DCC_RtdCall
121 };
122
123 enum AddrSpaceMapMangling { ASMM_Target, ASMM_On, ASMM_Off };
124
125 // Corresponds to _MSC_VER
126 enum MSVCMajorVersion {
127 MSVC2010 = 1600,
128 MSVC2012 = 1700,
129 MSVC2013 = 1800,
130 MSVC2015 = 1900,
131 MSVC2017 = 1910,
132 MSVC2017_5 = 1912,
133 MSVC2017_7 = 1914,
134 MSVC2019 = 1920,
135 MSVC2019_5 = 1925,
136 MSVC2019_8 = 1928,
137 MSVC2022_3 = 1933,
138 };
139
140 enum SYCLMajorVersion {
141 SYCL_None,
142 SYCL_2017,
143 SYCL_2020,
144 // The "default" SYCL version to be used when none is specified on the
145 // frontend command line.
146 SYCL_Default = SYCL_2020
147 };
148
149 enum HLSLLangStd {
150 HLSL_Unset = 0,
151 HLSL_2015 = 2015,
152 HLSL_2016 = 2016,
153 HLSL_2017 = 2017,
154 HLSL_2018 = 2018,
155 HLSL_2021 = 2021,
156 HLSL_202x = 2029,
157 };
158
159 /// Clang versions with different platform ABI conformance.
160 enum class ClangABI {
161 /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
162 /// (SVN r257626). This causes <1 x long long> to be passed in an
163 /// integer register instead of an SSE register on x64_64.
164 Ver3_8,
165
166 /// Attempt to be ABI-compatible with code generated by Clang 4.0.x
167 /// (SVN r291814). This causes move operations to be ignored when
168 /// determining whether a class type can be passed or returned directly.
169 Ver4,
170
171 /// Attempt to be ABI-compatible with code generated by Clang 6.0.x
172 /// (SVN r321711). This causes determination of whether a type is
173 /// standard-layout to ignore collisions between empty base classes
174 /// and between base classes and member subobjects, which affects
175 /// whether we reuse base class tail padding in some ABIs.
176 Ver6,
177
178 /// Attempt to be ABI-compatible with code generated by Clang 7.0.x
179 /// (SVN r338536). This causes alignof (C++) and _Alignof (C11) to be
180 /// compatible with __alignof (i.e., return the preferred alignment)
181 /// rather than returning the required alignment.
182 Ver7,
183
184 /// Attempt to be ABI-compatible with code generated by Clang 9.0.x
185 /// (SVN r351319). This causes vectors of __int128 to be passed in memory
186 /// instead of passing in multiple scalar registers on x86_64 on Linux and
187 /// NetBSD.
188 Ver9,
189
190 /// Attempt to be ABI-compatible with code generated by Clang 11.0.x
191 /// (git 2e10b7a39b93). This causes clang to pass unions with a 256-bit
192 /// vector member on the stack instead of using registers, to not properly
193 /// mangle substitutions for template names in some cases, and to mangle
194 /// declaration template arguments without a cast to the parameter type
195 /// even when that can lead to mangling collisions.
196 Ver11,
197
198 /// Attempt to be ABI-compatible with code generated by Clang 12.0.x
199 /// (git 8e464dd76bef). This causes clang to mangle lambdas within
200 /// global-scope inline variables incorrectly.
201 Ver12,
202
203 /// Attempt to be ABI-compatible with code generated by Clang 14.0.x.
204 /// This causes clang to:
205 /// - mangle dependent nested names incorrectly.
206 /// - make trivial only those defaulted copy constructors with a
207 /// parameter-type-list equivalent to the parameter-type-list of an
208 /// implicit declaration.
209 Ver14,
210
211 /// Attempt to be ABI-compatible with code generated by Clang 15.0.x.
212 /// This causes clang to:
213 /// - Reverse the implementation for DR692, DR1395 and DR1432.
214 /// - pack non-POD members of packed structs.
215 /// - consider classes with defaulted special member functions non-pod.
216 Ver15,
217
218 /// Attempt to be ABI-compatible with code generated by Clang 17.0.x.
219 /// This causes clang to revert some fixes to its implementation of the
220 /// Itanium name mangling scheme, with the consequence that overloaded
221 /// function templates are mangled the same if they differ only by:
222 /// - constraints
223 /// - whether a non-type template parameter has a deduced type
224 /// - the parameter list of a template template parameter
225 Ver17,
226
227 /// Attempt to be ABI-compatible with code generated by Clang 18.0.x.
228 /// This causes clang to revert some fixes to the mangling of lambdas
229 /// in the initializers of members of local classes.
230 Ver18,
231
232 /// Conform to the underlying platform's C and C++ ABIs as closely
233 /// as we can.
234 Latest
235 };
236
237 enum class CoreFoundationABI {
238 /// No interoperability ABI has been specified
239 Unspecified,
240 /// CoreFoundation does not have any language interoperability
241 Standalone,
242 /// Interoperability with the ObjectiveC runtime
243 ObjectiveC,
244 /// Interoperability with the latest known version of the Swift runtime
245 Swift,
246 /// Interoperability with the Swift 5.0 runtime
247 Swift5_0,
248 /// Interoperability with the Swift 4.2 runtime
249 Swift4_2,
250 /// Interoperability with the Swift 4.1 runtime
251 Swift4_1,
252 };
253
254 enum FPModeKind {
255 // Disable the floating point pragma
256 FPM_Off,
257
258 // Enable the floating point pragma
259 FPM_On,
260
261 // Aggressively fuse FP ops (E.g. FMA) disregarding pragmas.
262 FPM_Fast,
263
264 // Aggressively fuse FP ops and honor pragmas.
265 FPM_FastHonorPragmas
266 };
267
268 /// Possible floating point exception behavior.
269 enum FPExceptionModeKind {
270 /// Assume that floating-point exceptions are masked.
271 FPE_Ignore,
272 /// Transformations do not cause new exceptions but may hide some.
273 FPE_MayTrap,
274 /// Strictly preserve the floating-point exception semantics.
275 FPE_Strict,
276 /// Used internally to represent initial unspecified value.
277 FPE_Default
278 };
279
280 /// Possible float expression evaluation method choices.
281 enum FPEvalMethodKind {
282 /// The evaluation method cannot be determined or is inconsistent for this
283 /// target.
284 FEM_Indeterminable = -1,
285 /// Use the declared type for fp arithmetic.
286 FEM_Source = 0,
287 /// Use the type double for fp arithmetic.
288 FEM_Double = 1,
289 /// Use extended type for fp arithmetic.
290 FEM_Extended = 2,
291 /// Used only for FE option processing; this is only used to indicate that
292 /// the user did not specify an explicit evaluation method on the command
293 /// line and so the target should be queried for its default evaluation
294 /// method instead.
295 FEM_UnsetOnCommandLine = 3
296 };
297
298 enum ExcessPrecisionKind { FPP_Standard, FPP_Fast, FPP_None };
299
300 /// Possible exception handling behavior.
301 enum class ExceptionHandlingKind { None, SjLj, WinEH, DwarfCFI, Wasm };
302
303 enum class LaxVectorConversionKind {
304 /// Permit no implicit vector bitcasts.
305 None,
306 /// Permit vector bitcasts between integer vectors with different numbers
307 /// of elements but the same total bit-width.
308 Integer,
309 /// Permit vector bitcasts between all vectors with the same total
310 /// bit-width.
311 All,
312 };
313
314 enum class AltivecSrcCompatKind {
315 // All vector compares produce scalars except vector pixel and vector bool.
316 // The types vector pixel and vector bool return vector results.
317 Mixed,
318 // All vector compares produce vector results as in GCC.
319 GCC,
320 // All vector compares produce scalars as in XL.
321 XL,
322 // Default clang behaviour.
323 Default = Mixed,
324 };
325
326 enum class SignReturnAddressScopeKind {
327 /// No signing for any function.
328 None,
329 /// Sign the return address of functions that spill LR.
330 NonLeaf,
331 /// Sign the return address of all functions,
332 All
333 };
334
335 enum class SignReturnAddressKeyKind {
336 /// Return address signing uses APIA key.
337 AKey,
338 /// Return address signing uses APIB key.
339 BKey
340 };
341
342 enum class ThreadModelKind {
343 /// POSIX Threads.
344 POSIX,
345 /// Single Threaded Environment.
346 Single
347 };
348
349 enum class ExtendArgsKind {
350 /// Integer arguments are sign or zero extended to 32/64 bits
351 /// during default argument promotions.
352 ExtendTo32,
353 ExtendTo64
354 };
355
356 enum class GPUDefaultStreamKind {
357 /// Legacy default stream
358 Legacy,
359 /// Per-thread default stream
360 PerThread,
361 };
362
363 enum class DefaultVisiblityExportMapping {
364 None,
365 /// map only explicit default visibilities to exported
366 Explicit,
367 /// map all default visibilities to exported
368 All,
369 };
370
371 enum class VisibilityForcedKinds {
372 /// Force hidden visibility
373 ForceHidden,
374 /// Force protected visibility
375 ForceProtected,
376 /// Force default visibility
377 ForceDefault,
378 /// Don't alter the visibility
379 Source,
380 };
381
382 enum class VisibilityFromDLLStorageClassKinds {
383 /// Keep the IR-gen assigned visibility.
384 Keep,
385 /// Override the IR-gen assigned visibility with default visibility.
386 Default,
387 /// Override the IR-gen assigned visibility with hidden visibility.
388 Hidden,
389 /// Override the IR-gen assigned visibility with protected visibility.
390 Protected,
391 };
392
393 enum class StrictFlexArraysLevelKind {
394 /// Any trailing array member is a FAM.
395 Default = 0,
396 /// Any trailing array member of undefined, 0, or 1 size is a FAM.
397 OneZeroOrIncomplete = 1,
398 /// Any trailing array member of undefined or 0 size is a FAM.
399 ZeroOrIncomplete = 2,
400 /// Any trailing array member of undefined size is a FAM.
401 IncompleteOnly = 3,
402 };
403
404 /// Controls the various implementations for complex multiplication and
405 // division.
406 enum ComplexRangeKind {
407 /// Implementation of complex division and multiplication using a call to
408 /// runtime library functions(generally the case, but the BE might
409 /// sometimes replace the library call if it knows enough about the
410 /// potential range of the inputs). Overflow and non-finite values are
411 /// handled by the library implementation. This is the default value.
412 CX_Full,
413
414 /// Implementation of complex division offering an improved handling
415 /// for overflow in intermediate calculations with no special handling for
416 /// NaN and infinite values.
417 CX_Improved,
418
419 /// Implementation of complex division using algebraic formulas at
420 /// higher precision. Overflow is handled. Non-finite values are handled in
421 /// some cases. If the target hardware does not have native support for a
422 /// higher precision data type, an implementation for the complex operation
423 /// will be used to provide improved guards against intermediate overflow,
424 /// but overflow and underflow may still occur in some cases. NaN and
425 /// infinite values are not handled.
426 CX_Promoted,
427
428 /// Implementation of complex division and multiplication using
429 /// algebraic formulas at source precision. No special handling to avoid
430 /// overflow. NaN and infinite values are not handled.
431 CX_Basic,
432
433 /// No range rule is enabled.
434 CX_None
435 };
436
437 // Define simple language options (with no accessors).
438#define LANGOPT(Name, Bits, Default, Description) unsigned Name : Bits;
439#define ENUM_LANGOPT(Name, Type, Bits, Default, Description)
440#include "clang/Basic/LangOptions.def"
441
442protected:
443 // Define language options of enumeration type. These are private, and will
444 // have accessors (below).
445#define LANGOPT(Name, Bits, Default, Description)
446#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
447 LLVM_PREFERRED_TYPE(Type) \
448 unsigned Name : Bits;
449#include "clang/Basic/LangOptions.def"
450};
451
452/// Keeps track of the various options that can be
453/// enabled, which controls the dialect of C or C++ that is accepted.
454class LangOptions : public LangOptionsBase {
455public:
456 /// The used language standard.
457 LangStandard::Kind LangStd;
458
459 /// Set of enabled sanitizers.
460 SanitizerSet Sanitize;
461 /// Is at least one coverage instrumentation type enabled.
462 bool SanitizeCoverage = false;
463
464 /// Paths to files specifying which objects
465 /// (files, functions, variables) should not be instrumented.
466 std::vector<std::string> NoSanitizeFiles;
467
468 /// Paths to the XRay "always instrument" files specifying which
469 /// objects (files, functions, variables) should be imbued with the XRay
470 /// "always instrument" attribute.
471 /// WARNING: This is a deprecated field and will go away in the future.
472 std::vector<std::string> XRayAlwaysInstrumentFiles;
473
474 /// Paths to the XRay "never instrument" files specifying which
475 /// objects (files, functions, variables) should be imbued with the XRay
476 /// "never instrument" attribute.
477 /// WARNING: This is a deprecated field and will go away in the future.
478 std::vector<std::string> XRayNeverInstrumentFiles;
479
480 /// Paths to the XRay attribute list files, specifying which objects
481 /// (files, functions, variables) should be imbued with the appropriate XRay
482 /// attribute(s).
483 std::vector<std::string> XRayAttrListFiles;
484
485 /// Paths to special case list files specifying which entities
486 /// (files, functions) should or should not be instrumented.
487 std::vector<std::string> ProfileListFiles;
488
489 clang::ObjCRuntime ObjCRuntime;
490
491 CoreFoundationABI CFRuntime = CoreFoundationABI::Unspecified;
492
493 std::string ObjCConstantStringClass;
494
495 /// The name of the handler function to be called when -ftrapv is
496 /// specified.
497 ///
498 /// If none is specified, abort (GCC-compatible behaviour).
499 std::string OverflowHandler;
500
501 /// The module currently being compiled as specified by -fmodule-name.
502 std::string ModuleName;
503
504 /// The name of the current module, of which the main source file
505 /// is a part. If CompilingModule is set, we are compiling the interface
506 /// of this module, otherwise we are compiling an implementation file of
507 /// it. This starts as ModuleName in case -fmodule-name is provided and
508 /// changes during compilation to reflect the current module.
509 std::string CurrentModule;
510
511 /// The names of any features to enable in module 'requires' decls
512 /// in addition to the hard-coded list in Module.cpp and the target features.
513 ///
514 /// This list is sorted.
515 std::vector<std::string> ModuleFeatures;
516
517 /// Options for parsing comments.
518 CommentOptions CommentOpts;
519
520 /// A list of all -fno-builtin-* function names (e.g., memset).
521 std::vector<std::string> NoBuiltinFuncs;
522
523 /// A prefix map for __FILE__, __BASE_FILE__ and __builtin_FILE().
524 std::map<std::string, std::string, std::greater<std::string>> MacroPrefixMap;
525
526 /// Triples of the OpenMP targets that the host code codegen should
527 /// take into account in order to generate accurate offloading descriptors.
528 std::vector<llvm::Triple> OMPTargetTriples;
529
530 /// Name of the IR file that contains the result of the OpenMP target
531 /// host code generation.
532 std::string OMPHostIRFile;
533
534 /// The user provided compilation unit ID, if non-empty. This is used to
535 /// externalize static variables which is needed to support accessing static
536 /// device variables in host code for single source offloading languages
537 /// like CUDA/HIP.
538 std::string CUID;
539
540 /// C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
541 /// This overrides the default ABI used by the target.
542 std::optional<TargetCXXABI::Kind> CXXABI;
543
544 /// Indicates whether the front-end is explicitly told that the
545 /// input is a header file (i.e. -x c-header).
546 bool IsHeaderFile = false;
547
548 /// The default stream kind used for HIP kernel launching.
549 GPUDefaultStreamKind GPUDefaultStream;
550
551 /// The seed used by the randomize structure layout feature.
552 std::string RandstructSeed;
553
554 /// Indicates whether to use target's platform-specific file separator when
555 /// __FILE__ macro is used and when concatenating filename with directory or
556 /// to use build environment environment's platform-specific file separator.
557 ///
558 /// The plaform-specific path separator is the backslash(\) for Windows and
559 /// forward slash (/) elsewhere.
560 bool UseTargetPathSeparator = false;
561
562 // Indicates whether we should keep all nullptr checks for pointers
563 // received as a result of a standard operator new (-fcheck-new)
564 bool CheckNew = false;
565
566 // In OpenACC mode, contains a user provided override for the _OPENACC macro.
567 // This exists so that we can override the macro value and test our incomplete
568 // implementation on real-world examples.
569 std::string OpenACCMacroOverride;
570
571 LangOptions();
572
573 /// Set language defaults for the given input language and
574 /// language standard in the given LangOptions object.
575 ///
576 /// \param Opts - The LangOptions object to set up.
577 /// \param Lang - The input language.
578 /// \param T - The target triple.
579 /// \param Includes - If the language requires extra headers to be implicitly
580 /// included, they will be appended to this list.
581 /// \param LangStd - The input language standard.
582 static void
583 setLangDefaults(LangOptions &Opts, Language Lang, const llvm::Triple &T,
584 std::vector<std::string> &Includes,
585 LangStandard::Kind LangStd = LangStandard::lang_unspecified);
586
587 // Define accessors/mutators for language options of enumeration type.
588#define LANGOPT(Name, Bits, Default, Description)
589#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
590 Type get##Name() const { return static_cast<Type>(Name); } \
591 void set##Name(Type Value) { Name = static_cast<unsigned>(Value); }
592#include "clang/Basic/LangOptions.def"
593
594 /// Are we compiling a module?
595 bool isCompilingModule() const {
596 return getCompilingModule() != CMK_None;
597 }
598
599 /// Are we compiling a module implementation?
600 bool isCompilingModuleImplementation() const {
601 return !isCompilingModule() && !ModuleName.empty();
602 }
603
604 /// Do we need to track the owning module for a local declaration?
605 bool trackLocalOwningModule() const {
606 return isCompilingModule() || ModulesLocalVisibility;
607 }
608
609 bool isSignedOverflowDefined() const {
610 return getSignedOverflowBehavior() == SOB_Defined;
611 }
612
613 bool isSubscriptPointerArithmetic() const {
614 return ObjCRuntime.isSubscriptPointerArithmetic() &&
615 !ObjCSubscriptingLegacyRuntime;
616 }
617
618 bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const {
619 return MSCompatibilityVersion >= MajorVersion * 100000U;
620 }
621
622 /// Reset all of the options that are not considered when building a
623 /// module.
624 void resetNonModularOptions();
625
626 /// Is this a libc/libm function that is no longer recognized as a
627 /// builtin because a -fno-builtin-* option has been specified?
628 bool isNoBuiltinFunc(StringRef Name) const;
629
630 /// True if any ObjC types may have non-trivial lifetime qualifiers.
631 bool allowsNonTrivialObjCLifetimeQualifiers() const {
632 return ObjCAutoRefCount || ObjCWeak;
633 }
634
635 bool assumeFunctionsAreConvergent() const {
636 return ConvergentFunctions;
637 }
638
639 /// Return the OpenCL C or C++ version as a VersionTuple.
640 VersionTuple getOpenCLVersionTuple() const;
641
642 /// Return the OpenCL version that kernel language is compatible with
643 unsigned getOpenCLCompatibleVersion() const;
644
645 /// Return the OpenCL C or C++ for OpenCL language name and version
646 /// as a string.
647 std::string getOpenCLVersionString() const;
648
649 /// Returns true if functions without prototypes or functions with an
650 /// identifier list (aka K&R C functions) are not allowed.
651 bool requiresStrictPrototypes() const {
652 return CPlusPlus || C23 || DisableKNRFunctions;
653 }
654
655 /// Returns true if implicit function declarations are allowed in the current
656 /// language mode.
657 bool implicitFunctionsAllowed() const {
658 return !requiresStrictPrototypes() && !OpenCL;
659 }
660
661 /// Returns true if the language supports calling the 'atexit' function.
662 bool hasAtExit() const { return !(OpenMP && OpenMPIsTargetDevice); }
663
664 /// Returns true if implicit int is part of the language requirements.
665 bool isImplicitIntRequired() const { return !CPlusPlus && !C99; }
666
667 /// Returns true if implicit int is supported at all.
668 bool isImplicitIntAllowed() const { return !CPlusPlus && !C23; }
669
670 /// Check if return address signing is enabled.
671 bool hasSignReturnAddress() const {
672 return getSignReturnAddressScope() != SignReturnAddressScopeKind::None;
673 }
674
675 /// Check if return address signing uses AKey.
676 bool isSignReturnAddressWithAKey() const {
677 return getSignReturnAddressKey() == SignReturnAddressKeyKind::AKey;
678 }
679
680 /// Check if leaf functions are also signed.
681 bool isSignReturnAddressScopeAll() const {
682 return getSignReturnAddressScope() == SignReturnAddressScopeKind::All;
683 }
684
685 bool hasSjLjExceptions() const {
686 return getExceptionHandling() == ExceptionHandlingKind::SjLj;
687 }
688
689 bool hasSEHExceptions() const {
690 return getExceptionHandling() == ExceptionHandlingKind::WinEH;
691 }
692
693 bool hasDWARFExceptions() const {
694 return getExceptionHandling() == ExceptionHandlingKind::DwarfCFI;
695 }
696
697 bool hasWasmExceptions() const {
698 return getExceptionHandling() == ExceptionHandlingKind::Wasm;
699 }
700
701 bool isSYCL() const { return SYCLIsDevice || SYCLIsHost; }
702
703 bool hasDefaultVisibilityExportMapping() const {
704 return getDefaultVisibilityExportMapping() !=
705 DefaultVisiblityExportMapping::None;
706 }
707
708 bool isExplicitDefaultVisibilityExportMapping() const {
709 return getDefaultVisibilityExportMapping() ==
710 DefaultVisiblityExportMapping::Explicit;
711 }
712
713 bool isAllDefaultVisibilityExportMapping() const {
714 return getDefaultVisibilityExportMapping() ==
715 DefaultVisiblityExportMapping::All;
716 }
717
718 bool hasGlobalAllocationFunctionVisibility() const {
719 return getGlobalAllocationFunctionVisibility() !=
720 VisibilityForcedKinds::Source;
721 }
722
723 bool hasDefaultGlobalAllocationFunctionVisibility() const {
724 return getGlobalAllocationFunctionVisibility() ==
725 VisibilityForcedKinds::ForceDefault;
726 }
727
728 bool hasProtectedGlobalAllocationFunctionVisibility() const {
729 return getGlobalAllocationFunctionVisibility() ==
730 VisibilityForcedKinds::ForceProtected;
731 }
732
733 bool hasHiddenGlobalAllocationFunctionVisibility() const {
734 return getGlobalAllocationFunctionVisibility() ==
735 VisibilityForcedKinds::ForceHidden;
736 }
737
738 /// Remap path prefix according to -fmacro-prefix-path option.
739 void remapPathPrefix(SmallVectorImpl<char> &Path) const;
740
741 RoundingMode getDefaultRoundingMode() const {
742 return RoundingMath ? RoundingMode::Dynamic
743 : RoundingMode::NearestTiesToEven;
744 }
745
746 FPExceptionModeKind getDefaultExceptionMode() const {
747 FPExceptionModeKind EM = getFPExceptionMode();
748 if (EM == FPExceptionModeKind::FPE_Default)
749 return FPExceptionModeKind::FPE_Ignore;
750 return EM;
751 }
752};
753
754/// Floating point control options
755class FPOptionsOverride;
756class FPOptions {
757public:
758 // We start by defining the layout.
759 using storage_type = uint32_t;
760
761 using RoundingMode = llvm::RoundingMode;
762
763 static constexpr unsigned StorageBitSize = 8 * sizeof(storage_type);
764
765 // Define a fake option named "First" so that we have a PREVIOUS even for the
766 // real first option.
767 static constexpr storage_type FirstShift = 0, FirstWidth = 0;
768#define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
769 static constexpr storage_type NAME##Shift = \
770 PREVIOUS##Shift + PREVIOUS##Width; \
771 static constexpr storage_type NAME##Width = WIDTH; \
772 static constexpr storage_type NAME##Mask = ((1 << NAME##Width) - 1) \
773 << NAME##Shift;
774#include "clang/Basic/FPOptions.def"
775
776 static constexpr storage_type TotalWidth = 0
777#define OPTION(NAME, TYPE, WIDTH, PREVIOUS) +WIDTH
778#include "clang/Basic/FPOptions.def"
779 ;
780 static_assert(TotalWidth <= StorageBitSize, "Too short type for FPOptions");
781
782private:
783 storage_type Value;
784
785 FPOptionsOverride getChangesSlow(const FPOptions &Base) const;
786
787public:
788 FPOptions() : Value(0) {
789 setFPContractMode(LangOptions::FPM_Off);
790 setConstRoundingMode(RoundingMode::Dynamic);
791 setSpecifiedExceptionMode(LangOptions::FPE_Default);
792 }
793 explicit FPOptions(const LangOptions &LO) {
794 Value = 0;
795 // The language fp contract option FPM_FastHonorPragmas has the same effect
796 // as FPM_Fast in frontend. For simplicity, use FPM_Fast uniformly in
797 // frontend.
798 auto LangOptContractMode = LO.getDefaultFPContractMode();
799 if (LangOptContractMode == LangOptions::FPM_FastHonorPragmas)
800 LangOptContractMode = LangOptions::FPM_Fast;
801 setFPContractMode(LangOptContractMode);
802 setRoundingMath(LO.RoundingMath);
803 setConstRoundingMode(LangOptions::RoundingMode::Dynamic);
804 setSpecifiedExceptionMode(LO.getFPExceptionMode());
805 setAllowFPReassociate(LO.AllowFPReassoc);
806 setNoHonorNaNs(LO.NoHonorNaNs);
807 setNoHonorInfs(LO.NoHonorInfs);
808 setNoSignedZero(LO.NoSignedZero);
809 setAllowReciprocal(LO.AllowRecip);
810 setAllowApproxFunc(LO.ApproxFunc);
811 if (getFPContractMode() == LangOptions::FPM_On &&
812 getRoundingMode() == llvm::RoundingMode::Dynamic &&
813 getExceptionMode() == LangOptions::FPE_Strict)
814 // If the FP settings are set to the "strict" model, then
815 // FENV access is set to true. (ffp-model=strict)
816 setAllowFEnvAccess(true);
817 else
818 setAllowFEnvAccess(LangOptions::FPM_Off);
819 setComplexRange(LO.getComplexRange());
820 }
821
822 bool allowFPContractWithinStatement() const {
823 return getFPContractMode() == LangOptions::FPM_On;
824 }
825 void setAllowFPContractWithinStatement() {
826 setFPContractMode(LangOptions::FPM_On);
827 }
828
829 bool allowFPContractAcrossStatement() const {
830 return getFPContractMode() == LangOptions::FPM_Fast;
831 }
832 void setAllowFPContractAcrossStatement() {
833 setFPContractMode(LangOptions::FPM_Fast);
834 }
835
836 bool isFPConstrained() const {
837 return getRoundingMode() != llvm::RoundingMode::NearestTiesToEven ||
838 getExceptionMode() != LangOptions::FPE_Ignore ||
839 getAllowFEnvAccess();
840 }
841
842 RoundingMode getRoundingMode() const {
843 RoundingMode RM = getConstRoundingMode();
844 if (RM == RoundingMode::Dynamic) {
845 // C23: 7.6.2p3 If the FE_DYNAMIC mode is specified and FENV_ACCESS is
846 // "off", the translator may assume that the default rounding mode is in
847 // effect.
848 if (!getAllowFEnvAccess() && !getRoundingMath())
849 RM = RoundingMode::NearestTiesToEven;
850 }
851 return RM;
852 }
853
854 LangOptions::FPExceptionModeKind getExceptionMode() const {
855 LangOptions::FPExceptionModeKind EM = getSpecifiedExceptionMode();
856 if (EM == LangOptions::FPExceptionModeKind::FPE_Default) {
857 if (getAllowFEnvAccess())
858 return LangOptions::FPExceptionModeKind::FPE_Strict;
859 else
860 return LangOptions::FPExceptionModeKind::FPE_Ignore;
861 }
862 return EM;
863 }
864
865 bool operator==(FPOptions other) const { return Value == other.Value; }
866
867 /// Return the default value of FPOptions that's used when trailing
868 /// storage isn't required.
869 static FPOptions defaultWithoutTrailingStorage(const LangOptions &LO);
870
871 storage_type getAsOpaqueInt() const { return Value; }
872 static FPOptions getFromOpaqueInt(storage_type Value) {
873 FPOptions Opts;
874 Opts.Value = Value;
875 return Opts;
876 }
877
878 /// Return difference with the given option set.
879 FPOptionsOverride getChangesFrom(const FPOptions &Base) const;
880
881 void applyChanges(FPOptionsOverride FPO);
882
883 // We can define most of the accessors automatically:
884#define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
885 TYPE get##NAME() const { \
886 return static_cast<TYPE>((Value & NAME##Mask) >> NAME##Shift); \
887 } \
888 void set##NAME(TYPE value) { \
889 Value = (Value & ~NAME##Mask) | (storage_type(value) << NAME##Shift); \
890 }
891#include "clang/Basic/FPOptions.def"
892 LLVM_DUMP_METHOD void dump();
893};
894
895/// Represents difference between two FPOptions values.
896///
897/// The effect of language constructs changing the set of floating point options
898/// is usually a change of some FP properties while leaving others intact. This
899/// class describes such changes by keeping information about what FP options
900/// are overridden.
901///
902/// The integral set of FP options, described by the class FPOptions, may be
903/// represented as a default FP option set, defined by language standard and
904/// command line options, with the overrides introduced by pragmas.
905///
906/// The is implemented as a value of the new FPOptions plus a mask showing which
907/// fields are actually set in it.
908class FPOptionsOverride {
909 FPOptions Options = FPOptions::getFromOpaqueInt(Value: 0);
910 FPOptions::storage_type OverrideMask = 0;
911
912public:
913 using RoundingMode = llvm::RoundingMode;
914
915 /// The type suitable for storing values of FPOptionsOverride. Must be twice
916 /// as wide as bit size of FPOption.
917 using storage_type = uint64_t;
918 static_assert(sizeof(storage_type) >= 2 * sizeof(FPOptions::storage_type),
919 "Too short type for FPOptionsOverride");
920
921 /// Bit mask selecting bits of OverrideMask in serialized representation of
922 /// FPOptionsOverride.
923 static constexpr storage_type OverrideMaskBits =
924 (static_cast<storage_type>(1) << FPOptions::StorageBitSize) - 1;
925
926 FPOptionsOverride() {}
927 FPOptionsOverride(const LangOptions &LO)
928 : Options(LO), OverrideMask(OverrideMaskBits) {}
929 FPOptionsOverride(FPOptions FPO)
930 : Options(FPO), OverrideMask(OverrideMaskBits) {}
931 FPOptionsOverride(FPOptions FPO, FPOptions::storage_type Mask)
932 : Options(FPO), OverrideMask(Mask) {}
933
934 bool requiresTrailingStorage() const { return OverrideMask != 0; }
935
936 void setAllowFPContractWithinStatement() {
937 setFPContractModeOverride(LangOptions::FPM_On);
938 }
939
940 void setAllowFPContractAcrossStatement() {
941 setFPContractModeOverride(LangOptions::FPM_Fast);
942 }
943
944 void setDisallowFPContract() {
945 setFPContractModeOverride(LangOptions::FPM_Off);
946 }
947
948 void setFPPreciseEnabled(bool Value) {
949 setAllowFPReassociateOverride(!Value);
950 setNoHonorNaNsOverride(!Value);
951 setNoHonorInfsOverride(!Value);
952 setNoSignedZeroOverride(!Value);
953 setAllowReciprocalOverride(!Value);
954 setAllowApproxFuncOverride(!Value);
955 setMathErrnoOverride(Value);
956 if (Value)
957 /* Precise mode implies fp_contract=on and disables ffast-math */
958 setAllowFPContractWithinStatement();
959 else
960 /* Precise mode disabled sets fp_contract=fast and enables ffast-math */
961 setAllowFPContractAcrossStatement();
962 }
963
964 void setDisallowOptimizations() {
965 setFPPreciseEnabled(true);
966 setDisallowFPContract();
967 }
968
969 storage_type getAsOpaqueInt() const {
970 return (static_cast<storage_type>(Options.getAsOpaqueInt())
971 << FPOptions::StorageBitSize) |
972 OverrideMask;
973 }
974 static FPOptionsOverride getFromOpaqueInt(storage_type I) {
975 FPOptionsOverride Opts;
976 Opts.OverrideMask = I & OverrideMaskBits;
977 Opts.Options = FPOptions::getFromOpaqueInt(Value: I >> FPOptions::StorageBitSize);
978 return Opts;
979 }
980
981 FPOptions applyOverrides(FPOptions Base) {
982 FPOptions Result =
983 FPOptions::getFromOpaqueInt(Value: (Base.getAsOpaqueInt() & ~OverrideMask) |
984 (Options.getAsOpaqueInt() & OverrideMask));
985 return Result;
986 }
987
988 FPOptions applyOverrides(const LangOptions &LO) {
989 return applyOverrides(Base: FPOptions(LO));
990 }
991
992 bool operator==(FPOptionsOverride other) const {
993 return Options == other.Options && OverrideMask == other.OverrideMask;
994 }
995 bool operator!=(FPOptionsOverride other) const { return !(*this == other); }
996
997#define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
998 bool has##NAME##Override() const { \
999 return OverrideMask & FPOptions::NAME##Mask; \
1000 } \
1001 TYPE get##NAME##Override() const { \
1002 assert(has##NAME##Override()); \
1003 return Options.get##NAME(); \
1004 } \
1005 void clear##NAME##Override() { \
1006 /* Clear the actual value so that we don't have spurious differences when \
1007 * testing equality. */ \
1008 Options.set##NAME(TYPE(0)); \
1009 OverrideMask &= ~FPOptions::NAME##Mask; \
1010 } \
1011 void set##NAME##Override(TYPE value) { \
1012 Options.set##NAME(value); \
1013 OverrideMask |= FPOptions::NAME##Mask; \
1014 }
1015#include "clang/Basic/FPOptions.def"
1016 LLVM_DUMP_METHOD void dump();
1017};
1018
1019inline FPOptionsOverride FPOptions::getChangesFrom(const FPOptions &Base) const {
1020 if (Value == Base.Value)
1021 return FPOptionsOverride();
1022 return getChangesSlow(Base);
1023}
1024
1025inline void FPOptions::applyChanges(FPOptionsOverride FPO) {
1026 *this = FPO.applyOverrides(Base: *this);
1027}
1028
1029/// Describes the kind of translation unit being processed.
1030enum TranslationUnitKind {
1031 /// The translation unit is a complete translation unit.
1032 TU_Complete,
1033
1034 /// The translation unit is a prefix to a translation unit, and is
1035 /// not complete.
1036 TU_Prefix,
1037
1038 /// The translation unit is a clang module.
1039 TU_ClangModule,
1040
1041 /// The translation unit is a is a complete translation unit that we might
1042 /// incrementally extend later.
1043 TU_Incremental
1044};
1045
1046} // namespace clang
1047
1048#endif // LLVM_CLANG_BASIC_LANGOPTIONS_H
1049

source code of clang/include/clang/Basic/LangOptions.h