1 //===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
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 code simply runs the preprocessor on the input file and prints out the
11 // result.  This is the traditional behavior of the -E option.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Frontend/Utils.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Frontend/PreprocessorOutputOptions.h"
19 #include "clang/Lex/MacroInfo.h"
20 #include "clang/Lex/PPCallbacks.h"
21 #include "clang/Lex/Pragma.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Lex/TokenConcatenation.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include <cctype>
30 #include <cstdio>
31 using namespace clang;
32 
33 /// PrintMacroDefinition - Print a macro definition in a form that will be
34 /// properly accepted back as a definition.
35 static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
36                                  Preprocessor &PP, raw_ostream &OS) {
37   OS << "#define " << II.getName();
38 
39   if (MI.isFunctionLike()) {
40     OS << '(';
41     if (!MI.arg_empty()) {
42       MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
43       for (; AI+1 != E; ++AI) {
44         OS << (*AI)->getName();
45         OS << ',';
46       }
47 
48       // Last argument.
49       if ((*AI)->getName() == "__VA_ARGS__")
50         OS << "...";
51       else
52         OS << (*AI)->getName();
53     }
54 
55     if (MI.isGNUVarargs())
56       OS << "...";  // #define foo(x...)
57 
58     OS << ')';
59   }
60 
61   // GCC always emits a space, even if the macro body is empty.  However, do not
62   // want to emit two spaces if the first token has a leading space.
63   if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
64     OS << ' ';
65 
66   SmallString<128> SpellingBuffer;
67   for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
68        I != E; ++I) {
69     if (I->hasLeadingSpace())
70       OS << ' ';
71 
72     OS << PP.getSpelling(*I, SpellingBuffer);
73   }
74 }
75 
76 //===----------------------------------------------------------------------===//
77 // Preprocessed token printer
78 //===----------------------------------------------------------------------===//
79 
80 namespace {
81 class PrintPPOutputPPCallbacks : public PPCallbacks {
82   Preprocessor &PP;
83   SourceManager &SM;
84   TokenConcatenation ConcatInfo;
85 public:
86   raw_ostream &OS;
87 private:
88   unsigned CurLine;
89 
90   bool EmittedTokensOnThisLine;
91   bool EmittedDirectiveOnThisLine;
92   SrcMgr::CharacteristicKind FileType;
93   SmallString<512> CurFilename;
94   bool Initialized;
95   bool DisableLineMarkers;
96   bool DumpDefines;
97   bool UseLineDirective;
98   bool IsFirstFileEntered;
99 public:
100   PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os,
101                            bool lineMarkers, bool defines)
102      : PP(pp), SM(PP.getSourceManager()),
103        ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
104        DumpDefines(defines) {
105     CurLine = 0;
106     CurFilename += "<uninit>";
107     EmittedTokensOnThisLine = false;
108     EmittedDirectiveOnThisLine = false;
109     FileType = SrcMgr::C_User;
110     Initialized = false;
111     IsFirstFileEntered = false;
112 
113     // If we're in microsoft mode, use normal #line instead of line markers.
114     UseLineDirective = PP.getLangOpts().MicrosoftExt;
115   }
116 
117   void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
118   bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
119 
120   void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
121   bool hasEmittedDirectiveOnThisLine() const {
122     return EmittedDirectiveOnThisLine;
123   }
124 
125   bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
126 
127   virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
128                            SrcMgr::CharacteristicKind FileType,
129                            FileID PrevFID);
130   virtual void Ident(SourceLocation Loc, const std::string &str);
131   virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
132                              const std::string &Str);
133   virtual void PragmaMessage(SourceLocation Loc, StringRef Str);
134   virtual void PragmaDiagnosticPush(SourceLocation Loc,
135                                     StringRef Namespace);
136   virtual void PragmaDiagnosticPop(SourceLocation Loc,
137                                    StringRef Namespace);
138   virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
139                                 diag::Mapping Map, StringRef Str);
140 
141   bool HandleFirstTokOnLine(Token &Tok);
142   bool MoveToLine(SourceLocation Loc) {
143     PresumedLoc PLoc = SM.getPresumedLoc(Loc);
144     if (PLoc.isInvalid())
145       return false;
146     return MoveToLine(PLoc.getLine());
147   }
148   bool MoveToLine(unsigned LineNo);
149 
150   bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
151                    const Token &Tok) {
152     return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
153   }
154   void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
155   bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
156   void HandleNewlinesInToken(const char *TokStr, unsigned Len);
157 
158   /// MacroDefined - This hook is called whenever a macro definition is seen.
159   void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI);
160 
161   /// MacroUndefined - This hook is called whenever a macro #undef is seen.
162   void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI);
163 };
164 }  // end anonymous namespace
165 
166 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
167                                              const char *Extra,
168                                              unsigned ExtraLen) {
169   startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
170 
171   // Emit #line directives or GNU line markers depending on what mode we're in.
172   if (UseLineDirective) {
173     OS << "#line" << ' ' << LineNo << ' ' << '"';
174     OS.write(CurFilename.data(), CurFilename.size());
175     OS << '"';
176   } else {
177     OS << '#' << ' ' << LineNo << ' ' << '"';
178     OS.write(CurFilename.data(), CurFilename.size());
179     OS << '"';
180 
181     if (ExtraLen)
182       OS.write(Extra, ExtraLen);
183 
184     if (FileType == SrcMgr::C_System)
185       OS.write(" 3", 2);
186     else if (FileType == SrcMgr::C_ExternCSystem)
187       OS.write(" 3 4", 4);
188   }
189   OS << '\n';
190 }
191 
192 /// MoveToLine - Move the output to the source line specified by the location
193 /// object.  We can do this by emitting some number of \n's, or be emitting a
194 /// #line directive.  This returns false if already at the specified line, true
195 /// if some newlines were emitted.
196 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
197   // If this line is "close enough" to the original line, just print newlines,
198   // otherwise print a #line directive.
199   if (LineNo-CurLine <= 8) {
200     if (LineNo-CurLine == 1)
201       OS << '\n';
202     else if (LineNo == CurLine)
203       return false;    // Spelling line moved, but expansion line didn't.
204     else {
205       const char *NewLines = "\n\n\n\n\n\n\n\n";
206       OS.write(NewLines, LineNo-CurLine);
207     }
208   } else if (!DisableLineMarkers) {
209     // Emit a #line or line marker.
210     WriteLineInfo(LineNo, 0, 0);
211   } else {
212     // Okay, we're in -P mode, which turns off line markers.  However, we still
213     // need to emit a newline between tokens on different lines.
214     startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
215   }
216 
217   CurLine = LineNo;
218   return true;
219 }
220 
221 bool
222 PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
223   if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
224     OS << '\n';
225     EmittedTokensOnThisLine = false;
226     EmittedDirectiveOnThisLine = false;
227     if (ShouldUpdateCurrentLine)
228       ++CurLine;
229     return true;
230   }
231 
232   return false;
233 }
234 
235 /// FileChanged - Whenever the preprocessor enters or exits a #include file
236 /// it invokes this handler.  Update our conception of the current source
237 /// position.
238 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
239                                            FileChangeReason Reason,
240                                        SrcMgr::CharacteristicKind NewFileType,
241                                        FileID PrevFID) {
242   // Unless we are exiting a #include, make sure to skip ahead to the line the
243   // #include directive was at.
244   SourceManager &SourceMgr = SM;
245 
246   PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
247   if (UserLoc.isInvalid())
248     return;
249 
250   unsigned NewLine = UserLoc.getLine();
251 
252   if (Reason == PPCallbacks::EnterFile) {
253     SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
254     if (IncludeLoc.isValid())
255       MoveToLine(IncludeLoc);
256   } else if (Reason == PPCallbacks::SystemHeaderPragma) {
257     MoveToLine(NewLine);
258 
259     // TODO GCC emits the # directive for this directive on the line AFTER the
260     // directive and emits a bunch of spaces that aren't needed.  Emulate this
261     // strange behavior.
262   }
263 
264   CurLine = NewLine;
265 
266   CurFilename.clear();
267   CurFilename += UserLoc.getFilename();
268   Lexer::Stringify(CurFilename);
269   FileType = NewFileType;
270 
271   if (DisableLineMarkers) return;
272 
273   if (!Initialized) {
274     WriteLineInfo(CurLine);
275     Initialized = true;
276   }
277 
278   // Do not emit an enter marker for the main file (which we expect is the first
279   // entered file). This matches gcc, and improves compatibility with some tools
280   // which track the # line markers as a way to determine when the preprocessed
281   // output is in the context of the main file.
282   if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
283     IsFirstFileEntered = true;
284     return;
285   }
286 
287   switch (Reason) {
288   case PPCallbacks::EnterFile:
289     WriteLineInfo(CurLine, " 1", 2);
290     break;
291   case PPCallbacks::ExitFile:
292     WriteLineInfo(CurLine, " 2", 2);
293     break;
294   case PPCallbacks::SystemHeaderPragma:
295   case PPCallbacks::RenameFile:
296     WriteLineInfo(CurLine);
297     break;
298   }
299 }
300 
301 /// Ident - Handle #ident directives when read by the preprocessor.
302 ///
303 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
304   MoveToLine(Loc);
305 
306   OS.write("#ident ", strlen("#ident "));
307   OS.write(&S[0], S.size());
308   EmittedTokensOnThisLine = true;
309 }
310 
311 /// MacroDefined - This hook is called whenever a macro definition is seen.
312 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
313                                             const MacroInfo *MI) {
314   // Only print out macro definitions in -dD mode.
315   if (!DumpDefines ||
316       // Ignore __FILE__ etc.
317       MI->isBuiltinMacro()) return;
318 
319   MoveToLine(MI->getDefinitionLoc());
320   PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
321   setEmittedDirectiveOnThisLine();
322 }
323 
324 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
325                                               const MacroInfo *MI) {
326   // Only print out macro definitions in -dD mode.
327   if (!DumpDefines) return;
328 
329   MoveToLine(MacroNameTok.getLocation());
330   OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
331   setEmittedDirectiveOnThisLine();
332 }
333 
334 void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
335                                              const IdentifierInfo *Kind,
336                                              const std::string &Str) {
337   startNewLineIfNeeded();
338   MoveToLine(Loc);
339   OS << "#pragma comment(" << Kind->getName();
340 
341   if (!Str.empty()) {
342     OS << ", \"";
343 
344     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
345       unsigned char Char = Str[i];
346       if (isprint(Char) && Char != '\\' && Char != '"')
347         OS << (char)Char;
348       else  // Output anything hard as an octal escape.
349         OS << '\\'
350            << (char)('0'+ ((Char >> 6) & 7))
351            << (char)('0'+ ((Char >> 3) & 7))
352            << (char)('0'+ ((Char >> 0) & 7));
353     }
354     OS << '"';
355   }
356 
357   OS << ')';
358   setEmittedDirectiveOnThisLine();
359 }
360 
361 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
362                                              StringRef Str) {
363   startNewLineIfNeeded();
364   MoveToLine(Loc);
365   OS << "#pragma message(";
366 
367   OS << '"';
368 
369   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
370     unsigned char Char = Str[i];
371     if (isprint(Char) && Char != '\\' && Char != '"')
372       OS << (char)Char;
373     else  // Output anything hard as an octal escape.
374       OS << '\\'
375          << (char)('0'+ ((Char >> 6) & 7))
376          << (char)('0'+ ((Char >> 3) & 7))
377          << (char)('0'+ ((Char >> 0) & 7));
378   }
379   OS << '"';
380 
381   OS << ')';
382   setEmittedDirectiveOnThisLine();
383 }
384 
385 void PrintPPOutputPPCallbacks::
386 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
387   startNewLineIfNeeded();
388   MoveToLine(Loc);
389   OS << "#pragma " << Namespace << " diagnostic push";
390   setEmittedDirectiveOnThisLine();
391 }
392 
393 void PrintPPOutputPPCallbacks::
394 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
395   startNewLineIfNeeded();
396   MoveToLine(Loc);
397   OS << "#pragma " << Namespace << " diagnostic pop";
398   setEmittedDirectiveOnThisLine();
399 }
400 
401 void PrintPPOutputPPCallbacks::
402 PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
403                  diag::Mapping Map, StringRef Str) {
404   startNewLineIfNeeded();
405   MoveToLine(Loc);
406   OS << "#pragma " << Namespace << " diagnostic ";
407   switch (Map) {
408   case diag::MAP_WARNING:
409     OS << "warning";
410     break;
411   case diag::MAP_ERROR:
412     OS << "error";
413     break;
414   case diag::MAP_IGNORE:
415     OS << "ignored";
416     break;
417   case diag::MAP_FATAL:
418     OS << "fatal";
419     break;
420   }
421   OS << " \"" << Str << '"';
422   setEmittedDirectiveOnThisLine();
423 }
424 
425 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
426 /// is called for the first token on each new line.  If this really is the start
427 /// of a new logical line, handle it and return true, otherwise return false.
428 /// This may not be the start of a logical line because the "start of line"
429 /// marker is set for spelling lines, not expansion ones.
430 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
431   // Figure out what line we went to and insert the appropriate number of
432   // newline characters.
433   if (!MoveToLine(Tok.getLocation()))
434     return false;
435 
436   // Print out space characters so that the first token on a line is
437   // indented for easy reading.
438   unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
439 
440   // This hack prevents stuff like:
441   // #define HASH #
442   // HASH define foo bar
443   // From having the # character end up at column 1, which makes it so it
444   // is not handled as a #define next time through the preprocessor if in
445   // -fpreprocessed mode.
446   if (ColNo <= 1 && Tok.is(tok::hash))
447     OS << ' ';
448 
449   // Otherwise, indent the appropriate number of spaces.
450   for (; ColNo > 1; --ColNo)
451     OS << ' ';
452 
453   return true;
454 }
455 
456 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
457                                                      unsigned Len) {
458   unsigned NumNewlines = 0;
459   for (; Len; --Len, ++TokStr) {
460     if (*TokStr != '\n' &&
461         *TokStr != '\r')
462       continue;
463 
464     ++NumNewlines;
465 
466     // If we have \n\r or \r\n, skip both and count as one line.
467     if (Len != 1 &&
468         (TokStr[1] == '\n' || TokStr[1] == '\r') &&
469         TokStr[0] != TokStr[1])
470       ++TokStr, --Len;
471   }
472 
473   if (NumNewlines == 0) return;
474 
475   CurLine += NumNewlines;
476 }
477 
478 
479 namespace {
480 struct UnknownPragmaHandler : public PragmaHandler {
481   const char *Prefix;
482   PrintPPOutputPPCallbacks *Callbacks;
483 
484   UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
485     : Prefix(prefix), Callbacks(callbacks) {}
486   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
487                             Token &PragmaTok) {
488     // Figure out what line we went to and insert the appropriate number of
489     // newline characters.
490     Callbacks->startNewLineIfNeeded();
491     Callbacks->MoveToLine(PragmaTok.getLocation());
492     Callbacks->OS.write(Prefix, strlen(Prefix));
493     // Read and print all of the pragma tokens.
494     while (PragmaTok.isNot(tok::eod)) {
495       if (PragmaTok.hasLeadingSpace())
496         Callbacks->OS << ' ';
497       std::string TokSpell = PP.getSpelling(PragmaTok);
498       Callbacks->OS.write(&TokSpell[0], TokSpell.size());
499       PP.LexUnexpandedToken(PragmaTok);
500     }
501     Callbacks->setEmittedDirectiveOnThisLine();
502   }
503 };
504 } // end anonymous namespace
505 
506 
507 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
508                                     PrintPPOutputPPCallbacks *Callbacks,
509                                     raw_ostream &OS) {
510   char Buffer[256];
511   Token PrevPrevTok, PrevTok;
512   PrevPrevTok.startToken();
513   PrevTok.startToken();
514   while (1) {
515     if (Callbacks->hasEmittedDirectiveOnThisLine()) {
516       Callbacks->startNewLineIfNeeded();
517       Callbacks->MoveToLine(Tok.getLocation());
518     }
519 
520     // If this token is at the start of a line, emit newlines if needed.
521     if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
522       // done.
523     } else if (Tok.hasLeadingSpace() ||
524                // If we haven't emitted a token on this line yet, PrevTok isn't
525                // useful to look at and no concatenation could happen anyway.
526                (Callbacks->hasEmittedTokensOnThisLine() &&
527                 // Don't print "-" next to "-", it would form "--".
528                 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
529       OS << ' ';
530     }
531 
532     if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
533       OS << II->getName();
534     } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
535                Tok.getLiteralData()) {
536       OS.write(Tok.getLiteralData(), Tok.getLength());
537     } else if (Tok.getLength() < 256) {
538       const char *TokPtr = Buffer;
539       unsigned Len = PP.getSpelling(Tok, TokPtr);
540       OS.write(TokPtr, Len);
541 
542       // Tokens that can contain embedded newlines need to adjust our current
543       // line number.
544       if (Tok.getKind() == tok::comment)
545         Callbacks->HandleNewlinesInToken(TokPtr, Len);
546     } else {
547       std::string S = PP.getSpelling(Tok);
548       OS.write(&S[0], S.size());
549 
550       // Tokens that can contain embedded newlines need to adjust our current
551       // line number.
552       if (Tok.getKind() == tok::comment)
553         Callbacks->HandleNewlinesInToken(&S[0], S.size());
554     }
555     Callbacks->setEmittedTokensOnThisLine();
556 
557     if (Tok.is(tok::eof)) break;
558 
559     PrevPrevTok = PrevTok;
560     PrevTok = Tok;
561     PP.Lex(Tok);
562   }
563 }
564 
565 typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
566 static int MacroIDCompare(const void* a, const void* b) {
567   const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
568   const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
569   return LHS->first->getName().compare(RHS->first->getName());
570 }
571 
572 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
573   // Ignore unknown pragmas.
574   PP.AddPragmaHandler(new EmptyPragmaHandler());
575 
576   // -dM mode just scans and ignores all tokens in the files, then dumps out
577   // the macro table at the end.
578   PP.EnterMainSourceFile();
579 
580   Token Tok;
581   do PP.Lex(Tok);
582   while (Tok.isNot(tok::eof));
583 
584   SmallVector<id_macro_pair, 128> MacrosByID;
585   for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
586        I != E; ++I) {
587     if (I->first->hasMacroDefinition())
588       MacrosByID.push_back(id_macro_pair(I->first, I->second));
589   }
590   llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
591 
592   for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
593     MacroInfo &MI = *MacrosByID[i].second;
594     // Ignore computed macros like __LINE__ and friends.
595     if (MI.isBuiltinMacro()) continue;
596 
597     PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
598     *OS << '\n';
599   }
600 }
601 
602 /// DoPrintPreprocessedInput - This implements -E mode.
603 ///
604 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
605                                      const PreprocessorOutputOptions &Opts) {
606   // Show macros with no output is handled specially.
607   if (!Opts.ShowCPP) {
608     assert(Opts.ShowMacros && "Not yet implemented!");
609     DoPrintMacros(PP, OS);
610     return;
611   }
612 
613   // Inform the preprocessor whether we want it to retain comments or not, due
614   // to -C or -CC.
615   PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
616 
617   PrintPPOutputPPCallbacks *Callbacks =
618       new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
619                                    Opts.ShowMacros);
620   PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
621   PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
622   PP.AddPragmaHandler("clang",
623                       new UnknownPragmaHandler("#pragma clang", Callbacks));
624 
625   PP.addPPCallbacks(Callbacks);
626 
627   // After we have configured the preprocessor, enter the main file.
628   PP.EnterMainSourceFile();
629 
630   // Consume all of the tokens that come from the predefines buffer.  Those
631   // should not be emitted into the output and are guaranteed to be at the
632   // start.
633   const SourceManager &SourceMgr = PP.getSourceManager();
634   Token Tok;
635   do {
636     PP.Lex(Tok);
637     if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
638       break;
639 
640     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
641     if (PLoc.isInvalid())
642       break;
643 
644     if (strcmp(PLoc.getFilename(), "<built-in>"))
645       break;
646   } while (true);
647 
648   // Read all the preprocessed tokens, printing them out to the stream.
649   PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
650   *OS << '\n';
651 }
652