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/ObjCRuntime.h"
20#include "clang/Basic/Sanitizers.h"
21#include "clang/Basic/Visibility.h"
22#include "llvm/ADT/FloatingPointMode.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/Triple.h"
25#include <string>
26#include <vector>
27
28namespace clang {
29
30/// Bitfields of LangOptions, split out from LangOptions in order to ensure that
31/// this large collection of bitfields is a trivial class type.
32class LangOptionsBase {
33public:
34  // Define simple language options (with no accessors).
35#define LANGOPT(Name, Bits, Default, Description) unsigned Name : Bits;
36#define ENUM_LANGOPT(Name, Type, Bits, Default, Description)
37#include "clang/Basic/LangOptions.def"
38
39protected:
40  // Define language options of enumeration type. These are private, and will
41  // have accessors (below).
42#define LANGOPT(Name, Bits, Default, Description)
43#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
44  unsigned Name : Bits;
45#include "clang/Basic/LangOptions.def"
46};
47
48/// In the Microsoft ABI, this controls the placement of virtual displacement
49/// members used to implement virtual inheritance.
50enum class MSVtorDispMode { Never, ForVBaseOverride, ForVFTable };
51
52/// Keeps track of the various options that can be
53/// enabled, which controls the dialect of C or C++ that is accepted.
54class LangOptions : public LangOptionsBase {
55public:
56  using Visibility = clang::Visibility;
57  using RoundingMode = llvm::RoundingMode;
58
59  enum GCMode { NonGC, GCOnly, HybridGC };
60  enum StackProtectorMode { SSPOff, SSPOn, SSPStrong, SSPReq };
61
62  // Automatic variables live on the stack, and when trivial they're usually
63  // uninitialized because it's undefined behavior to use them without
64  // initializing them.
65  enum class TrivialAutoVarInitKind { Uninitialized, Zero, Pattern };
66
67  enum SignedOverflowBehaviorTy {
68    // Default C standard behavior.
69    SOB_Undefined,
70
71    // -fwrapv
72    SOB_Defined,
73
74    // -ftrapv
75    SOB_Trapping
76  };
77
78  // FIXME: Unify with TUKind.
79  enum CompilingModuleKind {
80    /// Not compiling a module interface at all.
81    CMK_None,
82
83    /// Compiling a module from a module map.
84    CMK_ModuleMap,
85
86    /// Compiling a module from a list of header files.
87    CMK_HeaderModule,
88
89    /// Compiling a C++ modules TS module interface unit.
90    CMK_ModuleInterface,
91  };
92
93  enum PragmaMSPointersToMembersKind {
94    PPTMK_BestCase,
95    PPTMK_FullGeneralitySingleInheritance,
96    PPTMK_FullGeneralityMultipleInheritance,
97    PPTMK_FullGeneralityVirtualInheritance
98  };
99
100  using MSVtorDispMode = clang::MSVtorDispMode;
101
102  enum DefaultCallingConvention {
103    DCC_None,
104    DCC_CDecl,
105    DCC_FastCall,
106    DCC_StdCall,
107    DCC_VectorCall,
108    DCC_RegCall
109  };
110
111  enum AddrSpaceMapMangling { ASMM_Target, ASMM_On, ASMM_Off };
112
113  // Corresponds to _MSC_VER
114  enum MSVCMajorVersion {
115    MSVC2010 = 1600,
116    MSVC2012 = 1700,
117    MSVC2013 = 1800,
118    MSVC2015 = 1900,
119    MSVC2017 = 1910,
120    MSVC2017_5 = 1912,
121    MSVC2017_7 = 1914,
122  };
123
124  /// Clang versions with different platform ABI conformance.
125  enum class ClangABI {
126    /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
127    /// (SVN r257626). This causes <1 x long long> to be passed in an
128    /// integer register instead of an SSE register on x64_64.
129    Ver3_8,
130
131    /// Attempt to be ABI-compatible with code generated by Clang 4.0.x
132    /// (SVN r291814). This causes move operations to be ignored when
133    /// determining whether a class type can be passed or returned directly.
134    Ver4,
135
136    /// Attempt to be ABI-compatible with code generated by Clang 6.0.x
137    /// (SVN r321711). This causes determination of whether a type is
138    /// standard-layout to ignore collisions between empty base classes
139    /// and between base classes and member subobjects, which affects
140    /// whether we reuse base class tail padding in some ABIs.
141    Ver6,
142
143    /// Attempt to be ABI-compatible with code generated by Clang 7.0.x
144    /// (SVN r338536). This causes alignof (C++) and _Alignof (C11) to be
145    /// compatible with __alignof (i.e., return the preferred alignment)
146    /// rather than returning the required alignment.
147    Ver7,
148
149    /// Attempt to be ABI-compatible with code generated by Clang 9.0.x
150    /// (SVN r351319). This causes vectors of __int128 to be passed in memory
151    /// instead of passing in multiple scalar registers on x86_64 on Linux and
152    /// NetBSD.
153    Ver9,
154
155    /// Conform to the underlying platform's C and C++ ABIs as closely
156    /// as we can.
157    Latest
158  };
159
160  enum class CoreFoundationABI {
161    /// No interoperability ABI has been specified
162    Unspecified,
163    /// CoreFoundation does not have any language interoperability
164    Standalone,
165    /// Interoperability with the ObjectiveC runtime
166    ObjectiveC,
167    /// Interoperability with the latest known version of the Swift runtime
168    Swift,
169    /// Interoperability with the Swift 5.0 runtime
170    Swift5_0,
171    /// Interoperability with the Swift 4.2 runtime
172    Swift4_2,
173    /// Interoperability with the Swift 4.1 runtime
174    Swift4_1,
175  };
176
177  enum FPModeKind {
178    // Disable the floating point pragma
179    FPM_Off,
180
181    // Enable the floating point pragma
182    FPM_On,
183
184    // Aggressively fuse FP ops (E.g. FMA).
185    FPM_Fast
186  };
187
188  /// Alias for RoundingMode::NearestTiesToEven.
189  static constexpr unsigned FPR_ToNearest =
190      static_cast<unsigned>(llvm::RoundingMode::NearestTiesToEven);
191
192  /// Possible floating point exception behavior.
193  enum FPExceptionModeKind {
194    /// Assume that floating-point exceptions are masked.
195    FPE_Ignore,
196    /// Transformations do not cause new exceptions but may hide some.
197    FPE_MayTrap,
198    /// Strictly preserve the floating-point exception semantics.
199    FPE_Strict
200  };
201
202  enum class LaxVectorConversionKind {
203    /// Permit no implicit vector bitcasts.
204    None,
205    /// Permit vector bitcasts between integer vectors with different numbers
206    /// of elements but the same total bit-width.
207    Integer,
208    /// Permit vector bitcasts between all vectors with the same total
209    /// bit-width.
210    All,
211  };
212
213  enum class SignReturnAddressScopeKind {
214    /// No signing for any function.
215    None,
216    /// Sign the return address of functions that spill LR.
217    NonLeaf,
218    /// Sign the return address of all functions,
219    All
220  };
221
222  enum class SignReturnAddressKeyKind {
223    /// Return address signing uses APIA key.
224    AKey,
225    /// Return address signing uses APIB key.
226    BKey
227  };
228
229public:
230  /// Set of enabled sanitizers.
231  SanitizerSet Sanitize;
232
233  /// Paths to blacklist files specifying which objects
234  /// (files, functions, variables) should not be instrumented.
235  std::vector<std::string> SanitizerBlacklistFiles;
236
237  /// Paths to the XRay "always instrument" files specifying which
238  /// objects (files, functions, variables) should be imbued with the XRay
239  /// "always instrument" attribute.
240  /// WARNING: This is a deprecated field and will go away in the future.
241  std::vector<std::string> XRayAlwaysInstrumentFiles;
242
243  /// Paths to the XRay "never instrument" files specifying which
244  /// objects (files, functions, variables) should be imbued with the XRay
245  /// "never instrument" attribute.
246  /// WARNING: This is a deprecated field and will go away in the future.
247  std::vector<std::string> XRayNeverInstrumentFiles;
248
249  /// Paths to the XRay attribute list files, specifying which objects
250  /// (files, functions, variables) should be imbued with the appropriate XRay
251  /// attribute(s).
252  std::vector<std::string> XRayAttrListFiles;
253
254  clang::ObjCRuntime ObjCRuntime;
255
256  CoreFoundationABI CFRuntime = CoreFoundationABI::Unspecified;
257
258  std::string ObjCConstantStringClass;
259
260  /// The name of the handler function to be called when -ftrapv is
261  /// specified.
262  ///
263  /// If none is specified, abort (GCC-compatible behaviour).
264  std::string OverflowHandler;
265
266  /// The module currently being compiled as specified by -fmodule-name.
267  std::string ModuleName;
268
269  /// The name of the current module, of which the main source file
270  /// is a part. If CompilingModule is set, we are compiling the interface
271  /// of this module, otherwise we are compiling an implementation file of
272  /// it. This starts as ModuleName in case -fmodule-name is provided and
273  /// changes during compilation to reflect the current module.
274  std::string CurrentModule;
275
276  /// The names of any features to enable in module 'requires' decls
277  /// in addition to the hard-coded list in Module.cpp and the target features.
278  ///
279  /// This list is sorted.
280  std::vector<std::string> ModuleFeatures;
281
282  /// Options for parsing comments.
283  CommentOptions CommentOpts;
284
285  /// A list of all -fno-builtin-* function names (e.g., memset).
286  std::vector<std::string> NoBuiltinFuncs;
287
288  /// Triples of the OpenMP targets that the host code codegen should
289  /// take into account in order to generate accurate offloading descriptors.
290  std::vector<llvm::Triple> OMPTargetTriples;
291
292  /// Name of the IR file that contains the result of the OpenMP target
293  /// host code generation.
294  std::string OMPHostIRFile;
295
296  /// Indicates whether the front-end is explicitly told that the
297  /// input is a header file (i.e. -x c-header).
298  bool IsHeaderFile = false;
299
300  LangOptions();
301
302  // Define accessors/mutators for language options of enumeration type.
303#define LANGOPT(Name, Bits, Default, Description)
304#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
305  Type get##Name() const { return static_cast<Type>(Name); } \
306  void set##Name(Type Value) { Name = static_cast<unsigned>(Value); }
307#include "clang/Basic/LangOptions.def"
308
309  /// Are we compiling a module interface (.cppm or module map)?
310  bool isCompilingModule() const {
311    return getCompilingModule() != CMK_None;
312  }
313
314  /// Do we need to track the owning module for a local declaration?
315  bool trackLocalOwningModule() const {
316    return isCompilingModule() || ModulesLocalVisibility;
317  }
318
319  bool isSignedOverflowDefined() const {
320    return getSignedOverflowBehavior() == SOB_Defined;
321  }
322
323  bool isSubscriptPointerArithmetic() const {
324    return ObjCRuntime.isSubscriptPointerArithmetic() &&
325           !ObjCSubscriptingLegacyRuntime;
326  }
327
328  bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const {
329    return MSCompatibilityVersion >= MajorVersion * 100000U;
330  }
331
332  /// Reset all of the options that are not considered when building a
333  /// module.
334  void resetNonModularOptions();
335
336  /// Is this a libc/libm function that is no longer recognized as a
337  /// builtin because a -fno-builtin-* option has been specified?
338  bool isNoBuiltinFunc(StringRef Name) const;
339
340  /// True if any ObjC types may have non-trivial lifetime qualifiers.
341  bool allowsNonTrivialObjCLifetimeQualifiers() const {
342    return ObjCAutoRefCount || ObjCWeak;
343  }
344
345  bool assumeFunctionsAreConvergent() const {
346    return ConvergentFunctions;
347  }
348
349  /// Return the OpenCL C or C++ version as a VersionTuple.
350  VersionTuple getOpenCLVersionTuple() const;
351
352  /// Check if return address signing is enabled.
353  bool hasSignReturnAddress() const {
354    return getSignReturnAddressScope() != SignReturnAddressScopeKind::None;
355  }
356
357  /// Check if return address signing uses AKey.
358  bool isSignReturnAddressWithAKey() const {
359    return getSignReturnAddressKey() == SignReturnAddressKeyKind::AKey;
360  }
361
362  /// Check if leaf functions are also signed.
363  bool isSignReturnAddressScopeAll() const {
364    return getSignReturnAddressScope() == SignReturnAddressScopeKind::All;
365  }
366};
367
368/// Floating point control options
369class FPOptionsOverride;
370class FPOptions {
371public:
372  // We start by defining the layout.
373  using storage_type = uint16_t;
374
375  using RoundingMode = llvm::RoundingMode;
376
377  // Define a fake option named "First" so that we have a PREVIOUS even for the
378  // real first option.
379  static constexpr storage_type FirstShift = 0, FirstWidth = 0;
380#define OPTION(NAME, TYPE, WIDTH, PREVIOUS)                                    \
381  static constexpr storage_type NAME##Shift =                                  \
382      PREVIOUS##Shift + PREVIOUS##Width;                                       \
383  static constexpr storage_type NAME##Width = WIDTH;                           \
384  static constexpr storage_type NAME##Mask = ((1 << NAME##Width) - 1)          \
385                                             << NAME##Shift;
386#include "clang/Basic/FPOptions.def"
387
388private:
389  storage_type Value;
390
391public:
392  FPOptions() : Value(0) {
393    setFPContractMode(LangOptions::FPM_Off);
394    setRoundingMode(static_cast<RoundingMode>(LangOptions::FPR_ToNearest));
395    setFPExceptionMode(LangOptions::FPE_Ignore);
396  }
397  // Used for serializing.
398  explicit FPOptions(unsigned I) { getFromOpaqueInt(I); }
399
400  explicit FPOptions(const LangOptions &LO) {
401    Value = 0;
402    setFPContractMode(LO.getDefaultFPContractMode());
403    setRoundingMode(LO.getFPRoundingMode());
404    setFPExceptionMode(LO.getFPExceptionMode());
405    setAllowFEnvAccess(LangOptions::FPM_Off),
406        setAllowFPReassociate(LO.AllowFPReassoc);
407    setNoHonorNaNs(LO.NoHonorNaNs);
408    setNoHonorInfs(LO.NoHonorInfs);
409    setNoSignedZero(LO.NoSignedZero);
410    setAllowReciprocal(LO.AllowRecip);
411    setAllowApproxFunc(LO.ApproxFunc);
412  }
413
414  bool allowFPContractWithinStatement() const {
415    return getFPContractMode() == LangOptions::FPM_On;
416  }
417  void setAllowFPContractWithinStatement() {
418    setFPContractMode(LangOptions::FPM_On);
419  }
420
421  bool allowFPContractAcrossStatement() const {
422    return getFPContractMode() == LangOptions::FPM_Fast;
423  }
424  void setAllowFPContractAcrossStatement() {
425    setFPContractMode(LangOptions::FPM_Fast);
426  }
427
428  bool isFPConstrained() const {
429    return getRoundingMode() !=
430               static_cast<unsigned>(RoundingMode::NearestTiesToEven) ||
431           getFPExceptionMode() != LangOptions::FPE_Ignore ||
432           getAllowFEnvAccess();
433  }
434
435  bool operator==(FPOptions other) const { return Value == other.Value; }
436
437  /// Return the default value of FPOptions that's used when trailing
438  /// storage isn't required.
439  static FPOptions defaultWithoutTrailingStorage(const LangOptions &LO);
440
441  storage_type getAsOpaqueInt() const { return Value; }
442  void getFromOpaqueInt(storage_type value) { Value = value; }
443
444  // We can define most of the accessors automatically:
445#define OPTION(NAME, TYPE, WIDTH, PREVIOUS)                                    \
446  unsigned get##NAME() const {                                                 \
447    return static_cast<unsigned>(TYPE((Value & NAME##Mask) >> NAME##Shift));   \
448  }                                                                            \
449  void set##NAME(TYPE value) {                                                 \
450    Value = (Value & ~NAME##Mask) | (storage_type(value) << NAME##Shift);      \
451  }
452#include "clang/Basic/FPOptions.def"
453  LLVM_DUMP_METHOD void dump();
454};
455
456/// The FPOptions override type is value of the new FPOptions
457///  plus a mask showing which fields are actually set in it:
458class FPOptionsOverride {
459  FPOptions Options;
460  FPOptions::storage_type OverrideMask = 0;
461
462public:
463  using RoundingMode = llvm::RoundingMode;
464  FPOptionsOverride() {}
465
466  // Used for serializing.
467  explicit FPOptionsOverride(unsigned I) { getFromOpaqueInt(I); }
468
469  bool requiresTrailingStorage() const { return OverrideMask != 0; }
470
471  void setAllowFPContractWithinStatement() {
472    setFPContractModeOverride(LangOptions::FPM_On);
473  }
474
475  void setAllowFPContractAcrossStatement() {
476    setFPContractModeOverride(LangOptions::FPM_Fast);
477  }
478
479  void setDisallowFPContract() {
480    setFPContractModeOverride(LangOptions::FPM_Off);
481  }
482
483  void setFPPreciseEnabled(bool Value) {
484    setAllowFPReassociateOverride(!Value);
485    setNoHonorNaNsOverride(!Value);
486    setNoHonorInfsOverride(!Value);
487    setNoSignedZeroOverride(!Value);
488    setAllowReciprocalOverride(!Value);
489    setAllowApproxFuncOverride(!Value);
490    if (Value)
491      /* Precise mode implies fp_contract=on and disables ffast-math */
492      setAllowFPContractWithinStatement();
493    else
494      /* Precise mode disabled sets fp_contract=fast and enables ffast-math */
495      setAllowFPContractAcrossStatement();
496  }
497
498  unsigned getAsOpaqueInt() const {
499    return Options.getAsOpaqueInt() << 16 | OverrideMask;
500  }
501  void getFromOpaqueInt(unsigned I) {
502    OverrideMask = I & 0xffff;
503    Options.getFromOpaqueInt(I >> 16);
504  }
505
506  FPOptions applyOverrides(const LangOptions &LO) {
507    FPOptions Base(LO);
508    FPOptions result((Base.getAsOpaqueInt() & ~OverrideMask) |
509                     (Options.getAsOpaqueInt() & OverrideMask));
510    return result;
511  }
512
513  bool operator==(FPOptionsOverride other) const {
514    return Options == other.Options && OverrideMask == other.OverrideMask;
515  }
516  bool operator!=(FPOptionsOverride other) const { return !(*this == other); }
517
518#define OPTION(NAME, TYPE, WIDTH, PREVIOUS)                                    \
519  bool has##NAME##Override() const {                                           \
520    return OverrideMask & FPOptions::NAME##Mask;                               \
521  }                                                                            \
522  unsigned get##NAME##Override() const {                                       \
523    assert(has##NAME##Override());                                             \
524    return Options.get##NAME();                                                \
525  }                                                                            \
526  void clear##NAME##Override() {                                               \
527    /* Clear the actual value so that we don't have spurious differences when  \
528     * testing equality. */                                                    \
529    Options.set##NAME(TYPE(0));                                                \
530    OverrideMask &= ~FPOptions::NAME##Mask;                                    \
531  }                                                                            \
532  void set##NAME##Override(TYPE value) {                                       \
533    Options.set##NAME(value);                                                  \
534    OverrideMask |= FPOptions::NAME##Mask;                                     \
535  }
536#include "clang/Basic/FPOptions.def"
537  LLVM_DUMP_METHOD void dump();
538};
539
540/// Describes the kind of translation unit being processed.
541enum TranslationUnitKind {
542  /// The translation unit is a complete translation unit.
543  TU_Complete,
544
545  /// The translation unit is a prefix to a translation unit, and is
546  /// not complete.
547  TU_Prefix,
548
549  /// The translation unit is a module.
550  TU_Module
551};
552
553} // namespace clang
554
555#endif // LLVM_CLANG_BASIC_LANGOPTIONS_H
556