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