InitPreprocessor.cpp 28 KB

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