InitPreprocessor.cpp 50 KB

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