InitPreprocessor.cpp 49 KB

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