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/HeaderSearch.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Basic/FileManager.h"
24 #include "clang/Basic/SourceManager.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;
31 // Append a #define line to Buf for Macro. Macro should be of the form XXX,
32 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
33 // "#define XXX Y z W". To get a #define with no value, use "XXX=".
34 static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro,
35 DiagnosticsEngine &Diags) {
36 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
37 StringRef MacroName = MacroPair.first;
38 StringRef MacroBody = MacroPair.second;
39 if (MacroName.size() != Macro.size()) {
40 // Per GCC -D semantics, the macro ends at \n if it exists.
41 StringRef::size_type End = MacroBody.find_first_of("\n\r");
42 if (End != StringRef::npos)
43 Diags.Report(diag::warn_fe_macro_contains_embedded_newline)
45 Builder.defineMacro(MacroName, MacroBody.substr(0, End));
47 // Push "macroname 1".
48 Builder.defineMacro(Macro);
52 /// AddImplicitInclude - Add an implicit #include of the specified file to the
53 /// predefines buffer.
54 static void AddImplicitInclude(MacroBuilder &Builder, StringRef File,
55 FileManager &FileMgr) {
56 Builder.append(Twine("#include \"") +
57 HeaderSearch::NormalizeDashIncludePath(File, FileMgr) + "\"");
60 static void AddImplicitIncludeMacros(MacroBuilder &Builder,
62 FileManager &FileMgr) {
63 Builder.append(Twine("#__include_macros \"") +
64 HeaderSearch::NormalizeDashIncludePath(File, FileMgr) + "\"");
65 // Marker token to stop the __include_macros fetch loop.
66 Builder.append("##"); // ##?
69 /// AddImplicitIncludePTH - Add an implicit #include using the original file
70 /// used to generate a PTH cache.
71 static void AddImplicitIncludePTH(MacroBuilder &Builder, Preprocessor &PP,
72 StringRef ImplicitIncludePTH) {
73 PTHManager *P = PP.getPTHManager();
74 // Null check 'P' in the corner case where it couldn't be created.
75 const char *OriginalFile = P ? P->getOriginalSourceFile() : 0;
78 PP.getDiagnostics().Report(diag::err_fe_pth_file_has_no_source_header)
79 << ImplicitIncludePTH;
83 AddImplicitInclude(Builder, OriginalFile, PP.getFileManager());
86 /// PickFP - This is used to pick a value based on the FP semantics of the
87 /// specified FP model.
89 static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
90 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
92 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle)
94 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble)
96 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended)
97 return X87DoubleExtendedVal;
98 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble)
99 return PPCDoubleDoubleVal;
100 assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad);
104 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
105 const llvm::fltSemantics *Sem) {
106 const char *DenormMin, *Epsilon, *Max, *Min;
107 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
108 "3.64519953188247460253e-4951L",
109 "4.94065645841246544176568792868221e-324L",
110 "6.47517511943802511092443895822764655e-4966L");
111 int Digits = PickFP(Sem, 6, 15, 18, 31, 33);
112 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
113 "1.08420217248550443401e-19L",
114 "4.94065645841246544176568792868221e-324L",
115 "1.92592994438723585305597794258492732e-34L");
116 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106, 113);
117 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291, -4931);
118 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308, 4932);
119 int MinExp = PickFP(Sem, -125, -1021, -16381, -968, -16381);
120 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024, 16384);
121 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
122 "3.36210314311209350626e-4932L",
123 "2.00416836000897277799610805135016e-292L",
124 "3.36210314311209350626267781732175260e-4932L");
125 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
126 "1.18973149535723176502e+4932L",
127 "1.79769313486231580793728971405301e+308L",
128 "1.18973149535723176508575932662800702e+4932L");
130 SmallString<32> DefPrefix;
135 Builder.defineMacro(DefPrefix + "DENORM_MIN__", DenormMin);
136 Builder.defineMacro(DefPrefix + "HAS_DENORM__");
137 Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
138 Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon));
139 Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
140 Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
141 Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits));
143 Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp));
144 Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp));
145 Builder.defineMacro(DefPrefix + "MAX__", Twine(Max));
147 Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")");
148 Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")");
149 Builder.defineMacro(DefPrefix + "MIN__", Twine(Min));
153 /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
154 /// named MacroName with the max value for a type with width 'TypeWidth' a
155 /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
156 static void DefineTypeSize(StringRef MacroName, unsigned TypeWidth,
157 StringRef ValSuffix, bool isSigned,
158 MacroBuilder &Builder) {
159 llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth)
160 : llvm::APInt::getMaxValue(TypeWidth);
161 Builder.defineMacro(MacroName, MaxVal.toString(10, isSigned) + ValSuffix);
164 /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
165 /// the width, suffix, and signedness of the given type
166 static void DefineTypeSize(StringRef MacroName, TargetInfo::IntType Ty,
167 const TargetInfo &TI, MacroBuilder &Builder) {
168 DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
169 TI.isTypeSigned(Ty), Builder);
172 static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
173 MacroBuilder &Builder) {
174 Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
177 static void DefineTypeWidth(StringRef MacroName, TargetInfo::IntType Ty,
178 const TargetInfo &TI, MacroBuilder &Builder) {
179 Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty)));
182 static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth,
183 const TargetInfo &TI, MacroBuilder &Builder) {
184 Builder.defineMacro(MacroName,
185 Twine(BitWidth / TI.getCharWidth()));
188 static void DefineExactWidthIntType(TargetInfo::IntType Ty,
189 const TargetInfo &TI, MacroBuilder &Builder) {
190 int TypeWidth = TI.getTypeWidth(Ty);
192 // Use the target specified int64 type, when appropriate, so that [u]int64_t
193 // ends up being defined in terms of the correct type.
195 Ty = TI.getInt64Type();
197 DefineType("__INT" + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
199 StringRef ConstSuffix(TargetInfo::getTypeConstantSuffix(Ty));
200 if (!ConstSuffix.empty())
201 Builder.defineMacro("__INT" + Twine(TypeWidth) + "_C_SUFFIX__",
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"
219 /// \brief Add definitions required for a smooth interaction between
220 /// Objective-C++ automated reference counting and libstdc++ (4.2).
221 static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts,
222 MacroBuilder &Builder) {
223 Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR");
227 // Provide specializations for the __is_scalar type trait so that
228 // lifetime-qualified objects are not considered "scalar" types, which
229 // libstdc++ uses as an indicator of the presence of trivial copy, assign,
230 // default-construct, and destruct semantics (none of which hold for
231 // lifetime-qualified objects in ARC).
232 llvm::raw_string_ostream Out(Result);
234 Out << "namespace std {\n"
236 << "struct __true_type;\n"
237 << "struct __false_type;\n"
240 Out << "template<typename _Tp> struct __is_scalar;\n"
243 Out << "template<typename _Tp>\n"
244 << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n"
245 << " enum { __value = 0 };\n"
246 << " typedef __false_type __type;\n"
250 if (LangOpts.ObjCRuntimeHasWeak) {
251 Out << "template<typename _Tp>\n"
252 << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n"
253 << " enum { __value = 0 };\n"
254 << " typedef __false_type __type;\n"
259 Out << "template<typename _Tp>\n"
260 << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))"
262 << " enum { __value = 0 };\n"
263 << " typedef __false_type __type;\n"
269 Builder.append(Result);
272 static void InitializeStandardPredefinedMacros(const TargetInfo &TI,
273 const LangOptions &LangOpts,
274 const FrontendOptions &FEOpts,
275 MacroBuilder &Builder) {
276 if (!LangOpts.MicrosoftMode && !LangOpts.TraditionalCPP)
277 Builder.defineMacro("__STDC__");
278 if (LangOpts.Freestanding)
279 Builder.defineMacro("__STDC_HOSTED__", "0");
281 Builder.defineMacro("__STDC_HOSTED__");
283 if (!LangOpts.CPlusPlus) {
285 Builder.defineMacro("__STDC_VERSION__", "201112L");
286 else if (LangOpts.C99)
287 Builder.defineMacro("__STDC_VERSION__", "199901L");
288 else if (!LangOpts.GNUMode && LangOpts.Digraphs)
289 Builder.defineMacro("__STDC_VERSION__", "199409L");
291 if (LangOpts.GNUMode)
292 Builder.defineMacro("__cplusplus");
294 // C++0x [cpp.predefined]p1:
295 // The name_ _cplusplus is defined to the value 201103L when compiling a
296 // C++ translation unit.
297 if (LangOpts.CPlusPlus0x)
298 Builder.defineMacro("__cplusplus", "201103L");
299 // C++03 [cpp.predefined]p1:
300 // The name_ _cplusplus is defined to the value 199711L when compiling a
301 // C++ translation unit.
303 Builder.defineMacro("__cplusplus", "199711L");
308 Builder.defineMacro("__OBJC__");
310 // Not "standard" per se, but available even with the -undef flag.
311 if (LangOpts.AsmPreprocessor)
312 Builder.defineMacro("__ASSEMBLER__");
315 static void InitializePredefinedMacros(const TargetInfo &TI,
316 const LangOptions &LangOpts,
317 const FrontendOptions &FEOpts,
318 MacroBuilder &Builder) {
319 // Compiler version introspection macros.
320 Builder.defineMacro("__llvm__"); // LLVM Backend
321 Builder.defineMacro("__clang__"); // Clang Frontend
323 #define TOSTR(X) TOSTR2(X)
324 Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
325 Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
326 #ifdef CLANG_VERSION_PATCHLEVEL
327 Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
329 Builder.defineMacro("__clang_patchlevel__", "0");
331 Builder.defineMacro("__clang_version__",
332 "\"" CLANG_VERSION_STRING " ("
333 + getClangFullRepositoryVersion() + ")\"");
336 if (!LangOpts.MicrosoftMode) {
337 // Currently claim to be compatible with GCC 4.2.1-5621, but only if we're
338 // not compiling for MSVC compatibility
339 Builder.defineMacro("__GNUC_MINOR__", "2");
340 Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
341 Builder.defineMacro("__GNUC__", "4");
342 Builder.defineMacro("__GXX_ABI_VERSION", "1002");
345 // Define macros for the C11 / C++11 memory orderings
346 Builder.defineMacro("__ATOMIC_RELAXED", "0");
347 Builder.defineMacro("__ATOMIC_CONSUME", "1");
348 Builder.defineMacro("__ATOMIC_ACQUIRE", "2");
349 Builder.defineMacro("__ATOMIC_RELEASE", "3");
350 Builder.defineMacro("__ATOMIC_ACQ_REL", "4");
351 Builder.defineMacro("__ATOMIC_SEQ_CST", "5");
353 // Support for #pragma redefine_extname (Sun compatibility)
354 Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1");
356 // As sad as it is, enough software depends on the __VERSION__ for version
357 // checks that it is necessary to report 4.2.1 (the base GCC version we claim
358 // compatibility with) first.
359 Builder.defineMacro("__VERSION__", "\"4.2.1 Compatible " +
360 Twine(getClangFullCPPVersion()) + "\"");
362 // Initialize language-specific preprocessor defines.
364 // Standard conforming mode?
365 if (!LangOpts.GNUMode)
366 Builder.defineMacro("__STRICT_ANSI__");
368 if (LangOpts.CPlusPlus0x)
369 Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
371 if (LangOpts.ObjC1) {
372 if (LangOpts.ObjCNonFragileABI) {
373 Builder.defineMacro("__OBJC2__");
375 if (LangOpts.ObjCExceptions)
376 Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
379 if (LangOpts.getGC() != LangOptions::NonGC)
380 Builder.defineMacro("__OBJC_GC__");
382 if (LangOpts.NeXTRuntime)
383 Builder.defineMacro("__NEXT_RUNTIME__");
386 // darwin_constant_cfstrings controls this. This is also dependent
387 // on other things like the runtime I believe. This is set even for C code.
388 if (!LangOpts.NoConstantCFStrings)
389 Builder.defineMacro("__CONSTANT_CFSTRINGS__");
392 Builder.defineMacro("OBJC_NEW_PROPERTIES");
394 if (LangOpts.PascalStrings)
395 Builder.defineMacro("__PASCAL_STRINGS__");
397 if (LangOpts.Blocks) {
398 Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
399 Builder.defineMacro("__BLOCKS__");
402 if (LangOpts.CXXExceptions)
403 Builder.defineMacro("__EXCEPTIONS");
405 Builder.defineMacro("__GXX_RTTI");
406 if (LangOpts.SjLjExceptions)
407 Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
409 if (LangOpts.Deprecated)
410 Builder.defineMacro("__DEPRECATED");
412 if (LangOpts.CPlusPlus) {
413 Builder.defineMacro("__GNUG__", "4");
414 Builder.defineMacro("__GXX_WEAK__");
415 Builder.defineMacro("__private_extern__", "extern");
418 if (LangOpts.MicrosoftExt) {
419 // Both __PRETTY_FUNCTION__ and __FUNCTION__ are GCC extensions, however
420 // VC++ appears to only like __FUNCTION__.
421 Builder.defineMacro("__PRETTY_FUNCTION__", "__FUNCTION__");
422 // Work around some issues with Visual C++ headerws.
423 if (LangOpts.CPlusPlus) {
424 // Since we define wchar_t in C++ mode.
425 Builder.defineMacro("_WCHAR_T_DEFINED");
426 Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
427 // FIXME: Support Microsoft's __identifier extension in the lexer.
428 Builder.append("#define __identifier(x) x");
429 Builder.append("class type_info;");
432 if (LangOpts.CPlusPlus0x) {
433 Builder.defineMacro("_HAS_CHAR16_T_LANGUAGE_SUPPORT", "1");
437 if (LangOpts.Optimize)
438 Builder.defineMacro("__OPTIMIZE__");
439 if (LangOpts.OptimizeSize)
440 Builder.defineMacro("__OPTIMIZE_SIZE__");
442 if (LangOpts.FastMath)
443 Builder.defineMacro("__FAST_MATH__");
445 // Initialize target-specific preprocessor defines.
447 // Define type sizing macros based on the target properties.
448 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
449 Builder.defineMacro("__CHAR_BIT__", "8");
451 DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Builder);
452 DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
453 DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
454 DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
455 DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
456 DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
457 DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
459 DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder);
460 DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder);
461 DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder);
462 DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder);
463 DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder);
464 DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder);
465 DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(0), TI, Builder);
466 DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder);
467 DefineTypeSizeof("__SIZEOF_PTRDIFF_T__",
468 TI.getTypeWidth(TI.getPtrDiffType(0)), TI, Builder);
469 DefineTypeSizeof("__SIZEOF_SIZE_T__",
470 TI.getTypeWidth(TI.getSizeType()), TI, Builder);
471 DefineTypeSizeof("__SIZEOF_WCHAR_T__",
472 TI.getTypeWidth(TI.getWCharType()), TI, Builder);
473 DefineTypeSizeof("__SIZEOF_WINT_T__",
474 TI.getTypeWidth(TI.getWIntType()), TI, Builder);
476 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
477 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
478 DefineTypeWidth("__INTMAX_WIDTH__", TI.getIntMaxType(), TI, Builder);
479 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
480 DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
481 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
482 DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
483 DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
484 DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
485 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
486 DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
487 DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
488 DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
489 DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
490 DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder);
491 DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder);
493 DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat());
494 DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat());
495 DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat());
497 // Define a __POINTER_WIDTH__ macro for stdint.h.
498 Builder.defineMacro("__POINTER_WIDTH__",
499 Twine((int)TI.getPointerWidth(0)));
501 if (!LangOpts.CharIsSigned)
502 Builder.defineMacro("__CHAR_UNSIGNED__");
504 if (!TargetInfo::isTypeSigned(TI.getWIntType()))
505 Builder.defineMacro("__WINT_UNSIGNED__");
507 // Define exact-width integer types for stdint.h
508 Builder.defineMacro("__INT" + Twine(TI.getCharWidth()) + "_TYPE__",
511 if (TI.getShortWidth() > TI.getCharWidth())
512 DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
514 if (TI.getIntWidth() > TI.getShortWidth())
515 DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
517 if (TI.getLongWidth() > TI.getIntWidth())
518 DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
520 if (TI.getLongLongWidth() > TI.getLongWidth())
521 DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
523 // Add __builtin_va_list typedef.
524 Builder.append(TI.getVAListDeclaration());
526 if (const char *Prefix = TI.getUserLabelPrefix())
527 Builder.defineMacro("__USER_LABEL_PREFIX__", Prefix);
529 // Build configuration options. FIXME: these should be controlled by
530 // command line options or something.
531 Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
533 if (LangOpts.GNUInline)
534 Builder.defineMacro("__GNUC_GNU_INLINE__");
536 Builder.defineMacro("__GNUC_STDC_INLINE__");
538 // The value written by __atomic_test_and_set.
539 // FIXME: This is target-dependent.
540 Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
542 // Used by libstdc++ to implement ATOMIC_<foo>_LOCK_FREE.
543 unsigned InlineWidthBits = TI.getMaxAtomicInlineWidth();
544 #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \
545 Builder.defineMacro("__GCC_ATOMIC_" #TYPE "_LOCK_FREE", \
546 getLockFreeValue(TI.get##Type##Width(), \
547 TI.get##Type##Align(), \
549 DEFINE_LOCK_FREE_MACRO(BOOL, Bool);
550 DEFINE_LOCK_FREE_MACRO(CHAR, Char);
551 DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16);
552 DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32);
553 DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar);
554 DEFINE_LOCK_FREE_MACRO(SHORT, Short);
555 DEFINE_LOCK_FREE_MACRO(INT, Int);
556 DEFINE_LOCK_FREE_MACRO(LONG, Long);
557 DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
558 Builder.defineMacro("__GCC_ATOMIC_POINTER_LOCK_FREE",
559 getLockFreeValue(TI.getPointerWidth(0),
560 TI.getPointerAlign(0),
562 #undef DEFINE_LOCK_FREE_MACRO
564 if (LangOpts.NoInlineDefine)
565 Builder.defineMacro("__NO_INLINE__");
567 if (unsigned PICLevel = LangOpts.PICLevel) {
568 Builder.defineMacro("__PIC__", Twine(PICLevel));
569 Builder.defineMacro("__pic__", Twine(PICLevel));
571 if (unsigned PIELevel = LangOpts.PIELevel) {
572 Builder.defineMacro("__PIE__", Twine(PIELevel));
573 Builder.defineMacro("__pie__", Twine(PIELevel));
576 // Macros to control C99 numerics and <float.h>
577 Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod()));
578 Builder.defineMacro("__FLT_RADIX__", "2");
579 int Dig = PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36);
580 Builder.defineMacro("__DECIMAL_DIG__", Twine(Dig));
582 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
583 Builder.defineMacro("__SSP__");
584 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
585 Builder.defineMacro("__SSP_ALL__", "2");
587 if (FEOpts.ProgramAction == frontend::RewriteObjC)
588 Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
590 // Define a macro that exists only when using the static analyzer.
591 if (FEOpts.ProgramAction == frontend::RunAnalysis)
592 Builder.defineMacro("__clang_analyzer__");
594 if (LangOpts.FastRelaxedMath)
595 Builder.defineMacro("__FAST_RELAXED_MATH__");
597 if (LangOpts.ObjCAutoRefCount) {
598 Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))");
599 Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))");
600 Builder.defineMacro("__autoreleasing",
601 "__attribute__((objc_ownership(autoreleasing)))");
602 Builder.defineMacro("__unsafe_unretained",
603 "__attribute__((objc_ownership(none)))");
606 // Get other target #defines.
607 TI.getTargetDefines(LangOpts, Builder);
610 // Initialize the remapping of files to alternative contents, e.g.,
611 // those specified through other files.
612 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
613 SourceManager &SourceMgr,
614 FileManager &FileMgr,
615 const PreprocessorOptions &InitOpts) {
616 // Remap files in the source manager (with buffers).
617 for (PreprocessorOptions::const_remapped_file_buffer_iterator
618 Remap = InitOpts.remapped_file_buffer_begin(),
619 RemapEnd = InitOpts.remapped_file_buffer_end();
622 // Create the file entry for the file that we're mapping from.
623 const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
624 Remap->second->getBufferSize(),
627 Diags.Report(diag::err_fe_remap_missing_from_file)
629 if (!InitOpts.RetainRemappedFileBuffers)
630 delete Remap->second;
634 // Override the contents of the "from" file with the contents of
636 SourceMgr.overrideFileContents(FromFile, Remap->second,
637 InitOpts.RetainRemappedFileBuffers);
640 // Remap files in the source manager (with other files).
641 for (PreprocessorOptions::const_remapped_file_iterator
642 Remap = InitOpts.remapped_file_begin(),
643 RemapEnd = InitOpts.remapped_file_end();
646 // Find the file that we're mapping to.
647 const FileEntry *ToFile = FileMgr.getFile(Remap->second);
649 Diags.Report(diag::err_fe_remap_missing_to_file)
650 << Remap->first << Remap->second;
654 // Create the file entry for the file that we're mapping from.
655 const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
656 ToFile->getSize(), 0);
658 Diags.Report(diag::err_fe_remap_missing_from_file)
663 // Override the contents of the "from" file with the contents of
665 SourceMgr.overrideFileContents(FromFile, ToFile);
668 SourceMgr.setOverridenFilesKeepOriginalName(
669 InitOpts.RemappedFilesKeepOriginalName);
672 /// InitializePreprocessor - Initialize the preprocessor getting it and the
673 /// environment ready to process a single file. This returns true on error.
675 void clang::InitializePreprocessor(Preprocessor &PP,
676 const PreprocessorOptions &InitOpts,
677 const HeaderSearchOptions &HSOpts,
678 const FrontendOptions &FEOpts) {
679 const LangOptions &LangOpts = PP.getLangOpts();
680 std::string PredefineBuffer;
681 PredefineBuffer.reserve(4080);
682 llvm::raw_string_ostream Predefines(PredefineBuffer);
683 MacroBuilder Builder(Predefines);
685 InitializeFileRemapping(PP.getDiagnostics(), PP.getSourceManager(),
686 PP.getFileManager(), InitOpts);
688 // Emit line markers for various builtin sections of the file. We don't do
689 // this in asm preprocessor mode, because "# 4" is not a line marker directive
691 if (!PP.getLangOpts().AsmPreprocessor)
692 Builder.append("# 1 \"<built-in>\" 3");
694 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
695 if (InitOpts.UsePredefines) {
696 InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, Builder);
698 // Install definitions to make Objective-C++ ARC work well with various
699 // C++ Standard Library implementations.
700 if (LangOpts.ObjC1 && LangOpts.CPlusPlus && LangOpts.ObjCAutoRefCount) {
701 switch (InitOpts.ObjCXXARCStandardLibrary) {
706 case ARCXX_libstdcxx:
707 AddObjCXXARCLibstdcxxDefines(LangOpts, Builder);
713 // Even with predefines off, some macros are still predefined.
714 // These should all be defined in the preprocessor according to the
715 // current language configuration.
716 InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOpts(),
719 // Add on the predefines from the driver. Wrap in a #line directive to report
720 // that they come from the command line.
721 if (!PP.getLangOpts().AsmPreprocessor)
722 Builder.append("# 1 \"<command line>\" 1");
724 // Process #define's and #undef's in the order they are given.
725 for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
726 if (InitOpts.Macros[i].second) // isUndef
727 Builder.undefineMacro(InitOpts.Macros[i].first);
729 DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
730 PP.getDiagnostics());
733 // If -imacros are specified, include them now. These are processed before
734 // any -include directives.
735 for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
736 AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i],
737 PP.getFileManager());
739 // Process -include directives.
740 for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
741 const std::string &Path = InitOpts.Includes[i];
742 if (Path == InitOpts.ImplicitPTHInclude)
743 AddImplicitIncludePTH(Builder, PP, Path);
745 AddImplicitInclude(Builder, Path, PP.getFileManager());
748 // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
749 if (!PP.getLangOpts().AsmPreprocessor)
750 Builder.append("# 1 \"<built-in>\" 2");
752 // Instruct the preprocessor to skip the preamble.
753 PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first,
754 InitOpts.PrecompiledPreambleBytes.second);
756 // Copy PredefinedBuffer into the Preprocessor.
757 PP.setPredefines(Predefines.str());
759 // Initialize the header search object.
760 ApplyHeaderSearchOptions(PP.getHeaderSearchInfo(), HSOpts,
762 PP.getTargetInfo().getTriple());