InitPreprocessor.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. //===--- InitPreprocessor.cpp - PP initialization code. ---------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the clang::InitializePreprocessor function.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Frontend/Utils.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/MacroBuilder.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "clang/Basic/Version.h"
  19. #include "clang/Frontend/FrontendDiagnostic.h"
  20. #include "clang/Frontend/FrontendOptions.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/Support/FileSystem.h"
  27. #include "llvm/Support/MemoryBuffer.h"
  28. #include "llvm/Support/Path.h"
  29. using namespace clang;
  30. static bool MacroBodyEndsInBackslash(StringRef MacroBody) {
  31. while (!MacroBody.empty() && isWhitespace(MacroBody.back()))
  32. MacroBody = MacroBody.drop_back();
  33. return !MacroBody.empty() && MacroBody.back() == '\\';
  34. }
  35. // Append a #define line to Buf for Macro. Macro should be of the form XXX,
  36. // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
  37. // "#define XXX Y z W". To get a #define with no value, use "XXX=".
  38. static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro,
  39. DiagnosticsEngine &Diags) {
  40. std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
  41. StringRef MacroName = MacroPair.first;
  42. StringRef MacroBody = MacroPair.second;
  43. if (MacroName.size() != Macro.size()) {
  44. // Per GCC -D semantics, the macro ends at \n if it exists.
  45. StringRef::size_type End = MacroBody.find_first_of("\n\r");
  46. if (End != StringRef::npos)
  47. Diags.Report(diag::warn_fe_macro_contains_embedded_newline)
  48. << MacroName;
  49. MacroBody = MacroBody.substr(0, End);
  50. // We handle macro bodies which end in a backslash by appending an extra
  51. // backslash+newline. This makes sure we don't accidentally treat the
  52. // backslash as a line continuation marker.
  53. if (MacroBodyEndsInBackslash(MacroBody))
  54. Builder.defineMacro(MacroName, Twine(MacroBody) + "\\\n");
  55. else
  56. Builder.defineMacro(MacroName, MacroBody);
  57. } else {
  58. // Push "macroname 1".
  59. Builder.defineMacro(Macro);
  60. }
  61. }
  62. /// AddImplicitInclude - Add an implicit \#include of the specified file to the
  63. /// predefines buffer.
  64. static void AddImplicitInclude(MacroBuilder &Builder, StringRef File,
  65. FileManager &FileMgr) {
  66. Builder.append(Twine("#include \"") +
  67. HeaderSearch::NormalizeDashIncludePath(File, FileMgr) + "\"");
  68. }
  69. static void AddImplicitIncludeMacros(MacroBuilder &Builder,
  70. StringRef File,
  71. FileManager &FileMgr) {
  72. Builder.append(Twine("#__include_macros \"") +
  73. HeaderSearch::NormalizeDashIncludePath(File, FileMgr) + "\"");
  74. // Marker token to stop the __include_macros fetch loop.
  75. Builder.append("##"); // ##?
  76. }
  77. /// AddImplicitIncludePTH - Add an implicit \#include using the original file
  78. /// used to generate a PTH cache.
  79. static void AddImplicitIncludePTH(MacroBuilder &Builder, Preprocessor &PP,
  80. StringRef ImplicitIncludePTH) {
  81. PTHManager *P = PP.getPTHManager();
  82. // Null check 'P' in the corner case where it couldn't be created.
  83. const char *OriginalFile = P ? P->getOriginalSourceFile() : 0;
  84. if (!OriginalFile) {
  85. PP.getDiagnostics().Report(diag::err_fe_pth_file_has_no_source_header)
  86. << ImplicitIncludePTH;
  87. return;
  88. }
  89. AddImplicitInclude(Builder, OriginalFile, PP.getFileManager());
  90. }
  91. /// \brief Add an implicit \#include using the original file used to generate
  92. /// a PCH file.
  93. static void AddImplicitIncludePCH(MacroBuilder &Builder, Preprocessor &PP,
  94. StringRef ImplicitIncludePCH) {
  95. std::string OriginalFile =
  96. ASTReader::getOriginalSourceFile(ImplicitIncludePCH, PP.getFileManager(),
  97. PP.getDiagnostics());
  98. if (OriginalFile.empty())
  99. return;
  100. AddImplicitInclude(Builder, OriginalFile, PP.getFileManager());
  101. }
  102. /// PickFP - This is used to pick a value based on the FP semantics of the
  103. /// specified FP model.
  104. template <typename T>
  105. static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
  106. T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
  107. T IEEEQuadVal) {
  108. if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle)
  109. return IEEESingleVal;
  110. if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble)
  111. return IEEEDoubleVal;
  112. if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended)
  113. return X87DoubleExtendedVal;
  114. if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble)
  115. return PPCDoubleDoubleVal;
  116. assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad);
  117. return IEEEQuadVal;
  118. }
  119. static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
  120. const llvm::fltSemantics *Sem, StringRef Ext) {
  121. const char *DenormMin, *Epsilon, *Max, *Min;
  122. DenormMin = PickFP(Sem, "1.40129846e-45", "4.9406564584124654e-324",
  123. "3.64519953188247460253e-4951",
  124. "4.94065645841246544176568792868221e-324",
  125. "6.47517511943802511092443895822764655e-4966");
  126. int Digits = PickFP(Sem, 6, 15, 18, 31, 33);
  127. Epsilon = PickFP(Sem, "1.19209290e-7", "2.2204460492503131e-16",
  128. "1.08420217248550443401e-19",
  129. "4.94065645841246544176568792868221e-324",
  130. "1.92592994438723585305597794258492732e-34");
  131. int MantissaDigits = PickFP(Sem, 24, 53, 64, 106, 113);
  132. int Min10Exp = PickFP(Sem, -37, -307, -4931, -291, -4931);
  133. int Max10Exp = PickFP(Sem, 38, 308, 4932, 308, 4932);
  134. int MinExp = PickFP(Sem, -125, -1021, -16381, -968, -16381);
  135. int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024, 16384);
  136. Min = PickFP(Sem, "1.17549435e-38", "2.2250738585072014e-308",
  137. "3.36210314311209350626e-4932",
  138. "2.00416836000897277799610805135016e-292",
  139. "3.36210314311209350626267781732175260e-4932");
  140. Max = PickFP(Sem, "3.40282347e+38", "1.7976931348623157e+308",
  141. "1.18973149535723176502e+4932",
  142. "1.79769313486231580793728971405301e+308",
  143. "1.18973149535723176508575932662800702e+4932");
  144. SmallString<32> DefPrefix;
  145. DefPrefix = "__";
  146. DefPrefix += Prefix;
  147. DefPrefix += "_";
  148. Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
  149. Builder.defineMacro(DefPrefix + "HAS_DENORM__");
  150. Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
  151. Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon)+Ext);
  152. Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
  153. Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
  154. Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits));
  155. Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp));
  156. Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp));
  157. Builder.defineMacro(DefPrefix + "MAX__", Twine(Max)+Ext);
  158. Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")");
  159. Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")");
  160. Builder.defineMacro(DefPrefix + "MIN__", Twine(Min)+Ext);
  161. }
  162. /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
  163. /// named MacroName with the max value for a type with width 'TypeWidth' a
  164. /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
  165. static void DefineTypeSize(StringRef MacroName, unsigned TypeWidth,
  166. StringRef ValSuffix, bool isSigned,
  167. MacroBuilder &Builder) {
  168. llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth)
  169. : llvm::APInt::getMaxValue(TypeWidth);
  170. Builder.defineMacro(MacroName, MaxVal.toString(10, isSigned) + ValSuffix);
  171. }
  172. /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
  173. /// the width, suffix, and signedness of the given type
  174. static void DefineTypeSize(StringRef MacroName, TargetInfo::IntType Ty,
  175. const TargetInfo &TI, MacroBuilder &Builder) {
  176. DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
  177. TI.isTypeSigned(Ty), Builder);
  178. }
  179. static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
  180. MacroBuilder &Builder) {
  181. Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
  182. }
  183. static void DefineTypeWidth(StringRef MacroName, TargetInfo::IntType Ty,
  184. const TargetInfo &TI, MacroBuilder &Builder) {
  185. Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty)));
  186. }
  187. static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth,
  188. const TargetInfo &TI, MacroBuilder &Builder) {
  189. Builder.defineMacro(MacroName,
  190. Twine(BitWidth / TI.getCharWidth()));
  191. }
  192. static void DefineExactWidthIntType(TargetInfo::IntType Ty,
  193. const TargetInfo &TI, MacroBuilder &Builder) {
  194. int TypeWidth = TI.getTypeWidth(Ty);
  195. // Use the target specified int64 type, when appropriate, so that [u]int64_t
  196. // ends up being defined in terms of the correct type.
  197. if (TypeWidth == 64)
  198. Ty = TI.getInt64Type();
  199. DefineType("__INT" + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
  200. StringRef ConstSuffix(TargetInfo::getTypeConstantSuffix(Ty));
  201. if (!ConstSuffix.empty())
  202. Builder.defineMacro("__INT" + Twine(TypeWidth) + "_C_SUFFIX__",
  203. ConstSuffix);
  204. }
  205. /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
  206. /// the specified properties.
  207. static const char *getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign,
  208. unsigned InlineWidth) {
  209. // Fully-aligned, power-of-2 sizes no larger than the inline
  210. // width will be inlined as lock-free operations.
  211. if (TypeWidth == TypeAlign && (TypeWidth & (TypeWidth - 1)) == 0 &&
  212. TypeWidth <= InlineWidth)
  213. return "2"; // "always lock free"
  214. // We cannot be certain what operations the lib calls might be
  215. // able to implement as lock-free on future processors.
  216. return "1"; // "sometimes lock free"
  217. }
  218. /// \brief Add definitions required for a smooth interaction between
  219. /// Objective-C++ automated reference counting and libstdc++ (4.2).
  220. static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts,
  221. MacroBuilder &Builder) {
  222. Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR");
  223. std::string Result;
  224. {
  225. // Provide specializations for the __is_scalar type trait so that
  226. // lifetime-qualified objects are not considered "scalar" types, which
  227. // libstdc++ uses as an indicator of the presence of trivial copy, assign,
  228. // default-construct, and destruct semantics (none of which hold for
  229. // lifetime-qualified objects in ARC).
  230. llvm::raw_string_ostream Out(Result);
  231. Out << "namespace std {\n"
  232. << "\n"
  233. << "struct __true_type;\n"
  234. << "struct __false_type;\n"
  235. << "\n";
  236. Out << "template<typename _Tp> struct __is_scalar;\n"
  237. << "\n";
  238. Out << "template<typename _Tp>\n"
  239. << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n"
  240. << " enum { __value = 0 };\n"
  241. << " typedef __false_type __type;\n"
  242. << "};\n"
  243. << "\n";
  244. if (LangOpts.ObjCARCWeak) {
  245. Out << "template<typename _Tp>\n"
  246. << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n"
  247. << " enum { __value = 0 };\n"
  248. << " typedef __false_type __type;\n"
  249. << "};\n"
  250. << "\n";
  251. }
  252. Out << "template<typename _Tp>\n"
  253. << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))"
  254. << " _Tp> {\n"
  255. << " enum { __value = 0 };\n"
  256. << " typedef __false_type __type;\n"
  257. << "};\n"
  258. << "\n";
  259. Out << "}\n";
  260. }
  261. Builder.append(Result);
  262. }
  263. static void InitializeStandardPredefinedMacros(const TargetInfo &TI,
  264. const LangOptions &LangOpts,
  265. const FrontendOptions &FEOpts,
  266. MacroBuilder &Builder) {
  267. if (!LangOpts.MicrosoftMode && !LangOpts.TraditionalCPP)
  268. Builder.defineMacro("__STDC__");
  269. if (LangOpts.Freestanding)
  270. Builder.defineMacro("__STDC_HOSTED__", "0");
  271. else
  272. Builder.defineMacro("__STDC_HOSTED__");
  273. if (!LangOpts.CPlusPlus) {
  274. if (LangOpts.C11)
  275. Builder.defineMacro("__STDC_VERSION__", "201112L");
  276. else if (LangOpts.C99)
  277. Builder.defineMacro("__STDC_VERSION__", "199901L");
  278. else if (!LangOpts.GNUMode && LangOpts.Digraphs)
  279. Builder.defineMacro("__STDC_VERSION__", "199409L");
  280. } else {
  281. // FIXME: Use the right value for __cplusplus for C++1y once one is chosen.
  282. if (LangOpts.CPlusPlus1y)
  283. Builder.defineMacro("__cplusplus", "201305L");
  284. // C++11 [cpp.predefined]p1:
  285. // The name __cplusplus is defined to the value 201103L when compiling a
  286. // C++ translation unit.
  287. else if (LangOpts.CPlusPlus11)
  288. Builder.defineMacro("__cplusplus", "201103L");
  289. // C++03 [cpp.predefined]p1:
  290. // The name __cplusplus is defined to the value 199711L when compiling a
  291. // C++ translation unit.
  292. else
  293. Builder.defineMacro("__cplusplus", "199711L");
  294. }
  295. if (LangOpts.ObjC1)
  296. Builder.defineMacro("__OBJC__");
  297. // Not "standard" per se, but available even with the -undef flag.
  298. if (LangOpts.AsmPreprocessor)
  299. Builder.defineMacro("__ASSEMBLER__");
  300. }
  301. static void InitializePredefinedMacros(const TargetInfo &TI,
  302. const LangOptions &LangOpts,
  303. const FrontendOptions &FEOpts,
  304. MacroBuilder &Builder) {
  305. // Compiler version introspection macros.
  306. Builder.defineMacro("__llvm__"); // LLVM Backend
  307. Builder.defineMacro("__clang__"); // Clang Frontend
  308. #define TOSTR2(X) #X
  309. #define TOSTR(X) TOSTR2(X)
  310. Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
  311. Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
  312. #ifdef CLANG_VERSION_PATCHLEVEL
  313. Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
  314. #else
  315. Builder.defineMacro("__clang_patchlevel__", "0");
  316. #endif
  317. Builder.defineMacro("__clang_version__",
  318. "\"" CLANG_VERSION_STRING " "
  319. + getClangFullRepositoryVersion() + "\"");
  320. #undef TOSTR
  321. #undef TOSTR2
  322. if (!LangOpts.MicrosoftMode) {
  323. // Currently claim to be compatible with GCC 4.2.1-5621, but only if we're
  324. // not compiling for MSVC compatibility
  325. Builder.defineMacro("__GNUC_MINOR__", "2");
  326. Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
  327. Builder.defineMacro("__GNUC__", "4");
  328. Builder.defineMacro("__GXX_ABI_VERSION", "1002");
  329. }
  330. // Define macros for the C11 / C++11 memory orderings
  331. Builder.defineMacro("__ATOMIC_RELAXED", "0");
  332. Builder.defineMacro("__ATOMIC_CONSUME", "1");
  333. Builder.defineMacro("__ATOMIC_ACQUIRE", "2");
  334. Builder.defineMacro("__ATOMIC_RELEASE", "3");
  335. Builder.defineMacro("__ATOMIC_ACQ_REL", "4");
  336. Builder.defineMacro("__ATOMIC_SEQ_CST", "5");
  337. // Support for #pragma redefine_extname (Sun compatibility)
  338. Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1");
  339. // As sad as it is, enough software depends on the __VERSION__ for version
  340. // checks that it is necessary to report 4.2.1 (the base GCC version we claim
  341. // compatibility with) first.
  342. Builder.defineMacro("__VERSION__", "\"4.2.1 Compatible " +
  343. Twine(getClangFullCPPVersion()) + "\"");
  344. // Initialize language-specific preprocessor defines.
  345. // Standard conforming mode?
  346. if (!LangOpts.GNUMode)
  347. Builder.defineMacro("__STRICT_ANSI__");
  348. if (LangOpts.CPlusPlus11)
  349. Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
  350. if (LangOpts.ObjC1) {
  351. if (LangOpts.ObjCRuntime.isNonFragile()) {
  352. Builder.defineMacro("__OBJC2__");
  353. if (LangOpts.ObjCExceptions)
  354. Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
  355. }
  356. if (LangOpts.getGC() != LangOptions::NonGC)
  357. Builder.defineMacro("__OBJC_GC__");
  358. if (LangOpts.ObjCRuntime.isNeXTFamily())
  359. Builder.defineMacro("__NEXT_RUNTIME__");
  360. Builder.defineMacro("IBOutlet", "__attribute__((iboutlet))");
  361. Builder.defineMacro("IBOutletCollection(ClassName)",
  362. "__attribute__((iboutletcollection(ClassName)))");
  363. Builder.defineMacro("IBAction", "void)__attribute__((ibaction)");
  364. }
  365. // darwin_constant_cfstrings controls this. This is also dependent
  366. // on other things like the runtime I believe. This is set even for C code.
  367. if (!LangOpts.NoConstantCFStrings)
  368. Builder.defineMacro("__CONSTANT_CFSTRINGS__");
  369. if (LangOpts.ObjC2)
  370. Builder.defineMacro("OBJC_NEW_PROPERTIES");
  371. if (LangOpts.PascalStrings)
  372. Builder.defineMacro("__PASCAL_STRINGS__");
  373. if (LangOpts.Blocks) {
  374. Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
  375. Builder.defineMacro("__BLOCKS__");
  376. }
  377. if (LangOpts.CXXExceptions)
  378. Builder.defineMacro("__EXCEPTIONS");
  379. if (LangOpts.RTTI)
  380. Builder.defineMacro("__GXX_RTTI");
  381. if (LangOpts.SjLjExceptions)
  382. Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
  383. if (LangOpts.Deprecated)
  384. Builder.defineMacro("__DEPRECATED");
  385. if (LangOpts.CPlusPlus) {
  386. Builder.defineMacro("__GNUG__", "4");
  387. Builder.defineMacro("__GXX_WEAK__");
  388. Builder.defineMacro("__private_extern__", "extern");
  389. }
  390. if (LangOpts.MicrosoftExt) {
  391. // Both __PRETTY_FUNCTION__ and __FUNCTION__ are GCC extensions, however
  392. // VC++ appears to only like __FUNCTION__.
  393. Builder.defineMacro("__PRETTY_FUNCTION__", "__FUNCTION__");
  394. // Work around some issues with Visual C++ headers.
  395. if (LangOpts.WChar) {
  396. // wchar_t supported as a keyword.
  397. Builder.defineMacro("_WCHAR_T_DEFINED");
  398. Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
  399. }
  400. if (LangOpts.CPlusPlus) {
  401. // FIXME: Support Microsoft's __identifier extension in the lexer.
  402. Builder.append("#define __identifier(x) x");
  403. Builder.append("class type_info;");
  404. }
  405. }
  406. if (LangOpts.Optimize)
  407. Builder.defineMacro("__OPTIMIZE__");
  408. if (LangOpts.OptimizeSize)
  409. Builder.defineMacro("__OPTIMIZE_SIZE__");
  410. if (LangOpts.FastMath)
  411. Builder.defineMacro("__FAST_MATH__");
  412. // Initialize target-specific preprocessor defines.
  413. // __BYTE_ORDER__ was added in GCC 4.6. It's analogous
  414. // to the macro __BYTE_ORDER (no trailing underscores)
  415. // from glibc's <endian.h> header.
  416. // We don't support the PDP-11 as a target, but include
  417. // the define so it can still be compared against.
  418. Builder.defineMacro("__ORDER_LITTLE_ENDIAN__", "1234");
  419. Builder.defineMacro("__ORDER_BIG_ENDIAN__", "4321");
  420. Builder.defineMacro("__ORDER_PDP_ENDIAN__", "3412");
  421. if (TI.isBigEndian())
  422. Builder.defineMacro("__BYTE_ORDER__", "__ORDER_BIG_ENDIAN__");
  423. else
  424. Builder.defineMacro("__BYTE_ORDER__", "__ORDER_LITTLE_ENDIAN__");
  425. if (TI.getPointerWidth(0) == 64 && TI.getLongWidth() == 64
  426. && TI.getIntWidth() == 32) {
  427. Builder.defineMacro("_LP64");
  428. Builder.defineMacro("__LP64__");
  429. }
  430. // Define type sizing macros based on the target properties.
  431. assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
  432. Builder.defineMacro("__CHAR_BIT__", "8");
  433. DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Builder);
  434. DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
  435. DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
  436. DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
  437. DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
  438. DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
  439. DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
  440. DefineTypeSize("__SIZE_MAX__", TI.getSizeType(), TI, Builder);
  441. DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder);
  442. DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder);
  443. DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder);
  444. DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder);
  445. DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder);
  446. DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder);
  447. DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(0), TI, Builder);
  448. DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder);
  449. DefineTypeSizeof("__SIZEOF_PTRDIFF_T__",
  450. TI.getTypeWidth(TI.getPtrDiffType(0)), TI, Builder);
  451. DefineTypeSizeof("__SIZEOF_SIZE_T__",
  452. TI.getTypeWidth(TI.getSizeType()), TI, Builder);
  453. DefineTypeSizeof("__SIZEOF_WCHAR_T__",
  454. TI.getTypeWidth(TI.getWCharType()), TI, Builder);
  455. DefineTypeSizeof("__SIZEOF_WINT_T__",
  456. TI.getTypeWidth(TI.getWIntType()), TI, Builder);
  457. if (TI.hasInt128Type())
  458. DefineTypeSizeof("__SIZEOF_INT128__", 128, TI, Builder);
  459. DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
  460. DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
  461. DefineTypeWidth("__INTMAX_WIDTH__", TI.getIntMaxType(), TI, Builder);
  462. DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
  463. DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
  464. DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
  465. DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
  466. DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
  467. DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
  468. DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
  469. DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
  470. DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
  471. DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
  472. DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
  473. DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder);
  474. DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder);
  475. DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F");
  476. DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), "");
  477. DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L");
  478. // Define a __POINTER_WIDTH__ macro for stdint.h.
  479. Builder.defineMacro("__POINTER_WIDTH__",
  480. Twine((int)TI.getPointerWidth(0)));
  481. if (!LangOpts.CharIsSigned)
  482. Builder.defineMacro("__CHAR_UNSIGNED__");
  483. if (!TargetInfo::isTypeSigned(TI.getWCharType()))
  484. Builder.defineMacro("__WCHAR_UNSIGNED__");
  485. if (!TargetInfo::isTypeSigned(TI.getWIntType()))
  486. Builder.defineMacro("__WINT_UNSIGNED__");
  487. // Define exact-width integer types for stdint.h
  488. Builder.defineMacro("__INT" + Twine(TI.getCharWidth()) + "_TYPE__",
  489. "char");
  490. if (TI.getShortWidth() > TI.getCharWidth())
  491. DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
  492. if (TI.getIntWidth() > TI.getShortWidth())
  493. DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
  494. if (TI.getLongWidth() > TI.getIntWidth())
  495. DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
  496. if (TI.getLongLongWidth() > TI.getLongWidth())
  497. DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
  498. if (const char *Prefix = TI.getUserLabelPrefix())
  499. Builder.defineMacro("__USER_LABEL_PREFIX__", Prefix);
  500. if (LangOpts.FastMath || LangOpts.FiniteMathOnly)
  501. Builder.defineMacro("__FINITE_MATH_ONLY__", "1");
  502. else
  503. Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
  504. if (LangOpts.GNUInline)
  505. Builder.defineMacro("__GNUC_GNU_INLINE__");
  506. else
  507. Builder.defineMacro("__GNUC_STDC_INLINE__");
  508. // The value written by __atomic_test_and_set.
  509. // FIXME: This is target-dependent.
  510. Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
  511. // Used by libstdc++ to implement ATOMIC_<foo>_LOCK_FREE.
  512. unsigned InlineWidthBits = TI.getMaxAtomicInlineWidth();
  513. #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \
  514. Builder.defineMacro("__GCC_ATOMIC_" #TYPE "_LOCK_FREE", \
  515. getLockFreeValue(TI.get##Type##Width(), \
  516. TI.get##Type##Align(), \
  517. InlineWidthBits));
  518. DEFINE_LOCK_FREE_MACRO(BOOL, Bool);
  519. DEFINE_LOCK_FREE_MACRO(CHAR, Char);
  520. DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16);
  521. DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32);
  522. DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar);
  523. DEFINE_LOCK_FREE_MACRO(SHORT, Short);
  524. DEFINE_LOCK_FREE_MACRO(INT, Int);
  525. DEFINE_LOCK_FREE_MACRO(LONG, Long);
  526. DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
  527. Builder.defineMacro("__GCC_ATOMIC_POINTER_LOCK_FREE",
  528. getLockFreeValue(TI.getPointerWidth(0),
  529. TI.getPointerAlign(0),
  530. InlineWidthBits));
  531. #undef DEFINE_LOCK_FREE_MACRO
  532. if (LangOpts.NoInlineDefine)
  533. Builder.defineMacro("__NO_INLINE__");
  534. if (unsigned PICLevel = LangOpts.PICLevel) {
  535. Builder.defineMacro("__PIC__", Twine(PICLevel));
  536. Builder.defineMacro("__pic__", Twine(PICLevel));
  537. }
  538. if (unsigned PIELevel = LangOpts.PIELevel) {
  539. Builder.defineMacro("__PIE__", Twine(PIELevel));
  540. Builder.defineMacro("__pie__", Twine(PIELevel));
  541. }
  542. // Macros to control C99 numerics and <float.h>
  543. Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod()));
  544. Builder.defineMacro("__FLT_RADIX__", "2");
  545. int Dig = PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36);
  546. Builder.defineMacro("__DECIMAL_DIG__", Twine(Dig));
  547. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  548. Builder.defineMacro("__SSP__");
  549. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  550. Builder.defineMacro("__SSP_ALL__", "2");
  551. if (FEOpts.ProgramAction == frontend::RewriteObjC)
  552. Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
  553. // Define a macro that exists only when using the static analyzer.
  554. if (FEOpts.ProgramAction == frontend::RunAnalysis)
  555. Builder.defineMacro("__clang_analyzer__");
  556. if (LangOpts.FastRelaxedMath)
  557. Builder.defineMacro("__FAST_RELAXED_MATH__");
  558. if (LangOpts.ObjCAutoRefCount) {
  559. Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))");
  560. Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))");
  561. Builder.defineMacro("__autoreleasing",
  562. "__attribute__((objc_ownership(autoreleasing)))");
  563. Builder.defineMacro("__unsafe_unretained",
  564. "__attribute__((objc_ownership(none)))");
  565. }
  566. // OpenMP definition
  567. if (LangOpts.OpenMP) {
  568. // OpenMP 2.2:
  569. // In implementations that support a preprocessor, the _OPENMP
  570. // macro name is defined to have the decimal value yyyymm where
  571. // yyyy and mm are the year and the month designations of the
  572. // version of the OpenMP API that the implementation support.
  573. Builder.defineMacro("_OPENMP", "201107");
  574. }
  575. // Get other target #defines.
  576. TI.getTargetDefines(LangOpts, Builder);
  577. }
  578. // Initialize the remapping of files to alternative contents, e.g.,
  579. // those specified through other files.
  580. static void InitializeFileRemapping(DiagnosticsEngine &Diags,
  581. SourceManager &SourceMgr,
  582. FileManager &FileMgr,
  583. const PreprocessorOptions &InitOpts) {
  584. // Remap files in the source manager (with buffers).
  585. for (PreprocessorOptions::const_remapped_file_buffer_iterator
  586. Remap = InitOpts.remapped_file_buffer_begin(),
  587. RemapEnd = InitOpts.remapped_file_buffer_end();
  588. Remap != RemapEnd;
  589. ++Remap) {
  590. // Create the file entry for the file that we're mapping from.
  591. const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
  592. Remap->second->getBufferSize(),
  593. 0);
  594. if (!FromFile) {
  595. Diags.Report(diag::err_fe_remap_missing_from_file)
  596. << Remap->first;
  597. if (!InitOpts.RetainRemappedFileBuffers)
  598. delete Remap->second;
  599. continue;
  600. }
  601. // Override the contents of the "from" file with the contents of
  602. // the "to" file.
  603. SourceMgr.overrideFileContents(FromFile, Remap->second,
  604. InitOpts.RetainRemappedFileBuffers);
  605. }
  606. // Remap files in the source manager (with other files).
  607. for (PreprocessorOptions::const_remapped_file_iterator
  608. Remap = InitOpts.remapped_file_begin(),
  609. RemapEnd = InitOpts.remapped_file_end();
  610. Remap != RemapEnd;
  611. ++Remap) {
  612. // Find the file that we're mapping to.
  613. const FileEntry *ToFile = FileMgr.getFile(Remap->second);
  614. if (!ToFile) {
  615. Diags.Report(diag::err_fe_remap_missing_to_file)
  616. << Remap->first << Remap->second;
  617. continue;
  618. }
  619. // Create the file entry for the file that we're mapping from.
  620. const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
  621. ToFile->getSize(), 0);
  622. if (!FromFile) {
  623. Diags.Report(diag::err_fe_remap_missing_from_file)
  624. << Remap->first;
  625. continue;
  626. }
  627. // Override the contents of the "from" file with the contents of
  628. // the "to" file.
  629. SourceMgr.overrideFileContents(FromFile, ToFile);
  630. }
  631. SourceMgr.setOverridenFilesKeepOriginalName(
  632. InitOpts.RemappedFilesKeepOriginalName);
  633. }
  634. /// InitializePreprocessor - Initialize the preprocessor getting it and the
  635. /// environment ready to process a single file. This returns true on error.
  636. ///
  637. void clang::InitializePreprocessor(Preprocessor &PP,
  638. const PreprocessorOptions &InitOpts,
  639. const HeaderSearchOptions &HSOpts,
  640. const FrontendOptions &FEOpts) {
  641. const LangOptions &LangOpts = PP.getLangOpts();
  642. std::string PredefineBuffer;
  643. PredefineBuffer.reserve(4080);
  644. llvm::raw_string_ostream Predefines(PredefineBuffer);
  645. MacroBuilder Builder(Predefines);
  646. InitializeFileRemapping(PP.getDiagnostics(), PP.getSourceManager(),
  647. PP.getFileManager(), InitOpts);
  648. // Emit line markers for various builtin sections of the file. We don't do
  649. // this in asm preprocessor mode, because "# 4" is not a line marker directive
  650. // in this mode.
  651. if (!PP.getLangOpts().AsmPreprocessor)
  652. Builder.append("# 1 \"<built-in>\" 3");
  653. // Install things like __POWERPC__, __GNUC__, etc into the macro table.
  654. if (InitOpts.UsePredefines) {
  655. InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, Builder);
  656. // Install definitions to make Objective-C++ ARC work well with various
  657. // C++ Standard Library implementations.
  658. if (LangOpts.ObjC1 && LangOpts.CPlusPlus && LangOpts.ObjCAutoRefCount) {
  659. switch (InitOpts.ObjCXXARCStandardLibrary) {
  660. case ARCXX_nolib:
  661. case ARCXX_libcxx:
  662. break;
  663. case ARCXX_libstdcxx:
  664. AddObjCXXARCLibstdcxxDefines(LangOpts, Builder);
  665. break;
  666. }
  667. }
  668. }
  669. // Even with predefines off, some macros are still predefined.
  670. // These should all be defined in the preprocessor according to the
  671. // current language configuration.
  672. InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOpts(),
  673. FEOpts, Builder);
  674. // Add on the predefines from the driver. Wrap in a #line directive to report
  675. // that they come from the command line.
  676. if (!PP.getLangOpts().AsmPreprocessor)
  677. Builder.append("# 1 \"<command line>\" 1");
  678. // Process #define's and #undef's in the order they are given.
  679. for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
  680. if (InitOpts.Macros[i].second) // isUndef
  681. Builder.undefineMacro(InitOpts.Macros[i].first);
  682. else
  683. DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
  684. PP.getDiagnostics());
  685. }
  686. // If -imacros are specified, include them now. These are processed before
  687. // any -include directives.
  688. for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
  689. AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i],
  690. PP.getFileManager());
  691. // Process -include-pch/-include-pth directives.
  692. if (!InitOpts.ImplicitPCHInclude.empty())
  693. AddImplicitIncludePCH(Builder, PP, InitOpts.ImplicitPCHInclude);
  694. if (!InitOpts.ImplicitPTHInclude.empty())
  695. AddImplicitIncludePTH(Builder, PP, InitOpts.ImplicitPTHInclude);
  696. // Process -include directives.
  697. for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
  698. const std::string &Path = InitOpts.Includes[i];
  699. AddImplicitInclude(Builder, Path, PP.getFileManager());
  700. }
  701. // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
  702. if (!PP.getLangOpts().AsmPreprocessor)
  703. Builder.append("# 1 \"<built-in>\" 2");
  704. // Instruct the preprocessor to skip the preamble.
  705. PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first,
  706. InitOpts.PrecompiledPreambleBytes.second);
  707. // Copy PredefinedBuffer into the Preprocessor.
  708. PP.setPredefines(Predefines.str());
  709. // Initialize the header search object.
  710. ApplyHeaderSearchOptions(PP.getHeaderSearchInfo(), HSOpts,
  711. PP.getLangOpts(),
  712. PP.getTargetInfo().getTriple());
  713. }