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