InitPreprocessor.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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 C++ version for OpenCL");
  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. }
  392. Builder.defineMacro("CL_VERSION_1_0", "100");
  393. Builder.defineMacro("CL_VERSION_1_1", "110");
  394. Builder.defineMacro("CL_VERSION_1_2", "120");
  395. Builder.defineMacro("CL_VERSION_2_0", "200");
  396. if (TI.isLittleEndian())
  397. Builder.defineMacro("__ENDIAN_LITTLE__");
  398. if (LangOpts.FastRelaxedMath)
  399. Builder.defineMacro("__FAST_RELAXED_MATH__");
  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.CPlusPlus2a ? "201907L" :
  431. LangOpts.CPlusPlus17 ? "201603L" :
  432. LangOpts.CPlusPlus14 ? "201304L" : "200704");
  433. Builder.defineMacro("__cpp_range_based_for",
  434. LangOpts.CPlusPlus17 ? "201603L" : "200907");
  435. Builder.defineMacro("__cpp_static_assert",
  436. LangOpts.CPlusPlus17 ? "201411L" : "200410");
  437. Builder.defineMacro("__cpp_decltype", "200707L");
  438. Builder.defineMacro("__cpp_attributes", "200809L");
  439. Builder.defineMacro("__cpp_rvalue_references", "200610L");
  440. Builder.defineMacro("__cpp_variadic_templates", "200704L");
  441. Builder.defineMacro("__cpp_initializer_lists", "200806L");
  442. Builder.defineMacro("__cpp_delegating_constructors", "200604L");
  443. Builder.defineMacro("__cpp_nsdmi", "200809L");
  444. Builder.defineMacro("__cpp_inheriting_constructors", "201511L");
  445. Builder.defineMacro("__cpp_ref_qualifiers", "200710L");
  446. Builder.defineMacro("__cpp_alias_templates", "200704L");
  447. }
  448. if (LangOpts.ThreadsafeStatics)
  449. Builder.defineMacro("__cpp_threadsafe_static_init", "200806L");
  450. // C++14 features.
  451. if (LangOpts.CPlusPlus14) {
  452. Builder.defineMacro("__cpp_binary_literals", "201304L");
  453. Builder.defineMacro("__cpp_digit_separators", "201309L");
  454. Builder.defineMacro("__cpp_init_captures", "201304L");
  455. Builder.defineMacro("__cpp_generic_lambdas", "201304L");
  456. Builder.defineMacro("__cpp_decltype_auto", "201304L");
  457. Builder.defineMacro("__cpp_return_type_deduction", "201304L");
  458. Builder.defineMacro("__cpp_aggregate_nsdmi", "201304L");
  459. Builder.defineMacro("__cpp_variable_templates", "201304L");
  460. }
  461. if (LangOpts.SizedDeallocation)
  462. Builder.defineMacro("__cpp_sized_deallocation", "201309L");
  463. // C++17 features.
  464. if (LangOpts.CPlusPlus17) {
  465. Builder.defineMacro("__cpp_hex_float", "201603L");
  466. Builder.defineMacro("__cpp_inline_variables", "201606L");
  467. Builder.defineMacro("__cpp_noexcept_function_type", "201510L");
  468. Builder.defineMacro("__cpp_capture_star_this", "201603L");
  469. Builder.defineMacro("__cpp_if_constexpr", "201606L");
  470. Builder.defineMacro("__cpp_deduction_guides", "201703L");
  471. Builder.defineMacro("__cpp_template_auto", "201606L"); // (old name)
  472. Builder.defineMacro("__cpp_namespace_attributes", "201411L");
  473. Builder.defineMacro("__cpp_enumerator_attributes", "201411L");
  474. Builder.defineMacro("__cpp_nested_namespace_definitions", "201411L");
  475. Builder.defineMacro("__cpp_variadic_using", "201611L");
  476. Builder.defineMacro("__cpp_aggregate_bases", "201603L");
  477. Builder.defineMacro("__cpp_structured_bindings", "201606L");
  478. Builder.defineMacro("__cpp_nontype_template_args", "201411L");
  479. Builder.defineMacro("__cpp_fold_expressions", "201603L");
  480. Builder.defineMacro("__cpp_guaranteed_copy_elision", "201606L");
  481. Builder.defineMacro("__cpp_nontype_template_parameter_auto", "201606L");
  482. }
  483. if (LangOpts.AlignedAllocation && !LangOpts.AlignedAllocationUnavailable)
  484. Builder.defineMacro("__cpp_aligned_new", "201606L");
  485. if (LangOpts.RelaxedTemplateTemplateArgs)
  486. Builder.defineMacro("__cpp_template_template_args", "201611L");
  487. // C++20 features.
  488. if (LangOpts.CPlusPlus2a) {
  489. Builder.defineMacro("__cpp_conditional_explicit", "201806L");
  490. Builder.defineMacro("__cpp_constexpr_dynamic_alloc", "201907L");
  491. Builder.defineMacro("__cpp_constinit", "201907L");
  492. }
  493. if (LangOpts.Char8)
  494. Builder.defineMacro("__cpp_char8_t", "201811L");
  495. Builder.defineMacro("__cpp_impl_destroying_delete", "201806L");
  496. // TS features.
  497. if (LangOpts.ConceptsTS)
  498. Builder.defineMacro("__cpp_experimental_concepts", "1L");
  499. if (LangOpts.Coroutines)
  500. Builder.defineMacro("__cpp_coroutines", "201703L");
  501. }
  502. static void InitializePredefinedMacros(const TargetInfo &TI,
  503. const LangOptions &LangOpts,
  504. const FrontendOptions &FEOpts,
  505. const PreprocessorOptions &PPOpts,
  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. Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
  515. #undef TOSTR
  516. #undef TOSTR2
  517. Builder.defineMacro("__clang_version__",
  518. "\"" CLANG_VERSION_STRING " "
  519. + getClangFullRepositoryVersion() + "\"");
  520. if (LangOpts.GNUCVersion != 0) {
  521. // Major, minor, patch, are given two decimal places each, so 4.2.1 becomes
  522. // 40201.
  523. unsigned GNUCMajor = LangOpts.GNUCVersion / 100 / 100;
  524. unsigned GNUCMinor = LangOpts.GNUCVersion / 100 % 100;
  525. unsigned GNUCPatch = LangOpts.GNUCVersion % 100;
  526. Builder.defineMacro("__GNUC__", Twine(GNUCMajor));
  527. Builder.defineMacro("__GNUC_MINOR__", Twine(GNUCMinor));
  528. Builder.defineMacro("__GNUC_PATCHLEVEL__", Twine(GNUCPatch));
  529. Builder.defineMacro("__GXX_ABI_VERSION", "1002");
  530. if (LangOpts.CPlusPlus) {
  531. Builder.defineMacro("__GNUG__", Twine(GNUCMajor));
  532. Builder.defineMacro("__GXX_WEAK__");
  533. }
  534. }
  535. // Define macros for the C11 / C++11 memory orderings
  536. Builder.defineMacro("__ATOMIC_RELAXED", "0");
  537. Builder.defineMacro("__ATOMIC_CONSUME", "1");
  538. Builder.defineMacro("__ATOMIC_ACQUIRE", "2");
  539. Builder.defineMacro("__ATOMIC_RELEASE", "3");
  540. Builder.defineMacro("__ATOMIC_ACQ_REL", "4");
  541. Builder.defineMacro("__ATOMIC_SEQ_CST", "5");
  542. // Define macros for the OpenCL memory scope.
  543. // The values should match AtomicScopeOpenCLModel::ID enum.
  544. static_assert(
  545. static_cast<unsigned>(AtomicScopeOpenCLModel::WorkGroup) == 1 &&
  546. static_cast<unsigned>(AtomicScopeOpenCLModel::Device) == 2 &&
  547. static_cast<unsigned>(AtomicScopeOpenCLModel::AllSVMDevices) == 3 &&
  548. static_cast<unsigned>(AtomicScopeOpenCLModel::SubGroup) == 4,
  549. "Invalid OpenCL memory scope enum definition");
  550. Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_ITEM", "0");
  551. Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_GROUP", "1");
  552. Builder.defineMacro("__OPENCL_MEMORY_SCOPE_DEVICE", "2");
  553. Builder.defineMacro("__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES", "3");
  554. Builder.defineMacro("__OPENCL_MEMORY_SCOPE_SUB_GROUP", "4");
  555. // Support for #pragma redefine_extname (Sun compatibility)
  556. Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1");
  557. // Previously this macro was set to a string aiming to achieve compatibility
  558. // with GCC 4.2.1. Now, just return the full Clang version
  559. Builder.defineMacro("__VERSION__", "\"" +
  560. Twine(getClangFullCPPVersion()) + "\"");
  561. // Initialize language-specific preprocessor defines.
  562. // Standard conforming mode?
  563. if (!LangOpts.GNUMode && !LangOpts.MSVCCompat)
  564. Builder.defineMacro("__STRICT_ANSI__");
  565. if (LangOpts.GNUCVersion && LangOpts.CPlusPlus11)
  566. Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
  567. if (LangOpts.ObjC) {
  568. if (LangOpts.ObjCRuntime.isNonFragile()) {
  569. Builder.defineMacro("__OBJC2__");
  570. if (LangOpts.ObjCExceptions)
  571. Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
  572. }
  573. if (LangOpts.getGC() != LangOptions::NonGC)
  574. Builder.defineMacro("__OBJC_GC__");
  575. if (LangOpts.ObjCRuntime.isNeXTFamily())
  576. Builder.defineMacro("__NEXT_RUNTIME__");
  577. if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::GNUstep) {
  578. auto version = LangOpts.ObjCRuntime.getVersion();
  579. std::string versionString = "1";
  580. // Don't rely on the tuple argument, because we can be asked to target
  581. // later ABIs than we actually support, so clamp these values to those
  582. // currently supported
  583. if (version >= VersionTuple(2, 0))
  584. Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__", "20");
  585. else
  586. Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__",
  587. "1" + Twine(std::min(8U, version.getMinor().getValueOr(0))));
  588. }
  589. if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::ObjFW) {
  590. VersionTuple tuple = LangOpts.ObjCRuntime.getVersion();
  591. unsigned minor = 0;
  592. if (tuple.getMinor().hasValue())
  593. minor = tuple.getMinor().getValue();
  594. unsigned subminor = 0;
  595. if (tuple.getSubminor().hasValue())
  596. subminor = tuple.getSubminor().getValue();
  597. Builder.defineMacro("__OBJFW_RUNTIME_ABI__",
  598. Twine(tuple.getMajor() * 10000 + minor * 100 +
  599. subminor));
  600. }
  601. Builder.defineMacro("IBOutlet", "__attribute__((iboutlet))");
  602. Builder.defineMacro("IBOutletCollection(ClassName)",
  603. "__attribute__((iboutletcollection(ClassName)))");
  604. Builder.defineMacro("IBAction", "void)__attribute__((ibaction)");
  605. Builder.defineMacro("IBInspectable", "");
  606. Builder.defineMacro("IB_DESIGNABLE", "");
  607. }
  608. // Define a macro that describes the Objective-C boolean type even for C
  609. // and C++ since BOOL can be used from non Objective-C code.
  610. Builder.defineMacro("__OBJC_BOOL_IS_BOOL",
  611. Twine(TI.useSignedCharForObjCBool() ? "0" : "1"));
  612. if (LangOpts.CPlusPlus)
  613. InitializeCPlusPlusFeatureTestMacros(LangOpts, Builder);
  614. // darwin_constant_cfstrings controls this. This is also dependent
  615. // on other things like the runtime I believe. This is set even for C code.
  616. if (!LangOpts.NoConstantCFStrings)
  617. Builder.defineMacro("__CONSTANT_CFSTRINGS__");
  618. if (LangOpts.ObjC)
  619. Builder.defineMacro("OBJC_NEW_PROPERTIES");
  620. if (LangOpts.PascalStrings)
  621. Builder.defineMacro("__PASCAL_STRINGS__");
  622. if (LangOpts.Blocks) {
  623. Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
  624. Builder.defineMacro("__BLOCKS__");
  625. }
  626. if (!LangOpts.MSVCCompat && LangOpts.Exceptions)
  627. Builder.defineMacro("__EXCEPTIONS");
  628. if (LangOpts.GNUCVersion && LangOpts.RTTI)
  629. Builder.defineMacro("__GXX_RTTI");
  630. if (LangOpts.SjLjExceptions)
  631. Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
  632. else if (LangOpts.SEHExceptions)
  633. Builder.defineMacro("__SEH__");
  634. else if (LangOpts.DWARFExceptions &&
  635. (TI.getTriple().isThumb() || TI.getTriple().isARM()))
  636. Builder.defineMacro("__ARM_DWARF_EH__");
  637. if (LangOpts.Deprecated)
  638. Builder.defineMacro("__DEPRECATED");
  639. if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus)
  640. Builder.defineMacro("__private_extern__", "extern");
  641. if (LangOpts.MicrosoftExt) {
  642. if (LangOpts.WChar) {
  643. // wchar_t supported as a keyword.
  644. Builder.defineMacro("_WCHAR_T_DEFINED");
  645. Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
  646. }
  647. }
  648. if (LangOpts.Optimize)
  649. Builder.defineMacro("__OPTIMIZE__");
  650. if (LangOpts.OptimizeSize)
  651. Builder.defineMacro("__OPTIMIZE_SIZE__");
  652. if (LangOpts.FastMath)
  653. Builder.defineMacro("__FAST_MATH__");
  654. // Initialize target-specific preprocessor defines.
  655. // __BYTE_ORDER__ was added in GCC 4.6. It's analogous
  656. // to the macro __BYTE_ORDER (no trailing underscores)
  657. // from glibc's <endian.h> header.
  658. // We don't support the PDP-11 as a target, but include
  659. // the define so it can still be compared against.
  660. Builder.defineMacro("__ORDER_LITTLE_ENDIAN__", "1234");
  661. Builder.defineMacro("__ORDER_BIG_ENDIAN__", "4321");
  662. Builder.defineMacro("__ORDER_PDP_ENDIAN__", "3412");
  663. if (TI.isBigEndian()) {
  664. Builder.defineMacro("__BYTE_ORDER__", "__ORDER_BIG_ENDIAN__");
  665. Builder.defineMacro("__BIG_ENDIAN__");
  666. } else {
  667. Builder.defineMacro("__BYTE_ORDER__", "__ORDER_LITTLE_ENDIAN__");
  668. Builder.defineMacro("__LITTLE_ENDIAN__");
  669. }
  670. if (TI.getPointerWidth(0) == 64 && TI.getLongWidth() == 64
  671. && TI.getIntWidth() == 32) {
  672. Builder.defineMacro("_LP64");
  673. Builder.defineMacro("__LP64__");
  674. }
  675. if (TI.getPointerWidth(0) == 32 && TI.getLongWidth() == 32
  676. && TI.getIntWidth() == 32) {
  677. Builder.defineMacro("_ILP32");
  678. Builder.defineMacro("__ILP32__");
  679. }
  680. // Define type sizing macros based on the target properties.
  681. assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
  682. Builder.defineMacro("__CHAR_BIT__", Twine(TI.getCharWidth()));
  683. DefineTypeSize("__SCHAR_MAX__", TargetInfo::SignedChar, TI, Builder);
  684. DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
  685. DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
  686. DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
  687. DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
  688. DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
  689. DefineTypeSize("__WINT_MAX__", TI.getWIntType(), TI, Builder);
  690. DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
  691. DefineTypeSize("__SIZE_MAX__", TI.getSizeType(), TI, Builder);
  692. DefineTypeSize("__UINTMAX_MAX__", TI.getUIntMaxType(), TI, Builder);
  693. DefineTypeSize("__PTRDIFF_MAX__", TI.getPtrDiffType(0), TI, Builder);
  694. DefineTypeSize("__INTPTR_MAX__", TI.getIntPtrType(), TI, Builder);
  695. DefineTypeSize("__UINTPTR_MAX__", TI.getUIntPtrType(), TI, Builder);
  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. DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
  715. DefineFmt("__INTMAX", TI.getIntMaxType(), TI, Builder);
  716. Builder.defineMacro("__INTMAX_C_SUFFIX__",
  717. TI.getTypeConstantSuffix(TI.getIntMaxType()));
  718. DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
  719. DefineFmt("__UINTMAX", TI.getUIntMaxType(), TI, Builder);
  720. Builder.defineMacro("__UINTMAX_C_SUFFIX__",
  721. TI.getTypeConstantSuffix(TI.getUIntMaxType()));
  722. DefineTypeWidth("__INTMAX_WIDTH__", TI.getIntMaxType(), TI, Builder);
  723. DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
  724. DefineFmt("__PTRDIFF", TI.getPtrDiffType(0), TI, Builder);
  725. DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
  726. DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
  727. DefineFmt("__INTPTR", TI.getIntPtrType(), TI, Builder);
  728. DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
  729. DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
  730. DefineFmt("__SIZE", TI.getSizeType(), TI, Builder);
  731. DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
  732. DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
  733. DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
  734. DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
  735. DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
  736. DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
  737. DefineTypeSize("__SIG_ATOMIC_MAX__", TI.getSigAtomicType(), TI, Builder);
  738. DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder);
  739. DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder);
  740. DefineTypeWidth("__UINTMAX_WIDTH__", TI.getUIntMaxType(), TI, Builder);
  741. DefineType("__UINTPTR_TYPE__", TI.getUIntPtrType(), Builder);
  742. DefineFmt("__UINTPTR", TI.getUIntPtrType(), TI, Builder);
  743. DefineTypeWidth("__UINTPTR_WIDTH__", TI.getUIntPtrType(), TI, Builder);
  744. if (TI.hasFloat16Type())
  745. DefineFloatMacros(Builder, "FLT16", &TI.getHalfFormat(), "F16");
  746. DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F");
  747. DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), "");
  748. DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L");
  749. // Define a __POINTER_WIDTH__ macro for stdint.h.
  750. Builder.defineMacro("__POINTER_WIDTH__",
  751. Twine((int)TI.getPointerWidth(0)));
  752. // Define __BIGGEST_ALIGNMENT__ to be compatible with gcc.
  753. Builder.defineMacro("__BIGGEST_ALIGNMENT__",
  754. Twine(TI.getSuitableAlign() / TI.getCharWidth()) );
  755. if (!LangOpts.CharIsSigned)
  756. Builder.defineMacro("__CHAR_UNSIGNED__");
  757. if (!TargetInfo::isTypeSigned(TI.getWCharType()))
  758. Builder.defineMacro("__WCHAR_UNSIGNED__");
  759. if (!TargetInfo::isTypeSigned(TI.getWIntType()))
  760. Builder.defineMacro("__WINT_UNSIGNED__");
  761. // Define exact-width integer types for stdint.h
  762. DefineExactWidthIntType(TargetInfo::SignedChar, TI, Builder);
  763. if (TI.getShortWidth() > TI.getCharWidth())
  764. DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
  765. if (TI.getIntWidth() > TI.getShortWidth())
  766. DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
  767. if (TI.getLongWidth() > TI.getIntWidth())
  768. DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
  769. if (TI.getLongLongWidth() > TI.getLongWidth())
  770. DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
  771. DefineExactWidthIntType(TargetInfo::UnsignedChar, TI, Builder);
  772. DefineExactWidthIntTypeSize(TargetInfo::UnsignedChar, TI, Builder);
  773. DefineExactWidthIntTypeSize(TargetInfo::SignedChar, TI, Builder);
  774. if (TI.getShortWidth() > TI.getCharWidth()) {
  775. DefineExactWidthIntType(TargetInfo::UnsignedShort, TI, Builder);
  776. DefineExactWidthIntTypeSize(TargetInfo::UnsignedShort, TI, Builder);
  777. DefineExactWidthIntTypeSize(TargetInfo::SignedShort, TI, Builder);
  778. }
  779. if (TI.getIntWidth() > TI.getShortWidth()) {
  780. DefineExactWidthIntType(TargetInfo::UnsignedInt, TI, Builder);
  781. DefineExactWidthIntTypeSize(TargetInfo::UnsignedInt, TI, Builder);
  782. DefineExactWidthIntTypeSize(TargetInfo::SignedInt, TI, Builder);
  783. }
  784. if (TI.getLongWidth() > TI.getIntWidth()) {
  785. DefineExactWidthIntType(TargetInfo::UnsignedLong, TI, Builder);
  786. DefineExactWidthIntTypeSize(TargetInfo::UnsignedLong, TI, Builder);
  787. DefineExactWidthIntTypeSize(TargetInfo::SignedLong, TI, Builder);
  788. }
  789. if (TI.getLongLongWidth() > TI.getLongWidth()) {
  790. DefineExactWidthIntType(TargetInfo::UnsignedLongLong, TI, Builder);
  791. DefineExactWidthIntTypeSize(TargetInfo::UnsignedLongLong, TI, Builder);
  792. DefineExactWidthIntTypeSize(TargetInfo::SignedLongLong, TI, Builder);
  793. }
  794. DefineLeastWidthIntType(8, true, TI, Builder);
  795. DefineLeastWidthIntType(8, false, TI, Builder);
  796. DefineLeastWidthIntType(16, true, TI, Builder);
  797. DefineLeastWidthIntType(16, false, TI, Builder);
  798. DefineLeastWidthIntType(32, true, TI, Builder);
  799. DefineLeastWidthIntType(32, false, TI, Builder);
  800. DefineLeastWidthIntType(64, true, TI, Builder);
  801. DefineLeastWidthIntType(64, false, TI, Builder);
  802. DefineFastIntType(8, true, TI, Builder);
  803. DefineFastIntType(8, false, TI, Builder);
  804. DefineFastIntType(16, true, TI, Builder);
  805. DefineFastIntType(16, false, TI, Builder);
  806. DefineFastIntType(32, true, TI, Builder);
  807. DefineFastIntType(32, false, TI, Builder);
  808. DefineFastIntType(64, true, TI, Builder);
  809. DefineFastIntType(64, false, TI, Builder);
  810. char UserLabelPrefix[2] = {TI.getDataLayout().getGlobalPrefix(), 0};
  811. Builder.defineMacro("__USER_LABEL_PREFIX__", UserLabelPrefix);
  812. if (LangOpts.FastMath || LangOpts.FiniteMathOnly)
  813. Builder.defineMacro("__FINITE_MATH_ONLY__", "1");
  814. else
  815. Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
  816. if (LangOpts.GNUCVersion) {
  817. if (LangOpts.GNUInline || LangOpts.CPlusPlus)
  818. Builder.defineMacro("__GNUC_GNU_INLINE__");
  819. else
  820. Builder.defineMacro("__GNUC_STDC_INLINE__");
  821. // The value written by __atomic_test_and_set.
  822. // FIXME: This is target-dependent.
  823. Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
  824. }
  825. auto addLockFreeMacros = [&](const llvm::Twine &Prefix) {
  826. // Used by libc++ and libstdc++ to implement ATOMIC_<foo>_LOCK_FREE.
  827. unsigned InlineWidthBits = TI.getMaxAtomicInlineWidth();
  828. #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \
  829. Builder.defineMacro(Prefix + #TYPE "_LOCK_FREE", \
  830. getLockFreeValue(TI.get##Type##Width(), \
  831. TI.get##Type##Align(), \
  832. InlineWidthBits));
  833. DEFINE_LOCK_FREE_MACRO(BOOL, Bool);
  834. DEFINE_LOCK_FREE_MACRO(CHAR, Char);
  835. if (LangOpts.Char8)
  836. DEFINE_LOCK_FREE_MACRO(CHAR8_T, Char); // Treat char8_t like char.
  837. DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16);
  838. DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32);
  839. DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar);
  840. DEFINE_LOCK_FREE_MACRO(SHORT, Short);
  841. DEFINE_LOCK_FREE_MACRO(INT, Int);
  842. DEFINE_LOCK_FREE_MACRO(LONG, Long);
  843. DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
  844. Builder.defineMacro(Prefix + "POINTER_LOCK_FREE",
  845. getLockFreeValue(TI.getPointerWidth(0),
  846. TI.getPointerAlign(0),
  847. InlineWidthBits));
  848. #undef DEFINE_LOCK_FREE_MACRO
  849. };
  850. addLockFreeMacros("__CLANG_ATOMIC_");
  851. if (LangOpts.GNUCVersion)
  852. addLockFreeMacros("__GCC_ATOMIC_");
  853. if (LangOpts.NoInlineDefine)
  854. Builder.defineMacro("__NO_INLINE__");
  855. if (unsigned PICLevel = LangOpts.PICLevel) {
  856. Builder.defineMacro("__PIC__", Twine(PICLevel));
  857. Builder.defineMacro("__pic__", Twine(PICLevel));
  858. if (LangOpts.PIE) {
  859. Builder.defineMacro("__PIE__", Twine(PICLevel));
  860. Builder.defineMacro("__pie__", Twine(PICLevel));
  861. }
  862. }
  863. // Macros to control C99 numerics and <float.h>
  864. Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod()));
  865. Builder.defineMacro("__FLT_RADIX__", "2");
  866. Builder.defineMacro("__DECIMAL_DIG__", "__LDBL_DECIMAL_DIG__");
  867. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  868. Builder.defineMacro("__SSP__");
  869. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  870. Builder.defineMacro("__SSP_STRONG__", "2");
  871. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  872. Builder.defineMacro("__SSP_ALL__", "3");
  873. if (PPOpts.SetUpStaticAnalyzer)
  874. Builder.defineMacro("__clang_analyzer__");
  875. if (LangOpts.FastRelaxedMath)
  876. Builder.defineMacro("__FAST_RELAXED_MATH__");
  877. if (FEOpts.ProgramAction == frontend::RewriteObjC ||
  878. LangOpts.getGC() != LangOptions::NonGC) {
  879. Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
  880. Builder.defineMacro("__strong", "__attribute__((objc_gc(strong)))");
  881. Builder.defineMacro("__autoreleasing", "");
  882. Builder.defineMacro("__unsafe_unretained", "");
  883. } else if (LangOpts.ObjC) {
  884. Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))");
  885. Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))");
  886. Builder.defineMacro("__autoreleasing",
  887. "__attribute__((objc_ownership(autoreleasing)))");
  888. Builder.defineMacro("__unsafe_unretained",
  889. "__attribute__((objc_ownership(none)))");
  890. }
  891. // On Darwin, there are __double_underscored variants of the type
  892. // nullability qualifiers.
  893. if (TI.getTriple().isOSDarwin()) {
  894. Builder.defineMacro("__nonnull", "_Nonnull");
  895. Builder.defineMacro("__null_unspecified", "_Null_unspecified");
  896. Builder.defineMacro("__nullable", "_Nullable");
  897. }
  898. // Add a macro to differentiate between regular iOS/tvOS/watchOS targets and
  899. // the corresponding simulator targets.
  900. if (TI.getTriple().isOSDarwin() && TI.getTriple().isSimulatorEnvironment())
  901. Builder.defineMacro("__APPLE_EMBEDDED_SIMULATOR__", "1");
  902. // OpenMP definition
  903. // OpenMP 2.2:
  904. // In implementations that support a preprocessor, the _OPENMP
  905. // macro name is defined to have the decimal value yyyymm where
  906. // yyyy and mm are the year and the month designations of the
  907. // version of the OpenMP API that the implementation support.
  908. if (!LangOpts.OpenMPSimd) {
  909. switch (LangOpts.OpenMP) {
  910. case 0:
  911. break;
  912. case 31:
  913. Builder.defineMacro("_OPENMP", "201107");
  914. break;
  915. case 40:
  916. Builder.defineMacro("_OPENMP", "201307");
  917. break;
  918. case 50:
  919. Builder.defineMacro("_OPENMP", "201811");
  920. break;
  921. default:
  922. // Default version is OpenMP 4.5
  923. Builder.defineMacro("_OPENMP", "201511");
  924. break;
  925. }
  926. }
  927. // CUDA device path compilaton
  928. if (LangOpts.CUDAIsDevice && !LangOpts.HIP) {
  929. // The CUDA_ARCH value is set for the GPU target specified in the NVPTX
  930. // backend's target defines.
  931. Builder.defineMacro("__CUDA_ARCH__");
  932. }
  933. // We need to communicate this to our CUDA header wrapper, which in turn
  934. // informs the proper CUDA headers of this choice.
  935. if (LangOpts.CUDADeviceApproxTranscendentals || LangOpts.FastMath) {
  936. Builder.defineMacro("__CLANG_CUDA_APPROX_TRANSCENDENTALS__");
  937. }
  938. // Define a macro indicating that the source file is being compiled with a
  939. // SYCL device compiler which doesn't produce host binary.
  940. if (LangOpts.SYCLIsDevice) {
  941. Builder.defineMacro("__SYCL_DEVICE_ONLY__", "1");
  942. }
  943. // OpenCL definitions.
  944. if (LangOpts.OpenCL) {
  945. #define OPENCLEXT(Ext) \
  946. if (TI.getSupportedOpenCLOpts().isSupported(#Ext, LangOpts)) \
  947. Builder.defineMacro(#Ext);
  948. #include "clang/Basic/OpenCLExtensions.def"
  949. if (TI.getTriple().isSPIR())
  950. Builder.defineMacro("__IMAGE_SUPPORT__");
  951. }
  952. if (TI.hasInt128Type() && LangOpts.CPlusPlus && LangOpts.GNUMode) {
  953. // For each extended integer type, g++ defines a macro mapping the
  954. // index of the type (0 in this case) in some list of extended types
  955. // to the type.
  956. Builder.defineMacro("__GLIBCXX_TYPE_INT_N_0", "__int128");
  957. Builder.defineMacro("__GLIBCXX_BITSIZE_INT_N_0", "128");
  958. }
  959. // Get other target #defines.
  960. TI.getTargetDefines(LangOpts, Builder);
  961. }
  962. /// InitializePreprocessor - Initialize the preprocessor getting it and the
  963. /// environment ready to process a single file. This returns true on error.
  964. ///
  965. void clang::InitializePreprocessor(
  966. Preprocessor &PP, const PreprocessorOptions &InitOpts,
  967. const PCHContainerReader &PCHContainerRdr,
  968. const FrontendOptions &FEOpts) {
  969. const LangOptions &LangOpts = PP.getLangOpts();
  970. std::string PredefineBuffer;
  971. PredefineBuffer.reserve(4080);
  972. llvm::raw_string_ostream Predefines(PredefineBuffer);
  973. MacroBuilder Builder(Predefines);
  974. // Emit line markers for various builtin sections of the file. We don't do
  975. // this in asm preprocessor mode, because "# 4" is not a line marker directive
  976. // in this mode.
  977. if (!PP.getLangOpts().AsmPreprocessor)
  978. Builder.append("# 1 \"<built-in>\" 3");
  979. // Install things like __POWERPC__, __GNUC__, etc into the macro table.
  980. if (InitOpts.UsePredefines) {
  981. // FIXME: This will create multiple definitions for most of the predefined
  982. // macros. This is not the right way to handle this.
  983. if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice) && PP.getAuxTargetInfo())
  984. InitializePredefinedMacros(*PP.getAuxTargetInfo(), LangOpts, FEOpts,
  985. PP.getPreprocessorOpts(), Builder);
  986. InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts,
  987. PP.getPreprocessorOpts(), Builder);
  988. // Install definitions to make Objective-C++ ARC work well with various
  989. // C++ Standard Library implementations.
  990. if (LangOpts.ObjC && LangOpts.CPlusPlus &&
  991. (LangOpts.ObjCAutoRefCount || LangOpts.ObjCWeak)) {
  992. switch (InitOpts.ObjCXXARCStandardLibrary) {
  993. case ARCXX_nolib:
  994. case ARCXX_libcxx:
  995. break;
  996. case ARCXX_libstdcxx:
  997. AddObjCXXARCLibstdcxxDefines(LangOpts, Builder);
  998. break;
  999. }
  1000. }
  1001. }
  1002. // Even with predefines off, some macros are still predefined.
  1003. // These should all be defined in the preprocessor according to the
  1004. // current language configuration.
  1005. InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOpts(),
  1006. FEOpts, Builder);
  1007. // Add on the predefines from the driver. Wrap in a #line directive to report
  1008. // that they come from the command line.
  1009. if (!PP.getLangOpts().AsmPreprocessor)
  1010. Builder.append("# 1 \"<command line>\" 1");
  1011. // Process #define's and #undef's in the order they are given.
  1012. for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
  1013. if (InitOpts.Macros[i].second) // isUndef
  1014. Builder.undefineMacro(InitOpts.Macros[i].first);
  1015. else
  1016. DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
  1017. PP.getDiagnostics());
  1018. }
  1019. // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
  1020. if (!PP.getLangOpts().AsmPreprocessor)
  1021. Builder.append("# 1 \"<built-in>\" 2");
  1022. // If -imacros are specified, include them now. These are processed before
  1023. // any -include directives.
  1024. for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
  1025. AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i]);
  1026. // Process -include-pch/-include-pth directives.
  1027. if (!InitOpts.ImplicitPCHInclude.empty())
  1028. AddImplicitIncludePCH(Builder, PP, PCHContainerRdr,
  1029. InitOpts.ImplicitPCHInclude);
  1030. // Process -include directives.
  1031. for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
  1032. const std::string &Path = InitOpts.Includes[i];
  1033. AddImplicitInclude(Builder, Path);
  1034. }
  1035. // Instruct the preprocessor to skip the preamble.
  1036. PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first,
  1037. InitOpts.PrecompiledPreambleBytes.second);
  1038. // Copy PredefinedBuffer into the Preprocessor.
  1039. PP.setPredefines(Predefines.str());
  1040. }