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/CharInfo.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Frontend/PreprocessorOutputOptions.h"
20 #include "clang/Lex/MacroInfo.h"
21 #include "clang/Lex/PPCallbacks.h"
22 #include "clang/Lex/Pragma.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Lex/TokenConcatenation.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
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 (const auto &T : MI.tokens()) {
68     if (T.hasLeadingSpace())
69       OS << ' ';
70 
71     OS << PP.getSpelling(T, 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 DumpIncludeDirectives;
97   bool UseLineDirectives;
98   bool IsFirstFileEntered;
99 public:
100   PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
101                            bool defines, bool DumpIncludeDirectives,
102                            bool UseLineDirectives)
103       : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
104         DisableLineMarkers(lineMarkers), DumpDefines(defines),
105         DumpIncludeDirectives(DumpIncludeDirectives),
106         UseLineDirectives(UseLineDirectives) {
107     CurLine = 0;
108     CurFilename += "<uninit>";
109     EmittedTokensOnThisLine = false;
110     EmittedDirectiveOnThisLine = false;
111     FileType = SrcMgr::C_User;
112     Initialized = false;
113     IsFirstFileEntered = false;
114   }
115 
116   void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
117   bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
118 
119   void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
120   bool hasEmittedDirectiveOnThisLine() const {
121     return EmittedDirectiveOnThisLine;
122   }
123 
124   bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
125 
126   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
127                    SrcMgr::CharacteristicKind FileType,
128                    FileID PrevFID) override;
129   void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
130                           StringRef FileName, bool IsAngled,
131                           CharSourceRange FilenameRange, const FileEntry *File,
132                           StringRef SearchPath, StringRef RelativePath,
133                           const Module *Imported) override;
134   void Ident(SourceLocation Loc, StringRef str) override;
135   void PragmaMessage(SourceLocation Loc, StringRef Namespace,
136                      PragmaMessageKind Kind, StringRef Str) override;
137   void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
138   void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
139   void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
140   void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
141                         diag::Severity Map, StringRef Str) override;
142   void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
143                      ArrayRef<int> Ids) override;
144   void PragmaWarningPush(SourceLocation Loc, int Level) override;
145   void PragmaWarningPop(SourceLocation Loc) override;
146 
147   bool HandleFirstTokOnLine(Token &Tok);
148 
149   /// Move to the line of the provided source location. This will
150   /// return true if the output stream required adjustment or if
151   /// the requested location is on the first line.
152   bool MoveToLine(SourceLocation Loc) {
153     PresumedLoc PLoc = SM.getPresumedLoc(Loc);
154     if (PLoc.isInvalid())
155       return false;
156     return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
157   }
158   bool MoveToLine(unsigned LineNo);
159 
160   bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
161                    const Token &Tok) {
162     return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
163   }
164   void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
165                      unsigned ExtraLen=0);
166   bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
167   void HandleNewlinesInToken(const char *TokStr, unsigned Len);
168 
169   /// MacroDefined - This hook is called whenever a macro definition is seen.
170   void MacroDefined(const Token &MacroNameTok,
171                     const MacroDirective *MD) override;
172 
173   /// MacroUndefined - This hook is called whenever a macro #undef is seen.
174   void MacroUndefined(const Token &MacroNameTok,
175                       const MacroDefinition &MD,
176                       const MacroDirective *Undef) override;
177 };
178 }  // end anonymous namespace
179 
180 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
181                                              const char *Extra,
182                                              unsigned ExtraLen) {
183   startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
184 
185   // Emit #line directives or GNU line markers depending on what mode we're in.
186   if (UseLineDirectives) {
187     OS << "#line" << ' ' << LineNo << ' ' << '"';
188     OS.write_escaped(CurFilename);
189     OS << '"';
190   } else {
191     OS << '#' << ' ' << LineNo << ' ' << '"';
192     OS.write_escaped(CurFilename);
193     OS << '"';
194 
195     if (ExtraLen)
196       OS.write(Extra, ExtraLen);
197 
198     if (FileType == SrcMgr::C_System)
199       OS.write(" 3", 2);
200     else if (FileType == SrcMgr::C_ExternCSystem)
201       OS.write(" 3 4", 4);
202   }
203   OS << '\n';
204 }
205 
206 /// MoveToLine - Move the output to the source line specified by the location
207 /// object.  We can do this by emitting some number of \n's, or be emitting a
208 /// #line directive.  This returns false if already at the specified line, true
209 /// if some newlines were emitted.
210 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
211   // If this line is "close enough" to the original line, just print newlines,
212   // otherwise print a #line directive.
213   if (LineNo-CurLine <= 8) {
214     if (LineNo-CurLine == 1)
215       OS << '\n';
216     else if (LineNo == CurLine)
217       return false;    // Spelling line moved, but expansion line didn't.
218     else {
219       const char *NewLines = "\n\n\n\n\n\n\n\n";
220       OS.write(NewLines, LineNo-CurLine);
221     }
222   } else if (!DisableLineMarkers) {
223     // Emit a #line or line marker.
224     WriteLineInfo(LineNo, nullptr, 0);
225   } else {
226     // Okay, we're in -P mode, which turns off line markers.  However, we still
227     // need to emit a newline between tokens on different lines.
228     startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
229   }
230 
231   CurLine = LineNo;
232   return true;
233 }
234 
235 bool
236 PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
237   if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
238     OS << '\n';
239     EmittedTokensOnThisLine = false;
240     EmittedDirectiveOnThisLine = false;
241     if (ShouldUpdateCurrentLine)
242       ++CurLine;
243     return true;
244   }
245 
246   return false;
247 }
248 
249 /// FileChanged - Whenever the preprocessor enters or exits a #include file
250 /// it invokes this handler.  Update our conception of the current source
251 /// position.
252 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
253                                            FileChangeReason Reason,
254                                        SrcMgr::CharacteristicKind NewFileType,
255                                        FileID PrevFID) {
256   // Unless we are exiting a #include, make sure to skip ahead to the line the
257   // #include directive was at.
258   SourceManager &SourceMgr = SM;
259 
260   PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
261   if (UserLoc.isInvalid())
262     return;
263 
264   unsigned NewLine = UserLoc.getLine();
265 
266   if (Reason == PPCallbacks::EnterFile) {
267     SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
268     if (IncludeLoc.isValid())
269       MoveToLine(IncludeLoc);
270   } else if (Reason == PPCallbacks::SystemHeaderPragma) {
271     // GCC emits the # directive for this directive on the line AFTER the
272     // directive and emits a bunch of spaces that aren't needed. This is because
273     // otherwise we will emit a line marker for THIS line, which requires an
274     // extra blank line after the directive to avoid making all following lines
275     // off by one. We can do better by simply incrementing NewLine here.
276     NewLine += 1;
277   }
278 
279   CurLine = NewLine;
280 
281   CurFilename.clear();
282   CurFilename += UserLoc.getFilename();
283   FileType = NewFileType;
284 
285   if (DisableLineMarkers) {
286     startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
287     return;
288   }
289 
290   if (!Initialized) {
291     WriteLineInfo(CurLine);
292     Initialized = true;
293   }
294 
295   // Do not emit an enter marker for the main file (which we expect is the first
296   // entered file). This matches gcc, and improves compatibility with some tools
297   // which track the # line markers as a way to determine when the preprocessed
298   // output is in the context of the main file.
299   if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
300     IsFirstFileEntered = true;
301     return;
302   }
303 
304   switch (Reason) {
305   case PPCallbacks::EnterFile:
306     WriteLineInfo(CurLine, " 1", 2);
307     break;
308   case PPCallbacks::ExitFile:
309     WriteLineInfo(CurLine, " 2", 2);
310     break;
311   case PPCallbacks::SystemHeaderPragma:
312   case PPCallbacks::RenameFile:
313     WriteLineInfo(CurLine);
314     break;
315   }
316 }
317 
318 void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
319                                                   const Token &IncludeTok,
320                                                   StringRef FileName,
321                                                   bool IsAngled,
322                                                   CharSourceRange FilenameRange,
323                                                   const FileEntry *File,
324                                                   StringRef SearchPath,
325                                                   StringRef RelativePath,
326                                                   const Module *Imported) {
327   if (Imported) {
328     // When preprocessing, turn implicit imports into @imports.
329     // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
330     // modules" solution is introduced.
331     startNewLineIfNeeded();
332     MoveToLine(HashLoc);
333     if (PP.getLangOpts().ObjC2) {
334       OS << "@import " << Imported->getFullModuleName() << ";"
335          << " /* clang -E: implicit import for \"" << File->getName()
336          << "\" */";
337     } else {
338       const std::string TokenText = PP.getSpelling(IncludeTok);
339       assert(!TokenText.empty());
340       OS << "#" << TokenText << " "
341          << (IsAngled ? '<' : '"')
342          << FileName
343          << (IsAngled ? '>' : '"')
344          << " /* clang -E: implicit import for module "
345          << Imported->getFullModuleName() << " */";
346     }
347     // Since we want a newline after the @import, but not a #<line>, start a new
348     // line immediately.
349     EmittedTokensOnThisLine = true;
350     startNewLineIfNeeded();
351   } else {
352     // Not a module import; it's a more vanilla inclusion of some file using one
353     // of: #include, #import, #include_next, #include_macros.
354     if (DumpIncludeDirectives) {
355       startNewLineIfNeeded();
356       MoveToLine(HashLoc);
357       const std::string TokenText = PP.getSpelling(IncludeTok);
358       assert(!TokenText.empty());
359       OS << "#" << TokenText << " "
360          << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
361          << " /* clang -E -dI */";
362       setEmittedDirectiveOnThisLine();
363       startNewLineIfNeeded();
364     }
365   }
366 }
367 
368 /// Ident - Handle #ident directives when read by the preprocessor.
369 ///
370 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
371   MoveToLine(Loc);
372 
373   OS.write("#ident ", strlen("#ident "));
374   OS.write(S.begin(), S.size());
375   EmittedTokensOnThisLine = true;
376 }
377 
378 /// MacroDefined - This hook is called whenever a macro definition is seen.
379 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
380                                             const MacroDirective *MD) {
381   const MacroInfo *MI = MD->getMacroInfo();
382   // Only print out macro definitions in -dD mode.
383   if (!DumpDefines ||
384       // Ignore __FILE__ etc.
385       MI->isBuiltinMacro()) return;
386 
387   MoveToLine(MI->getDefinitionLoc());
388   PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
389   setEmittedDirectiveOnThisLine();
390 }
391 
392 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
393                                               const MacroDefinition &MD,
394                                               const MacroDirective *Undef) {
395   // Only print out macro definitions in -dD mode.
396   if (!DumpDefines) return;
397 
398   MoveToLine(MacroNameTok.getLocation());
399   OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
400   setEmittedDirectiveOnThisLine();
401 }
402 
403 static void outputPrintable(raw_ostream &OS, StringRef Str) {
404   for (unsigned char Char : Str) {
405     if (isPrintable(Char) && Char != '\\' && Char != '"')
406       OS << (char)Char;
407     else // Output anything hard as an octal escape.
408       OS << '\\'
409          << (char)('0' + ((Char >> 6) & 7))
410          << (char)('0' + ((Char >> 3) & 7))
411          << (char)('0' + ((Char >> 0) & 7));
412   }
413 }
414 
415 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
416                                              StringRef Namespace,
417                                              PragmaMessageKind Kind,
418                                              StringRef Str) {
419   startNewLineIfNeeded();
420   MoveToLine(Loc);
421   OS << "#pragma ";
422   if (!Namespace.empty())
423     OS << Namespace << ' ';
424   switch (Kind) {
425     case PMK_Message:
426       OS << "message(\"";
427       break;
428     case PMK_Warning:
429       OS << "warning \"";
430       break;
431     case PMK_Error:
432       OS << "error \"";
433       break;
434   }
435 
436   outputPrintable(OS, Str);
437   OS << '"';
438   if (Kind == PMK_Message)
439     OS << ')';
440   setEmittedDirectiveOnThisLine();
441 }
442 
443 void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
444                                            StringRef DebugType) {
445   startNewLineIfNeeded();
446   MoveToLine(Loc);
447 
448   OS << "#pragma clang __debug ";
449   OS << DebugType;
450 
451   setEmittedDirectiveOnThisLine();
452 }
453 
454 void PrintPPOutputPPCallbacks::
455 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
456   startNewLineIfNeeded();
457   MoveToLine(Loc);
458   OS << "#pragma " << Namespace << " diagnostic push";
459   setEmittedDirectiveOnThisLine();
460 }
461 
462 void PrintPPOutputPPCallbacks::
463 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
464   startNewLineIfNeeded();
465   MoveToLine(Loc);
466   OS << "#pragma " << Namespace << " diagnostic pop";
467   setEmittedDirectiveOnThisLine();
468 }
469 
470 void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
471                                                 StringRef Namespace,
472                                                 diag::Severity Map,
473                                                 StringRef Str) {
474   startNewLineIfNeeded();
475   MoveToLine(Loc);
476   OS << "#pragma " << Namespace << " diagnostic ";
477   switch (Map) {
478   case diag::Severity::Remark:
479     OS << "remark";
480     break;
481   case diag::Severity::Warning:
482     OS << "warning";
483     break;
484   case diag::Severity::Error:
485     OS << "error";
486     break;
487   case diag::Severity::Ignored:
488     OS << "ignored";
489     break;
490   case diag::Severity::Fatal:
491     OS << "fatal";
492     break;
493   }
494   OS << " \"" << Str << '"';
495   setEmittedDirectiveOnThisLine();
496 }
497 
498 void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
499                                              StringRef WarningSpec,
500                                              ArrayRef<int> Ids) {
501   startNewLineIfNeeded();
502   MoveToLine(Loc);
503   OS << "#pragma warning(" << WarningSpec << ':';
504   for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
505     OS << ' ' << *I;
506   OS << ')';
507   setEmittedDirectiveOnThisLine();
508 }
509 
510 void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
511                                                  int Level) {
512   startNewLineIfNeeded();
513   MoveToLine(Loc);
514   OS << "#pragma warning(push";
515   if (Level >= 0)
516     OS << ", " << Level;
517   OS << ')';
518   setEmittedDirectiveOnThisLine();
519 }
520 
521 void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
522   startNewLineIfNeeded();
523   MoveToLine(Loc);
524   OS << "#pragma warning(pop)";
525   setEmittedDirectiveOnThisLine();
526 }
527 
528 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
529 /// is called for the first token on each new line.  If this really is the start
530 /// of a new logical line, handle it and return true, otherwise return false.
531 /// This may not be the start of a logical line because the "start of line"
532 /// marker is set for spelling lines, not expansion ones.
533 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
534   // Figure out what line we went to and insert the appropriate number of
535   // newline characters.
536   if (!MoveToLine(Tok.getLocation()))
537     return false;
538 
539   // Print out space characters so that the first token on a line is
540   // indented for easy reading.
541   unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
542 
543   // The first token on a line can have a column number of 1, yet still expect
544   // leading white space, if a macro expansion in column 1 starts with an empty
545   // macro argument, or an empty nested macro expansion. In this case, move the
546   // token to column 2.
547   if (ColNo == 1 && Tok.hasLeadingSpace())
548     ColNo = 2;
549 
550   // This hack prevents stuff like:
551   // #define HASH #
552   // HASH define foo bar
553   // From having the # character end up at column 1, which makes it so it
554   // is not handled as a #define next time through the preprocessor if in
555   // -fpreprocessed mode.
556   if (ColNo <= 1 && Tok.is(tok::hash))
557     OS << ' ';
558 
559   // Otherwise, indent the appropriate number of spaces.
560   for (; ColNo > 1; --ColNo)
561     OS << ' ';
562 
563   return true;
564 }
565 
566 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
567                                                      unsigned Len) {
568   unsigned NumNewlines = 0;
569   for (; Len; --Len, ++TokStr) {
570     if (*TokStr != '\n' &&
571         *TokStr != '\r')
572       continue;
573 
574     ++NumNewlines;
575 
576     // If we have \n\r or \r\n, skip both and count as one line.
577     if (Len != 1 &&
578         (TokStr[1] == '\n' || TokStr[1] == '\r') &&
579         TokStr[0] != TokStr[1]) {
580       ++TokStr;
581       --Len;
582     }
583   }
584 
585   if (NumNewlines == 0) return;
586 
587   CurLine += NumNewlines;
588 }
589 
590 
591 namespace {
592 struct UnknownPragmaHandler : public PragmaHandler {
593   const char *Prefix;
594   PrintPPOutputPPCallbacks *Callbacks;
595 
596   // Set to true if tokens should be expanded
597   bool ShouldExpandTokens;
598 
599   UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
600                        bool RequireTokenExpansion)
601       : Prefix(prefix), Callbacks(callbacks),
602         ShouldExpandTokens(RequireTokenExpansion) {}
603   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
604                     Token &PragmaTok) override {
605     // Figure out what line we went to and insert the appropriate number of
606     // newline characters.
607     Callbacks->startNewLineIfNeeded();
608     Callbacks->MoveToLine(PragmaTok.getLocation());
609     Callbacks->OS.write(Prefix, strlen(Prefix));
610 
611     if (ShouldExpandTokens) {
612       // The first token does not have expanded macros. Expand them, if
613       // required.
614       auto Toks = llvm::make_unique<Token[]>(1);
615       Toks[0] = PragmaTok;
616       PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
617                           /*DisableMacroExpansion=*/false);
618       PP.Lex(PragmaTok);
619     }
620     Token PrevToken;
621     Token PrevPrevToken;
622     PrevToken.startToken();
623     PrevPrevToken.startToken();
624 
625     // Read and print all of the pragma tokens.
626     while (PragmaTok.isNot(tok::eod)) {
627       if (PragmaTok.hasLeadingSpace() ||
628           Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
629         Callbacks->OS << ' ';
630       std::string TokSpell = PP.getSpelling(PragmaTok);
631       Callbacks->OS.write(&TokSpell[0], TokSpell.size());
632 
633       PrevPrevToken = PrevToken;
634       PrevToken = PragmaTok;
635 
636       if (ShouldExpandTokens)
637         PP.Lex(PragmaTok);
638       else
639         PP.LexUnexpandedToken(PragmaTok);
640     }
641     Callbacks->setEmittedDirectiveOnThisLine();
642   }
643 };
644 } // end anonymous namespace
645 
646 
647 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
648                                     PrintPPOutputPPCallbacks *Callbacks,
649                                     raw_ostream &OS) {
650   bool DropComments = PP.getLangOpts().TraditionalCPP &&
651                       !PP.getCommentRetentionState();
652 
653   char Buffer[256];
654   Token PrevPrevTok, PrevTok;
655   PrevPrevTok.startToken();
656   PrevTok.startToken();
657   while (1) {
658     if (Callbacks->hasEmittedDirectiveOnThisLine()) {
659       Callbacks->startNewLineIfNeeded();
660       Callbacks->MoveToLine(Tok.getLocation());
661     }
662 
663     // If this token is at the start of a line, emit newlines if needed.
664     if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
665       // done.
666     } else if (Tok.hasLeadingSpace() ||
667                // If we haven't emitted a token on this line yet, PrevTok isn't
668                // useful to look at and no concatenation could happen anyway.
669                (Callbacks->hasEmittedTokensOnThisLine() &&
670                 // Don't print "-" next to "-", it would form "--".
671                 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
672       OS << ' ';
673     }
674 
675     if (DropComments && Tok.is(tok::comment)) {
676       // Skip comments. Normally the preprocessor does not generate
677       // tok::comment nodes at all when not keeping comments, but under
678       // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
679       SourceLocation StartLoc = Tok.getLocation();
680       Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
681     } else if (Tok.is(tok::annot_module_include) ||
682                Tok.is(tok::annot_module_begin) ||
683                Tok.is(tok::annot_module_end)) {
684       // PrintPPOutputPPCallbacks::InclusionDirective handles producing
685       // appropriate output here. Ignore this token entirely.
686       PP.Lex(Tok);
687       continue;
688     } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
689       OS << II->getName();
690     } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
691                Tok.getLiteralData()) {
692       OS.write(Tok.getLiteralData(), Tok.getLength());
693     } else if (Tok.getLength() < 256) {
694       const char *TokPtr = Buffer;
695       unsigned Len = PP.getSpelling(Tok, TokPtr);
696       OS.write(TokPtr, Len);
697 
698       // Tokens that can contain embedded newlines need to adjust our current
699       // line number.
700       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
701         Callbacks->HandleNewlinesInToken(TokPtr, Len);
702     } else {
703       std::string S = PP.getSpelling(Tok);
704       OS.write(&S[0], S.size());
705 
706       // Tokens that can contain embedded newlines need to adjust our current
707       // line number.
708       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
709         Callbacks->HandleNewlinesInToken(&S[0], S.size());
710     }
711     Callbacks->setEmittedTokensOnThisLine();
712 
713     if (Tok.is(tok::eof)) break;
714 
715     PrevPrevTok = PrevTok;
716     PrevTok = Tok;
717     PP.Lex(Tok);
718   }
719 }
720 
721 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
722 static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
723   return LHS->first->getName().compare(RHS->first->getName());
724 }
725 
726 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
727   // Ignore unknown pragmas.
728   PP.IgnorePragmas();
729 
730   // -dM mode just scans and ignores all tokens in the files, then dumps out
731   // the macro table at the end.
732   PP.EnterMainSourceFile();
733 
734   Token Tok;
735   do PP.Lex(Tok);
736   while (Tok.isNot(tok::eof));
737 
738   SmallVector<id_macro_pair, 128> MacrosByID;
739   for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
740        I != E; ++I) {
741     auto *MD = I->second.getLatest();
742     if (MD && MD->isDefined())
743       MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
744   }
745   llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
746 
747   for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
748     MacroInfo &MI = *MacrosByID[i].second;
749     // Ignore computed macros like __LINE__ and friends.
750     if (MI.isBuiltinMacro()) continue;
751 
752     PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
753     *OS << '\n';
754   }
755 }
756 
757 /// DoPrintPreprocessedInput - This implements -E mode.
758 ///
759 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
760                                      const PreprocessorOutputOptions &Opts) {
761   // Show macros with no output is handled specially.
762   if (!Opts.ShowCPP) {
763     assert(Opts.ShowMacros && "Not yet implemented!");
764     DoPrintMacros(PP, OS);
765     return;
766   }
767 
768   // Inform the preprocessor whether we want it to retain comments or not, due
769   // to -C or -CC.
770   PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
771 
772   PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
773       PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
774       Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
775 
776   // Expand macros in pragmas with -fms-extensions.  The assumption is that
777   // the majority of pragmas in such a file will be Microsoft pragmas.
778   // Remember the handlers we will add so that we can remove them later.
779   std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
780       new UnknownPragmaHandler(
781           "#pragma", Callbacks,
782           /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
783 
784   std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
785       "#pragma GCC", Callbacks,
786       /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
787 
788   std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
789       "#pragma clang", Callbacks,
790       /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
791 
792   PP.AddPragmaHandler(MicrosoftExtHandler.get());
793   PP.AddPragmaHandler("GCC", GCCHandler.get());
794   PP.AddPragmaHandler("clang", ClangHandler.get());
795 
796   // The tokens after pragma omp need to be expanded.
797   //
798   //  OpenMP [2.1, Directive format]
799   //  Preprocessing tokens following the #pragma omp are subject to macro
800   //  replacement.
801   std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
802       new UnknownPragmaHandler("#pragma omp", Callbacks,
803                                /*RequireTokenExpansion=*/true));
804   PP.AddPragmaHandler("omp", OpenMPHandler.get());
805 
806   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
807 
808   // After we have configured the preprocessor, enter the main file.
809   PP.EnterMainSourceFile();
810 
811   // Consume all of the tokens that come from the predefines buffer.  Those
812   // should not be emitted into the output and are guaranteed to be at the
813   // start.
814   const SourceManager &SourceMgr = PP.getSourceManager();
815   Token Tok;
816   do {
817     PP.Lex(Tok);
818     if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
819       break;
820 
821     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
822     if (PLoc.isInvalid())
823       break;
824 
825     if (strcmp(PLoc.getFilename(), "<built-in>"))
826       break;
827   } while (true);
828 
829   // Read all the preprocessed tokens, printing them out to the stream.
830   PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
831   *OS << '\n';
832 
833   // Remove the handlers we just added to leave the preprocessor in a sane state
834   // so that it can be reused (for example by a clang::Parser instance).
835   PP.RemovePragmaHandler(MicrosoftExtHandler.get());
836   PP.RemovePragmaHandler("GCC", GCCHandler.get());
837   PP.RemovePragmaHandler("clang", ClangHandler.get());
838   PP.RemovePragmaHandler("omp", OpenMPHandler.get());
839 }
840