xref: /llvm-project/clang/lib/Frontend/InitPreprocessor.cpp (revision 5fe2ddbdf47dddc90233e3240a3aa6bcdea8721f)
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.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Basic/FileManager.h"
14 #include "clang/Basic/MacroBuilder.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Basic/SyncScope.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Basic/Version.h"
19 #include "clang/Frontend/FrontendDiagnostic.h"
20 #include "clang/Frontend/FrontendOptions.h"
21 #include "clang/Frontend/Utils.h"
22 #include "clang/Lex/HeaderSearch.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Lex/PreprocessorOptions.h"
25 #include "clang/Serialization/ASTReader.h"
26 #include "llvm/ADT/APFloat.h"
27 using namespace clang;
28 
29 static bool MacroBodyEndsInBackslash(StringRef MacroBody) {
30   while (!MacroBody.empty() && isWhitespace(MacroBody.back()))
31     MacroBody = MacroBody.drop_back();
32   return !MacroBody.empty() && MacroBody.back() == '\\';
33 }
34 
35 // Append a #define line to Buf for Macro.  Macro should be of the form XXX,
36 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
37 // "#define XXX Y z W".  To get a #define with no value, use "XXX=".
38 static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro,
39                                DiagnosticsEngine &Diags) {
40   std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
41   StringRef MacroName = MacroPair.first;
42   StringRef MacroBody = MacroPair.second;
43   if (MacroName.size() != Macro.size()) {
44     // Per GCC -D semantics, the macro ends at \n if it exists.
45     StringRef::size_type End = MacroBody.find_first_of("\n\r");
46     if (End != StringRef::npos)
47       Diags.Report(diag::warn_fe_macro_contains_embedded_newline)
48         << MacroName;
49     MacroBody = MacroBody.substr(0, End);
50     // We handle macro bodies which end in a backslash by appending an extra
51     // backslash+newline.  This makes sure we don't accidentally treat the
52     // backslash as a line continuation marker.
53     if (MacroBodyEndsInBackslash(MacroBody))
54       Builder.defineMacro(MacroName, Twine(MacroBody) + "\\\n");
55     else
56       Builder.defineMacro(MacroName, MacroBody);
57   } else {
58     // Push "macroname 1".
59     Builder.defineMacro(Macro);
60   }
61 }
62 
63 /// AddImplicitInclude - Add an implicit \#include of the specified file to the
64 /// predefines buffer.
65 /// As these includes are generated by -include arguments the header search
66 /// logic is going to search relatively to the current working directory.
67 static void AddImplicitInclude(MacroBuilder &Builder, StringRef File) {
68   Builder.append(Twine("#include \"") + File + "\"");
69 }
70 
71 static void AddImplicitIncludeMacros(MacroBuilder &Builder, StringRef File) {
72   Builder.append(Twine("#__include_macros \"") + File + "\"");
73   // Marker token to stop the __include_macros fetch loop.
74   Builder.append("##"); // ##?
75 }
76 
77 /// Add an implicit \#include using the original file used to generate
78 /// a PCH file.
79 static void AddImplicitIncludePCH(MacroBuilder &Builder, Preprocessor &PP,
80                                   const PCHContainerReader &PCHContainerRdr,
81                                   StringRef ImplicitIncludePCH) {
82   std::string OriginalFile =
83       ASTReader::getOriginalSourceFile(ImplicitIncludePCH, PP.getFileManager(),
84                                        PCHContainerRdr, PP.getDiagnostics());
85   if (OriginalFile.empty())
86     return;
87 
88   AddImplicitInclude(Builder, OriginalFile);
89 }
90 
91 /// PickFP - This is used to pick a value based on the FP semantics of the
92 /// specified FP model.
93 template <typename T>
94 static T PickFP(const llvm::fltSemantics *Sem, T IEEEHalfVal, T IEEESingleVal,
95                 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
96                 T IEEEQuadVal) {
97   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEhalf())
98     return IEEEHalfVal;
99   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle())
100     return IEEESingleVal;
101   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble())
102     return IEEEDoubleVal;
103   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended())
104     return X87DoubleExtendedVal;
105   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble())
106     return PPCDoubleDoubleVal;
107   assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad());
108   return IEEEQuadVal;
109 }
110 
111 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
112                               const llvm::fltSemantics *Sem, StringRef Ext) {
113   const char *DenormMin, *Epsilon, *Max, *Min;
114   DenormMin = PickFP(Sem, "5.9604644775390625e-8", "1.40129846e-45",
115                      "4.9406564584124654e-324", "3.64519953188247460253e-4951",
116                      "4.94065645841246544176568792868221e-324",
117                      "6.47517511943802511092443895822764655e-4966");
118   int Digits = PickFP(Sem, 3, 6, 15, 18, 31, 33);
119   int DecimalDigits = PickFP(Sem, 5, 9, 17, 21, 33, 36);
120   Epsilon = PickFP(Sem, "9.765625e-4", "1.19209290e-7",
121                    "2.2204460492503131e-16", "1.08420217248550443401e-19",
122                    "4.94065645841246544176568792868221e-324",
123                    "1.92592994438723585305597794258492732e-34");
124   int MantissaDigits = PickFP(Sem, 11, 24, 53, 64, 106, 113);
125   int Min10Exp = PickFP(Sem, -13, -37, -307, -4931, -291, -4931);
126   int Max10Exp = PickFP(Sem, 4, 38, 308, 4932, 308, 4932);
127   int MinExp = PickFP(Sem, -14, -125, -1021, -16381, -968, -16381);
128   int MaxExp = PickFP(Sem, 15, 128, 1024, 16384, 1024, 16384);
129   Min = PickFP(Sem, "6.103515625e-5", "1.17549435e-38", "2.2250738585072014e-308",
130                "3.36210314311209350626e-4932",
131                "2.00416836000897277799610805135016e-292",
132                "3.36210314311209350626267781732175260e-4932");
133   Max = PickFP(Sem, "6.5504e+4", "3.40282347e+38", "1.7976931348623157e+308",
134                "1.18973149535723176502e+4932",
135                "1.79769313486231580793728971405301e+308",
136                "1.18973149535723176508575932662800702e+4932");
137 
138   SmallString<32> DefPrefix;
139   DefPrefix = "__";
140   DefPrefix += Prefix;
141   DefPrefix += "_";
142 
143   Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
144   Builder.defineMacro(DefPrefix + "HAS_DENORM__");
145   Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
146   Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits));
147   Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon)+Ext);
148   Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
149   Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
150   Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits));
151 
152   Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp));
153   Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp));
154   Builder.defineMacro(DefPrefix + "MAX__", Twine(Max)+Ext);
155 
156   Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")");
157   Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")");
158   Builder.defineMacro(DefPrefix + "MIN__", Twine(Min)+Ext);
159 }
160 
161 
162 /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
163 /// named MacroName with the max value for a type with width 'TypeWidth' a
164 /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
165 static void DefineTypeSize(const Twine &MacroName, unsigned TypeWidth,
166                            StringRef ValSuffix, bool isSigned,
167                            MacroBuilder &Builder) {
168   llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth)
169                                 : llvm::APInt::getMaxValue(TypeWidth);
170   Builder.defineMacro(MacroName, MaxVal.toString(10, isSigned) + ValSuffix);
171 }
172 
173 /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
174 /// the width, suffix, and signedness of the given type
175 static void DefineTypeSize(const Twine &MacroName, TargetInfo::IntType Ty,
176                            const TargetInfo &TI, MacroBuilder &Builder) {
177   DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
178                  TI.isTypeSigned(Ty), Builder);
179 }
180 
181 static void DefineFmt(const Twine &Prefix, TargetInfo::IntType Ty,
182                       const TargetInfo &TI, MacroBuilder &Builder) {
183   bool IsSigned = TI.isTypeSigned(Ty);
184   StringRef FmtModifier = TI.getTypeFormatModifier(Ty);
185   for (const char *Fmt = IsSigned ? "di" : "ouxX"; *Fmt; ++Fmt) {
186     Builder.defineMacro(Prefix + "_FMT" + Twine(*Fmt) + "__",
187                         Twine("\"") + FmtModifier + Twine(*Fmt) + "\"");
188   }
189 }
190 
191 static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
192                        MacroBuilder &Builder) {
193   Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
194 }
195 
196 static void DefineTypeWidth(StringRef MacroName, TargetInfo::IntType Ty,
197                             const TargetInfo &TI, MacroBuilder &Builder) {
198   Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty)));
199 }
200 
201 static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth,
202                              const TargetInfo &TI, MacroBuilder &Builder) {
203   Builder.defineMacro(MacroName,
204                       Twine(BitWidth / TI.getCharWidth()));
205 }
206 
207 static void DefineExactWidthIntType(TargetInfo::IntType Ty,
208                                     const TargetInfo &TI,
209                                     MacroBuilder &Builder) {
210   int TypeWidth = TI.getTypeWidth(Ty);
211   bool IsSigned = TI.isTypeSigned(Ty);
212 
213   // Use the target specified int64 type, when appropriate, so that [u]int64_t
214   // ends up being defined in terms of the correct type.
215   if (TypeWidth == 64)
216     Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type();
217 
218   const char *Prefix = IsSigned ? "__INT" : "__UINT";
219 
220   DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
221   DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
222 
223   StringRef ConstSuffix(TI.getTypeConstantSuffix(Ty));
224   Builder.defineMacro(Prefix + Twine(TypeWidth) + "_C_SUFFIX__", ConstSuffix);
225 }
226 
227 static void DefineExactWidthIntTypeSize(TargetInfo::IntType Ty,
228                                         const TargetInfo &TI,
229                                         MacroBuilder &Builder) {
230   int TypeWidth = TI.getTypeWidth(Ty);
231   bool IsSigned = TI.isTypeSigned(Ty);
232 
233   // Use the target specified int64 type, when appropriate, so that [u]int64_t
234   // ends up being defined in terms of the correct type.
235   if (TypeWidth == 64)
236     Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type();
237 
238   const char *Prefix = IsSigned ? "__INT" : "__UINT";
239   DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
240 }
241 
242 static void DefineLeastWidthIntType(unsigned TypeWidth, bool IsSigned,
243                                     const TargetInfo &TI,
244                                     MacroBuilder &Builder) {
245   TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned);
246   if (Ty == TargetInfo::NoInt)
247     return;
248 
249   const char *Prefix = IsSigned ? "__INT_LEAST" : "__UINT_LEAST";
250   DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
251   DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
252   DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
253 }
254 
255 static void DefineFastIntType(unsigned TypeWidth, bool IsSigned,
256                               const TargetInfo &TI, MacroBuilder &Builder) {
257   // stdint.h currently defines the fast int types as equivalent to the least
258   // types.
259   TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned);
260   if (Ty == TargetInfo::NoInt)
261     return;
262 
263   const char *Prefix = IsSigned ? "__INT_FAST" : "__UINT_FAST";
264   DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
265   DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
266 
267   DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
268 }
269 
270 
271 /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
272 /// the specified properties.
273 static const char *getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign,
274                                     unsigned InlineWidth) {
275   // Fully-aligned, power-of-2 sizes no larger than the inline
276   // width will be inlined as lock-free operations.
277   if (TypeWidth == TypeAlign && (TypeWidth & (TypeWidth - 1)) == 0 &&
278       TypeWidth <= InlineWidth)
279     return "2"; // "always lock free"
280   // We cannot be certain what operations the lib calls might be
281   // able to implement as lock-free on future processors.
282   return "1"; // "sometimes lock free"
283 }
284 
285 /// Add definitions required for a smooth interaction between
286 /// Objective-C++ automated reference counting and libstdc++ (4.2).
287 static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts,
288                                          MacroBuilder &Builder) {
289   Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR");
290 
291   std::string Result;
292   {
293     // Provide specializations for the __is_scalar type trait so that
294     // lifetime-qualified objects are not considered "scalar" types, which
295     // libstdc++ uses as an indicator of the presence of trivial copy, assign,
296     // default-construct, and destruct semantics (none of which hold for
297     // lifetime-qualified objects in ARC).
298     llvm::raw_string_ostream Out(Result);
299 
300     Out << "namespace std {\n"
301         << "\n"
302         << "struct __true_type;\n"
303         << "struct __false_type;\n"
304         << "\n";
305 
306     Out << "template<typename _Tp> struct __is_scalar;\n"
307         << "\n";
308 
309     if (LangOpts.ObjCAutoRefCount) {
310       Out << "template<typename _Tp>\n"
311           << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n"
312           << "  enum { __value = 0 };\n"
313           << "  typedef __false_type __type;\n"
314           << "};\n"
315           << "\n";
316     }
317 
318     if (LangOpts.ObjCWeak) {
319       Out << "template<typename _Tp>\n"
320           << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n"
321           << "  enum { __value = 0 };\n"
322           << "  typedef __false_type __type;\n"
323           << "};\n"
324           << "\n";
325     }
326 
327     if (LangOpts.ObjCAutoRefCount) {
328       Out << "template<typename _Tp>\n"
329           << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))"
330           << " _Tp> {\n"
331           << "  enum { __value = 0 };\n"
332           << "  typedef __false_type __type;\n"
333           << "};\n"
334           << "\n";
335     }
336 
337     Out << "}\n";
338   }
339   Builder.append(Result);
340 }
341 
342 static void InitializeStandardPredefinedMacros(const TargetInfo &TI,
343                                                const LangOptions &LangOpts,
344                                                const FrontendOptions &FEOpts,
345                                                MacroBuilder &Builder) {
346   if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
347     Builder.defineMacro("__STDC__");
348   if (LangOpts.Freestanding)
349     Builder.defineMacro("__STDC_HOSTED__", "0");
350   else
351     Builder.defineMacro("__STDC_HOSTED__");
352 
353   if (!LangOpts.CPlusPlus) {
354     if (LangOpts.C17)
355       Builder.defineMacro("__STDC_VERSION__", "201710L");
356     else if (LangOpts.C11)
357       Builder.defineMacro("__STDC_VERSION__", "201112L");
358     else if (LangOpts.C99)
359       Builder.defineMacro("__STDC_VERSION__", "199901L");
360     else if (!LangOpts.GNUMode && LangOpts.Digraphs)
361       Builder.defineMacro("__STDC_VERSION__", "199409L");
362   } else {
363     // FIXME: Use correct value for C++20.
364     if (LangOpts.CPlusPlus2a)
365       Builder.defineMacro("__cplusplus", "201707L");
366     // C++17 [cpp.predefined]p1:
367     //   The name __cplusplus is defined to the value 201703L when compiling a
368     //   C++ translation unit.
369     else if (LangOpts.CPlusPlus17)
370       Builder.defineMacro("__cplusplus", "201703L");
371     // C++1y [cpp.predefined]p1:
372     //   The name __cplusplus is defined to the value 201402L when compiling a
373     //   C++ translation unit.
374     else if (LangOpts.CPlusPlus14)
375       Builder.defineMacro("__cplusplus", "201402L");
376     // C++11 [cpp.predefined]p1:
377     //   The name __cplusplus is defined to the value 201103L when compiling a
378     //   C++ translation unit.
379     else if (LangOpts.CPlusPlus11)
380       Builder.defineMacro("__cplusplus", "201103L");
381     // C++03 [cpp.predefined]p1:
382     //   The name __cplusplus is defined to the value 199711L when compiling a
383     //   C++ translation unit.
384     else
385       Builder.defineMacro("__cplusplus", "199711L");
386 
387     // C++1z [cpp.predefined]p1:
388     //   An integer literal of type std::size_t whose value is the alignment
389     //   guaranteed by a call to operator new(std::size_t)
390     //
391     // We provide this in all language modes, since it seems generally useful.
392     Builder.defineMacro("__STDCPP_DEFAULT_NEW_ALIGNMENT__",
393                         Twine(TI.getNewAlign() / TI.getCharWidth()) +
394                             TI.getTypeConstantSuffix(TI.getSizeType()));
395   }
396 
397   // In C11 these are environment macros. In C++11 they are only defined
398   // as part of <cuchar>. To prevent breakage when mixing C and C++
399   // code, define these macros unconditionally. We can define them
400   // unconditionally, as Clang always uses UTF-16 and UTF-32 for 16-bit
401   // and 32-bit character literals.
402   Builder.defineMacro("__STDC_UTF_16__", "1");
403   Builder.defineMacro("__STDC_UTF_32__", "1");
404 
405   if (LangOpts.ObjC)
406     Builder.defineMacro("__OBJC__");
407 
408   // OpenCL v1.0/1.1 s6.9, v1.2/2.0 s6.10: Preprocessor Directives and Macros.
409   if (LangOpts.OpenCL) {
410     if (LangOpts.CPlusPlus) {
411       if (LangOpts.OpenCLCPlusPlusVersion == 100)
412         Builder.defineMacro("__OPENCL_CPP_VERSION__", "100");
413       else
414         llvm_unreachable("Unsupported OpenCL C++ version");
415       Builder.defineMacro("__CL_CPP_VERSION_1_0__", "100");
416     } else {
417       // OpenCL v1.0 and v1.1 do not have a predefined macro to indicate the
418       // language standard with which the program is compiled. __OPENCL_VERSION__
419       // is for the OpenCL version supported by the OpenCL device, which is not
420       // necessarily the language standard with which the program is compiled.
421       // A shared OpenCL header file requires a macro to indicate the language
422       // standard. As a workaround, __OPENCL_C_VERSION__ is defined for
423       // OpenCL v1.0 and v1.1.
424       switch (LangOpts.OpenCLVersion) {
425       case 100:
426         Builder.defineMacro("__OPENCL_C_VERSION__", "100");
427         break;
428       case 110:
429         Builder.defineMacro("__OPENCL_C_VERSION__", "110");
430         break;
431       case 120:
432         Builder.defineMacro("__OPENCL_C_VERSION__", "120");
433         break;
434       case 200:
435         Builder.defineMacro("__OPENCL_C_VERSION__", "200");
436         break;
437       default:
438         llvm_unreachable("Unsupported OpenCL version");
439       }
440       Builder.defineMacro("CL_VERSION_1_0", "100");
441       Builder.defineMacro("CL_VERSION_1_1", "110");
442       Builder.defineMacro("CL_VERSION_1_2", "120");
443       Builder.defineMacro("CL_VERSION_2_0", "200");
444 
445       if (TI.isLittleEndian())
446         Builder.defineMacro("__ENDIAN_LITTLE__");
447 
448       if (LangOpts.FastRelaxedMath)
449         Builder.defineMacro("__FAST_RELAXED_MATH__");
450     }
451   }
452   // Not "standard" per se, but available even with the -undef flag.
453   if (LangOpts.AsmPreprocessor)
454     Builder.defineMacro("__ASSEMBLER__");
455   if (LangOpts.CUDA && !LangOpts.HIP)
456     Builder.defineMacro("__CUDA__");
457   if (LangOpts.HIP) {
458     Builder.defineMacro("__HIP__");
459     Builder.defineMacro("__HIPCC__");
460     if (LangOpts.CUDAIsDevice)
461       Builder.defineMacro("__HIP_DEVICE_COMPILE__");
462   }
463 }
464 
465 /// Initialize the predefined C++ language feature test macros defined in
466 /// ISO/IEC JTC1/SC22/WG21 (C++) SD-6: "SG10 Feature Test Recommendations".
467 static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts,
468                                                  MacroBuilder &Builder) {
469   // C++98 features.
470   if (LangOpts.RTTI)
471     Builder.defineMacro("__cpp_rtti", "199711L");
472   if (LangOpts.CXXExceptions)
473     Builder.defineMacro("__cpp_exceptions", "199711L");
474 
475   // C++11 features.
476   if (LangOpts.CPlusPlus11) {
477     Builder.defineMacro("__cpp_unicode_characters", "200704L");
478     Builder.defineMacro("__cpp_raw_strings", "200710L");
479     Builder.defineMacro("__cpp_unicode_literals", "200710L");
480     Builder.defineMacro("__cpp_user_defined_literals", "200809L");
481     Builder.defineMacro("__cpp_lambdas", "200907L");
482     Builder.defineMacro("__cpp_constexpr",
483                         LangOpts.CPlusPlus17 ? "201603L" :
484                         LangOpts.CPlusPlus14 ? "201304L" : "200704");
485     Builder.defineMacro("__cpp_range_based_for",
486                         LangOpts.CPlusPlus17 ? "201603L" : "200907");
487     Builder.defineMacro("__cpp_static_assert",
488                         LangOpts.CPlusPlus17 ? "201411L" : "200410");
489     Builder.defineMacro("__cpp_decltype", "200707L");
490     Builder.defineMacro("__cpp_attributes", "200809L");
491     Builder.defineMacro("__cpp_rvalue_references", "200610L");
492     Builder.defineMacro("__cpp_variadic_templates", "200704L");
493     Builder.defineMacro("__cpp_initializer_lists", "200806L");
494     Builder.defineMacro("__cpp_delegating_constructors", "200604L");
495     Builder.defineMacro("__cpp_nsdmi", "200809L");
496     Builder.defineMacro("__cpp_inheriting_constructors", "201511L");
497     Builder.defineMacro("__cpp_ref_qualifiers", "200710L");
498     Builder.defineMacro("__cpp_alias_templates", "200704L");
499   }
500   if (LangOpts.ThreadsafeStatics)
501     Builder.defineMacro("__cpp_threadsafe_static_init", "200806L");
502 
503   // C++14 features.
504   if (LangOpts.CPlusPlus14) {
505     Builder.defineMacro("__cpp_binary_literals", "201304L");
506     Builder.defineMacro("__cpp_digit_separators", "201309L");
507     Builder.defineMacro("__cpp_init_captures", "201304L");
508     Builder.defineMacro("__cpp_generic_lambdas", "201304L");
509     Builder.defineMacro("__cpp_decltype_auto", "201304L");
510     Builder.defineMacro("__cpp_return_type_deduction", "201304L");
511     Builder.defineMacro("__cpp_aggregate_nsdmi", "201304L");
512     Builder.defineMacro("__cpp_variable_templates", "201304L");
513   }
514   if (LangOpts.SizedDeallocation)
515     Builder.defineMacro("__cpp_sized_deallocation", "201309L");
516 
517   // C++17 features.
518   if (LangOpts.CPlusPlus17) {
519     Builder.defineMacro("__cpp_hex_float", "201603L");
520     Builder.defineMacro("__cpp_inline_variables", "201606L");
521     Builder.defineMacro("__cpp_noexcept_function_type", "201510L");
522     Builder.defineMacro("__cpp_capture_star_this", "201603L");
523     Builder.defineMacro("__cpp_if_constexpr", "201606L");
524     Builder.defineMacro("__cpp_deduction_guides", "201703L");
525     Builder.defineMacro("__cpp_template_auto", "201606L"); // (old name)
526     Builder.defineMacro("__cpp_namespace_attributes", "201411L");
527     Builder.defineMacro("__cpp_enumerator_attributes", "201411L");
528     Builder.defineMacro("__cpp_nested_namespace_definitions", "201411L");
529     Builder.defineMacro("__cpp_variadic_using", "201611L");
530     Builder.defineMacro("__cpp_aggregate_bases", "201603L");
531     Builder.defineMacro("__cpp_structured_bindings", "201606L");
532     Builder.defineMacro("__cpp_nontype_template_args", "201411L");
533     Builder.defineMacro("__cpp_fold_expressions", "201603L");
534     Builder.defineMacro("__cpp_guaranteed_copy_elision", "201606L");
535     Builder.defineMacro("__cpp_nontype_template_parameter_auto", "201606L");
536   }
537   if (LangOpts.AlignedAllocation && !LangOpts.AlignedAllocationUnavailable)
538     Builder.defineMacro("__cpp_aligned_new", "201606L");
539   if (LangOpts.RelaxedTemplateTemplateArgs)
540     Builder.defineMacro("__cpp_template_template_args", "201611L");
541 
542   // C++20 features.
543   if (LangOpts.CPlusPlus2a)
544     Builder.defineMacro("__cpp_conditional_explicit", "201806L");
545   if (LangOpts.Char8)
546     Builder.defineMacro("__cpp_char8_t", "201811L");
547   Builder.defineMacro("__cpp_impl_destroying_delete", "201806L");
548 
549   // TS features.
550   if (LangOpts.ConceptsTS)
551     Builder.defineMacro("__cpp_experimental_concepts", "1L");
552   if (LangOpts.Coroutines)
553     Builder.defineMacro("__cpp_coroutines", "201703L");
554 }
555 
556 static void InitializePredefinedMacros(const TargetInfo &TI,
557                                        const LangOptions &LangOpts,
558                                        const FrontendOptions &FEOpts,
559                                        MacroBuilder &Builder) {
560   // Compiler version introspection macros.
561   Builder.defineMacro("__llvm__");  // LLVM Backend
562   Builder.defineMacro("__clang__"); // Clang Frontend
563 #define TOSTR2(X) #X
564 #define TOSTR(X) TOSTR2(X)
565   Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
566   Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
567   Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
568 #undef TOSTR
569 #undef TOSTR2
570   Builder.defineMacro("__clang_version__",
571                       "\"" CLANG_VERSION_STRING " "
572                       + getClangFullRepositoryVersion() + "\"");
573   if (!LangOpts.MSVCCompat) {
574     // Currently claim to be compatible with GCC 4.2.1-5621, but only if we're
575     // not compiling for MSVC compatibility
576     Builder.defineMacro("__GNUC_MINOR__", "2");
577     Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
578     Builder.defineMacro("__GNUC__", "4");
579     Builder.defineMacro("__GXX_ABI_VERSION", "1002");
580   }
581 
582   // Define macros for the C11 / C++11 memory orderings
583   Builder.defineMacro("__ATOMIC_RELAXED", "0");
584   Builder.defineMacro("__ATOMIC_CONSUME", "1");
585   Builder.defineMacro("__ATOMIC_ACQUIRE", "2");
586   Builder.defineMacro("__ATOMIC_RELEASE", "3");
587   Builder.defineMacro("__ATOMIC_ACQ_REL", "4");
588   Builder.defineMacro("__ATOMIC_SEQ_CST", "5");
589 
590   // Define macros for the OpenCL memory scope.
591   // The values should match AtomicScopeOpenCLModel::ID enum.
592   static_assert(
593       static_cast<unsigned>(AtomicScopeOpenCLModel::WorkGroup) == 1 &&
594           static_cast<unsigned>(AtomicScopeOpenCLModel::Device) == 2 &&
595           static_cast<unsigned>(AtomicScopeOpenCLModel::AllSVMDevices) == 3 &&
596           static_cast<unsigned>(AtomicScopeOpenCLModel::SubGroup) == 4,
597       "Invalid OpenCL memory scope enum definition");
598   Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_ITEM", "0");
599   Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_GROUP", "1");
600   Builder.defineMacro("__OPENCL_MEMORY_SCOPE_DEVICE", "2");
601   Builder.defineMacro("__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES", "3");
602   Builder.defineMacro("__OPENCL_MEMORY_SCOPE_SUB_GROUP", "4");
603 
604   // Support for #pragma redefine_extname (Sun compatibility)
605   Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1");
606 
607   // As sad as it is, enough software depends on the __VERSION__ for version
608   // checks that it is necessary to report 4.2.1 (the base GCC version we claim
609   // compatibility with) first.
610   Builder.defineMacro("__VERSION__", "\"4.2.1 Compatible " +
611                       Twine(getClangFullCPPVersion()) + "\"");
612 
613   // Initialize language-specific preprocessor defines.
614 
615   // Standard conforming mode?
616   if (!LangOpts.GNUMode && !LangOpts.MSVCCompat)
617     Builder.defineMacro("__STRICT_ANSI__");
618 
619   if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus11)
620     Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
621 
622   if (LangOpts.ObjC) {
623     if (LangOpts.ObjCRuntime.isNonFragile()) {
624       Builder.defineMacro("__OBJC2__");
625 
626       if (LangOpts.ObjCExceptions)
627         Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
628     }
629 
630     if (LangOpts.getGC() != LangOptions::NonGC)
631       Builder.defineMacro("__OBJC_GC__");
632 
633     if (LangOpts.ObjCRuntime.isNeXTFamily())
634       Builder.defineMacro("__NEXT_RUNTIME__");
635 
636     if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::GNUstep) {
637       auto version = LangOpts.ObjCRuntime.getVersion();
638       std::string versionString = "1";
639       // Don't rely on the tuple argument, because we can be asked to target
640       // later ABIs than we actually support, so clamp these values to those
641       // currently supported
642       if (version >= VersionTuple(2, 0))
643         Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__", "20");
644       else
645         Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__",
646             "1" + Twine(std::min(8U, version.getMinor().getValueOr(0))));
647     }
648 
649     if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::ObjFW) {
650       VersionTuple tuple = LangOpts.ObjCRuntime.getVersion();
651 
652       unsigned minor = 0;
653       if (tuple.getMinor().hasValue())
654         minor = tuple.getMinor().getValue();
655 
656       unsigned subminor = 0;
657       if (tuple.getSubminor().hasValue())
658         subminor = tuple.getSubminor().getValue();
659 
660       Builder.defineMacro("__OBJFW_RUNTIME_ABI__",
661                           Twine(tuple.getMajor() * 10000 + minor * 100 +
662                                 subminor));
663     }
664 
665     Builder.defineMacro("IBOutlet", "__attribute__((iboutlet))");
666     Builder.defineMacro("IBOutletCollection(ClassName)",
667                         "__attribute__((iboutletcollection(ClassName)))");
668     Builder.defineMacro("IBAction", "void)__attribute__((ibaction)");
669     Builder.defineMacro("IBInspectable", "");
670     Builder.defineMacro("IB_DESIGNABLE", "");
671   }
672 
673   // Define a macro that describes the Objective-C boolean type even for C
674   // and C++ since BOOL can be used from non Objective-C code.
675   Builder.defineMacro("__OBJC_BOOL_IS_BOOL",
676                       Twine(TI.useSignedCharForObjCBool() ? "0" : "1"));
677 
678   if (LangOpts.CPlusPlus)
679     InitializeCPlusPlusFeatureTestMacros(LangOpts, Builder);
680 
681   // darwin_constant_cfstrings controls this. This is also dependent
682   // on other things like the runtime I believe.  This is set even for C code.
683   if (!LangOpts.NoConstantCFStrings)
684       Builder.defineMacro("__CONSTANT_CFSTRINGS__");
685 
686   if (LangOpts.ObjC)
687     Builder.defineMacro("OBJC_NEW_PROPERTIES");
688 
689   if (LangOpts.PascalStrings)
690     Builder.defineMacro("__PASCAL_STRINGS__");
691 
692   if (LangOpts.Blocks) {
693     Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
694     Builder.defineMacro("__BLOCKS__");
695   }
696 
697   if (!LangOpts.MSVCCompat && LangOpts.Exceptions)
698     Builder.defineMacro("__EXCEPTIONS");
699   if (!LangOpts.MSVCCompat && LangOpts.RTTI)
700     Builder.defineMacro("__GXX_RTTI");
701 
702   if (LangOpts.SjLjExceptions)
703     Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
704   else if (LangOpts.SEHExceptions)
705     Builder.defineMacro("__SEH__");
706   else if (LangOpts.DWARFExceptions &&
707           (TI.getTriple().isThumb() || TI.getTriple().isARM()))
708     Builder.defineMacro("__ARM_DWARF_EH__");
709 
710   if (LangOpts.Deprecated)
711     Builder.defineMacro("__DEPRECATED");
712 
713   if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus) {
714     Builder.defineMacro("__GNUG__", "4");
715     Builder.defineMacro("__GXX_WEAK__");
716     Builder.defineMacro("__private_extern__", "extern");
717   }
718 
719   if (LangOpts.MicrosoftExt) {
720     if (LangOpts.WChar) {
721       // wchar_t supported as a keyword.
722       Builder.defineMacro("_WCHAR_T_DEFINED");
723       Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
724     }
725   }
726 
727   if (LangOpts.Optimize)
728     Builder.defineMacro("__OPTIMIZE__");
729   if (LangOpts.OptimizeSize)
730     Builder.defineMacro("__OPTIMIZE_SIZE__");
731 
732   if (LangOpts.FastMath)
733     Builder.defineMacro("__FAST_MATH__");
734 
735   // Initialize target-specific preprocessor defines.
736 
737   // __BYTE_ORDER__ was added in GCC 4.6. It's analogous
738   // to the macro __BYTE_ORDER (no trailing underscores)
739   // from glibc's <endian.h> header.
740   // We don't support the PDP-11 as a target, but include
741   // the define so it can still be compared against.
742   Builder.defineMacro("__ORDER_LITTLE_ENDIAN__", "1234");
743   Builder.defineMacro("__ORDER_BIG_ENDIAN__",    "4321");
744   Builder.defineMacro("__ORDER_PDP_ENDIAN__",    "3412");
745   if (TI.isBigEndian()) {
746     Builder.defineMacro("__BYTE_ORDER__", "__ORDER_BIG_ENDIAN__");
747     Builder.defineMacro("__BIG_ENDIAN__");
748   } else {
749     Builder.defineMacro("__BYTE_ORDER__", "__ORDER_LITTLE_ENDIAN__");
750     Builder.defineMacro("__LITTLE_ENDIAN__");
751   }
752 
753   if (TI.getPointerWidth(0) == 64 && TI.getLongWidth() == 64
754       && TI.getIntWidth() == 32) {
755     Builder.defineMacro("_LP64");
756     Builder.defineMacro("__LP64__");
757   }
758 
759   if (TI.getPointerWidth(0) == 32 && TI.getLongWidth() == 32
760       && TI.getIntWidth() == 32) {
761     Builder.defineMacro("_ILP32");
762     Builder.defineMacro("__ILP32__");
763   }
764 
765   // Define type sizing macros based on the target properties.
766   assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
767   Builder.defineMacro("__CHAR_BIT__", Twine(TI.getCharWidth()));
768 
769   DefineTypeSize("__SCHAR_MAX__", TargetInfo::SignedChar, TI, Builder);
770   DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
771   DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
772   DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
773   DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
774   DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
775   DefineTypeSize("__WINT_MAX__", TI.getWIntType(), TI, Builder);
776   DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
777   DefineTypeSize("__SIZE_MAX__", TI.getSizeType(), TI, Builder);
778 
779   DefineTypeSize("__UINTMAX_MAX__", TI.getUIntMaxType(), TI, Builder);
780   DefineTypeSize("__PTRDIFF_MAX__", TI.getPtrDiffType(0), TI, Builder);
781   DefineTypeSize("__INTPTR_MAX__", TI.getIntPtrType(), TI, Builder);
782   DefineTypeSize("__UINTPTR_MAX__", TI.getUIntPtrType(), TI, Builder);
783 
784   DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder);
785   DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder);
786   DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder);
787   DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder);
788   DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder);
789   DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder);
790   DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(0), TI, Builder);
791   DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder);
792   DefineTypeSizeof("__SIZEOF_PTRDIFF_T__",
793                    TI.getTypeWidth(TI.getPtrDiffType(0)), TI, Builder);
794   DefineTypeSizeof("__SIZEOF_SIZE_T__",
795                    TI.getTypeWidth(TI.getSizeType()), TI, Builder);
796   DefineTypeSizeof("__SIZEOF_WCHAR_T__",
797                    TI.getTypeWidth(TI.getWCharType()), TI, Builder);
798   DefineTypeSizeof("__SIZEOF_WINT_T__",
799                    TI.getTypeWidth(TI.getWIntType()), TI, Builder);
800   if (TI.hasInt128Type())
801     DefineTypeSizeof("__SIZEOF_INT128__", 128, TI, Builder);
802 
803   DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
804   DefineFmt("__INTMAX", TI.getIntMaxType(), TI, Builder);
805   Builder.defineMacro("__INTMAX_C_SUFFIX__",
806                       TI.getTypeConstantSuffix(TI.getIntMaxType()));
807   DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
808   DefineFmt("__UINTMAX", TI.getUIntMaxType(), TI, Builder);
809   Builder.defineMacro("__UINTMAX_C_SUFFIX__",
810                       TI.getTypeConstantSuffix(TI.getUIntMaxType()));
811   DefineTypeWidth("__INTMAX_WIDTH__",  TI.getIntMaxType(), TI, Builder);
812   DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
813   DefineFmt("__PTRDIFF", TI.getPtrDiffType(0), TI, Builder);
814   DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
815   DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
816   DefineFmt("__INTPTR", TI.getIntPtrType(), TI, Builder);
817   DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
818   DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
819   DefineFmt("__SIZE", TI.getSizeType(), TI, Builder);
820   DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
821   DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
822   DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
823   DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
824   DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
825   DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
826   DefineTypeSize("__SIG_ATOMIC_MAX__", TI.getSigAtomicType(), TI, Builder);
827   DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder);
828   DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder);
829 
830   DefineTypeWidth("__UINTMAX_WIDTH__",  TI.getUIntMaxType(), TI, Builder);
831   DefineType("__UINTPTR_TYPE__", TI.getUIntPtrType(), Builder);
832   DefineFmt("__UINTPTR", TI.getUIntPtrType(), TI, Builder);
833   DefineTypeWidth("__UINTPTR_WIDTH__", TI.getUIntPtrType(), TI, Builder);
834 
835   if (TI.hasFloat16Type())
836     DefineFloatMacros(Builder, "FLT16", &TI.getHalfFormat(), "F16");
837   DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F");
838   DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), "");
839   DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L");
840 
841   // Define a __POINTER_WIDTH__ macro for stdint.h.
842   Builder.defineMacro("__POINTER_WIDTH__",
843                       Twine((int)TI.getPointerWidth(0)));
844 
845   // Define __BIGGEST_ALIGNMENT__ to be compatible with gcc.
846   Builder.defineMacro("__BIGGEST_ALIGNMENT__",
847                       Twine(TI.getSuitableAlign() / TI.getCharWidth()) );
848 
849   if (!LangOpts.CharIsSigned)
850     Builder.defineMacro("__CHAR_UNSIGNED__");
851 
852   if (!TargetInfo::isTypeSigned(TI.getWCharType()))
853     Builder.defineMacro("__WCHAR_UNSIGNED__");
854 
855   if (!TargetInfo::isTypeSigned(TI.getWIntType()))
856     Builder.defineMacro("__WINT_UNSIGNED__");
857 
858   // Define exact-width integer types for stdint.h
859   DefineExactWidthIntType(TargetInfo::SignedChar, TI, Builder);
860 
861   if (TI.getShortWidth() > TI.getCharWidth())
862     DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
863 
864   if (TI.getIntWidth() > TI.getShortWidth())
865     DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
866 
867   if (TI.getLongWidth() > TI.getIntWidth())
868     DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
869 
870   if (TI.getLongLongWidth() > TI.getLongWidth())
871     DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
872 
873   DefineExactWidthIntType(TargetInfo::UnsignedChar, TI, Builder);
874   DefineExactWidthIntTypeSize(TargetInfo::UnsignedChar, TI, Builder);
875   DefineExactWidthIntTypeSize(TargetInfo::SignedChar, TI, Builder);
876 
877   if (TI.getShortWidth() > TI.getCharWidth()) {
878     DefineExactWidthIntType(TargetInfo::UnsignedShort, TI, Builder);
879     DefineExactWidthIntTypeSize(TargetInfo::UnsignedShort, TI, Builder);
880     DefineExactWidthIntTypeSize(TargetInfo::SignedShort, TI, Builder);
881   }
882 
883   if (TI.getIntWidth() > TI.getShortWidth()) {
884     DefineExactWidthIntType(TargetInfo::UnsignedInt, TI, Builder);
885     DefineExactWidthIntTypeSize(TargetInfo::UnsignedInt, TI, Builder);
886     DefineExactWidthIntTypeSize(TargetInfo::SignedInt, TI, Builder);
887   }
888 
889   if (TI.getLongWidth() > TI.getIntWidth()) {
890     DefineExactWidthIntType(TargetInfo::UnsignedLong, TI, Builder);
891     DefineExactWidthIntTypeSize(TargetInfo::UnsignedLong, TI, Builder);
892     DefineExactWidthIntTypeSize(TargetInfo::SignedLong, TI, Builder);
893   }
894 
895   if (TI.getLongLongWidth() > TI.getLongWidth()) {
896     DefineExactWidthIntType(TargetInfo::UnsignedLongLong, TI, Builder);
897     DefineExactWidthIntTypeSize(TargetInfo::UnsignedLongLong, TI, Builder);
898     DefineExactWidthIntTypeSize(TargetInfo::SignedLongLong, TI, Builder);
899   }
900 
901   DefineLeastWidthIntType(8, true, TI, Builder);
902   DefineLeastWidthIntType(8, false, TI, Builder);
903   DefineLeastWidthIntType(16, true, TI, Builder);
904   DefineLeastWidthIntType(16, false, TI, Builder);
905   DefineLeastWidthIntType(32, true, TI, Builder);
906   DefineLeastWidthIntType(32, false, TI, Builder);
907   DefineLeastWidthIntType(64, true, TI, Builder);
908   DefineLeastWidthIntType(64, false, TI, Builder);
909 
910   DefineFastIntType(8, true, TI, Builder);
911   DefineFastIntType(8, false, TI, Builder);
912   DefineFastIntType(16, true, TI, Builder);
913   DefineFastIntType(16, false, TI, Builder);
914   DefineFastIntType(32, true, TI, Builder);
915   DefineFastIntType(32, false, TI, Builder);
916   DefineFastIntType(64, true, TI, Builder);
917   DefineFastIntType(64, false, TI, Builder);
918 
919   char UserLabelPrefix[2] = {TI.getDataLayout().getGlobalPrefix(), 0};
920   Builder.defineMacro("__USER_LABEL_PREFIX__", UserLabelPrefix);
921 
922   if (LangOpts.FastMath || LangOpts.FiniteMathOnly)
923     Builder.defineMacro("__FINITE_MATH_ONLY__", "1");
924   else
925     Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
926 
927   if (!LangOpts.MSVCCompat) {
928     if (LangOpts.GNUInline || LangOpts.CPlusPlus)
929       Builder.defineMacro("__GNUC_GNU_INLINE__");
930     else
931       Builder.defineMacro("__GNUC_STDC_INLINE__");
932 
933     // The value written by __atomic_test_and_set.
934     // FIXME: This is target-dependent.
935     Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
936   }
937 
938   auto addLockFreeMacros = [&](const llvm::Twine &Prefix) {
939     // Used by libc++ and libstdc++ to implement ATOMIC_<foo>_LOCK_FREE.
940     unsigned InlineWidthBits = TI.getMaxAtomicInlineWidth();
941 #define DEFINE_LOCK_FREE_MACRO(TYPE, Type)                                     \
942   Builder.defineMacro(Prefix + #TYPE "_LOCK_FREE",                             \
943                       getLockFreeValue(TI.get##Type##Width(),                  \
944                                        TI.get##Type##Align(),                  \
945                                        InlineWidthBits));
946     DEFINE_LOCK_FREE_MACRO(BOOL, Bool);
947     DEFINE_LOCK_FREE_MACRO(CHAR, Char);
948     if (LangOpts.Char8)
949       DEFINE_LOCK_FREE_MACRO(CHAR8_T, Char); // Treat char8_t like char.
950     DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16);
951     DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32);
952     DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar);
953     DEFINE_LOCK_FREE_MACRO(SHORT, Short);
954     DEFINE_LOCK_FREE_MACRO(INT, Int);
955     DEFINE_LOCK_FREE_MACRO(LONG, Long);
956     DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
957     Builder.defineMacro(Prefix + "POINTER_LOCK_FREE",
958                         getLockFreeValue(TI.getPointerWidth(0),
959                                          TI.getPointerAlign(0),
960                                          InlineWidthBits));
961 #undef DEFINE_LOCK_FREE_MACRO
962   };
963   addLockFreeMacros("__CLANG_ATOMIC_");
964   if (!LangOpts.MSVCCompat)
965     addLockFreeMacros("__GCC_ATOMIC_");
966 
967   if (LangOpts.NoInlineDefine)
968     Builder.defineMacro("__NO_INLINE__");
969 
970   if (unsigned PICLevel = LangOpts.PICLevel) {
971     Builder.defineMacro("__PIC__", Twine(PICLevel));
972     Builder.defineMacro("__pic__", Twine(PICLevel));
973     if (LangOpts.PIE) {
974       Builder.defineMacro("__PIE__", Twine(PICLevel));
975       Builder.defineMacro("__pie__", Twine(PICLevel));
976     }
977   }
978 
979   // Macros to control C99 numerics and <float.h>
980   Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod()));
981   Builder.defineMacro("__FLT_RADIX__", "2");
982   Builder.defineMacro("__DECIMAL_DIG__", "__LDBL_DECIMAL_DIG__");
983 
984   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
985     Builder.defineMacro("__SSP__");
986   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
987     Builder.defineMacro("__SSP_STRONG__", "2");
988   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
989     Builder.defineMacro("__SSP_ALL__", "3");
990 
991   // Define a macro that exists only when using the static analyzer.
992   if (FEOpts.ProgramAction == frontend::RunAnalysis)
993     Builder.defineMacro("__clang_analyzer__");
994 
995   if (LangOpts.FastRelaxedMath)
996     Builder.defineMacro("__FAST_RELAXED_MATH__");
997 
998   if (FEOpts.ProgramAction == frontend::RewriteObjC ||
999       LangOpts.getGC() != LangOptions::NonGC) {
1000     Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
1001     Builder.defineMacro("__strong", "__attribute__((objc_gc(strong)))");
1002     Builder.defineMacro("__autoreleasing", "");
1003     Builder.defineMacro("__unsafe_unretained", "");
1004   } else if (LangOpts.ObjC) {
1005     Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))");
1006     Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))");
1007     Builder.defineMacro("__autoreleasing",
1008                         "__attribute__((objc_ownership(autoreleasing)))");
1009     Builder.defineMacro("__unsafe_unretained",
1010                         "__attribute__((objc_ownership(none)))");
1011   }
1012 
1013   // On Darwin, there are __double_underscored variants of the type
1014   // nullability qualifiers.
1015   if (TI.getTriple().isOSDarwin()) {
1016     Builder.defineMacro("__nonnull", "_Nonnull");
1017     Builder.defineMacro("__null_unspecified", "_Null_unspecified");
1018     Builder.defineMacro("__nullable", "_Nullable");
1019   }
1020 
1021   // Add a macro to differentiate between regular iOS/tvOS/watchOS targets and
1022   // the corresponding simulator targets.
1023   if (TI.getTriple().isOSDarwin() && TI.getTriple().isSimulatorEnvironment())
1024     Builder.defineMacro("__APPLE_EMBEDDED_SIMULATOR__", "1");
1025 
1026   // OpenMP definition
1027   // OpenMP 2.2:
1028   //   In implementations that support a preprocessor, the _OPENMP
1029   //   macro name is defined to have the decimal value yyyymm where
1030   //   yyyy and mm are the year and the month designations of the
1031   //   version of the OpenMP API that the implementation support.
1032   if (!LangOpts.OpenMPSimd) {
1033     switch (LangOpts.OpenMP) {
1034     case 0:
1035       break;
1036     case 40:
1037       Builder.defineMacro("_OPENMP", "201307");
1038       break;
1039     case 45:
1040       Builder.defineMacro("_OPENMP", "201511");
1041       break;
1042     default:
1043       // Default version is OpenMP 3.1
1044       Builder.defineMacro("_OPENMP", "201107");
1045       break;
1046     }
1047   }
1048 
1049   // CUDA device path compilaton
1050   if (LangOpts.CUDAIsDevice && !LangOpts.HIP) {
1051     // The CUDA_ARCH value is set for the GPU target specified in the NVPTX
1052     // backend's target defines.
1053     Builder.defineMacro("__CUDA_ARCH__");
1054   }
1055 
1056   // We need to communicate this to our CUDA header wrapper, which in turn
1057   // informs the proper CUDA headers of this choice.
1058   if (LangOpts.CUDADeviceApproxTranscendentals || LangOpts.FastMath) {
1059     Builder.defineMacro("__CLANG_CUDA_APPROX_TRANSCENDENTALS__");
1060   }
1061 
1062   // Define a macro indicating that the source file is being compiled with a
1063   // SYCL device compiler which doesn't produce host binary.
1064   if (LangOpts.SYCLIsDevice) {
1065     Builder.defineMacro("__SYCL_DEVICE_ONLY__", "1");
1066   }
1067 
1068   // OpenCL definitions.
1069   if (LangOpts.OpenCL) {
1070 #define OPENCLEXT(Ext)                                                         \
1071   if (TI.getSupportedOpenCLOpts().isSupported(#Ext, LangOpts))                 \
1072     Builder.defineMacro(#Ext);
1073 #include "clang/Basic/OpenCLExtensions.def"
1074 
1075     auto Arch = TI.getTriple().getArch();
1076     if (Arch == llvm::Triple::spir || Arch == llvm::Triple::spir64)
1077       Builder.defineMacro("__IMAGE_SUPPORT__");
1078   }
1079 
1080   if (TI.hasInt128Type() && LangOpts.CPlusPlus && LangOpts.GNUMode) {
1081     // For each extended integer type, g++ defines a macro mapping the
1082     // index of the type (0 in this case) in some list of extended types
1083     // to the type.
1084     Builder.defineMacro("__GLIBCXX_TYPE_INT_N_0", "__int128");
1085     Builder.defineMacro("__GLIBCXX_BITSIZE_INT_N_0", "128");
1086   }
1087 
1088   // Get other target #defines.
1089   TI.getTargetDefines(LangOpts, Builder);
1090 }
1091 
1092 /// InitializePreprocessor - Initialize the preprocessor getting it and the
1093 /// environment ready to process a single file. This returns true on error.
1094 ///
1095 void clang::InitializePreprocessor(
1096     Preprocessor &PP, const PreprocessorOptions &InitOpts,
1097     const PCHContainerReader &PCHContainerRdr,
1098     const FrontendOptions &FEOpts) {
1099   const LangOptions &LangOpts = PP.getLangOpts();
1100   std::string PredefineBuffer;
1101   PredefineBuffer.reserve(4080);
1102   llvm::raw_string_ostream Predefines(PredefineBuffer);
1103   MacroBuilder Builder(Predefines);
1104 
1105   // Emit line markers for various builtin sections of the file.  We don't do
1106   // this in asm preprocessor mode, because "# 4" is not a line marker directive
1107   // in this mode.
1108   if (!PP.getLangOpts().AsmPreprocessor)
1109     Builder.append("# 1 \"<built-in>\" 3");
1110 
1111   // Install things like __POWERPC__, __GNUC__, etc into the macro table.
1112   if (InitOpts.UsePredefines) {
1113     // FIXME: This will create multiple definitions for most of the predefined
1114     // macros. This is not the right way to handle this.
1115     if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice) && PP.getAuxTargetInfo())
1116       InitializePredefinedMacros(*PP.getAuxTargetInfo(), LangOpts, FEOpts,
1117                                  Builder);
1118 
1119     InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, Builder);
1120 
1121     // Install definitions to make Objective-C++ ARC work well with various
1122     // C++ Standard Library implementations.
1123     if (LangOpts.ObjC && LangOpts.CPlusPlus &&
1124         (LangOpts.ObjCAutoRefCount || LangOpts.ObjCWeak)) {
1125       switch (InitOpts.ObjCXXARCStandardLibrary) {
1126       case ARCXX_nolib:
1127       case ARCXX_libcxx:
1128         break;
1129 
1130       case ARCXX_libstdcxx:
1131         AddObjCXXARCLibstdcxxDefines(LangOpts, Builder);
1132         break;
1133       }
1134     }
1135   }
1136 
1137   // Even with predefines off, some macros are still predefined.
1138   // These should all be defined in the preprocessor according to the
1139   // current language configuration.
1140   InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOpts(),
1141                                      FEOpts, Builder);
1142 
1143   // Add on the predefines from the driver.  Wrap in a #line directive to report
1144   // that they come from the command line.
1145   if (!PP.getLangOpts().AsmPreprocessor)
1146     Builder.append("# 1 \"<command line>\" 1");
1147 
1148   // Process #define's and #undef's in the order they are given.
1149   for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
1150     if (InitOpts.Macros[i].second)  // isUndef
1151       Builder.undefineMacro(InitOpts.Macros[i].first);
1152     else
1153       DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
1154                          PP.getDiagnostics());
1155   }
1156 
1157   // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
1158   if (!PP.getLangOpts().AsmPreprocessor)
1159     Builder.append("# 1 \"<built-in>\" 2");
1160 
1161   // If -imacros are specified, include them now.  These are processed before
1162   // any -include directives.
1163   for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
1164     AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i]);
1165 
1166   // Process -include-pch/-include-pth directives.
1167   if (!InitOpts.ImplicitPCHInclude.empty())
1168     AddImplicitIncludePCH(Builder, PP, PCHContainerRdr,
1169                           InitOpts.ImplicitPCHInclude);
1170 
1171   // Process -include directives.
1172   for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
1173     const std::string &Path = InitOpts.Includes[i];
1174     AddImplicitInclude(Builder, Path);
1175   }
1176 
1177   // Instruct the preprocessor to skip the preamble.
1178   PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first,
1179                              InitOpts.PrecompiledPreambleBytes.second);
1180 
1181   // Copy PredefinedBuffer into the Preprocessor.
1182   PP.setPredefines(Predefines.str());
1183 }
1184