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