xref: /llvm-project/clang/lib/Frontend/InitPreprocessor.cpp (revision 34ddec630c9d069f641c99812c4b68eb3f2ff565)
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 
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/MemoryBuffer.h"
26 #include "llvm/System/Path.h"
27 using namespace clang;
28 
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, llvm::StringRef Macro,
33                                Diagnostic &Diags) {
34   std::pair<llvm::StringRef, llvm::StringRef> MacroPair = Macro.split('=');
35   llvm::StringRef MacroName = MacroPair.first;
36   llvm::StringRef MacroBody = MacroPair.second;
37   if (MacroName.size() != Macro.size()) {
38     // Per GCC -D semantics, the macro ends at \n if it exists.
39     llvm::StringRef::size_type End = MacroBody.find_first_of("\n\r");
40     if (End != llvm::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 
50 std::string clang::NormalizeDashIncludePath(llvm::StringRef File) {
51   // Implicit include paths should be resolved relative to the current
52   // working directory first, and then use the regular header search
53   // mechanism. The proper way to handle this is to have the
54   // predefines buffer located at the current working directory, but
55   // it has not file entry. For now, workaround this by using an
56   // absolute path if we find the file here, and otherwise letting
57   // header search handle it.
58   llvm::sys::Path Path(File);
59   Path.makeAbsolute();
60   if (!Path.exists())
61     Path = File;
62 
63   return Lexer::Stringify(Path.str());
64 }
65 
66 /// AddImplicitInclude - Add an implicit #include of the specified file to the
67 /// predefines buffer.
68 static void AddImplicitInclude(MacroBuilder &Builder, llvm::StringRef File) {
69   Builder.append("#include \"" +
70                  llvm::Twine(NormalizeDashIncludePath(File)) + "\"");
71 }
72 
73 static void AddImplicitIncludeMacros(MacroBuilder &Builder,
74                                      llvm::StringRef File) {
75   Builder.append("#__include_macros \"" +
76                  llvm::Twine(NormalizeDashIncludePath(File)) + "\"");
77   // Marker token to stop the __include_macros fetch loop.
78   Builder.append("##"); // ##?
79 }
80 
81 /// AddImplicitIncludePTH - Add an implicit #include using the original file
82 ///  used to generate a PTH cache.
83 static void AddImplicitIncludePTH(MacroBuilder &Builder, Preprocessor &PP,
84                                   llvm::StringRef ImplicitIncludePTH) {
85   PTHManager *P = PP.getPTHManager();
86   assert(P && "No PTHManager.");
87   const char *OriginalFile = P->getOriginalSourceFile();
88 
89   if (!OriginalFile) {
90     PP.getDiagnostics().Report(diag::err_fe_pth_file_has_no_source_header)
91       << ImplicitIncludePTH;
92     return;
93   }
94 
95   AddImplicitInclude(Builder, OriginalFile);
96 }
97 
98 /// PickFP - This is used to pick a value based on the FP semantics of the
99 /// specified FP model.
100 template <typename T>
101 static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
102                 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
103                 T IEEEQuadVal) {
104   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle)
105     return IEEESingleVal;
106   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble)
107     return IEEEDoubleVal;
108   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended)
109     return X87DoubleExtendedVal;
110   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble)
111     return PPCDoubleDoubleVal;
112   assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad);
113   return IEEEQuadVal;
114 }
115 
116 static void DefineFloatMacros(MacroBuilder &Builder, llvm::StringRef Prefix,
117                               const llvm::fltSemantics *Sem) {
118   const char *DenormMin, *Epsilon, *Max, *Min;
119   DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
120                      "3.64519953188247460253e-4951L",
121                      "4.94065645841246544176568792868221e-324L",
122                      "6.47517511943802511092443895822764655e-4966L");
123   int Digits = PickFP(Sem, 6, 15, 18, 31, 33);
124   Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
125                    "1.08420217248550443401e-19L",
126                    "4.94065645841246544176568792868221e-324L",
127                    "1.92592994438723585305597794258492732e-34L");
128   int MantissaDigits = PickFP(Sem, 24, 53, 64, 106, 113);
129   int Min10Exp = PickFP(Sem, -37, -307, -4931, -291, -4931);
130   int Max10Exp = PickFP(Sem, 38, 308, 4932, 308, 4932);
131   int MinExp = PickFP(Sem, -125, -1021, -16381, -968, -16381);
132   int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024, 16384);
133   Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
134                "3.36210314311209350626e-4932L",
135                "2.00416836000897277799610805135016e-292L",
136                "3.36210314311209350626267781732175260e-4932L");
137   Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
138                "1.18973149535723176502e+4932L",
139                "1.79769313486231580793728971405301e+308L",
140                "1.18973149535723176508575932662800702e+4932L");
141 
142   llvm::SmallString<32> DefPrefix;
143   DefPrefix = "__";
144   DefPrefix += Prefix;
145   DefPrefix += "_";
146 
147   Builder.defineMacro(DefPrefix + "DENORM_MIN__", DenormMin);
148   Builder.defineMacro(DefPrefix + "HAS_DENORM__");
149   Builder.defineMacro(DefPrefix + "DIG__", llvm::Twine(Digits));
150   Builder.defineMacro(DefPrefix + "EPSILON__", llvm::Twine(Epsilon));
151   Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
152   Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
153   Builder.defineMacro(DefPrefix + "MANT_DIG__", llvm::Twine(MantissaDigits));
154 
155   Builder.defineMacro(DefPrefix + "MAX_10_EXP__", llvm::Twine(Max10Exp));
156   Builder.defineMacro(DefPrefix + "MAX_EXP__", llvm::Twine(MaxExp));
157   Builder.defineMacro(DefPrefix + "MAX__", llvm::Twine(Max));
158 
159   Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+llvm::Twine(Min10Exp)+")");
160   Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+llvm::Twine(MinExp)+")");
161   Builder.defineMacro(DefPrefix + "MIN__", llvm::Twine(Min));
162 }
163 
164 
165 /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
166 /// named MacroName with the max value for a type with width 'TypeWidth' a
167 /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
168 static void DefineTypeSize(llvm::StringRef MacroName, unsigned TypeWidth,
169                            llvm::StringRef ValSuffix, bool isSigned,
170                            MacroBuilder& Builder) {
171   long long MaxVal;
172   if (isSigned)
173     MaxVal = (1LL << (TypeWidth - 1)) - 1;
174   else
175     MaxVal = ~0LL >> (64-TypeWidth);
176 
177   Builder.defineMacro(MacroName, llvm::Twine(MaxVal) + ValSuffix);
178 }
179 
180 /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
181 /// the width, suffix, and signedness of the given type
182 static void DefineTypeSize(llvm::StringRef MacroName, TargetInfo::IntType Ty,
183                            const TargetInfo &TI, MacroBuilder &Builder) {
184   DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
185                  TI.isTypeSigned(Ty), Builder);
186 }
187 
188 static void DefineType(const llvm::Twine &MacroName, TargetInfo::IntType Ty,
189                        MacroBuilder &Builder) {
190   Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
191 }
192 
193 static void DefineTypeWidth(llvm::StringRef MacroName, TargetInfo::IntType Ty,
194                             const TargetInfo &TI, MacroBuilder &Builder) {
195   Builder.defineMacro(MacroName, llvm::Twine(TI.getTypeWidth(Ty)));
196 }
197 
198 static void DefineExactWidthIntType(TargetInfo::IntType Ty,
199                                const TargetInfo &TI, MacroBuilder &Builder) {
200   int TypeWidth = TI.getTypeWidth(Ty);
201   DefineType("__INT" + llvm::Twine(TypeWidth) + "_TYPE__", Ty, Builder);
202 
203   llvm::StringRef ConstSuffix(TargetInfo::getTypeConstantSuffix(Ty));
204   if (!ConstSuffix.empty())
205     Builder.defineMacro("__INT" + llvm::Twine(TypeWidth) + "_C_SUFFIX__",
206                         ConstSuffix);
207 }
208 
209 static void InitializePredefinedMacros(const TargetInfo &TI,
210                                        const LangOptions &LangOpts,
211                                        const FrontendOptions &FEOpts,
212                                        MacroBuilder &Builder) {
213   // Compiler version introspection macros.
214   Builder.defineMacro("__llvm__");  // LLVM Backend
215   Builder.defineMacro("__clang__"); // Clang Frontend
216 #define TOSTR2(X) #X
217 #define TOSTR(X) TOSTR2(X)
218   Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
219   Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
220 #ifdef CLANG_VERSION_PATCHLEVEL
221   Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
222 #else
223   Builder.defineMacro("__clang_patchlevel__", "0");
224 #endif
225   Builder.defineMacro("__clang_version__",
226                       "\"" CLANG_VERSION_STRING " ("
227                       + getClangFullRepositoryVersion() + ")\"");
228 #undef TOSTR
229 #undef TOSTR2
230   // Currently claim to be compatible with GCC 4.2.1-5621.
231   Builder.defineMacro("__GNUC_MINOR__", "2");
232   Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
233   Builder.defineMacro("__GNUC__", "4");
234   Builder.defineMacro("__GXX_ABI_VERSION", "1002");
235   Builder.defineMacro("__VERSION__", "\"4.2.1 Compatible Clang Compiler\"");
236 
237   // Initialize language-specific preprocessor defines.
238 
239   // These should all be defined in the preprocessor according to the
240   // current language configuration.
241   if (!LangOpts.Microsoft)
242     Builder.defineMacro("__STDC__");
243   if (LangOpts.AsmPreprocessor)
244     Builder.defineMacro("__ASSEMBLER__");
245 
246   if (!LangOpts.CPlusPlus) {
247     if (LangOpts.C99)
248       Builder.defineMacro("__STDC_VERSION__", "199901L");
249     else if (!LangOpts.GNUMode && LangOpts.Digraphs)
250       Builder.defineMacro("__STDC_VERSION__", "199409L");
251   }
252 
253   // Standard conforming mode?
254   if (!LangOpts.GNUMode)
255     Builder.defineMacro("__STRICT_ANSI__");
256 
257   if (LangOpts.CPlusPlus0x)
258     Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
259 
260   if (LangOpts.Freestanding)
261     Builder.defineMacro("__STDC_HOSTED__", "0");
262   else
263     Builder.defineMacro("__STDC_HOSTED__");
264 
265   if (LangOpts.ObjC1) {
266     Builder.defineMacro("__OBJC__");
267     if (LangOpts.ObjCNonFragileABI) {
268       Builder.defineMacro("__OBJC2__");
269       Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
270     }
271 
272     if (LangOpts.getGCMode() != LangOptions::NonGC)
273       Builder.defineMacro("__OBJC_GC__");
274 
275     if (LangOpts.NeXTRuntime)
276       Builder.defineMacro("__NEXT_RUNTIME__");
277   }
278 
279   // darwin_constant_cfstrings controls this. This is also dependent
280   // on other things like the runtime I believe.  This is set even for C code.
281   Builder.defineMacro("__CONSTANT_CFSTRINGS__");
282 
283   if (LangOpts.ObjC2)
284     Builder.defineMacro("OBJC_NEW_PROPERTIES");
285 
286   if (LangOpts.PascalStrings)
287     Builder.defineMacro("__PASCAL_STRINGS__");
288 
289   if (LangOpts.Blocks) {
290     Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
291     Builder.defineMacro("__BLOCKS__");
292   }
293 
294   if (LangOpts.Exceptions)
295     Builder.defineMacro("__EXCEPTIONS");
296   if (LangOpts.SjLjExceptions)
297     Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
298 
299   if (LangOpts.CPlusPlus) {
300     Builder.defineMacro("__DEPRECATED");
301     Builder.defineMacro("__GNUG__", "4");
302     Builder.defineMacro("__GXX_WEAK__");
303     if (LangOpts.GNUMode)
304       Builder.defineMacro("__cplusplus");
305     else
306       // C++ [cpp.predefined]p1:
307       //   The name_ _cplusplusis defined to the value199711Lwhen compiling a
308       //   C++ translation unit.
309       Builder.defineMacro("__cplusplus", "199711L");
310     Builder.defineMacro("__private_extern__", "extern");
311   }
312 
313   if (LangOpts.Microsoft) {
314     // Filter out some microsoft extensions when trying to parse in ms-compat
315     // mode.
316     Builder.defineMacro("__int8", "__INT8_TYPE__");
317     Builder.defineMacro("__int16", "__INT16_TYPE__");
318     Builder.defineMacro("__int32", "__INT32_TYPE__");
319     Builder.defineMacro("__int64", "__INT64_TYPE__");
320     // Both __PRETTY_FUNCTION__ and __FUNCTION__ are GCC extensions, however
321     // VC++ appears to only like __FUNCTION__.
322     Builder.defineMacro("__PRETTY_FUNCTION__", "__FUNCTION__");
323     // Work around some issues with Visual C++ headerws.
324     if (LangOpts.CPlusPlus) {
325       // Since we define wchar_t in C++ mode.
326       Builder.defineMacro("_WCHAR_T_DEFINED");
327       Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
328       // FIXME:  This should be temporary until we have a __pragma
329       // solution, to avoid some errors flagged in VC++ headers.
330       Builder.defineMacro("_CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES", "0");
331     }
332   }
333 
334   if (LangOpts.Optimize)
335     Builder.defineMacro("__OPTIMIZE__");
336   if (LangOpts.OptimizeSize)
337     Builder.defineMacro("__OPTIMIZE_SIZE__");
338 
339   // Initialize target-specific preprocessor defines.
340 
341   // Define type sizing macros based on the target properties.
342   assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
343   Builder.defineMacro("__CHAR_BIT__", "8");
344 
345   DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Builder);
346   DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
347   DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
348   DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
349   DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
350   DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
351   DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
352 
353   DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
354   DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
355   DefineTypeWidth("__INTMAX_WIDTH__",  TI.getIntMaxType(), TI, Builder);
356   DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
357   DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
358   DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
359   DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
360   DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
361   DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
362   DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
363   DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
364   DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
365   DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
366   DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
367 
368   DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat());
369   DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat());
370   DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat());
371 
372   // Define a __POINTER_WIDTH__ macro for stdint.h.
373   Builder.defineMacro("__POINTER_WIDTH__",
374                       llvm::Twine((int)TI.getPointerWidth(0)));
375 
376   if (!LangOpts.CharIsSigned)
377     Builder.defineMacro("__CHAR_UNSIGNED__");
378 
379   // Define exact-width integer types for stdint.h
380   Builder.defineMacro("__INT" + llvm::Twine(TI.getCharWidth()) + "_TYPE__",
381                       "char");
382 
383   if (TI.getShortWidth() > TI.getCharWidth())
384     DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
385 
386   if (TI.getIntWidth() > TI.getShortWidth())
387     DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
388 
389   if (TI.getLongWidth() > TI.getIntWidth())
390     DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
391 
392   if (TI.getLongLongWidth() > TI.getLongWidth())
393     DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
394 
395   // Add __builtin_va_list typedef.
396   Builder.append(TI.getVAListDeclaration());
397 
398   if (const char *Prefix = TI.getUserLabelPrefix())
399     Builder.defineMacro("__USER_LABEL_PREFIX__", Prefix);
400 
401   // Build configuration options.  FIXME: these should be controlled by
402   // command line options or something.
403   Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
404 
405   if (LangOpts.GNUInline)
406     Builder.defineMacro("__GNUC_GNU_INLINE__");
407   else
408     Builder.defineMacro("__GNUC_STDC_INLINE__");
409 
410   if (LangOpts.NoInline)
411     Builder.defineMacro("__NO_INLINE__");
412 
413   if (unsigned PICLevel = LangOpts.PICLevel) {
414     Builder.defineMacro("__PIC__", llvm::Twine(PICLevel));
415     Builder.defineMacro("__pic__", llvm::Twine(PICLevel));
416   }
417 
418   // Macros to control C99 numerics and <float.h>
419   Builder.defineMacro("__FLT_EVAL_METHOD__", "0");
420   Builder.defineMacro("__FLT_RADIX__", "2");
421   int Dig = PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36);
422   Builder.defineMacro("__DECIMAL_DIG__", llvm::Twine(Dig));
423 
424   if (LangOpts.getStackProtectorMode() == LangOptions::SSPOn)
425     Builder.defineMacro("__SSP__");
426   else if (LangOpts.getStackProtectorMode() == LangOptions::SSPReq)
427     Builder.defineMacro("__SSP_ALL__", "2");
428 
429   if (FEOpts.ProgramAction == frontend::RewriteObjC)
430     Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
431 
432   // Define a macro that exists only when using the static analyzer.
433   if (FEOpts.ProgramAction == frontend::RunAnalysis)
434     Builder.defineMacro("__clang_analyzer__");
435 
436   // Get other target #defines.
437   TI.getTargetDefines(LangOpts, Builder);
438 }
439 
440 // Initialize the remapping of files to alternative contents, e.g.,
441 // those specified through other files.
442 static void InitializeFileRemapping(Diagnostic &Diags,
443                                     SourceManager &SourceMgr,
444                                     FileManager &FileMgr,
445                                     const PreprocessorOptions &InitOpts) {
446   // Remap files in the source manager (with buffers).
447   for (PreprocessorOptions::remapped_file_buffer_iterator
448          Remap = InitOpts.remapped_file_buffer_begin(),
449          RemapEnd = InitOpts.remapped_file_buffer_end();
450        Remap != RemapEnd;
451        ++Remap) {
452     // Create the file entry for the file that we're mapping from.
453     const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
454                                                 Remap->second->getBufferSize(),
455                                                        0);
456     if (!FromFile) {
457       Diags.Report(diag::err_fe_remap_missing_from_file)
458         << Remap->first;
459       delete Remap->second;
460       continue;
461     }
462 
463     // Override the contents of the "from" file with the contents of
464     // the "to" file.
465     SourceMgr.overrideFileContents(FromFile, Remap->second);
466   }
467 
468   // Remap files in the source manager (with other files).
469   for (PreprocessorOptions::remapped_file_iterator
470        Remap = InitOpts.remapped_file_begin(),
471        RemapEnd = InitOpts.remapped_file_end();
472        Remap != RemapEnd;
473        ++Remap) {
474     // Find the file that we're mapping to.
475     const FileEntry *ToFile = FileMgr.getFile(Remap->second);
476     if (!ToFile) {
477       Diags.Report(diag::err_fe_remap_missing_to_file)
478       << Remap->first << Remap->second;
479       continue;
480     }
481 
482     // Create the file entry for the file that we're mapping from.
483     const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
484                                                        ToFile->getSize(),
485                                                        0);
486     if (!FromFile) {
487       Diags.Report(diag::err_fe_remap_missing_from_file)
488       << Remap->first;
489       continue;
490     }
491 
492     // Load the contents of the file we're mapping to.
493     std::string ErrorStr;
494     const llvm::MemoryBuffer *Buffer
495     = llvm::MemoryBuffer::getFile(ToFile->getName(), &ErrorStr);
496     if (!Buffer) {
497       Diags.Report(diag::err_fe_error_opening)
498         << Remap->second << ErrorStr;
499       continue;
500     }
501 
502     // Override the contents of the "from" file with the contents of
503     // the "to" file.
504     SourceMgr.overrideFileContents(FromFile, Buffer);
505   }
506 }
507 
508 /// InitializePreprocessor - Initialize the preprocessor getting it and the
509 /// environment ready to process a single file. This returns true on error.
510 ///
511 void clang::InitializePreprocessor(Preprocessor &PP,
512                                    const PreprocessorOptions &InitOpts,
513                                    const HeaderSearchOptions &HSOpts,
514                                    const FrontendOptions &FEOpts) {
515   std::string PredefineBuffer;
516   PredefineBuffer.reserve(4080);
517   llvm::raw_string_ostream Predefines(PredefineBuffer);
518   MacroBuilder Builder(Predefines);
519 
520   InitializeFileRemapping(PP.getDiagnostics(), PP.getSourceManager(),
521                           PP.getFileManager(), InitOpts);
522 
523   // Emit line markers for various builtin sections of the file.  We don't do
524   // this in asm preprocessor mode, because "# 4" is not a line marker directive
525   // in this mode.
526   if (!PP.getLangOptions().AsmPreprocessor)
527     Builder.append("# 1 \"<built-in>\" 3");
528 
529   // Install things like __POWERPC__, __GNUC__, etc into the macro table.
530   if (InitOpts.UsePredefines)
531     InitializePredefinedMacros(PP.getTargetInfo(), PP.getLangOptions(),
532                                FEOpts, Builder);
533 
534   // Add on the predefines from the driver.  Wrap in a #line directive to report
535   // that they come from the command line.
536   if (!PP.getLangOptions().AsmPreprocessor)
537     Builder.append("# 1 \"<command line>\" 1");
538 
539   // Process #define's and #undef's in the order they are given.
540   for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
541     if (InitOpts.Macros[i].second)  // isUndef
542       Builder.undefineMacro(InitOpts.Macros[i].first);
543     else
544       DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
545                          PP.getDiagnostics());
546   }
547 
548   // If -imacros are specified, include them now.  These are processed before
549   // any -include directives.
550   for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
551     AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i]);
552 
553   // Process -include directives.
554   for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
555     const std::string &Path = InitOpts.Includes[i];
556     if (Path == InitOpts.ImplicitPTHInclude)
557       AddImplicitIncludePTH(Builder, PP, Path);
558     else
559       AddImplicitInclude(Builder, Path);
560   }
561 
562   // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
563   if (!PP.getLangOptions().AsmPreprocessor)
564     Builder.append("# 1 \"<built-in>\" 2");
565 
566   // Copy PredefinedBuffer into the Preprocessor.
567   PP.setPredefines(Predefines.str());
568 
569   // Initialize the header search object.
570   ApplyHeaderSearchOptions(PP.getHeaderSearchInfo(), HSOpts,
571                            PP.getLangOptions(),
572                            PP.getTargetInfo().getTriple());
573 }
574