]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Frontend/PrintPreprocessedOutput.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r302069, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Frontend / PrintPreprocessedOutput.cpp
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   // In -dI mode, dump #include directives prior to dumping their content or
328   // interpretation.
329   if (DumpIncludeDirectives) {
330     startNewLineIfNeeded();
331     MoveToLine(HashLoc);
332     const std::string TokenText = PP.getSpelling(IncludeTok);
333     assert(!TokenText.empty());
334     OS << "#" << TokenText << " "
335        << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
336        << " /* clang -E -dI */";
337     setEmittedDirectiveOnThisLine();
338     startNewLineIfNeeded();
339   }
340
341   // When preprocessing, turn implicit imports into module import pragmas.
342   if (Imported) {
343     switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
344     case tok::pp_include:
345     case tok::pp_import:
346     case tok::pp_include_next:
347       startNewLineIfNeeded();
348       MoveToLine(HashLoc);
349       OS << "#pragma clang module import " << Imported->getFullModuleName()
350          << " /* clang -E: implicit import for "
351          << "#" << PP.getSpelling(IncludeTok) << " "
352          << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
353          << " */";
354       // Since we want a newline after the pragma, but not a #<line>, start a
355       // new line immediately.
356       EmittedTokensOnThisLine = true;
357       startNewLineIfNeeded();
358       break;
359
360     case tok::pp___include_macros:
361       // #__include_macros has no effect on a user of a preprocessed source
362       // file; the only effect is on preprocessing.
363       //
364       // FIXME: That's not *quite* true: it causes the module in question to
365       // be loaded, which can affect downstream diagnostics.
366       break;
367
368     default:
369       llvm_unreachable("unknown include directive kind");
370       break;
371     }
372   }
373 }
374
375 /// Ident - Handle #ident directives when read by the preprocessor.
376 ///
377 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
378   MoveToLine(Loc);
379
380   OS.write("#ident ", strlen("#ident "));
381   OS.write(S.begin(), S.size());
382   EmittedTokensOnThisLine = true;
383 }
384
385 /// MacroDefined - This hook is called whenever a macro definition is seen.
386 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
387                                             const MacroDirective *MD) {
388   const MacroInfo *MI = MD->getMacroInfo();
389   // Only print out macro definitions in -dD mode.
390   if (!DumpDefines ||
391       // Ignore __FILE__ etc.
392       MI->isBuiltinMacro()) return;
393
394   MoveToLine(MI->getDefinitionLoc());
395   PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
396   setEmittedDirectiveOnThisLine();
397 }
398
399 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
400                                               const MacroDefinition &MD,
401                                               const MacroDirective *Undef) {
402   // Only print out macro definitions in -dD mode.
403   if (!DumpDefines) return;
404
405   MoveToLine(MacroNameTok.getLocation());
406   OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
407   setEmittedDirectiveOnThisLine();
408 }
409
410 static void outputPrintable(raw_ostream &OS, StringRef Str) {
411   for (unsigned char Char : Str) {
412     if (isPrintable(Char) && Char != '\\' && Char != '"')
413       OS << (char)Char;
414     else // Output anything hard as an octal escape.
415       OS << '\\'
416          << (char)('0' + ((Char >> 6) & 7))
417          << (char)('0' + ((Char >> 3) & 7))
418          << (char)('0' + ((Char >> 0) & 7));
419   }
420 }
421
422 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
423                                              StringRef Namespace,
424                                              PragmaMessageKind Kind,
425                                              StringRef Str) {
426   startNewLineIfNeeded();
427   MoveToLine(Loc);
428   OS << "#pragma ";
429   if (!Namespace.empty())
430     OS << Namespace << ' ';
431   switch (Kind) {
432     case PMK_Message:
433       OS << "message(\"";
434       break;
435     case PMK_Warning:
436       OS << "warning \"";
437       break;
438     case PMK_Error:
439       OS << "error \"";
440       break;
441   }
442
443   outputPrintable(OS, Str);
444   OS << '"';
445   if (Kind == PMK_Message)
446     OS << ')';
447   setEmittedDirectiveOnThisLine();
448 }
449
450 void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
451                                            StringRef DebugType) {
452   startNewLineIfNeeded();
453   MoveToLine(Loc);
454
455   OS << "#pragma clang __debug ";
456   OS << DebugType;
457
458   setEmittedDirectiveOnThisLine();
459 }
460
461 void PrintPPOutputPPCallbacks::
462 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
463   startNewLineIfNeeded();
464   MoveToLine(Loc);
465   OS << "#pragma " << Namespace << " diagnostic push";
466   setEmittedDirectiveOnThisLine();
467 }
468
469 void PrintPPOutputPPCallbacks::
470 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
471   startNewLineIfNeeded();
472   MoveToLine(Loc);
473   OS << "#pragma " << Namespace << " diagnostic pop";
474   setEmittedDirectiveOnThisLine();
475 }
476
477 void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
478                                                 StringRef Namespace,
479                                                 diag::Severity Map,
480                                                 StringRef Str) {
481   startNewLineIfNeeded();
482   MoveToLine(Loc);
483   OS << "#pragma " << Namespace << " diagnostic ";
484   switch (Map) {
485   case diag::Severity::Remark:
486     OS << "remark";
487     break;
488   case diag::Severity::Warning:
489     OS << "warning";
490     break;
491   case diag::Severity::Error:
492     OS << "error";
493     break;
494   case diag::Severity::Ignored:
495     OS << "ignored";
496     break;
497   case diag::Severity::Fatal:
498     OS << "fatal";
499     break;
500   }
501   OS << " \"" << Str << '"';
502   setEmittedDirectiveOnThisLine();
503 }
504
505 void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
506                                              StringRef WarningSpec,
507                                              ArrayRef<int> Ids) {
508   startNewLineIfNeeded();
509   MoveToLine(Loc);
510   OS << "#pragma warning(" << WarningSpec << ':';
511   for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
512     OS << ' ' << *I;
513   OS << ')';
514   setEmittedDirectiveOnThisLine();
515 }
516
517 void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
518                                                  int Level) {
519   startNewLineIfNeeded();
520   MoveToLine(Loc);
521   OS << "#pragma warning(push";
522   if (Level >= 0)
523     OS << ", " << Level;
524   OS << ')';
525   setEmittedDirectiveOnThisLine();
526 }
527
528 void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
529   startNewLineIfNeeded();
530   MoveToLine(Loc);
531   OS << "#pragma warning(pop)";
532   setEmittedDirectiveOnThisLine();
533 }
534
535 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
536 /// is called for the first token on each new line.  If this really is the start
537 /// of a new logical line, handle it and return true, otherwise return false.
538 /// This may not be the start of a logical line because the "start of line"
539 /// marker is set for spelling lines, not expansion ones.
540 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
541   // Figure out what line we went to and insert the appropriate number of
542   // newline characters.
543   if (!MoveToLine(Tok.getLocation()))
544     return false;
545
546   // Print out space characters so that the first token on a line is
547   // indented for easy reading.
548   unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
549
550   // The first token on a line can have a column number of 1, yet still expect
551   // leading white space, if a macro expansion in column 1 starts with an empty
552   // macro argument, or an empty nested macro expansion. In this case, move the
553   // token to column 2.
554   if (ColNo == 1 && Tok.hasLeadingSpace())
555     ColNo = 2;
556
557   // This hack prevents stuff like:
558   // #define HASH #
559   // HASH define foo bar
560   // From having the # character end up at column 1, which makes it so it
561   // is not handled as a #define next time through the preprocessor if in
562   // -fpreprocessed mode.
563   if (ColNo <= 1 && Tok.is(tok::hash))
564     OS << ' ';
565
566   // Otherwise, indent the appropriate number of spaces.
567   for (; ColNo > 1; --ColNo)
568     OS << ' ';
569
570   return true;
571 }
572
573 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
574                                                      unsigned Len) {
575   unsigned NumNewlines = 0;
576   for (; Len; --Len, ++TokStr) {
577     if (*TokStr != '\n' &&
578         *TokStr != '\r')
579       continue;
580
581     ++NumNewlines;
582
583     // If we have \n\r or \r\n, skip both and count as one line.
584     if (Len != 1 &&
585         (TokStr[1] == '\n' || TokStr[1] == '\r') &&
586         TokStr[0] != TokStr[1]) {
587       ++TokStr;
588       --Len;
589     }
590   }
591
592   if (NumNewlines == 0) return;
593
594   CurLine += NumNewlines;
595 }
596
597
598 namespace {
599 struct UnknownPragmaHandler : public PragmaHandler {
600   const char *Prefix;
601   PrintPPOutputPPCallbacks *Callbacks;
602
603   // Set to true if tokens should be expanded
604   bool ShouldExpandTokens;
605
606   UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
607                        bool RequireTokenExpansion)
608       : Prefix(prefix), Callbacks(callbacks),
609         ShouldExpandTokens(RequireTokenExpansion) {}
610   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
611                     Token &PragmaTok) override {
612     // Figure out what line we went to and insert the appropriate number of
613     // newline characters.
614     Callbacks->startNewLineIfNeeded();
615     Callbacks->MoveToLine(PragmaTok.getLocation());
616     Callbacks->OS.write(Prefix, strlen(Prefix));
617
618     if (ShouldExpandTokens) {
619       // The first token does not have expanded macros. Expand them, if
620       // required.
621       auto Toks = llvm::make_unique<Token[]>(1);
622       Toks[0] = PragmaTok;
623       PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
624                           /*DisableMacroExpansion=*/false);
625       PP.Lex(PragmaTok);
626     }
627     Token PrevToken;
628     Token PrevPrevToken;
629     PrevToken.startToken();
630     PrevPrevToken.startToken();
631
632     // Read and print all of the pragma tokens.
633     while (PragmaTok.isNot(tok::eod)) {
634       if (PragmaTok.hasLeadingSpace() ||
635           Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
636         Callbacks->OS << ' ';
637       std::string TokSpell = PP.getSpelling(PragmaTok);
638       Callbacks->OS.write(&TokSpell[0], TokSpell.size());
639
640       PrevPrevToken = PrevToken;
641       PrevToken = PragmaTok;
642
643       if (ShouldExpandTokens)
644         PP.Lex(PragmaTok);
645       else
646         PP.LexUnexpandedToken(PragmaTok);
647     }
648     Callbacks->setEmittedDirectiveOnThisLine();
649   }
650 };
651 } // end anonymous namespace
652
653
654 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
655                                     PrintPPOutputPPCallbacks *Callbacks,
656                                     raw_ostream &OS) {
657   bool DropComments = PP.getLangOpts().TraditionalCPP &&
658                       !PP.getCommentRetentionState();
659
660   char Buffer[256];
661   Token PrevPrevTok, PrevTok;
662   PrevPrevTok.startToken();
663   PrevTok.startToken();
664   while (1) {
665     if (Callbacks->hasEmittedDirectiveOnThisLine()) {
666       Callbacks->startNewLineIfNeeded();
667       Callbacks->MoveToLine(Tok.getLocation());
668     }
669
670     // If this token is at the start of a line, emit newlines if needed.
671     if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
672       // done.
673     } else if (Tok.hasLeadingSpace() ||
674                // If we haven't emitted a token on this line yet, PrevTok isn't
675                // useful to look at and no concatenation could happen anyway.
676                (Callbacks->hasEmittedTokensOnThisLine() &&
677                 // Don't print "-" next to "-", it would form "--".
678                 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
679       OS << ' ';
680     }
681
682     if (DropComments && Tok.is(tok::comment)) {
683       // Skip comments. Normally the preprocessor does not generate
684       // tok::comment nodes at all when not keeping comments, but under
685       // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
686       SourceLocation StartLoc = Tok.getLocation();
687       Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
688     } else if (Tok.is(tok::annot_module_include) ||
689                Tok.is(tok::annot_module_begin) ||
690                Tok.is(tok::annot_module_end)) {
691       // PrintPPOutputPPCallbacks::InclusionDirective handles producing
692       // appropriate output here. Ignore this token entirely.
693       PP.Lex(Tok);
694       continue;
695     } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
696       OS << II->getName();
697     } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
698                Tok.getLiteralData()) {
699       OS.write(Tok.getLiteralData(), Tok.getLength());
700     } else if (Tok.getLength() < 256) {
701       const char *TokPtr = Buffer;
702       unsigned Len = PP.getSpelling(Tok, TokPtr);
703       OS.write(TokPtr, Len);
704
705       // Tokens that can contain embedded newlines need to adjust our current
706       // line number.
707       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
708         Callbacks->HandleNewlinesInToken(TokPtr, Len);
709     } else {
710       std::string S = PP.getSpelling(Tok);
711       OS.write(&S[0], S.size());
712
713       // Tokens that can contain embedded newlines need to adjust our current
714       // line number.
715       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
716         Callbacks->HandleNewlinesInToken(&S[0], S.size());
717     }
718     Callbacks->setEmittedTokensOnThisLine();
719
720     if (Tok.is(tok::eof)) break;
721
722     PrevPrevTok = PrevTok;
723     PrevTok = Tok;
724     PP.Lex(Tok);
725   }
726 }
727
728 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
729 static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
730   return LHS->first->getName().compare(RHS->first->getName());
731 }
732
733 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
734   // Ignore unknown pragmas.
735   PP.IgnorePragmas();
736
737   // -dM mode just scans and ignores all tokens in the files, then dumps out
738   // the macro table at the end.
739   PP.EnterMainSourceFile();
740
741   Token Tok;
742   do PP.Lex(Tok);
743   while (Tok.isNot(tok::eof));
744
745   SmallVector<id_macro_pair, 128> MacrosByID;
746   for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
747        I != E; ++I) {
748     auto *MD = I->second.getLatest();
749     if (MD && MD->isDefined())
750       MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
751   }
752   llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
753
754   for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
755     MacroInfo &MI = *MacrosByID[i].second;
756     // Ignore computed macros like __LINE__ and friends.
757     if (MI.isBuiltinMacro()) continue;
758
759     PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
760     *OS << '\n';
761   }
762 }
763
764 /// DoPrintPreprocessedInput - This implements -E mode.
765 ///
766 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
767                                      const PreprocessorOutputOptions &Opts) {
768   // Show macros with no output is handled specially.
769   if (!Opts.ShowCPP) {
770     assert(Opts.ShowMacros && "Not yet implemented!");
771     DoPrintMacros(PP, OS);
772     return;
773   }
774
775   // Inform the preprocessor whether we want it to retain comments or not, due
776   // to -C or -CC.
777   PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
778
779   PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
780       PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
781       Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
782
783   // Expand macros in pragmas with -fms-extensions.  The assumption is that
784   // the majority of pragmas in such a file will be Microsoft pragmas.
785   // Remember the handlers we will add so that we can remove them later.
786   std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
787       new UnknownPragmaHandler(
788           "#pragma", Callbacks,
789           /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
790
791   std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
792       "#pragma GCC", Callbacks,
793       /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
794
795   std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
796       "#pragma clang", Callbacks,
797       /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
798
799   PP.AddPragmaHandler(MicrosoftExtHandler.get());
800   PP.AddPragmaHandler("GCC", GCCHandler.get());
801   PP.AddPragmaHandler("clang", ClangHandler.get());
802
803   // The tokens after pragma omp need to be expanded.
804   //
805   //  OpenMP [2.1, Directive format]
806   //  Preprocessing tokens following the #pragma omp are subject to macro
807   //  replacement.
808   std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
809       new UnknownPragmaHandler("#pragma omp", Callbacks,
810                                /*RequireTokenExpansion=*/true));
811   PP.AddPragmaHandler("omp", OpenMPHandler.get());
812
813   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
814
815   // After we have configured the preprocessor, enter the main file.
816   PP.EnterMainSourceFile();
817
818   // Consume all of the tokens that come from the predefines buffer.  Those
819   // should not be emitted into the output and are guaranteed to be at the
820   // start.
821   const SourceManager &SourceMgr = PP.getSourceManager();
822   Token Tok;
823   do {
824     PP.Lex(Tok);
825     if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
826       break;
827
828     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
829     if (PLoc.isInvalid())
830       break;
831
832     if (strcmp(PLoc.getFilename(), "<built-in>"))
833       break;
834   } while (true);
835
836   // Read all the preprocessed tokens, printing them out to the stream.
837   PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
838   *OS << '\n';
839
840   // Remove the handlers we just added to leave the preprocessor in a sane state
841   // so that it can be reused (for example by a clang::Parser instance).
842   PP.RemovePragmaHandler(MicrosoftExtHandler.get());
843   PP.RemovePragmaHandler("GCC", GCCHandler.get());
844   PP.RemovePragmaHandler("clang", ClangHandler.get());
845   PP.RemovePragmaHandler("omp", OpenMPHandler.get());
846 }