[clang] Handle __declspec() attributes in using
[llvm-project.git] / clang / lib / Frontend / InitPreprocessor.cpp
blob208c6a8db1598e1ccbd5436d1d90e75c68b2850d
1 //===--- InitPreprocessor.cpp - PP initialization code. ---------*- 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 // This file implements the clang::InitializePreprocessor function.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Basic/FileManager.h"
14 #include "clang/Basic/HLSLRuntime.h"
15 #include "clang/Basic/MacroBuilder.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/SyncScope.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Basic/Version.h"
20 #include "clang/Frontend/FrontendDiagnostic.h"
21 #include "clang/Frontend/FrontendOptions.h"
22 #include "clang/Frontend/Utils.h"
23 #include "clang/Lex/HeaderSearch.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Lex/PreprocessorOptions.h"
26 #include "clang/Serialization/ASTReader.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 using namespace clang;
32 static bool MacroBodyEndsInBackslash(StringRef MacroBody) {
33 while (!MacroBody.empty() && isWhitespace(MacroBody.back()))
34 MacroBody = MacroBody.drop_back();
35 return !MacroBody.empty() && MacroBody.back() == '\\';
38 // Append a #define line to Buf for Macro. Macro should be of the form XXX,
39 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
40 // "#define XXX Y z W". To get a #define with no value, use "XXX=".
41 static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro,
42 DiagnosticsEngine &Diags) {
43 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
44 StringRef MacroName = MacroPair.first;
45 StringRef MacroBody = MacroPair.second;
46 if (MacroName.size() != Macro.size()) {
47 // Per GCC -D semantics, the macro ends at \n if it exists.
48 StringRef::size_type End = MacroBody.find_first_of("\n\r");
49 if (End != StringRef::npos)
50 Diags.Report(diag::warn_fe_macro_contains_embedded_newline)
51 << MacroName;
52 MacroBody = MacroBody.substr(0, End);
53 // We handle macro bodies which end in a backslash by appending an extra
54 // backslash+newline. This makes sure we don't accidentally treat the
55 // backslash as a line continuation marker.
56 if (MacroBodyEndsInBackslash(MacroBody))
57 Builder.defineMacro(MacroName, Twine(MacroBody) + "\\\n");
58 else
59 Builder.defineMacro(MacroName, MacroBody);
60 } else {
61 // Push "macroname 1".
62 Builder.defineMacro(Macro);
66 /// AddImplicitInclude - Add an implicit \#include of the specified file to the
67 /// predefines buffer.
68 /// As these includes are generated by -include arguments the header search
69 /// logic is going to search relatively to the current working directory.
70 static void AddImplicitInclude(MacroBuilder &Builder, StringRef File) {
71 Builder.append(Twine("#include \"") + File + "\"");
74 static void AddImplicitIncludeMacros(MacroBuilder &Builder, StringRef File) {
75 Builder.append(Twine("#__include_macros \"") + File + "\"");
76 // Marker token to stop the __include_macros fetch loop.
77 Builder.append("##"); // ##?
80 /// Add an implicit \#include using the original file used to generate
81 /// a PCH file.
82 static void AddImplicitIncludePCH(MacroBuilder &Builder, Preprocessor &PP,
83 const PCHContainerReader &PCHContainerRdr,
84 StringRef ImplicitIncludePCH) {
85 std::string OriginalFile = ASTReader::getOriginalSourceFile(
86 std::string(ImplicitIncludePCH), PP.getFileManager(), PCHContainerRdr,
87 PP.getDiagnostics());
88 if (OriginalFile.empty())
89 return;
91 AddImplicitInclude(Builder, OriginalFile);
94 /// PickFP - This is used to pick a value based on the FP semantics of the
95 /// specified FP model.
96 template <typename T>
97 static T PickFP(const llvm::fltSemantics *Sem, T IEEEHalfVal, T IEEESingleVal,
98 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
99 T IEEEQuadVal) {
100 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEhalf())
101 return IEEEHalfVal;
102 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle())
103 return IEEESingleVal;
104 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble())
105 return IEEEDoubleVal;
106 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended())
107 return X87DoubleExtendedVal;
108 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble())
109 return PPCDoubleDoubleVal;
110 assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad());
111 return IEEEQuadVal;
114 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
115 const llvm::fltSemantics *Sem, StringRef Ext) {
116 const char *DenormMin, *Epsilon, *Max, *Min;
117 DenormMin = PickFP(Sem, "5.9604644775390625e-8", "1.40129846e-45",
118 "4.9406564584124654e-324", "3.64519953188247460253e-4951",
119 "4.94065645841246544176568792868221e-324",
120 "6.47517511943802511092443895822764655e-4966");
121 int Digits = PickFP(Sem, 3, 6, 15, 18, 31, 33);
122 int DecimalDigits = PickFP(Sem, 5, 9, 17, 21, 33, 36);
123 Epsilon = PickFP(Sem, "9.765625e-4", "1.19209290e-7",
124 "2.2204460492503131e-16", "1.08420217248550443401e-19",
125 "4.94065645841246544176568792868221e-324",
126 "1.92592994438723585305597794258492732e-34");
127 int MantissaDigits = PickFP(Sem, 11, 24, 53, 64, 106, 113);
128 int Min10Exp = PickFP(Sem, -4, -37, -307, -4931, -291, -4931);
129 int Max10Exp = PickFP(Sem, 4, 38, 308, 4932, 308, 4932);
130 int MinExp = PickFP(Sem, -13, -125, -1021, -16381, -968, -16381);
131 int MaxExp = PickFP(Sem, 16, 128, 1024, 16384, 1024, 16384);
132 Min = PickFP(Sem, "6.103515625e-5", "1.17549435e-38", "2.2250738585072014e-308",
133 "3.36210314311209350626e-4932",
134 "2.00416836000897277799610805135016e-292",
135 "3.36210314311209350626267781732175260e-4932");
136 Max = PickFP(Sem, "6.5504e+4", "3.40282347e+38", "1.7976931348623157e+308",
137 "1.18973149535723176502e+4932",
138 "1.79769313486231580793728971405301e+308",
139 "1.18973149535723176508575932662800702e+4932");
141 SmallString<32> DefPrefix;
142 DefPrefix = "__";
143 DefPrefix += Prefix;
144 DefPrefix += "_";
146 Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
147 Builder.defineMacro(DefPrefix + "HAS_DENORM__");
148 Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
149 Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits));
150 Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon)+Ext);
151 Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
152 Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
153 Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits));
155 Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp));
156 Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp));
157 Builder.defineMacro(DefPrefix + "MAX__", Twine(Max)+Ext);
159 Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")");
160 Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")");
161 Builder.defineMacro(DefPrefix + "MIN__", Twine(Min)+Ext);
165 /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
166 /// named MacroName with the max value for a type with width 'TypeWidth' a
167 /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
168 static void DefineTypeSize(const Twine &MacroName, unsigned TypeWidth,
169 StringRef ValSuffix, bool isSigned,
170 MacroBuilder &Builder) {
171 llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth)
172 : llvm::APInt::getMaxValue(TypeWidth);
173 Builder.defineMacro(MacroName, toString(MaxVal, 10, isSigned) + ValSuffix);
176 /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
177 /// the width, suffix, and signedness of the given type
178 static void DefineTypeSize(const Twine &MacroName, TargetInfo::IntType Ty,
179 const TargetInfo &TI, MacroBuilder &Builder) {
180 DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
181 TI.isTypeSigned(Ty), Builder);
184 static void DefineFmt(const Twine &Prefix, TargetInfo::IntType Ty,
185 const TargetInfo &TI, MacroBuilder &Builder) {
186 bool IsSigned = TI.isTypeSigned(Ty);
187 StringRef FmtModifier = TI.getTypeFormatModifier(Ty);
188 for (const char *Fmt = IsSigned ? "di" : "ouxX"; *Fmt; ++Fmt) {
189 Builder.defineMacro(Prefix + "_FMT" + Twine(*Fmt) + "__",
190 Twine("\"") + FmtModifier + Twine(*Fmt) + "\"");
194 static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
195 MacroBuilder &Builder) {
196 Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
199 static void DefineTypeWidth(const Twine &MacroName, TargetInfo::IntType Ty,
200 const TargetInfo &TI, MacroBuilder &Builder) {
201 Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty)));
204 static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth,
205 const TargetInfo &TI, MacroBuilder &Builder) {
206 Builder.defineMacro(MacroName,
207 Twine(BitWidth / TI.getCharWidth()));
210 // This will generate a macro based on the prefix with `_MAX__` as the suffix
211 // for the max value representable for the type, and a macro with a `_WIDTH__`
212 // suffix for the width of the type.
213 static void DefineTypeSizeAndWidth(const Twine &Prefix, TargetInfo::IntType Ty,
214 const TargetInfo &TI,
215 MacroBuilder &Builder) {
216 DefineTypeSize(Prefix + "_MAX__", Ty, TI, Builder);
217 DefineTypeWidth(Prefix + "_WIDTH__", Ty, TI, Builder);
220 static void DefineExactWidthIntType(TargetInfo::IntType Ty,
221 const TargetInfo &TI,
222 MacroBuilder &Builder) {
223 int TypeWidth = TI.getTypeWidth(Ty);
224 bool IsSigned = TI.isTypeSigned(Ty);
226 // Use the target specified int64 type, when appropriate, so that [u]int64_t
227 // ends up being defined in terms of the correct type.
228 if (TypeWidth == 64)
229 Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type();
231 // Use the target specified int16 type when appropriate. Some MCU targets
232 // (such as AVR) have definition of [u]int16_t to [un]signed int.
233 if (TypeWidth == 16)
234 Ty = IsSigned ? TI.getInt16Type() : TI.getUInt16Type();
236 const char *Prefix = IsSigned ? "__INT" : "__UINT";
238 DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
239 DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
241 StringRef ConstSuffix(TI.getTypeConstantSuffix(Ty));
242 Builder.defineMacro(Prefix + Twine(TypeWidth) + "_C_SUFFIX__", ConstSuffix);
245 static void DefineExactWidthIntTypeSize(TargetInfo::IntType Ty,
246 const TargetInfo &TI,
247 MacroBuilder &Builder) {
248 int TypeWidth = TI.getTypeWidth(Ty);
249 bool IsSigned = TI.isTypeSigned(Ty);
251 // Use the target specified int64 type, when appropriate, so that [u]int64_t
252 // ends up being defined in terms of the correct type.
253 if (TypeWidth == 64)
254 Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type();
256 // We don't need to define a _WIDTH macro for the exact-width types because
257 // we already know the width.
258 const char *Prefix = IsSigned ? "__INT" : "__UINT";
259 DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
262 static void DefineLeastWidthIntType(unsigned TypeWidth, bool IsSigned,
263 const TargetInfo &TI,
264 MacroBuilder &Builder) {
265 TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned);
266 if (Ty == TargetInfo::NoInt)
267 return;
269 const char *Prefix = IsSigned ? "__INT_LEAST" : "__UINT_LEAST";
270 DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
271 // We only want the *_WIDTH macro for the signed types to avoid too many
272 // predefined macros (the unsigned width and the signed width are identical.)
273 if (IsSigned)
274 DefineTypeSizeAndWidth(Prefix + Twine(TypeWidth), Ty, TI, Builder);
275 else
276 DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
277 DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
280 static void DefineFastIntType(unsigned TypeWidth, bool IsSigned,
281 const TargetInfo &TI, MacroBuilder &Builder) {
282 // stdint.h currently defines the fast int types as equivalent to the least
283 // types.
284 TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned);
285 if (Ty == TargetInfo::NoInt)
286 return;
288 const char *Prefix = IsSigned ? "__INT_FAST" : "__UINT_FAST";
289 DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
290 // We only want the *_WIDTH macro for the signed types to avoid too many
291 // predefined macros (the unsigned width and the signed width are identical.)
292 if (IsSigned)
293 DefineTypeSizeAndWidth(Prefix + Twine(TypeWidth), Ty, TI, Builder);
294 else
295 DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
296 DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
300 /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
301 /// the specified properties.
302 static const char *getLockFreeValue(unsigned TypeWidth, const TargetInfo &TI) {
303 // Fully-aligned, power-of-2 sizes no larger than the inline
304 // width will be inlined as lock-free operations.
305 // Note: we do not need to check alignment since _Atomic(T) is always
306 // appropriately-aligned in clang.
307 if (TI.hasBuiltinAtomic(TypeWidth, TypeWidth))
308 return "2"; // "always lock free"
309 // We cannot be certain what operations the lib calls might be
310 // able to implement as lock-free on future processors.
311 return "1"; // "sometimes lock free"
314 /// Add definitions required for a smooth interaction between
315 /// Objective-C++ automated reference counting and libstdc++ (4.2).
316 static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts,
317 MacroBuilder &Builder) {
318 Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR");
320 std::string Result;
322 // Provide specializations for the __is_scalar type trait so that
323 // lifetime-qualified objects are not considered "scalar" types, which
324 // libstdc++ uses as an indicator of the presence of trivial copy, assign,
325 // default-construct, and destruct semantics (none of which hold for
326 // lifetime-qualified objects in ARC).
327 llvm::raw_string_ostream Out(Result);
329 Out << "namespace std {\n"
330 << "\n"
331 << "struct __true_type;\n"
332 << "struct __false_type;\n"
333 << "\n";
335 Out << "template<typename _Tp> struct __is_scalar;\n"
336 << "\n";
338 if (LangOpts.ObjCAutoRefCount) {
339 Out << "template<typename _Tp>\n"
340 << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n"
341 << " enum { __value = 0 };\n"
342 << " typedef __false_type __type;\n"
343 << "};\n"
344 << "\n";
347 if (LangOpts.ObjCWeak) {
348 Out << "template<typename _Tp>\n"
349 << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n"
350 << " enum { __value = 0 };\n"
351 << " typedef __false_type __type;\n"
352 << "};\n"
353 << "\n";
356 if (LangOpts.ObjCAutoRefCount) {
357 Out << "template<typename _Tp>\n"
358 << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))"
359 << " _Tp> {\n"
360 << " enum { __value = 0 };\n"
361 << " typedef __false_type __type;\n"
362 << "};\n"
363 << "\n";
366 Out << "}\n";
368 Builder.append(Result);
371 static void InitializeStandardPredefinedMacros(const TargetInfo &TI,
372 const LangOptions &LangOpts,
373 const FrontendOptions &FEOpts,
374 MacroBuilder &Builder) {
375 if (LangOpts.HLSL) {
376 Builder.defineMacro("__hlsl_clang");
377 // HLSL Version
378 Builder.defineMacro("__HLSL_VERSION",
379 Twine((unsigned)LangOpts.getHLSLVersion()));
381 if (LangOpts.NativeHalfType)
382 Builder.defineMacro("__HLSL_ENABLE_16_BIT",
383 Twine((unsigned)LangOpts.getHLSLVersion()));
385 // Shader target information
386 // "enums" for shader stages
387 Builder.defineMacro("__SHADER_STAGE_VERTEX",
388 Twine((uint32_t)ShaderStage::Vertex));
389 Builder.defineMacro("__SHADER_STAGE_PIXEL",
390 Twine((uint32_t)ShaderStage::Pixel));
391 Builder.defineMacro("__SHADER_STAGE_GEOMETRY",
392 Twine((uint32_t)ShaderStage::Geometry));
393 Builder.defineMacro("__SHADER_STAGE_HULL",
394 Twine((uint32_t)ShaderStage::Hull));
395 Builder.defineMacro("__SHADER_STAGE_DOMAIN",
396 Twine((uint32_t)ShaderStage::Domain));
397 Builder.defineMacro("__SHADER_STAGE_COMPUTE",
398 Twine((uint32_t)ShaderStage::Compute));
399 Builder.defineMacro("__SHADER_STAGE_AMPLIFICATION",
400 Twine((uint32_t)ShaderStage::Amplification));
401 Builder.defineMacro("__SHADER_STAGE_MESH",
402 Twine((uint32_t)ShaderStage::Mesh));
403 Builder.defineMacro("__SHADER_STAGE_LIBRARY",
404 Twine((uint32_t)ShaderStage::Library));
405 // The current shader stage itself
406 uint32_t StageInteger = static_cast<uint32_t>(
407 hlsl::getStageFromEnvironment(TI.getTriple().getEnvironment()));
409 Builder.defineMacro("__SHADER_TARGET_STAGE", Twine(StageInteger));
410 // Add target versions
411 if (TI.getTriple().getOS() == llvm::Triple::ShaderModel) {
412 VersionTuple Version = TI.getTriple().getOSVersion();
413 Builder.defineMacro("__SHADER_TARGET_MAJOR", Twine(Version.getMajor()));
414 unsigned Minor = Version.getMinor().value_or(0);
415 Builder.defineMacro("__SHADER_TARGET_MINOR", Twine(Minor));
417 return;
419 // C++ [cpp.predefined]p1:
420 // The following macro names shall be defined by the implementation:
422 // -- __STDC__
423 // [C++] Whether __STDC__ is predefined and if so, what its value is,
424 // are implementation-defined.
425 // (Removed in C++20.)
426 if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
427 Builder.defineMacro("__STDC__");
428 // -- __STDC_HOSTED__
429 // The integer literal 1 if the implementation is a hosted
430 // implementation or the integer literal 0 if it is not.
431 if (LangOpts.Freestanding)
432 Builder.defineMacro("__STDC_HOSTED__", "0");
433 else
434 Builder.defineMacro("__STDC_HOSTED__");
436 // -- __STDC_VERSION__
437 // [C++] Whether __STDC_VERSION__ is predefined and if so, what its
438 // value is, are implementation-defined.
439 // (Removed in C++20.)
440 if (!LangOpts.CPlusPlus) {
441 // FIXME: Use correct value for C23.
442 if (LangOpts.C2x)
443 Builder.defineMacro("__STDC_VERSION__", "202000L");
444 else if (LangOpts.C17)
445 Builder.defineMacro("__STDC_VERSION__", "201710L");
446 else if (LangOpts.C11)
447 Builder.defineMacro("__STDC_VERSION__", "201112L");
448 else if (LangOpts.C99)
449 Builder.defineMacro("__STDC_VERSION__", "199901L");
450 else if (!LangOpts.GNUMode && LangOpts.Digraphs)
451 Builder.defineMacro("__STDC_VERSION__", "199409L");
452 } else {
453 // -- __cplusplus
454 // FIXME: Use correct value for C++23.
455 if (LangOpts.CPlusPlus2b)
456 Builder.defineMacro("__cplusplus", "202101L");
457 // [C++20] The integer literal 202002L.
458 else if (LangOpts.CPlusPlus20)
459 Builder.defineMacro("__cplusplus", "202002L");
460 // [C++17] The integer literal 201703L.
461 else if (LangOpts.CPlusPlus17)
462 Builder.defineMacro("__cplusplus", "201703L");
463 // [C++14] The name __cplusplus is defined to the value 201402L when
464 // compiling a C++ translation unit.
465 else if (LangOpts.CPlusPlus14)
466 Builder.defineMacro("__cplusplus", "201402L");
467 // [C++11] The name __cplusplus is defined to the value 201103L when
468 // compiling a C++ translation unit.
469 else if (LangOpts.CPlusPlus11)
470 Builder.defineMacro("__cplusplus", "201103L");
471 // [C++03] The name __cplusplus is defined to the value 199711L when
472 // compiling a C++ translation unit.
473 else
474 Builder.defineMacro("__cplusplus", "199711L");
476 // -- __STDCPP_DEFAULT_NEW_ALIGNMENT__
477 // [C++17] An integer literal of type std::size_t whose value is the
478 // alignment guaranteed by a call to operator new(std::size_t)
480 // We provide this in all language modes, since it seems generally useful.
481 Builder.defineMacro("__STDCPP_DEFAULT_NEW_ALIGNMENT__",
482 Twine(TI.getNewAlign() / TI.getCharWidth()) +
483 TI.getTypeConstantSuffix(TI.getSizeType()));
485 // -- __STDCPP_­THREADS__
486 // Defined, and has the value integer literal 1, if and only if a
487 // program can have more than one thread of execution.
488 if (LangOpts.getThreadModel() == LangOptions::ThreadModelKind::POSIX)
489 Builder.defineMacro("__STDCPP_THREADS__", "1");
492 // In C11 these are environment macros. In C++11 they are only defined
493 // as part of <cuchar>. To prevent breakage when mixing C and C++
494 // code, define these macros unconditionally. We can define them
495 // unconditionally, as Clang always uses UTF-16 and UTF-32 for 16-bit
496 // and 32-bit character literals.
497 Builder.defineMacro("__STDC_UTF_16__", "1");
498 Builder.defineMacro("__STDC_UTF_32__", "1");
500 if (LangOpts.ObjC)
501 Builder.defineMacro("__OBJC__");
503 // OpenCL v1.0/1.1 s6.9, v1.2/2.0 s6.10: Preprocessor Directives and Macros.
504 if (LangOpts.OpenCL) {
505 if (LangOpts.CPlusPlus) {
506 switch (LangOpts.OpenCLCPlusPlusVersion) {
507 case 100:
508 Builder.defineMacro("__OPENCL_CPP_VERSION__", "100");
509 break;
510 case 202100:
511 Builder.defineMacro("__OPENCL_CPP_VERSION__", "202100");
512 break;
513 default:
514 llvm_unreachable("Unsupported C++ version for OpenCL");
516 Builder.defineMacro("__CL_CPP_VERSION_1_0__", "100");
517 Builder.defineMacro("__CL_CPP_VERSION_2021__", "202100");
518 } else {
519 // OpenCL v1.0 and v1.1 do not have a predefined macro to indicate the
520 // language standard with which the program is compiled. __OPENCL_VERSION__
521 // is for the OpenCL version supported by the OpenCL device, which is not
522 // necessarily the language standard with which the program is compiled.
523 // A shared OpenCL header file requires a macro to indicate the language
524 // standard. As a workaround, __OPENCL_C_VERSION__ is defined for
525 // OpenCL v1.0 and v1.1.
526 switch (LangOpts.OpenCLVersion) {
527 case 100:
528 Builder.defineMacro("__OPENCL_C_VERSION__", "100");
529 break;
530 case 110:
531 Builder.defineMacro("__OPENCL_C_VERSION__", "110");
532 break;
533 case 120:
534 Builder.defineMacro("__OPENCL_C_VERSION__", "120");
535 break;
536 case 200:
537 Builder.defineMacro("__OPENCL_C_VERSION__", "200");
538 break;
539 case 300:
540 Builder.defineMacro("__OPENCL_C_VERSION__", "300");
541 break;
542 default:
543 llvm_unreachable("Unsupported OpenCL version");
546 Builder.defineMacro("CL_VERSION_1_0", "100");
547 Builder.defineMacro("CL_VERSION_1_1", "110");
548 Builder.defineMacro("CL_VERSION_1_2", "120");
549 Builder.defineMacro("CL_VERSION_2_0", "200");
550 Builder.defineMacro("CL_VERSION_3_0", "300");
552 if (TI.isLittleEndian())
553 Builder.defineMacro("__ENDIAN_LITTLE__");
555 if (LangOpts.FastRelaxedMath)
556 Builder.defineMacro("__FAST_RELAXED_MATH__");
559 if (LangOpts.SYCLIsDevice || LangOpts.SYCLIsHost) {
560 // SYCL Version is set to a value when building SYCL applications
561 if (LangOpts.getSYCLVersion() == LangOptions::SYCL_2017)
562 Builder.defineMacro("CL_SYCL_LANGUAGE_VERSION", "121");
563 else if (LangOpts.getSYCLVersion() == LangOptions::SYCL_2020)
564 Builder.defineMacro("SYCL_LANGUAGE_VERSION", "202001");
567 // Not "standard" per se, but available even with the -undef flag.
568 if (LangOpts.AsmPreprocessor)
569 Builder.defineMacro("__ASSEMBLER__");
570 if (LangOpts.CUDA) {
571 if (LangOpts.GPURelocatableDeviceCode)
572 Builder.defineMacro("__CLANG_RDC__");
573 if (!LangOpts.HIP)
574 Builder.defineMacro("__CUDA__");
576 if (LangOpts.HIP) {
577 Builder.defineMacro("__HIP__");
578 Builder.defineMacro("__HIPCC__");
579 Builder.defineMacro("__HIP_MEMORY_SCOPE_SINGLETHREAD", "1");
580 Builder.defineMacro("__HIP_MEMORY_SCOPE_WAVEFRONT", "2");
581 Builder.defineMacro("__HIP_MEMORY_SCOPE_WORKGROUP", "3");
582 Builder.defineMacro("__HIP_MEMORY_SCOPE_AGENT", "4");
583 Builder.defineMacro("__HIP_MEMORY_SCOPE_SYSTEM", "5");
584 if (LangOpts.CUDAIsDevice)
585 Builder.defineMacro("__HIP_DEVICE_COMPILE__");
586 if (LangOpts.GPUDefaultStream ==
587 LangOptions::GPUDefaultStreamKind::PerThread)
588 Builder.defineMacro("HIP_API_PER_THREAD_DEFAULT_STREAM");
592 /// Initialize the predefined C++ language feature test macros defined in
593 /// ISO/IEC JTC1/SC22/WG21 (C++) SD-6: "SG10 Feature Test Recommendations".
594 static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts,
595 MacroBuilder &Builder) {
596 // C++98 features.
597 if (LangOpts.RTTI)
598 Builder.defineMacro("__cpp_rtti", "199711L");
599 if (LangOpts.CXXExceptions)
600 Builder.defineMacro("__cpp_exceptions", "199711L");
602 // C++11 features.
603 if (LangOpts.CPlusPlus11) {
604 Builder.defineMacro("__cpp_unicode_characters", "200704L");
605 Builder.defineMacro("__cpp_raw_strings", "200710L");
606 Builder.defineMacro("__cpp_unicode_literals", "200710L");
607 Builder.defineMacro("__cpp_user_defined_literals", "200809L");
608 Builder.defineMacro("__cpp_lambdas", "200907L");
609 Builder.defineMacro("__cpp_constexpr", LangOpts.CPlusPlus2b ? "202211L"
610 : LangOpts.CPlusPlus20 ? "201907L"
611 : LangOpts.CPlusPlus17 ? "201603L"
612 : LangOpts.CPlusPlus14 ? "201304L"
613 : "200704");
614 Builder.defineMacro("__cpp_constexpr_in_decltype", "201711L");
615 Builder.defineMacro("__cpp_range_based_for",
616 LangOpts.CPlusPlus17 ? "201603L" : "200907");
617 Builder.defineMacro("__cpp_static_assert",
618 LangOpts.CPlusPlus17 ? "201411L" : "200410");
619 Builder.defineMacro("__cpp_decltype", "200707L");
620 Builder.defineMacro("__cpp_attributes", "200809L");
621 Builder.defineMacro("__cpp_rvalue_references", "200610L");
622 Builder.defineMacro("__cpp_variadic_templates", "200704L");
623 Builder.defineMacro("__cpp_initializer_lists", "200806L");
624 Builder.defineMacro("__cpp_delegating_constructors", "200604L");
625 Builder.defineMacro("__cpp_nsdmi", "200809L");
626 Builder.defineMacro("__cpp_inheriting_constructors", "201511L");
627 Builder.defineMacro("__cpp_ref_qualifiers", "200710L");
628 Builder.defineMacro("__cpp_alias_templates", "200704L");
630 if (LangOpts.ThreadsafeStatics)
631 Builder.defineMacro("__cpp_threadsafe_static_init", "200806L");
633 // C++14 features.
634 if (LangOpts.CPlusPlus14) {
635 Builder.defineMacro("__cpp_binary_literals", "201304L");
636 Builder.defineMacro("__cpp_digit_separators", "201309L");
637 Builder.defineMacro("__cpp_init_captures",
638 LangOpts.CPlusPlus20 ? "201803L" : "201304L");
639 Builder.defineMacro("__cpp_generic_lambdas",
640 LangOpts.CPlusPlus20 ? "201707L" : "201304L");
641 Builder.defineMacro("__cpp_decltype_auto", "201304L");
642 Builder.defineMacro("__cpp_return_type_deduction", "201304L");
643 Builder.defineMacro("__cpp_aggregate_nsdmi", "201304L");
644 Builder.defineMacro("__cpp_variable_templates", "201304L");
646 if (LangOpts.SizedDeallocation)
647 Builder.defineMacro("__cpp_sized_deallocation", "201309L");
649 // C++17 features.
650 if (LangOpts.CPlusPlus17) {
651 Builder.defineMacro("__cpp_hex_float", "201603L");
652 Builder.defineMacro("__cpp_inline_variables", "201606L");
653 Builder.defineMacro("__cpp_noexcept_function_type", "201510L");
654 Builder.defineMacro("__cpp_capture_star_this", "201603L");
655 Builder.defineMacro("__cpp_if_constexpr", "201606L");
656 Builder.defineMacro("__cpp_deduction_guides", "201703L"); // (not latest)
657 Builder.defineMacro("__cpp_template_auto", "201606L"); // (old name)
658 Builder.defineMacro("__cpp_namespace_attributes", "201411L");
659 Builder.defineMacro("__cpp_enumerator_attributes", "201411L");
660 Builder.defineMacro("__cpp_nested_namespace_definitions", "201411L");
661 Builder.defineMacro("__cpp_variadic_using", "201611L");
662 Builder.defineMacro("__cpp_aggregate_bases", "201603L");
663 Builder.defineMacro("__cpp_structured_bindings", "201606L");
664 Builder.defineMacro("__cpp_nontype_template_args",
665 "201411L"); // (not latest)
666 Builder.defineMacro("__cpp_fold_expressions", "201603L");
667 Builder.defineMacro("__cpp_guaranteed_copy_elision", "201606L");
668 Builder.defineMacro("__cpp_nontype_template_parameter_auto", "201606L");
670 if (LangOpts.AlignedAllocation && !LangOpts.AlignedAllocationUnavailable)
671 Builder.defineMacro("__cpp_aligned_new", "201606L");
672 if (LangOpts.RelaxedTemplateTemplateArgs)
673 Builder.defineMacro("__cpp_template_template_args", "201611L");
675 // C++20 features.
676 if (LangOpts.CPlusPlus20) {
677 Builder.defineMacro("__cpp_aggregate_paren_init", "201902L");
679 // P0848 is implemented, but we're still waiting for other concepts
680 // issues to be addressed before bumping __cpp_concepts up to 202002L.
681 // Refer to the discussion of this at https://reviews.llvm.org/D128619.
682 Builder.defineMacro("__cpp_concepts", "201907L");
683 Builder.defineMacro("__cpp_conditional_explicit", "201806L");
684 //Builder.defineMacro("__cpp_consteval", "201811L");
685 Builder.defineMacro("__cpp_constexpr_dynamic_alloc", "201907L");
686 Builder.defineMacro("__cpp_constinit", "201907L");
687 Builder.defineMacro("__cpp_impl_coroutine", "201902L");
688 Builder.defineMacro("__cpp_designated_initializers", "201707L");
689 Builder.defineMacro("__cpp_impl_three_way_comparison", "201907L");
690 //Builder.defineMacro("__cpp_modules", "201907L");
691 Builder.defineMacro("__cpp_using_enum", "201907L");
693 // C++2b features.
694 if (LangOpts.CPlusPlus2b) {
695 Builder.defineMacro("__cpp_implicit_move", "202011L");
696 Builder.defineMacro("__cpp_size_t_suffix", "202011L");
697 Builder.defineMacro("__cpp_if_consteval", "202106L");
698 Builder.defineMacro("__cpp_multidimensional_subscript", "202211L");
701 // We provide those C++2b features as extensions in earlier language modes, so
702 // we also define their feature test macros.
703 if (LangOpts.CPlusPlus11)
704 Builder.defineMacro("__cpp_static_call_operator", "202207L");
705 Builder.defineMacro("__cpp_named_character_escapes", "202207L");
707 if (LangOpts.Char8)
708 Builder.defineMacro("__cpp_char8_t", "202207L");
709 Builder.defineMacro("__cpp_impl_destroying_delete", "201806L");
711 // TS features.
712 if (LangOpts.Coroutines)
713 Builder.defineMacro("__cpp_coroutines", "201703L");
716 /// InitializeOpenCLFeatureTestMacros - Define OpenCL macros based on target
717 /// settings and language version
718 void InitializeOpenCLFeatureTestMacros(const TargetInfo &TI,
719 const LangOptions &Opts,
720 MacroBuilder &Builder) {
721 const llvm::StringMap<bool> &OpenCLFeaturesMap = TI.getSupportedOpenCLOpts();
722 // FIXME: OpenCL options which affect language semantics/syntax
723 // should be moved into LangOptions.
724 auto defineOpenCLExtMacro = [&](llvm::StringRef Name, auto... OptArgs) {
725 // Check if extension is supported by target and is available in this
726 // OpenCL version
727 if (TI.hasFeatureEnabled(OpenCLFeaturesMap, Name) &&
728 OpenCLOptions::isOpenCLOptionAvailableIn(Opts, OptArgs...))
729 Builder.defineMacro(Name);
731 #define OPENCL_GENERIC_EXTENSION(Ext, ...) \
732 defineOpenCLExtMacro(#Ext, __VA_ARGS__);
733 #include "clang/Basic/OpenCLExtensions.def"
735 // Assume compiling for FULL profile
736 Builder.defineMacro("__opencl_c_int64");
739 static void InitializePredefinedMacros(const TargetInfo &TI,
740 const LangOptions &LangOpts,
741 const FrontendOptions &FEOpts,
742 const PreprocessorOptions &PPOpts,
743 MacroBuilder &Builder) {
744 // Compiler version introspection macros.
745 Builder.defineMacro("__llvm__"); // LLVM Backend
746 Builder.defineMacro("__clang__"); // Clang Frontend
747 #define TOSTR2(X) #X
748 #define TOSTR(X) TOSTR2(X)
749 Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
750 Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
751 Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
752 #undef TOSTR
753 #undef TOSTR2
754 Builder.defineMacro("__clang_version__",
755 "\"" CLANG_VERSION_STRING " "
756 + getClangFullRepositoryVersion() + "\"");
758 if (LangOpts.GNUCVersion != 0) {
759 // Major, minor, patch, are given two decimal places each, so 4.2.1 becomes
760 // 40201.
761 unsigned GNUCMajor = LangOpts.GNUCVersion / 100 / 100;
762 unsigned GNUCMinor = LangOpts.GNUCVersion / 100 % 100;
763 unsigned GNUCPatch = LangOpts.GNUCVersion % 100;
764 Builder.defineMacro("__GNUC__", Twine(GNUCMajor));
765 Builder.defineMacro("__GNUC_MINOR__", Twine(GNUCMinor));
766 Builder.defineMacro("__GNUC_PATCHLEVEL__", Twine(GNUCPatch));
767 Builder.defineMacro("__GXX_ABI_VERSION", "1002");
769 if (LangOpts.CPlusPlus) {
770 Builder.defineMacro("__GNUG__", Twine(GNUCMajor));
771 Builder.defineMacro("__GXX_WEAK__");
775 // Define macros for the C11 / C++11 memory orderings
776 Builder.defineMacro("__ATOMIC_RELAXED", "0");
777 Builder.defineMacro("__ATOMIC_CONSUME", "1");
778 Builder.defineMacro("__ATOMIC_ACQUIRE", "2");
779 Builder.defineMacro("__ATOMIC_RELEASE", "3");
780 Builder.defineMacro("__ATOMIC_ACQ_REL", "4");
781 Builder.defineMacro("__ATOMIC_SEQ_CST", "5");
783 // Define macros for the OpenCL memory scope.
784 // The values should match AtomicScopeOpenCLModel::ID enum.
785 static_assert(
786 static_cast<unsigned>(AtomicScopeOpenCLModel::WorkGroup) == 1 &&
787 static_cast<unsigned>(AtomicScopeOpenCLModel::Device) == 2 &&
788 static_cast<unsigned>(AtomicScopeOpenCLModel::AllSVMDevices) == 3 &&
789 static_cast<unsigned>(AtomicScopeOpenCLModel::SubGroup) == 4,
790 "Invalid OpenCL memory scope enum definition");
791 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_ITEM", "0");
792 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_GROUP", "1");
793 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_DEVICE", "2");
794 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES", "3");
795 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_SUB_GROUP", "4");
797 // Support for #pragma redefine_extname (Sun compatibility)
798 Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1");
800 // Previously this macro was set to a string aiming to achieve compatibility
801 // with GCC 4.2.1. Now, just return the full Clang version
802 Builder.defineMacro("__VERSION__", "\"" +
803 Twine(getClangFullCPPVersion()) + "\"");
805 // Initialize language-specific preprocessor defines.
807 // Standard conforming mode?
808 if (!LangOpts.GNUMode && !LangOpts.MSVCCompat)
809 Builder.defineMacro("__STRICT_ANSI__");
811 if (LangOpts.GNUCVersion && LangOpts.CPlusPlus11)
812 Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
814 if (LangOpts.ObjC) {
815 if (LangOpts.ObjCRuntime.isNonFragile()) {
816 Builder.defineMacro("__OBJC2__");
818 if (LangOpts.ObjCExceptions)
819 Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
822 if (LangOpts.getGC() != LangOptions::NonGC)
823 Builder.defineMacro("__OBJC_GC__");
825 if (LangOpts.ObjCRuntime.isNeXTFamily())
826 Builder.defineMacro("__NEXT_RUNTIME__");
828 if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::GNUstep) {
829 auto version = LangOpts.ObjCRuntime.getVersion();
830 std::string versionString = "1";
831 // Don't rely on the tuple argument, because we can be asked to target
832 // later ABIs than we actually support, so clamp these values to those
833 // currently supported
834 if (version >= VersionTuple(2, 0))
835 Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__", "20");
836 else
837 Builder.defineMacro(
838 "__OBJC_GNUSTEP_RUNTIME_ABI__",
839 "1" + Twine(std::min(8U, version.getMinor().value_or(0))));
842 if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::ObjFW) {
843 VersionTuple tuple = LangOpts.ObjCRuntime.getVersion();
844 unsigned minor = tuple.getMinor().value_or(0);
845 unsigned subminor = tuple.getSubminor().value_or(0);
846 Builder.defineMacro("__OBJFW_RUNTIME_ABI__",
847 Twine(tuple.getMajor() * 10000 + minor * 100 +
848 subminor));
851 Builder.defineMacro("IBOutlet", "__attribute__((iboutlet))");
852 Builder.defineMacro("IBOutletCollection(ClassName)",
853 "__attribute__((iboutletcollection(ClassName)))");
854 Builder.defineMacro("IBAction", "void)__attribute__((ibaction)");
855 Builder.defineMacro("IBInspectable", "");
856 Builder.defineMacro("IB_DESIGNABLE", "");
859 // Define a macro that describes the Objective-C boolean type even for C
860 // and C++ since BOOL can be used from non Objective-C code.
861 Builder.defineMacro("__OBJC_BOOL_IS_BOOL",
862 Twine(TI.useSignedCharForObjCBool() ? "0" : "1"));
864 if (LangOpts.CPlusPlus)
865 InitializeCPlusPlusFeatureTestMacros(LangOpts, Builder);
867 // darwin_constant_cfstrings controls this. This is also dependent
868 // on other things like the runtime I believe. This is set even for C code.
869 if (!LangOpts.NoConstantCFStrings)
870 Builder.defineMacro("__CONSTANT_CFSTRINGS__");
872 if (LangOpts.ObjC)
873 Builder.defineMacro("OBJC_NEW_PROPERTIES");
875 if (LangOpts.PascalStrings)
876 Builder.defineMacro("__PASCAL_STRINGS__");
878 if (LangOpts.Blocks) {
879 Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
880 Builder.defineMacro("__BLOCKS__");
883 if (!LangOpts.MSVCCompat && LangOpts.Exceptions)
884 Builder.defineMacro("__EXCEPTIONS");
885 if (LangOpts.GNUCVersion && LangOpts.RTTI)
886 Builder.defineMacro("__GXX_RTTI");
888 if (LangOpts.hasSjLjExceptions())
889 Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
890 else if (LangOpts.hasSEHExceptions())
891 Builder.defineMacro("__SEH__");
892 else if (LangOpts.hasDWARFExceptions() &&
893 (TI.getTriple().isThumb() || TI.getTriple().isARM()))
894 Builder.defineMacro("__ARM_DWARF_EH__");
896 if (LangOpts.Deprecated)
897 Builder.defineMacro("__DEPRECATED");
899 if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus)
900 Builder.defineMacro("__private_extern__", "extern");
902 if (LangOpts.MicrosoftExt) {
903 if (LangOpts.WChar) {
904 // wchar_t supported as a keyword.
905 Builder.defineMacro("_WCHAR_T_DEFINED");
906 Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
910 // Macros to help identify the narrow and wide character sets
911 // FIXME: clang currently ignores -fexec-charset=. If this changes,
912 // then this may need to be updated.
913 Builder.defineMacro("__clang_literal_encoding__", "\"UTF-8\"");
914 if (TI.getTypeWidth(TI.getWCharType()) >= 32) {
915 // FIXME: 32-bit wchar_t signals UTF-32. This may change
916 // if -fwide-exec-charset= is ever supported.
917 Builder.defineMacro("__clang_wide_literal_encoding__", "\"UTF-32\"");
918 } else {
919 // FIXME: Less-than 32-bit wchar_t generally means UTF-16
920 // (e.g., Windows, 32-bit IBM). This may need to be
921 // updated if -fwide-exec-charset= is ever supported.
922 Builder.defineMacro("__clang_wide_literal_encoding__", "\"UTF-16\"");
925 if (LangOpts.Optimize)
926 Builder.defineMacro("__OPTIMIZE__");
927 if (LangOpts.OptimizeSize)
928 Builder.defineMacro("__OPTIMIZE_SIZE__");
930 if (LangOpts.FastMath)
931 Builder.defineMacro("__FAST_MATH__");
933 // Initialize target-specific preprocessor defines.
935 // __BYTE_ORDER__ was added in GCC 4.6. It's analogous
936 // to the macro __BYTE_ORDER (no trailing underscores)
937 // from glibc's <endian.h> header.
938 // We don't support the PDP-11 as a target, but include
939 // the define so it can still be compared against.
940 Builder.defineMacro("__ORDER_LITTLE_ENDIAN__", "1234");
941 Builder.defineMacro("__ORDER_BIG_ENDIAN__", "4321");
942 Builder.defineMacro("__ORDER_PDP_ENDIAN__", "3412");
943 if (TI.isBigEndian()) {
944 Builder.defineMacro("__BYTE_ORDER__", "__ORDER_BIG_ENDIAN__");
945 Builder.defineMacro("__BIG_ENDIAN__");
946 } else {
947 Builder.defineMacro("__BYTE_ORDER__", "__ORDER_LITTLE_ENDIAN__");
948 Builder.defineMacro("__LITTLE_ENDIAN__");
951 if (TI.getPointerWidth(LangAS::Default) == 64 && TI.getLongWidth() == 64 &&
952 TI.getIntWidth() == 32) {
953 Builder.defineMacro("_LP64");
954 Builder.defineMacro("__LP64__");
957 if (TI.getPointerWidth(LangAS::Default) == 32 && TI.getLongWidth() == 32 &&
958 TI.getIntWidth() == 32) {
959 Builder.defineMacro("_ILP32");
960 Builder.defineMacro("__ILP32__");
963 // Define type sizing macros based on the target properties.
964 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
965 Builder.defineMacro("__CHAR_BIT__", Twine(TI.getCharWidth()));
967 Builder.defineMacro("__BOOL_WIDTH__", Twine(TI.getBoolWidth()));
968 Builder.defineMacro("__SHRT_WIDTH__", Twine(TI.getShortWidth()));
969 Builder.defineMacro("__INT_WIDTH__", Twine(TI.getIntWidth()));
970 Builder.defineMacro("__LONG_WIDTH__", Twine(TI.getLongWidth()));
971 Builder.defineMacro("__LLONG_WIDTH__", Twine(TI.getLongLongWidth()));
973 size_t BitIntMaxWidth = TI.getMaxBitIntWidth();
974 assert(BitIntMaxWidth <= llvm::IntegerType::MAX_INT_BITS &&
975 "Target defined a max bit width larger than LLVM can support!");
976 assert(BitIntMaxWidth >= TI.getLongLongWidth() &&
977 "Target defined a max bit width smaller than the C standard allows!");
978 Builder.defineMacro("__BITINT_MAXWIDTH__", Twine(BitIntMaxWidth));
980 DefineTypeSize("__SCHAR_MAX__", TargetInfo::SignedChar, TI, Builder);
981 DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
982 DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
983 DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
984 DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
985 DefineTypeSizeAndWidth("__WCHAR", TI.getWCharType(), TI, Builder);
986 DefineTypeSizeAndWidth("__WINT", TI.getWIntType(), TI, Builder);
987 DefineTypeSizeAndWidth("__INTMAX", TI.getIntMaxType(), TI, Builder);
988 DefineTypeSizeAndWidth("__SIZE", TI.getSizeType(), TI, Builder);
990 DefineTypeSizeAndWidth("__UINTMAX", TI.getUIntMaxType(), TI, Builder);
991 DefineTypeSizeAndWidth("__PTRDIFF", TI.getPtrDiffType(LangAS::Default), TI,
992 Builder);
993 DefineTypeSizeAndWidth("__INTPTR", TI.getIntPtrType(), TI, Builder);
994 DefineTypeSizeAndWidth("__UINTPTR", TI.getUIntPtrType(), TI, Builder);
996 DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder);
997 DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder);
998 DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder);
999 DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder);
1000 DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder);
1001 DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder);
1002 DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(LangAS::Default),
1003 TI, Builder);
1004 DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder);
1005 DefineTypeSizeof("__SIZEOF_PTRDIFF_T__",
1006 TI.getTypeWidth(TI.getPtrDiffType(LangAS::Default)), TI,
1007 Builder);
1008 DefineTypeSizeof("__SIZEOF_SIZE_T__",
1009 TI.getTypeWidth(TI.getSizeType()), TI, Builder);
1010 DefineTypeSizeof("__SIZEOF_WCHAR_T__",
1011 TI.getTypeWidth(TI.getWCharType()), TI, Builder);
1012 DefineTypeSizeof("__SIZEOF_WINT_T__",
1013 TI.getTypeWidth(TI.getWIntType()), TI, Builder);
1014 if (TI.hasInt128Type())
1015 DefineTypeSizeof("__SIZEOF_INT128__", 128, TI, Builder);
1017 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
1018 DefineFmt("__INTMAX", TI.getIntMaxType(), TI, Builder);
1019 Builder.defineMacro("__INTMAX_C_SUFFIX__",
1020 TI.getTypeConstantSuffix(TI.getIntMaxType()));
1021 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
1022 DefineFmt("__UINTMAX", TI.getUIntMaxType(), TI, Builder);
1023 Builder.defineMacro("__UINTMAX_C_SUFFIX__",
1024 TI.getTypeConstantSuffix(TI.getUIntMaxType()));
1025 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(LangAS::Default), Builder);
1026 DefineFmt("__PTRDIFF", TI.getPtrDiffType(LangAS::Default), TI, Builder);
1027 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
1028 DefineFmt("__INTPTR", TI.getIntPtrType(), TI, Builder);
1029 DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
1030 DefineFmt("__SIZE", TI.getSizeType(), TI, Builder);
1031 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
1032 DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
1033 DefineTypeSizeAndWidth("__SIG_ATOMIC", TI.getSigAtomicType(), TI, Builder);
1034 DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder);
1035 DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder);
1037 DefineType("__UINTPTR_TYPE__", TI.getUIntPtrType(), Builder);
1038 DefineFmt("__UINTPTR", TI.getUIntPtrType(), TI, Builder);
1040 // The C standard requires the width of uintptr_t and intptr_t to be the same,
1041 // per 7.20.2.4p1. Same for intmax_t and uintmax_t, per 7.20.2.5p1.
1042 assert(TI.getTypeWidth(TI.getUIntPtrType()) ==
1043 TI.getTypeWidth(TI.getIntPtrType()) &&
1044 "uintptr_t and intptr_t have different widths?");
1045 assert(TI.getTypeWidth(TI.getUIntMaxType()) ==
1046 TI.getTypeWidth(TI.getIntMaxType()) &&
1047 "uintmax_t and intmax_t have different widths?");
1049 if (TI.hasFloat16Type())
1050 DefineFloatMacros(Builder, "FLT16", &TI.getHalfFormat(), "F16");
1051 DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F");
1052 DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), "");
1053 DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L");
1055 // Define a __POINTER_WIDTH__ macro for stdint.h.
1056 Builder.defineMacro("__POINTER_WIDTH__",
1057 Twine((int)TI.getPointerWidth(LangAS::Default)));
1059 // Define __BIGGEST_ALIGNMENT__ to be compatible with gcc.
1060 Builder.defineMacro("__BIGGEST_ALIGNMENT__",
1061 Twine(TI.getSuitableAlign() / TI.getCharWidth()) );
1063 if (!LangOpts.CharIsSigned)
1064 Builder.defineMacro("__CHAR_UNSIGNED__");
1066 if (!TargetInfo::isTypeSigned(TI.getWCharType()))
1067 Builder.defineMacro("__WCHAR_UNSIGNED__");
1069 if (!TargetInfo::isTypeSigned(TI.getWIntType()))
1070 Builder.defineMacro("__WINT_UNSIGNED__");
1072 // Define exact-width integer types for stdint.h
1073 DefineExactWidthIntType(TargetInfo::SignedChar, TI, Builder);
1075 if (TI.getShortWidth() > TI.getCharWidth())
1076 DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
1078 if (TI.getIntWidth() > TI.getShortWidth())
1079 DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
1081 if (TI.getLongWidth() > TI.getIntWidth())
1082 DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
1084 if (TI.getLongLongWidth() > TI.getLongWidth())
1085 DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
1087 DefineExactWidthIntType(TargetInfo::UnsignedChar, TI, Builder);
1088 DefineExactWidthIntTypeSize(TargetInfo::UnsignedChar, TI, Builder);
1089 DefineExactWidthIntTypeSize(TargetInfo::SignedChar, TI, Builder);
1091 if (TI.getShortWidth() > TI.getCharWidth()) {
1092 DefineExactWidthIntType(TargetInfo::UnsignedShort, TI, Builder);
1093 DefineExactWidthIntTypeSize(TargetInfo::UnsignedShort, TI, Builder);
1094 DefineExactWidthIntTypeSize(TargetInfo::SignedShort, TI, Builder);
1097 if (TI.getIntWidth() > TI.getShortWidth()) {
1098 DefineExactWidthIntType(TargetInfo::UnsignedInt, TI, Builder);
1099 DefineExactWidthIntTypeSize(TargetInfo::UnsignedInt, TI, Builder);
1100 DefineExactWidthIntTypeSize(TargetInfo::SignedInt, TI, Builder);
1103 if (TI.getLongWidth() > TI.getIntWidth()) {
1104 DefineExactWidthIntType(TargetInfo::UnsignedLong, TI, Builder);
1105 DefineExactWidthIntTypeSize(TargetInfo::UnsignedLong, TI, Builder);
1106 DefineExactWidthIntTypeSize(TargetInfo::SignedLong, TI, Builder);
1109 if (TI.getLongLongWidth() > TI.getLongWidth()) {
1110 DefineExactWidthIntType(TargetInfo::UnsignedLongLong, TI, Builder);
1111 DefineExactWidthIntTypeSize(TargetInfo::UnsignedLongLong, TI, Builder);
1112 DefineExactWidthIntTypeSize(TargetInfo::SignedLongLong, TI, Builder);
1115 DefineLeastWidthIntType(8, true, TI, Builder);
1116 DefineLeastWidthIntType(8, false, TI, Builder);
1117 DefineLeastWidthIntType(16, true, TI, Builder);
1118 DefineLeastWidthIntType(16, false, TI, Builder);
1119 DefineLeastWidthIntType(32, true, TI, Builder);
1120 DefineLeastWidthIntType(32, false, TI, Builder);
1121 DefineLeastWidthIntType(64, true, TI, Builder);
1122 DefineLeastWidthIntType(64, false, TI, Builder);
1124 DefineFastIntType(8, true, TI, Builder);
1125 DefineFastIntType(8, false, TI, Builder);
1126 DefineFastIntType(16, true, TI, Builder);
1127 DefineFastIntType(16, false, TI, Builder);
1128 DefineFastIntType(32, true, TI, Builder);
1129 DefineFastIntType(32, false, TI, Builder);
1130 DefineFastIntType(64, true, TI, Builder);
1131 DefineFastIntType(64, false, TI, Builder);
1133 Builder.defineMacro("__USER_LABEL_PREFIX__", TI.getUserLabelPrefix());
1135 if (!LangOpts.MathErrno)
1136 Builder.defineMacro("__NO_MATH_ERRNO__");
1138 if (LangOpts.FastMath || LangOpts.FiniteMathOnly)
1139 Builder.defineMacro("__FINITE_MATH_ONLY__", "1");
1140 else
1141 Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
1143 if (LangOpts.GNUCVersion) {
1144 if (LangOpts.GNUInline || LangOpts.CPlusPlus)
1145 Builder.defineMacro("__GNUC_GNU_INLINE__");
1146 else
1147 Builder.defineMacro("__GNUC_STDC_INLINE__");
1149 // The value written by __atomic_test_and_set.
1150 // FIXME: This is target-dependent.
1151 Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
1154 auto addLockFreeMacros = [&](const llvm::Twine &Prefix) {
1155 // Used by libc++ and libstdc++ to implement ATOMIC_<foo>_LOCK_FREE.
1156 #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \
1157 Builder.defineMacro(Prefix + #TYPE "_LOCK_FREE", \
1158 getLockFreeValue(TI.get##Type##Width(), TI));
1159 DEFINE_LOCK_FREE_MACRO(BOOL, Bool);
1160 DEFINE_LOCK_FREE_MACRO(CHAR, Char);
1161 if (LangOpts.Char8)
1162 DEFINE_LOCK_FREE_MACRO(CHAR8_T, Char); // Treat char8_t like char.
1163 DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16);
1164 DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32);
1165 DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar);
1166 DEFINE_LOCK_FREE_MACRO(SHORT, Short);
1167 DEFINE_LOCK_FREE_MACRO(INT, Int);
1168 DEFINE_LOCK_FREE_MACRO(LONG, Long);
1169 DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
1170 Builder.defineMacro(
1171 Prefix + "POINTER_LOCK_FREE",
1172 getLockFreeValue(TI.getPointerWidth(LangAS::Default), TI));
1173 #undef DEFINE_LOCK_FREE_MACRO
1175 addLockFreeMacros("__CLANG_ATOMIC_");
1176 if (LangOpts.GNUCVersion)
1177 addLockFreeMacros("__GCC_ATOMIC_");
1179 if (LangOpts.NoInlineDefine)
1180 Builder.defineMacro("__NO_INLINE__");
1182 if (unsigned PICLevel = LangOpts.PICLevel) {
1183 Builder.defineMacro("__PIC__", Twine(PICLevel));
1184 Builder.defineMacro("__pic__", Twine(PICLevel));
1185 if (LangOpts.PIE) {
1186 Builder.defineMacro("__PIE__", Twine(PICLevel));
1187 Builder.defineMacro("__pie__", Twine(PICLevel));
1191 // Macros to control C99 numerics and <float.h>
1192 Builder.defineMacro("__FLT_RADIX__", "2");
1193 Builder.defineMacro("__DECIMAL_DIG__", "__LDBL_DECIMAL_DIG__");
1195 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1196 Builder.defineMacro("__SSP__");
1197 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1198 Builder.defineMacro("__SSP_STRONG__", "2");
1199 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1200 Builder.defineMacro("__SSP_ALL__", "3");
1202 if (PPOpts.SetUpStaticAnalyzer)
1203 Builder.defineMacro("__clang_analyzer__");
1205 if (LangOpts.FastRelaxedMath)
1206 Builder.defineMacro("__FAST_RELAXED_MATH__");
1208 if (FEOpts.ProgramAction == frontend::RewriteObjC ||
1209 LangOpts.getGC() != LangOptions::NonGC) {
1210 Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
1211 Builder.defineMacro("__strong", "__attribute__((objc_gc(strong)))");
1212 Builder.defineMacro("__autoreleasing", "");
1213 Builder.defineMacro("__unsafe_unretained", "");
1214 } else if (LangOpts.ObjC) {
1215 Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))");
1216 Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))");
1217 Builder.defineMacro("__autoreleasing",
1218 "__attribute__((objc_ownership(autoreleasing)))");
1219 Builder.defineMacro("__unsafe_unretained",
1220 "__attribute__((objc_ownership(none)))");
1223 // On Darwin, there are __double_underscored variants of the type
1224 // nullability qualifiers.
1225 if (TI.getTriple().isOSDarwin()) {
1226 Builder.defineMacro("__nonnull", "_Nonnull");
1227 Builder.defineMacro("__null_unspecified", "_Null_unspecified");
1228 Builder.defineMacro("__nullable", "_Nullable");
1231 // Add a macro to differentiate between regular iOS/tvOS/watchOS targets and
1232 // the corresponding simulator targets.
1233 if (TI.getTriple().isOSDarwin() && TI.getTriple().isSimulatorEnvironment())
1234 Builder.defineMacro("__APPLE_EMBEDDED_SIMULATOR__", "1");
1236 // OpenMP definition
1237 // OpenMP 2.2:
1238 // In implementations that support a preprocessor, the _OPENMP
1239 // macro name is defined to have the decimal value yyyymm where
1240 // yyyy and mm are the year and the month designations of the
1241 // version of the OpenMP API that the implementation support.
1242 if (!LangOpts.OpenMPSimd) {
1243 switch (LangOpts.OpenMP) {
1244 case 0:
1245 break;
1246 case 31:
1247 Builder.defineMacro("_OPENMP", "201107");
1248 break;
1249 case 40:
1250 Builder.defineMacro("_OPENMP", "201307");
1251 break;
1252 case 45:
1253 Builder.defineMacro("_OPENMP", "201511");
1254 break;
1255 case 51:
1256 Builder.defineMacro("_OPENMP", "202011");
1257 break;
1258 case 52:
1259 Builder.defineMacro("_OPENMP", "202111");
1260 break;
1261 case 50:
1262 default:
1263 // Default version is OpenMP 5.0
1264 Builder.defineMacro("_OPENMP", "201811");
1265 break;
1269 // CUDA device path compilaton
1270 if (LangOpts.CUDAIsDevice && !LangOpts.HIP) {
1271 // The CUDA_ARCH value is set for the GPU target specified in the NVPTX
1272 // backend's target defines.
1273 Builder.defineMacro("__CUDA_ARCH__");
1276 // We need to communicate this to our CUDA header wrapper, which in turn
1277 // informs the proper CUDA headers of this choice.
1278 if (LangOpts.CUDADeviceApproxTranscendentals || LangOpts.FastMath) {
1279 Builder.defineMacro("__CLANG_CUDA_APPROX_TRANSCENDENTALS__");
1282 // Define a macro indicating that the source file is being compiled with a
1283 // SYCL device compiler which doesn't produce host binary.
1284 if (LangOpts.SYCLIsDevice) {
1285 Builder.defineMacro("__SYCL_DEVICE_ONLY__", "1");
1288 // OpenCL definitions.
1289 if (LangOpts.OpenCL) {
1290 InitializeOpenCLFeatureTestMacros(TI, LangOpts, Builder);
1292 if (TI.getTriple().isSPIR() || TI.getTriple().isSPIRV())
1293 Builder.defineMacro("__IMAGE_SUPPORT__");
1296 if (TI.hasInt128Type() && LangOpts.CPlusPlus && LangOpts.GNUMode) {
1297 // For each extended integer type, g++ defines a macro mapping the
1298 // index of the type (0 in this case) in some list of extended types
1299 // to the type.
1300 Builder.defineMacro("__GLIBCXX_TYPE_INT_N_0", "__int128");
1301 Builder.defineMacro("__GLIBCXX_BITSIZE_INT_N_0", "128");
1304 // Get other target #defines.
1305 TI.getTargetDefines(LangOpts, Builder);
1308 /// InitializePreprocessor - Initialize the preprocessor getting it and the
1309 /// environment ready to process a single file.
1310 void clang::InitializePreprocessor(
1311 Preprocessor &PP, const PreprocessorOptions &InitOpts,
1312 const PCHContainerReader &PCHContainerRdr,
1313 const FrontendOptions &FEOpts) {
1314 const LangOptions &LangOpts = PP.getLangOpts();
1315 std::string PredefineBuffer;
1316 PredefineBuffer.reserve(4080);
1317 llvm::raw_string_ostream Predefines(PredefineBuffer);
1318 MacroBuilder Builder(Predefines);
1320 // Emit line markers for various builtin sections of the file. We don't do
1321 // this in asm preprocessor mode, because "# 4" is not a line marker directive
1322 // in this mode.
1323 if (!PP.getLangOpts().AsmPreprocessor)
1324 Builder.append("# 1 \"<built-in>\" 3");
1326 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
1327 if (InitOpts.UsePredefines) {
1328 // FIXME: This will create multiple definitions for most of the predefined
1329 // macros. This is not the right way to handle this.
1330 if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice || LangOpts.SYCLIsDevice) &&
1331 PP.getAuxTargetInfo())
1332 InitializePredefinedMacros(*PP.getAuxTargetInfo(), LangOpts, FEOpts,
1333 PP.getPreprocessorOpts(), Builder);
1335 InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts,
1336 PP.getPreprocessorOpts(), Builder);
1338 // Install definitions to make Objective-C++ ARC work well with various
1339 // C++ Standard Library implementations.
1340 if (LangOpts.ObjC && LangOpts.CPlusPlus &&
1341 (LangOpts.ObjCAutoRefCount || LangOpts.ObjCWeak)) {
1342 switch (InitOpts.ObjCXXARCStandardLibrary) {
1343 case ARCXX_nolib:
1344 case ARCXX_libcxx:
1345 break;
1347 case ARCXX_libstdcxx:
1348 AddObjCXXARCLibstdcxxDefines(LangOpts, Builder);
1349 break;
1354 // Even with predefines off, some macros are still predefined.
1355 // These should all be defined in the preprocessor according to the
1356 // current language configuration.
1357 InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOpts(),
1358 FEOpts, Builder);
1360 // Add on the predefines from the driver. Wrap in a #line directive to report
1361 // that they come from the command line.
1362 if (!PP.getLangOpts().AsmPreprocessor)
1363 Builder.append("# 1 \"<command line>\" 1");
1365 // Process #define's and #undef's in the order they are given.
1366 for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
1367 if (InitOpts.Macros[i].second) // isUndef
1368 Builder.undefineMacro(InitOpts.Macros[i].first);
1369 else
1370 DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
1371 PP.getDiagnostics());
1374 // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
1375 if (!PP.getLangOpts().AsmPreprocessor)
1376 Builder.append("# 1 \"<built-in>\" 2");
1378 // If -imacros are specified, include them now. These are processed before
1379 // any -include directives.
1380 for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
1381 AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i]);
1383 // Process -include-pch/-include-pth directives.
1384 if (!InitOpts.ImplicitPCHInclude.empty())
1385 AddImplicitIncludePCH(Builder, PP, PCHContainerRdr,
1386 InitOpts.ImplicitPCHInclude);
1388 // Process -include directives.
1389 for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
1390 const std::string &Path = InitOpts.Includes[i];
1391 AddImplicitInclude(Builder, Path);
1394 // Instruct the preprocessor to skip the preamble.
1395 PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first,
1396 InitOpts.PrecompiledPreambleBytes.second);
1398 // Copy PredefinedBuffer into the Preprocessor.
1399 PP.setPredefines(std::move(PredefineBuffer));