clang API Documentation

InitPreprocessor.cpp

Go to the documentation of this file.
00001 //===--- InitPreprocessor.cpp - PP initialization code. ---------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the clang::InitializePreprocessor function.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Basic/Version.h"
00015 #include "clang/Frontend/Utils.h"
00016 #include "clang/Basic/MacroBuilder.h"
00017 #include "clang/Basic/TargetInfo.h"
00018 #include "clang/Frontend/FrontendDiagnostic.h"
00019 #include "clang/Frontend/FrontendOptions.h"
00020 #include "clang/Frontend/PreprocessorOptions.h"
00021 #include "clang/Lex/Preprocessor.h"
00022 #include "clang/Basic/FileManager.h"
00023 #include "clang/Basic/SourceManager.h"
00024 #include "llvm/ADT/APFloat.h"
00025 #include "llvm/Support/MemoryBuffer.h"
00026 #include "llvm/System/Path.h"
00027 using namespace clang;
00028 
00029 // Append a #define line to Buf for Macro.  Macro should be of the form XXX,
00030 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
00031 // "#define XXX Y z W".  To get a #define with no value, use "XXX=".
00032 static void DefineBuiltinMacro(MacroBuilder &Builder, llvm::StringRef Macro,
00033                                Diagnostic &Diags) {
00034   std::pair<llvm::StringRef, llvm::StringRef> MacroPair = Macro.split('=');
00035   llvm::StringRef MacroName = MacroPair.first;
00036   llvm::StringRef MacroBody = MacroPair.second;
00037   if (MacroName.size() != Macro.size()) {
00038     // Per GCC -D semantics, the macro ends at \n if it exists.
00039     llvm::StringRef::size_type End = MacroBody.find_first_of("\n\r");
00040     if (End != llvm::StringRef::npos)
00041       Diags.Report(diag::warn_fe_macro_contains_embedded_newline)
00042         << MacroName;
00043     Builder.defineMacro(MacroName, MacroBody.substr(0, End));
00044   } else {
00045     // Push "macroname 1".
00046     Builder.defineMacro(Macro);
00047   }
00048 }
00049 
00050 std::string clang::NormalizeDashIncludePath(llvm::StringRef File) {
00051   // Implicit include paths should be resolved relative to the current
00052   // working directory first, and then use the regular header search
00053   // mechanism. The proper way to handle this is to have the
00054   // predefines buffer located at the current working directory, but
00055   // it has not file entry. For now, workaround this by using an
00056   // absolute path if we find the file here, and otherwise letting
00057   // header search handle it.
00058   llvm::sys::Path Path(File);
00059   Path.makeAbsolute();
00060   if (!Path.exists())
00061     Path = File;
00062 
00063   return Lexer::Stringify(Path.str());
00064 }
00065 
00066 /// AddImplicitInclude - Add an implicit #include of the specified file to the
00067 /// predefines buffer.
00068 static void AddImplicitInclude(MacroBuilder &Builder, llvm::StringRef File) {
00069   Builder.append("#include \"" +
00070                  llvm::Twine(NormalizeDashIncludePath(File)) + "\"");
00071 }
00072 
00073 static void AddImplicitIncludeMacros(MacroBuilder &Builder,
00074                                      llvm::StringRef File) {
00075   Builder.append("#__include_macros \"" +
00076                  llvm::Twine(NormalizeDashIncludePath(File)) + "\"");
00077   // Marker token to stop the __include_macros fetch loop.
00078   Builder.append("##"); // ##?
00079 }
00080 
00081 /// AddImplicitIncludePTH - Add an implicit #include using the original file
00082 ///  used to generate a PTH cache.
00083 static void AddImplicitIncludePTH(MacroBuilder &Builder, Preprocessor &PP,
00084                                   llvm::StringRef ImplicitIncludePTH) {
00085   PTHManager *P = PP.getPTHManager();
00086   assert(P && "No PTHManager.");
00087   const char *OriginalFile = P->getOriginalSourceFile();
00088 
00089   if (!OriginalFile) {
00090     PP.getDiagnostics().Report(diag::err_fe_pth_file_has_no_source_header)
00091       << ImplicitIncludePTH;
00092     return;
00093   }
00094 
00095   AddImplicitInclude(Builder, OriginalFile);
00096 }
00097 
00098 /// PickFP - This is used to pick a value based on the FP semantics of the
00099 /// specified FP model.
00100 template <typename T>
00101 static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
00102                 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
00103                 T IEEEQuadVal) {
00104   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle)
00105     return IEEESingleVal;
00106   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble)
00107     return IEEEDoubleVal;
00108   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended)
00109     return X87DoubleExtendedVal;
00110   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble)
00111     return PPCDoubleDoubleVal;
00112   assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad);
00113   return IEEEQuadVal;
00114 }
00115 
00116 static void DefineFloatMacros(MacroBuilder &Builder, llvm::StringRef Prefix,
00117                               const llvm::fltSemantics *Sem) {
00118   const char *DenormMin, *Epsilon, *Max, *Min;
00119   DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
00120                      "3.64519953188247460253e-4951L",
00121                      "4.94065645841246544176568792868221e-324L",
00122                      "6.47517511943802511092443895822764655e-4966L");
00123   int Digits = PickFP(Sem, 6, 15, 18, 31, 33);
00124   Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
00125                    "1.08420217248550443401e-19L",
00126                    "4.94065645841246544176568792868221e-324L",
00127                    "1.92592994438723585305597794258492732e-34L");
00128   int MantissaDigits = PickFP(Sem, 24, 53, 64, 106, 113);
00129   int Min10Exp = PickFP(Sem, -37, -307, -4931, -291, -4931);
00130   int Max10Exp = PickFP(Sem, 38, 308, 4932, 308, 4932);
00131   int MinExp = PickFP(Sem, -125, -1021, -16381, -968, -16381);
00132   int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024, 16384);
00133   Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
00134                "3.36210314311209350626e-4932L",
00135                "2.00416836000897277799610805135016e-292L",
00136                "3.36210314311209350626267781732175260e-4932L");
00137   Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
00138                "1.18973149535723176502e+4932L",
00139                "1.79769313486231580793728971405301e+308L",
00140                "1.18973149535723176508575932662800702e+4932L");
00141 
00142   llvm::SmallString<32> DefPrefix;
00143   DefPrefix = "__";
00144   DefPrefix += Prefix;
00145   DefPrefix += "_";
00146 
00147   Builder.defineMacro(DefPrefix + "DENORM_MIN__", DenormMin);
00148   Builder.defineMacro(DefPrefix + "HAS_DENORM__");
00149   Builder.defineMacro(DefPrefix + "DIG__", llvm::Twine(Digits));
00150   Builder.defineMacro(DefPrefix + "EPSILON__", llvm::Twine(Epsilon));
00151   Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
00152   Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
00153   Builder.defineMacro(DefPrefix + "MANT_DIG__", llvm::Twine(MantissaDigits));
00154 
00155   Builder.defineMacro(DefPrefix + "MAX_10_EXP__", llvm::Twine(Max10Exp));
00156   Builder.defineMacro(DefPrefix + "MAX_EXP__", llvm::Twine(MaxExp));
00157   Builder.defineMacro(DefPrefix + "MAX__", llvm::Twine(Max));
00158 
00159   Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+llvm::Twine(Min10Exp)+")");
00160   Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+llvm::Twine(MinExp)+")");
00161   Builder.defineMacro(DefPrefix + "MIN__", llvm::Twine(Min));
00162 }
00163 
00164 
00165 /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
00166 /// named MacroName with the max value for a type with width 'TypeWidth' a
00167 /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
00168 static void DefineTypeSize(llvm::StringRef MacroName, unsigned TypeWidth,
00169                            llvm::StringRef ValSuffix, bool isSigned,
00170                            MacroBuilder& Builder) {
00171   long long MaxVal;
00172   if (isSigned)
00173     MaxVal = (1LL << (TypeWidth - 1)) - 1;
00174   else
00175     MaxVal = ~0LL >> (64-TypeWidth);
00176 
00177   Builder.defineMacro(MacroName, llvm::Twine(MaxVal) + ValSuffix);
00178 }
00179 
00180 /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
00181 /// the width, suffix, and signedness of the given type
00182 static void DefineTypeSize(llvm::StringRef MacroName, TargetInfo::IntType Ty,
00183                            const TargetInfo &TI, MacroBuilder &Builder) {
00184   DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty), 
00185                  TI.isTypeSigned(Ty), Builder);
00186 }
00187 
00188 static void DefineType(const llvm::Twine &MacroName, TargetInfo::IntType Ty,
00189                        MacroBuilder &Builder) {
00190   Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
00191 }
00192 
00193 static void DefineTypeWidth(llvm::StringRef MacroName, TargetInfo::IntType Ty,
00194                             const TargetInfo &TI, MacroBuilder &Builder) {
00195   Builder.defineMacro(MacroName, llvm::Twine(TI.getTypeWidth(Ty)));
00196 }
00197 
00198 static void DefineExactWidthIntType(TargetInfo::IntType Ty, 
00199                                const TargetInfo &TI, MacroBuilder &Builder) {
00200   int TypeWidth = TI.getTypeWidth(Ty);
00201   DefineType("__INT" + llvm::Twine(TypeWidth) + "_TYPE__", Ty, Builder);
00202 
00203   llvm::StringRef ConstSuffix(TargetInfo::getTypeConstantSuffix(Ty));
00204   if (!ConstSuffix.empty())
00205     Builder.defineMacro("__INT" + llvm::Twine(TypeWidth) + "_C_SUFFIX__",
00206                         ConstSuffix);
00207 }
00208 
00209 static void InitializePredefinedMacros(const TargetInfo &TI,
00210                                        const LangOptions &LangOpts,
00211                                        const FrontendOptions &FEOpts,
00212                                        MacroBuilder &Builder) {
00213   // Compiler version introspection macros.
00214   Builder.defineMacro("__llvm__");  // LLVM Backend
00215   Builder.defineMacro("__clang__"); // Clang Frontend
00216 #define TOSTR2(X) #X
00217 #define TOSTR(X) TOSTR2(X)
00218   Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
00219   Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
00220 #ifdef CLANG_VERSION_PATCHLEVEL
00221   Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
00222 #else
00223   Builder.defineMacro("__clang_patchlevel__", "0");
00224 #endif
00225   Builder.defineMacro("__clang_version__", 
00226                       "\"" CLANG_VERSION_STRING " ("
00227                       + getClangFullRepositoryVersion() + ")\"");
00228 #undef TOSTR
00229 #undef TOSTR2
00230   // Currently claim to be compatible with GCC 4.2.1-5621.
00231   Builder.defineMacro("__GNUC_MINOR__", "2");
00232   Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
00233   Builder.defineMacro("__GNUC__", "4");
00234   Builder.defineMacro("__GXX_ABI_VERSION", "1002");
00235   Builder.defineMacro("__VERSION__", "\"4.2.1 Compatible Clang Compiler\"");
00236 
00237   // Initialize language-specific preprocessor defines.
00238 
00239   // These should all be defined in the preprocessor according to the
00240   // current language configuration.
00241   if (!LangOpts.Microsoft)
00242     Builder.defineMacro("__STDC__");
00243   if (LangOpts.AsmPreprocessor)
00244     Builder.defineMacro("__ASSEMBLER__");
00245 
00246   if (!LangOpts.CPlusPlus) {
00247     if (LangOpts.C99)
00248       Builder.defineMacro("__STDC_VERSION__", "199901L");
00249     else if (!LangOpts.GNUMode && LangOpts.Digraphs)
00250       Builder.defineMacro("__STDC_VERSION__", "199409L");
00251   }
00252 
00253   // Standard conforming mode?
00254   if (!LangOpts.GNUMode)
00255     Builder.defineMacro("__STRICT_ANSI__");
00256 
00257   if (LangOpts.CPlusPlus0x)
00258     Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
00259 
00260   if (LangOpts.Freestanding)
00261     Builder.defineMacro("__STDC_HOSTED__", "0");
00262   else
00263     Builder.defineMacro("__STDC_HOSTED__");
00264 
00265   if (LangOpts.ObjC1) {
00266     Builder.defineMacro("__OBJC__");
00267     if (LangOpts.ObjCNonFragileABI) {
00268       Builder.defineMacro("__OBJC2__");
00269       Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
00270     }
00271 
00272     if (LangOpts.getGCMode() != LangOptions::NonGC)
00273       Builder.defineMacro("__OBJC_GC__");
00274 
00275     if (LangOpts.NeXTRuntime)
00276       Builder.defineMacro("__NEXT_RUNTIME__");
00277   }
00278 
00279   // darwin_constant_cfstrings controls this. This is also dependent
00280   // on other things like the runtime I believe.  This is set even for C code.
00281   Builder.defineMacro("__CONSTANT_CFSTRINGS__");
00282 
00283   if (LangOpts.ObjC2)
00284     Builder.defineMacro("OBJC_NEW_PROPERTIES");
00285 
00286   if (LangOpts.PascalStrings)
00287     Builder.defineMacro("__PASCAL_STRINGS__");
00288 
00289   if (LangOpts.Blocks) {
00290     Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
00291     Builder.defineMacro("__BLOCKS__");
00292   }
00293 
00294   if (LangOpts.Exceptions)
00295     Builder.defineMacro("__EXCEPTIONS");
00296   if (LangOpts.SjLjExceptions)
00297     Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
00298 
00299   if (LangOpts.CPlusPlus) {
00300     Builder.defineMacro("__DEPRECATED");
00301     Builder.defineMacro("__GNUG__", "4");
00302     Builder.defineMacro("__GXX_WEAK__");
00303     if (LangOpts.GNUMode)
00304       Builder.defineMacro("__cplusplus");
00305     else
00306       // C++ [cpp.predefined]p1:
00307       //   The name_ _cplusplusis defined to the value199711Lwhen compiling a
00308       //   C++ translation unit.
00309       Builder.defineMacro("__cplusplus", "199711L");
00310     Builder.defineMacro("__private_extern__", "extern");
00311   }
00312 
00313   if (LangOpts.Microsoft) {
00314     // Filter out some microsoft extensions when trying to parse in ms-compat
00315     // mode.
00316     Builder.defineMacro("__int8", "__INT8_TYPE__");
00317     Builder.defineMacro("__int16", "__INT16_TYPE__");
00318     Builder.defineMacro("__int32", "__INT32_TYPE__");
00319     Builder.defineMacro("__int64", "__INT64_TYPE__");
00320     // Both __PRETTY_FUNCTION__ and __FUNCTION__ are GCC extensions, however
00321     // VC++ appears to only like __FUNCTION__.
00322     Builder.defineMacro("__PRETTY_FUNCTION__", "__FUNCTION__");
00323     // Work around some issues with Visual C++ headerws.
00324     if (LangOpts.CPlusPlus) {
00325       // Since we define wchar_t in C++ mode.
00326       Builder.defineMacro("_WCHAR_T_DEFINED");
00327       Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
00328       // FIXME:  This should be temporary until we have a __pragma
00329       // solution, to avoid some errors flagged in VC++ headers.
00330       Builder.defineMacro("_CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES", "0");
00331     }
00332   }
00333 
00334   if (LangOpts.Optimize)
00335     Builder.defineMacro("__OPTIMIZE__");
00336   if (LangOpts.OptimizeSize)
00337     Builder.defineMacro("__OPTIMIZE_SIZE__");
00338 
00339   // Initialize target-specific preprocessor defines.
00340 
00341   // Define type sizing macros based on the target properties.
00342   assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
00343   Builder.defineMacro("__CHAR_BIT__", "8");
00344 
00345   DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Builder);
00346   DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
00347   DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
00348   DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
00349   DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
00350   DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
00351   DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
00352 
00353   DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
00354   DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
00355   DefineTypeWidth("__INTMAX_WIDTH__",  TI.getIntMaxType(), TI, Builder);
00356   DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
00357   DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
00358   DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
00359   DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
00360   DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
00361   DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
00362   DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
00363   DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
00364   DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
00365   DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
00366   DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
00367 
00368   DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat());
00369   DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat());
00370   DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat());
00371 
00372   // Define a __POINTER_WIDTH__ macro for stdint.h.
00373   Builder.defineMacro("__POINTER_WIDTH__",
00374                       llvm::Twine((int)TI.getPointerWidth(0)));
00375 
00376   if (!LangOpts.CharIsSigned)
00377     Builder.defineMacro("__CHAR_UNSIGNED__");
00378 
00379   // Define exact-width integer types for stdint.h
00380   Builder.defineMacro("__INT" + llvm::Twine(TI.getCharWidth()) + "_TYPE__",
00381                       "char");
00382 
00383   if (TI.getShortWidth() > TI.getCharWidth())
00384     DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
00385 
00386   if (TI.getIntWidth() > TI.getShortWidth())
00387     DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
00388 
00389   if (TI.getLongWidth() > TI.getIntWidth())
00390     DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
00391 
00392   if (TI.getLongLongWidth() > TI.getLongWidth())
00393     DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
00394 
00395   // Add __builtin_va_list typedef.
00396   Builder.append(TI.getVAListDeclaration());
00397 
00398   if (const char *Prefix = TI.getUserLabelPrefix())
00399     Builder.defineMacro("__USER_LABEL_PREFIX__", Prefix);
00400 
00401   // Build configuration options.  FIXME: these should be controlled by
00402   // command line options or something.
00403   Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
00404 
00405   if (LangOpts.GNUInline)
00406     Builder.defineMacro("__GNUC_GNU_INLINE__");
00407   else
00408     Builder.defineMacro("__GNUC_STDC_INLINE__");
00409 
00410   if (LangOpts.NoInline)
00411     Builder.defineMacro("__NO_INLINE__");
00412 
00413   if (unsigned PICLevel = LangOpts.PICLevel) {
00414     Builder.defineMacro("__PIC__", llvm::Twine(PICLevel));
00415     Builder.defineMacro("__pic__", llvm::Twine(PICLevel));
00416   }
00417 
00418   // Macros to control C99 numerics and <float.h>
00419   Builder.defineMacro("__FLT_EVAL_METHOD__", "0");
00420   Builder.defineMacro("__FLT_RADIX__", "2");
00421   int Dig = PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36);
00422   Builder.defineMacro("__DECIMAL_DIG__", llvm::Twine(Dig));
00423 
00424   if (LangOpts.getStackProtectorMode() == LangOptions::SSPOn)
00425     Builder.defineMacro("__SSP__");
00426   else if (LangOpts.getStackProtectorMode() == LangOptions::SSPReq)
00427     Builder.defineMacro("__SSP_ALL__", "2");
00428 
00429   if (FEOpts.ProgramAction == frontend::RewriteObjC)
00430     Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
00431   // Get other target #defines.
00432   TI.getTargetDefines(LangOpts, Builder);
00433 }
00434 
00435 // Initialize the remapping of files to alternative contents, e.g.,
00436 // those specified through other files.
00437 static void InitializeFileRemapping(Diagnostic &Diags,
00438                                     SourceManager &SourceMgr,
00439                                     FileManager &FileMgr,
00440                                     const PreprocessorOptions &InitOpts) {
00441   // Remap files in the source manager (with buffers).
00442   for (PreprocessorOptions::remapped_file_buffer_iterator
00443          Remap = InitOpts.remapped_file_buffer_begin(),
00444          RemapEnd = InitOpts.remapped_file_buffer_end();
00445        Remap != RemapEnd;
00446        ++Remap) {
00447     // Create the file entry for the file that we're mapping from.
00448     const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
00449                                                 Remap->second->getBufferSize(),
00450                                                        0);
00451     if (!FromFile) {
00452       Diags.Report(diag::err_fe_remap_missing_from_file)
00453         << Remap->first;
00454       delete Remap->second;
00455       continue;
00456     }
00457 
00458     // Override the contents of the "from" file with the contents of
00459     // the "to" file.
00460     SourceMgr.overrideFileContents(FromFile, Remap->second);
00461   }
00462 
00463   // Remap files in the source manager (with other files).
00464   for (PreprocessorOptions::remapped_file_iterator
00465        Remap = InitOpts.remapped_file_begin(),
00466        RemapEnd = InitOpts.remapped_file_end();
00467        Remap != RemapEnd;
00468        ++Remap) {
00469     // Find the file that we're mapping to.
00470     const FileEntry *ToFile = FileMgr.getFile(Remap->second);
00471     if (!ToFile) {
00472       Diags.Report(diag::err_fe_remap_missing_to_file)
00473       << Remap->first << Remap->second;
00474       continue;
00475     }
00476     
00477     // Create the file entry for the file that we're mapping from.
00478     const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
00479                                                        ToFile->getSize(),
00480                                                        0);
00481     if (!FromFile) {
00482       Diags.Report(diag::err_fe_remap_missing_from_file)
00483       << Remap->first;
00484       continue;
00485     }
00486     
00487     // Load the contents of the file we're mapping to.
00488     std::string ErrorStr;
00489     const llvm::MemoryBuffer *Buffer
00490     = llvm::MemoryBuffer::getFile(ToFile->getName(), &ErrorStr);
00491     if (!Buffer) {
00492       Diags.Report(diag::err_fe_error_opening)
00493         << Remap->second << ErrorStr;
00494       continue;
00495     }
00496     
00497     // Override the contents of the "from" file with the contents of
00498     // the "to" file.
00499     SourceMgr.overrideFileContents(FromFile, Buffer);
00500   }
00501 }
00502 
00503 /// InitializePreprocessor - Initialize the preprocessor getting it and the
00504 /// environment ready to process a single file. This returns true on error.
00505 ///
00506 void clang::InitializePreprocessor(Preprocessor &PP,
00507                                    const PreprocessorOptions &InitOpts,
00508                                    const HeaderSearchOptions &HSOpts,
00509                                    const FrontendOptions &FEOpts) {
00510   std::string PredefineBuffer;
00511   PredefineBuffer.reserve(4080);
00512   llvm::raw_string_ostream Predefines(PredefineBuffer);
00513   MacroBuilder Builder(Predefines);
00514 
00515   InitializeFileRemapping(PP.getDiagnostics(), PP.getSourceManager(),
00516                           PP.getFileManager(), InitOpts);
00517 
00518   // Emit line markers for various builtin sections of the file.  We don't do
00519   // this in asm preprocessor mode, because "# 4" is not a line marker directive
00520   // in this mode.
00521   if (!PP.getLangOptions().AsmPreprocessor)
00522     Builder.append("# 1 \"<built-in>\" 3");
00523 
00524   // Install things like __POWERPC__, __GNUC__, etc into the macro table.
00525   if (InitOpts.UsePredefines)
00526     InitializePredefinedMacros(PP.getTargetInfo(), PP.getLangOptions(),
00527                                FEOpts, Builder);
00528 
00529   // Add on the predefines from the driver.  Wrap in a #line directive to report
00530   // that they come from the command line.
00531   if (!PP.getLangOptions().AsmPreprocessor)
00532     Builder.append("# 1 \"<command line>\" 1");
00533 
00534   // Process #define's and #undef's in the order they are given.
00535   for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
00536     if (InitOpts.Macros[i].second)  // isUndef
00537       Builder.undefineMacro(InitOpts.Macros[i].first);
00538     else
00539       DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
00540                          PP.getDiagnostics());
00541   }
00542 
00543   // If -imacros are specified, include them now.  These are processed before
00544   // any -include directives.
00545   for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
00546     AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i]);
00547 
00548   // Process -include directives.
00549   for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
00550     const std::string &Path = InitOpts.Includes[i];
00551     if (Path == InitOpts.ImplicitPTHInclude)
00552       AddImplicitIncludePTH(Builder, PP, Path);
00553     else
00554       AddImplicitInclude(Builder, Path);
00555   }
00556 
00557   // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
00558   if (!PP.getLangOptions().AsmPreprocessor)
00559     Builder.append("# 1 \"<built-in>\" 2");
00560 
00561   // Copy PredefinedBuffer into the Preprocessor.
00562   PP.setPredefines(Predefines.str());
00563 
00564   // Initialize the header search object.
00565   ApplyHeaderSearchOptions(PP.getHeaderSearchInfo(), HSOpts,
00566                            PP.getLangOptions(),
00567                            PP.getTargetInfo().getTriple());
00568 }