1 //===--- InitPreprocessor.cpp - PP initialization code. ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the clang::InitializePreprocessor function.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Basic/Version.h"
15 #include "clang/Frontend/Utils.h"
16 #include "clang/Basic/MacroBuilder.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Frontend/FrontendDiagnostic.h"
19 #include "clang/Frontend/FrontendOptions.h"
20 #include "clang/Frontend/PreprocessorOptions.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;
30 // Append a #define line to Buf for Macro. Macro should be of the form XXX,
31 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
32 // "#define XXX Y z W". To get a #define with no value, use "XXX=".
33 static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro,
34 DiagnosticsEngine &Diags) {
35 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
36 StringRef MacroName = MacroPair.first;
37 StringRef MacroBody = MacroPair.second;
38 if (MacroName.size() != Macro.size()) {
39 // Per GCC -D semantics, the macro ends at \n if it exists.
40 StringRef::size_type End = MacroBody.find_first_of("\n\r");
41 if (End != StringRef::npos)
42 Diags.Report(diag::warn_fe_macro_contains_embedded_newline)
44 Builder.defineMacro(MacroName, MacroBody.substr(0, End));
46 // Push "macroname 1".
47 Builder.defineMacro(Macro);
51 std::string clang::NormalizeDashIncludePath(StringRef File,
52 FileManager &FileMgr) {
53 // Implicit include paths should be resolved relative to the current
54 // working directory first, and then use the regular header search
55 // mechanism. The proper way to handle this is to have the
56 // predefines buffer located at the current working directory, but
57 // it has no file entry. For now, workaround this by using an
58 // absolute path if we find the file here, and otherwise letting
59 // header search handle it.
60 llvm::SmallString<128> Path(File);
61 llvm::sys::fs::make_absolute(Path);
63 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
66 FileMgr.getFile(File);
68 return Lexer::Stringify(Path.str());
71 /// AddImplicitInclude - Add an implicit #include of the specified file to the
72 /// predefines buffer.
73 static void AddImplicitInclude(MacroBuilder &Builder, StringRef File,
74 FileManager &FileMgr) {
75 Builder.append("#include \"" +
76 Twine(NormalizeDashIncludePath(File, FileMgr)) + "\"");
79 static void AddImplicitIncludeMacros(MacroBuilder &Builder,
81 FileManager &FileMgr) {
82 Builder.append("#__include_macros \"" +
83 Twine(NormalizeDashIncludePath(File, FileMgr)) + "\"");
84 // Marker token to stop the __include_macros fetch loop.
85 Builder.append("##"); // ##?
88 /// AddImplicitIncludePTH - Add an implicit #include using the original file
89 /// used to generate a PTH cache.
90 static void AddImplicitIncludePTH(MacroBuilder &Builder, Preprocessor &PP,
91 StringRef ImplicitIncludePTH) {
92 PTHManager *P = PP.getPTHManager();
93 // Null check 'P' in the corner case where it couldn't be created.
94 const char *OriginalFile = P ? P->getOriginalSourceFile() : 0;
97 PP.getDiagnostics().Report(diag::err_fe_pth_file_has_no_source_header)
98 << ImplicitIncludePTH;
102 AddImplicitInclude(Builder, OriginalFile, PP.getFileManager());
105 /// PickFP - This is used to pick a value based on the FP semantics of the
106 /// specified FP model.
107 template <typename T>
108 static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
109 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
111 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle)
112 return IEEESingleVal;
113 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble)
114 return IEEEDoubleVal;
115 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended)
116 return X87DoubleExtendedVal;
117 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble)
118 return PPCDoubleDoubleVal;
119 assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad);
123 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
124 const llvm::fltSemantics *Sem) {
125 const char *DenormMin, *Epsilon, *Max, *Min;
126 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
127 "3.64519953188247460253e-4951L",
128 "4.94065645841246544176568792868221e-324L",
129 "6.47517511943802511092443895822764655e-4966L");
130 int Digits = PickFP(Sem, 6, 15, 18, 31, 33);
131 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
132 "1.08420217248550443401e-19L",
133 "4.94065645841246544176568792868221e-324L",
134 "1.92592994438723585305597794258492732e-34L");
135 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106, 113);
136 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291, -4931);
137 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308, 4932);
138 int MinExp = PickFP(Sem, -125, -1021, -16381, -968, -16381);
139 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024, 16384);
140 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
141 "3.36210314311209350626e-4932L",
142 "2.00416836000897277799610805135016e-292L",
143 "3.36210314311209350626267781732175260e-4932L");
144 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
145 "1.18973149535723176502e+4932L",
146 "1.79769313486231580793728971405301e+308L",
147 "1.18973149535723176508575932662800702e+4932L");
149 llvm::SmallString<32> DefPrefix;
154 Builder.defineMacro(DefPrefix + "DENORM_MIN__", DenormMin);
155 Builder.defineMacro(DefPrefix + "HAS_DENORM__");
156 Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
157 Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon));
158 Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
159 Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
160 Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits));
162 Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp));
163 Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp));
164 Builder.defineMacro(DefPrefix + "MAX__", Twine(Max));
166 Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")");
167 Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")");
168 Builder.defineMacro(DefPrefix + "MIN__", Twine(Min));
172 /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
173 /// named MacroName with the max value for a type with width 'TypeWidth' a
174 /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
175 static void DefineTypeSize(StringRef MacroName, unsigned TypeWidth,
176 StringRef ValSuffix, bool isSigned,
177 MacroBuilder &Builder) {
178 llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth)
179 : llvm::APInt::getMaxValue(TypeWidth);
180 Builder.defineMacro(MacroName, MaxVal.toString(10, isSigned) + ValSuffix);
183 /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
184 /// the width, suffix, and signedness of the given type
185 static void DefineTypeSize(StringRef MacroName, TargetInfo::IntType Ty,
186 const TargetInfo &TI, MacroBuilder &Builder) {
187 DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
188 TI.isTypeSigned(Ty), Builder);
191 static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
192 MacroBuilder &Builder) {
193 Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
196 static void DefineTypeWidth(StringRef MacroName, TargetInfo::IntType Ty,
197 const TargetInfo &TI, MacroBuilder &Builder) {
198 Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty)));
201 static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth,
202 const TargetInfo &TI, MacroBuilder &Builder) {
203 Builder.defineMacro(MacroName,
204 Twine(BitWidth / TI.getCharWidth()));
207 static void DefineExactWidthIntType(TargetInfo::IntType Ty,
208 const TargetInfo &TI, MacroBuilder &Builder) {
209 int TypeWidth = TI.getTypeWidth(Ty);
211 // Use the target specified int64 type, when appropriate, so that [u]int64_t
212 // ends up being defined in terms of the correct type.
214 Ty = TI.getInt64Type();
216 DefineType("__INT" + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
218 StringRef ConstSuffix(TargetInfo::getTypeConstantSuffix(Ty));
219 if (!ConstSuffix.empty())
220 Builder.defineMacro("__INT" + Twine(TypeWidth) + "_C_SUFFIX__",
224 /// \brief Add definitions required for a smooth interaction between
225 /// Objective-C++ automated reference counting and libstdc++ (4.2).
226 static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts,
227 MacroBuilder &Builder) {
228 Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR");
232 // Provide specializations for the __is_scalar type trait so that
233 // lifetime-qualified objects are not considered "scalar" types, which
234 // libstdc++ uses as an indicator of the presence of trivial copy, assign,
235 // default-construct, and destruct semantics (none of which hold for
236 // lifetime-qualified objects in ARC).
237 llvm::raw_string_ostream Out(Result);
239 Out << "namespace std {\n"
241 << "struct __true_type;\n"
242 << "struct __false_type;\n"
245 Out << "template<typename _Tp> struct __is_scalar;\n"
248 Out << "template<typename _Tp>\n"
249 << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n"
250 << " enum { __value = 0 };\n"
251 << " typedef __false_type __type;\n"
255 if (LangOpts.ObjCRuntimeHasWeak) {
256 Out << "template<typename _Tp>\n"
257 << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n"
258 << " enum { __value = 0 };\n"
259 << " typedef __false_type __type;\n"
264 Out << "template<typename _Tp>\n"
265 << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))"
267 << " enum { __value = 0 };\n"
268 << " typedef __false_type __type;\n"
274 Builder.append(Result);
277 static void InitializeStandardPredefinedMacros(const TargetInfo &TI,
278 const LangOptions &LangOpts,
279 const FrontendOptions &FEOpts,
280 MacroBuilder &Builder) {
281 if (!LangOpts.MicrosoftExt && !LangOpts.TraditionalCPP)
282 Builder.defineMacro("__STDC__");
283 if (LangOpts.Freestanding)
284 Builder.defineMacro("__STDC_HOSTED__", "0");
286 Builder.defineMacro("__STDC_HOSTED__");
288 if (!LangOpts.CPlusPlus) {
290 Builder.defineMacro("__STDC_VERSION__", "199901L");
291 else if (!LangOpts.GNUMode && LangOpts.Digraphs)
292 Builder.defineMacro("__STDC_VERSION__", "199409L");
294 if (LangOpts.GNUMode)
295 Builder.defineMacro("__cplusplus");
297 // C++0x [cpp.predefined]p1:
298 // The name_ _cplusplus is defined to the value 201103L when compiling a
299 // C++ translation unit.
300 if (LangOpts.CPlusPlus0x)
301 Builder.defineMacro("__cplusplus", "201103L");
302 // C++03 [cpp.predefined]p1:
303 // The name_ _cplusplus is defined to the value 199711L when compiling a
304 // C++ translation unit.
306 Builder.defineMacro("__cplusplus", "199711L");
311 Builder.defineMacro("__OBJC__");
313 // Not "standard" per se, but available even with the -undef flag.
314 if (LangOpts.AsmPreprocessor)
315 Builder.defineMacro("__ASSEMBLER__");
318 static void InitializePredefinedMacros(const TargetInfo &TI,
319 const LangOptions &LangOpts,
320 const FrontendOptions &FEOpts,
321 MacroBuilder &Builder) {
322 // Compiler version introspection macros.
323 Builder.defineMacro("__llvm__"); // LLVM Backend
324 Builder.defineMacro("__clang__"); // Clang Frontend
326 #define TOSTR(X) TOSTR2(X)
327 Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
328 Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
329 #ifdef CLANG_VERSION_PATCHLEVEL
330 Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
332 Builder.defineMacro("__clang_patchlevel__", "0");
334 Builder.defineMacro("__clang_version__",
335 "\"" CLANG_VERSION_STRING " ("
336 + getClangFullRepositoryVersion() + ")\"");
339 // Currently claim to be compatible with GCC 4.2.1-5621.
340 Builder.defineMacro("__GNUC_MINOR__", "2");
341 Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
342 Builder.defineMacro("__GNUC__", "4");
343 Builder.defineMacro("__GXX_ABI_VERSION", "1002");
345 // As sad as it is, enough software depends on the __VERSION__ for version
346 // checks that it is necessary to report 4.2.1 (the base GCC version we claim
347 // compatibility with) first.
348 Builder.defineMacro("__VERSION__", "\"4.2.1 Compatible " +
349 Twine(getClangFullCPPVersion()) + "\"");
351 // Initialize language-specific preprocessor defines.
353 // Standard conforming mode?
354 if (!LangOpts.GNUMode)
355 Builder.defineMacro("__STRICT_ANSI__");
357 if (LangOpts.CPlusPlus0x)
358 Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
360 if (LangOpts.ObjC1) {
361 if (LangOpts.ObjCNonFragileABI) {
362 Builder.defineMacro("__OBJC2__");
364 if (LangOpts.ObjCExceptions)
365 Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
368 if (LangOpts.getGC() != LangOptions::NonGC)
369 Builder.defineMacro("__OBJC_GC__");
371 if (LangOpts.NeXTRuntime)
372 Builder.defineMacro("__NEXT_RUNTIME__");
375 // darwin_constant_cfstrings controls this. This is also dependent
376 // on other things like the runtime I believe. This is set even for C code.
377 if (!LangOpts.NoConstantCFStrings)
378 Builder.defineMacro("__CONSTANT_CFSTRINGS__");
381 Builder.defineMacro("OBJC_NEW_PROPERTIES");
383 if (LangOpts.PascalStrings)
384 Builder.defineMacro("__PASCAL_STRINGS__");
386 if (LangOpts.Blocks) {
387 Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
388 Builder.defineMacro("__BLOCKS__");
391 if (LangOpts.CXXExceptions)
392 Builder.defineMacro("__EXCEPTIONS");
394 Builder.defineMacro("__GXX_RTTI");
395 if (LangOpts.SjLjExceptions)
396 Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
398 if (LangOpts.Deprecated)
399 Builder.defineMacro("__DEPRECATED");
401 if (LangOpts.CPlusPlus) {
402 Builder.defineMacro("__GNUG__", "4");
403 Builder.defineMacro("__GXX_WEAK__");
404 Builder.defineMacro("__private_extern__", "extern");
407 if (LangOpts.MicrosoftExt) {
408 // Both __PRETTY_FUNCTION__ and __FUNCTION__ are GCC extensions, however
409 // VC++ appears to only like __FUNCTION__.
410 Builder.defineMacro("__PRETTY_FUNCTION__", "__FUNCTION__");
411 // Work around some issues with Visual C++ headerws.
412 if (LangOpts.CPlusPlus) {
413 // Since we define wchar_t in C++ mode.
414 Builder.defineMacro("_WCHAR_T_DEFINED");
415 Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
416 // FIXME: Support Microsoft's __identifier extension in the lexer.
417 Builder.append("#define __identifier(x) x");
418 Builder.append("class type_info;");
421 if (LangOpts.CPlusPlus0x) {
422 Builder.defineMacro("_HAS_CHAR16_T_LANGUAGE_SUPPORT", "1");
426 if (LangOpts.Optimize)
427 Builder.defineMacro("__OPTIMIZE__");
428 if (LangOpts.OptimizeSize)
429 Builder.defineMacro("__OPTIMIZE_SIZE__");
431 // Initialize target-specific preprocessor defines.
433 // Define type sizing macros based on the target properties.
434 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
435 Builder.defineMacro("__CHAR_BIT__", "8");
437 DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Builder);
438 DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
439 DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
440 DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
441 DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
442 DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
443 DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
445 DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder);
446 DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder);
447 DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder);
448 DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder);
449 DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder);
450 DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder);
451 DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(0), TI, Builder);
452 DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder);
453 DefineTypeSizeof("__SIZEOF_PTRDIFF_T__",
454 TI.getTypeWidth(TI.getPtrDiffType(0)), TI, Builder);
455 DefineTypeSizeof("__SIZEOF_SIZE_T__",
456 TI.getTypeWidth(TI.getSizeType()), TI, Builder);
457 DefineTypeSizeof("__SIZEOF_WCHAR_T__",
458 TI.getTypeWidth(TI.getWCharType()), TI, Builder);
459 DefineTypeSizeof("__SIZEOF_WINT_T__",
460 TI.getTypeWidth(TI.getWIntType()), TI, Builder);
462 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
463 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
464 DefineTypeWidth("__INTMAX_WIDTH__", TI.getIntMaxType(), TI, Builder);
465 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
466 DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
467 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
468 DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
469 DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
470 DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
471 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
472 DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
473 DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
474 DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
475 DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
476 DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder);
477 DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder);
479 DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat());
480 DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat());
481 DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat());
483 // Define a __POINTER_WIDTH__ macro for stdint.h.
484 Builder.defineMacro("__POINTER_WIDTH__",
485 Twine((int)TI.getPointerWidth(0)));
487 if (!LangOpts.CharIsSigned)
488 Builder.defineMacro("__CHAR_UNSIGNED__");
490 if (!TargetInfo::isTypeSigned(TI.getWIntType()))
491 Builder.defineMacro("__WINT_UNSIGNED__");
493 // Define exact-width integer types for stdint.h
494 Builder.defineMacro("__INT" + Twine(TI.getCharWidth()) + "_TYPE__",
497 if (TI.getShortWidth() > TI.getCharWidth())
498 DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
500 if (TI.getIntWidth() > TI.getShortWidth())
501 DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
503 if (TI.getLongWidth() > TI.getIntWidth())
504 DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
506 if (TI.getLongLongWidth() > TI.getLongWidth())
507 DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
509 // Add __builtin_va_list typedef.
510 Builder.append(TI.getVAListDeclaration());
512 if (const char *Prefix = TI.getUserLabelPrefix())
513 Builder.defineMacro("__USER_LABEL_PREFIX__", Prefix);
515 // Build configuration options. FIXME: these should be controlled by
516 // command line options or something.
517 Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
519 if (LangOpts.GNUInline)
520 Builder.defineMacro("__GNUC_GNU_INLINE__");
522 Builder.defineMacro("__GNUC_STDC_INLINE__");
524 if (LangOpts.NoInline)
525 Builder.defineMacro("__NO_INLINE__");
527 if (unsigned PICLevel = LangOpts.PICLevel) {
528 Builder.defineMacro("__PIC__", Twine(PICLevel));
529 Builder.defineMacro("__pic__", Twine(PICLevel));
532 // Macros to control C99 numerics and <float.h>
533 Builder.defineMacro("__FLT_EVAL_METHOD__", "0");
534 Builder.defineMacro("__FLT_RADIX__", "2");
535 int Dig = PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36);
536 Builder.defineMacro("__DECIMAL_DIG__", Twine(Dig));
538 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
539 Builder.defineMacro("__SSP__");
540 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
541 Builder.defineMacro("__SSP_ALL__", "2");
543 if (FEOpts.ProgramAction == frontend::RewriteObjC)
544 Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
546 // Define a macro that exists only when using the static analyzer.
547 if (FEOpts.ProgramAction == frontend::RunAnalysis)
548 Builder.defineMacro("__clang_analyzer__");
550 if (LangOpts.FastRelaxedMath)
551 Builder.defineMacro("__FAST_RELAXED_MATH__");
553 if (LangOpts.ObjCAutoRefCount) {
554 Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))");
555 Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))");
556 Builder.defineMacro("__autoreleasing",
557 "__attribute__((objc_ownership(autoreleasing)))");
558 Builder.defineMacro("__unsafe_unretained",
559 "__attribute__((objc_ownership(none)))");
562 // Get other target #defines.
563 TI.getTargetDefines(LangOpts, Builder);
566 // Initialize the remapping of files to alternative contents, e.g.,
567 // those specified through other files.
568 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
569 SourceManager &SourceMgr,
570 FileManager &FileMgr,
571 const PreprocessorOptions &InitOpts) {
572 // Remap files in the source manager (with buffers).
573 for (PreprocessorOptions::const_remapped_file_buffer_iterator
574 Remap = InitOpts.remapped_file_buffer_begin(),
575 RemapEnd = InitOpts.remapped_file_buffer_end();
578 // Create the file entry for the file that we're mapping from.
579 const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
580 Remap->second->getBufferSize(),
583 Diags.Report(diag::err_fe_remap_missing_from_file)
585 if (!InitOpts.RetainRemappedFileBuffers)
586 delete Remap->second;
590 // Override the contents of the "from" file with the contents of
592 SourceMgr.overrideFileContents(FromFile, Remap->second,
593 InitOpts.RetainRemappedFileBuffers);
596 // Remap files in the source manager (with other files).
597 for (PreprocessorOptions::const_remapped_file_iterator
598 Remap = InitOpts.remapped_file_begin(),
599 RemapEnd = InitOpts.remapped_file_end();
602 // Find the file that we're mapping to.
603 const FileEntry *ToFile = FileMgr.getFile(Remap->second);
605 Diags.Report(diag::err_fe_remap_missing_to_file)
606 << Remap->first << Remap->second;
610 // Create the file entry for the file that we're mapping from.
611 const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
612 ToFile->getSize(), 0);
614 Diags.Report(diag::err_fe_remap_missing_from_file)
619 // Override the contents of the "from" file with the contents of
621 SourceMgr.overrideFileContents(FromFile, ToFile);
624 SourceMgr.setOverridenFilesKeepOriginalName(
625 InitOpts.RemappedFilesKeepOriginalName);
628 /// InitializePreprocessor - Initialize the preprocessor getting it and the
629 /// environment ready to process a single file. This returns true on error.
631 void clang::InitializePreprocessor(Preprocessor &PP,
632 const PreprocessorOptions &InitOpts,
633 const HeaderSearchOptions &HSOpts,
634 const FrontendOptions &FEOpts) {
635 const LangOptions &LangOpts = PP.getLangOptions();
636 std::string PredefineBuffer;
637 PredefineBuffer.reserve(4080);
638 llvm::raw_string_ostream Predefines(PredefineBuffer);
639 MacroBuilder Builder(Predefines);
641 InitializeFileRemapping(PP.getDiagnostics(), PP.getSourceManager(),
642 PP.getFileManager(), InitOpts);
644 // Specify whether the preprocessor should replace #include/#import with
645 // module imports when plausible.
646 PP.setAutoModuleImport(InitOpts.AutoModuleImport);
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
651 if (!PP.getLangOptions().AsmPreprocessor)
652 Builder.append("# 1 \"<built-in>\" 3");
654 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
655 if (InitOpts.UsePredefines) {
656 InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, Builder);
658 // Install definitions to make Objective-C++ ARC work well with various
659 // C++ Standard Library implementations.
660 if (LangOpts.ObjC1 && LangOpts.CPlusPlus && LangOpts.ObjCAutoRefCount) {
661 switch (InitOpts.ObjCXXARCStandardLibrary) {
666 case ARCXX_libstdcxx:
667 AddObjCXXARCLibstdcxxDefines(LangOpts, Builder);
673 // Even with predefines off, some macros are still predefined.
674 // These should all be defined in the preprocessor according to the
675 // current language configuration.
676 InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOptions(),
679 // Add on the predefines from the driver. Wrap in a #line directive to report
680 // that they come from the command line.
681 if (!PP.getLangOptions().AsmPreprocessor)
682 Builder.append("# 1 \"<command line>\" 1");
684 // Process #define's and #undef's in the order they are given.
685 for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
686 if (InitOpts.Macros[i].second) // isUndef
687 Builder.undefineMacro(InitOpts.Macros[i].first);
689 DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
690 PP.getDiagnostics());
693 // If -imacros are specified, include them now. These are processed before
694 // any -include directives.
695 for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
696 AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i],
697 PP.getFileManager());
699 // Process -include directives.
700 for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
701 const std::string &Path = InitOpts.Includes[i];
702 if (Path == InitOpts.ImplicitPTHInclude)
703 AddImplicitIncludePTH(Builder, PP, Path);
705 AddImplicitInclude(Builder, Path, PP.getFileManager());
708 // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
709 if (!PP.getLangOptions().AsmPreprocessor)
710 Builder.append("# 1 \"<built-in>\" 2");
712 // Instruct the preprocessor to skip the preamble.
713 PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first,
714 InitOpts.PrecompiledPreambleBytes.second);
716 // Copy PredefinedBuffer into the Preprocessor.
717 PP.setPredefines(Predefines.str());
719 // Initialize the header search object.
720 ApplyHeaderSearchOptions(PP.getHeaderSearchInfo(), HSOpts,
722 PP.getTargetInfo().getTriple());