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