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