1 //===--- DiagnosticRenderer.cpp - Diagnostic Pretty-Printing --------------===//
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 #include "clang/Frontend/DiagnosticRenderer.h"
11 #include "clang/Basic/DiagnosticOptions.h"
12 #include "clang/Basic/FileManager.h"
13 #include "clang/Basic/SourceManager.h"
14 #include "clang/Edit/Commit.h"
15 #include "clang/Edit/EditedSource.h"
16 #include "clang/Edit/EditsReceiver.h"
17 #include "clang/Lex/Lexer.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <algorithm>
24 using namespace clang;
25 
26 /// \brief Retrieve the name of the immediate macro expansion.
27 ///
28 /// This routine starts from a source location, and finds the name of the macro
29 /// responsible for its immediate expansion. It looks through any intervening
30 /// macro argument expansions to compute this. It returns a StringRef which
31 /// refers to the SourceManager-owned buffer of the source where that macro
32 /// name is spelled. Thus, the result shouldn't out-live that SourceManager.
33 ///
34 /// This differs from Lexer::getImmediateMacroName in that any macro argument
35 /// location will result in the topmost function macro that accepted it.
36 /// e.g.
37 /// \code
38 ///   MAC1( MAC2(foo) )
39 /// \endcode
40 /// for location of 'foo' token, this function will return "MAC1" while
41 /// Lexer::getImmediateMacroName will return "MAC2".
42 static StringRef getImmediateMacroName(SourceLocation Loc,
43                                        const SourceManager &SM,
44                                        const LangOptions &LangOpts) {
45    assert(Loc.isMacroID() && "Only reasonble to call this on macros");
46    // Walk past macro argument expanions.
47    while (SM.isMacroArgExpansion(Loc))
48      Loc = SM.getImmediateExpansionRange(Loc).first;
49 
50    // If the macro's spelling has no FileID, then it's actually a token paste
51    // or stringization (or similar) and not a macro at all.
52    if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
53      return StringRef();
54 
55    // Find the spelling location of the start of the non-argument expansion
56    // range. This is where the macro name was spelled in order to begin
57    // expanding this macro.
58    Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
59 
60    // Dig out the buffer where the macro name was spelled and the extents of the
61    // name so that we can render it into the expansion note.
62    std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
63    unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
64    StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
65    return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
66 }
67 
68 DiagnosticRenderer::DiagnosticRenderer(const LangOptions &LangOpts,
69                                        DiagnosticOptions *DiagOpts)
70   : LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
71 
72 DiagnosticRenderer::~DiagnosticRenderer() {}
73 
74 namespace {
75 
76 class FixitReceiver : public edit::EditsReceiver {
77   SmallVectorImpl<FixItHint> &MergedFixits;
78 
79 public:
80   FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
81     : MergedFixits(MergedFixits) { }
82   void insert(SourceLocation loc, StringRef text) override {
83     MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
84   }
85   void replace(CharSourceRange range, StringRef text) override {
86     MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
87   }
88 };
89 
90 }
91 
92 static void mergeFixits(ArrayRef<FixItHint> FixItHints,
93                         const SourceManager &SM, const LangOptions &LangOpts,
94                         SmallVectorImpl<FixItHint> &MergedFixits) {
95   edit::Commit commit(SM, LangOpts);
96   for (ArrayRef<FixItHint>::const_iterator
97          I = FixItHints.begin(), E = FixItHints.end(); I != E; ++I) {
98     const FixItHint &Hint = *I;
99     if (Hint.CodeToInsert.empty()) {
100       if (Hint.InsertFromRange.isValid())
101         commit.insertFromRange(Hint.RemoveRange.getBegin(),
102                            Hint.InsertFromRange, /*afterToken=*/false,
103                            Hint.BeforePreviousInsertions);
104       else
105         commit.remove(Hint.RemoveRange);
106     } else {
107       if (Hint.RemoveRange.isTokenRange() ||
108           Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
109         commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
110       else
111         commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
112                     /*afterToken=*/false, Hint.BeforePreviousInsertions);
113     }
114   }
115 
116   edit::EditedSource Editor(SM, LangOpts);
117   if (Editor.commit(commit)) {
118     FixitReceiver Rec(MergedFixits);
119     Editor.applyRewrites(Rec);
120   }
121 }
122 
123 void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc,
124                                         DiagnosticsEngine::Level Level,
125                                         StringRef Message,
126                                         ArrayRef<CharSourceRange> Ranges,
127                                         ArrayRef<FixItHint> FixItHints,
128                                         const SourceManager *SM,
129                                         DiagOrStoredDiag D) {
130   assert(SM || Loc.isInvalid());
131 
132   beginDiagnostic(D, Level);
133 
134   if (!Loc.isValid())
135     // If we have no source location, just emit the diagnostic message.
136     emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, SM, D);
137   else {
138     // Get the ranges into a local array we can hack on.
139     SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
140                                                    Ranges.end());
141 
142     SmallVector<FixItHint, 8> MergedFixits;
143     if (!FixItHints.empty()) {
144       mergeFixits(FixItHints, *SM, LangOpts, MergedFixits);
145       FixItHints = MergedFixits;
146     }
147 
148     for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
149          E = FixItHints.end();
150          I != E; ++I)
151       if (I->RemoveRange.isValid())
152         MutableRanges.push_back(I->RemoveRange);
153 
154     SourceLocation UnexpandedLoc = Loc;
155 
156     // Find the ultimate expansion location for the diagnostic.
157     Loc = SM->getFileLoc(Loc);
158 
159     PresumedLoc PLoc = SM->getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
160 
161     // First, if this diagnostic is not in the main file, print out the
162     // "included from" lines.
163     emitIncludeStack(Loc, PLoc, Level, *SM);
164 
165     // Next, emit the actual diagnostic message and caret.
166     emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, SM, D);
167     emitCaret(Loc, Level, MutableRanges, FixItHints, *SM);
168 
169     // If this location is within a macro, walk from UnexpandedLoc up to Loc
170     // and produce a macro backtrace.
171     if (UnexpandedLoc.isValid() && UnexpandedLoc.isMacroID()) {
172       emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints, *SM);
173     }
174   }
175 
176   LastLoc = Loc;
177   LastLevel = Level;
178 
179   endDiagnostic(D, Level);
180 }
181 
182 
183 void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
184   emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
185                  Diag.getRanges(), Diag.getFixIts(),
186                  Diag.getLocation().isValid() ? &Diag.getLocation().getManager()
187                                               : nullptr,
188                  &Diag);
189 }
190 
191 void DiagnosticRenderer::emitBasicNote(StringRef Message) {
192   emitDiagnosticMessage(
193       SourceLocation(), PresumedLoc(), DiagnosticsEngine::Note, Message,
194       None, nullptr, DiagOrStoredDiag());
195 }
196 
197 /// \brief Prints an include stack when appropriate for a particular
198 /// diagnostic level and location.
199 ///
200 /// This routine handles all the logic of suppressing particular include
201 /// stacks (such as those for notes) and duplicate include stacks when
202 /// repeated warnings occur within the same file. It also handles the logic
203 /// of customizing the formatting and display of the include stack.
204 ///
205 /// \param Loc   The diagnostic location.
206 /// \param PLoc  The presumed location of the diagnostic location.
207 /// \param Level The diagnostic level of the message this stack pertains to.
208 void DiagnosticRenderer::emitIncludeStack(SourceLocation Loc,
209                                           PresumedLoc PLoc,
210                                           DiagnosticsEngine::Level Level,
211                                           const SourceManager &SM) {
212   SourceLocation IncludeLoc = PLoc.getIncludeLoc();
213 
214   // Skip redundant include stacks altogether.
215   if (LastIncludeLoc == IncludeLoc)
216     return;
217 
218   LastIncludeLoc = IncludeLoc;
219 
220   if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
221     return;
222 
223   if (IncludeLoc.isValid())
224     emitIncludeStackRecursively(IncludeLoc, SM);
225   else {
226     emitModuleBuildStack(SM);
227     emitImportStack(Loc, SM);
228   }
229 }
230 
231 /// \brief Helper to recursivly walk up the include stack and print each layer
232 /// on the way back down.
233 void DiagnosticRenderer::emitIncludeStackRecursively(SourceLocation Loc,
234                                                      const SourceManager &SM) {
235   if (Loc.isInvalid()) {
236     emitModuleBuildStack(SM);
237     return;
238   }
239 
240   PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
241   if (PLoc.isInvalid())
242     return;
243 
244   // If this source location was imported from a module, print the module
245   // import stack rather than the
246   // FIXME: We want submodule granularity here.
247   std::pair<SourceLocation, StringRef> Imported = SM.getModuleImportLoc(Loc);
248   if (!Imported.second.empty()) {
249     // This location was imported by a module. Emit the module import stack.
250     emitImportStackRecursively(Imported.first, Imported.second, SM);
251     return;
252   }
253 
254   // Emit the other include frames first.
255   emitIncludeStackRecursively(PLoc.getIncludeLoc(), SM);
256 
257   // Emit the inclusion text/note.
258   emitIncludeLocation(Loc, PLoc, SM);
259 }
260 
261 /// \brief Emit the module import stack associated with the current location.
262 void DiagnosticRenderer::emitImportStack(SourceLocation Loc,
263                                          const SourceManager &SM) {
264   if (Loc.isInvalid()) {
265     emitModuleBuildStack(SM);
266     return;
267   }
268 
269   std::pair<SourceLocation, StringRef> NextImportLoc
270     = SM.getModuleImportLoc(Loc);
271   emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
272 }
273 
274 /// \brief Helper to recursivly walk up the import stack and print each layer
275 /// on the way back down.
276 void DiagnosticRenderer::emitImportStackRecursively(SourceLocation Loc,
277                                                     StringRef ModuleName,
278                                                     const SourceManager &SM) {
279   if (ModuleName.empty()) {
280     return;
281   }
282 
283   PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
284 
285   // Emit the other import frames first.
286   std::pair<SourceLocation, StringRef> NextImportLoc
287     = SM.getModuleImportLoc(Loc);
288   emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
289 
290   // Emit the inclusion text/note.
291   emitImportLocation(Loc, PLoc, ModuleName, SM);
292 }
293 
294 /// \brief Emit the module build stack, for cases where a module is (re-)built
295 /// on demand.
296 void DiagnosticRenderer::emitModuleBuildStack(const SourceManager &SM) {
297   ModuleBuildStack Stack = SM.getModuleBuildStack();
298   for (unsigned I = 0, N = Stack.size(); I != N; ++I) {
299     const SourceManager &CurSM = Stack[I].second.getManager();
300     SourceLocation CurLoc = Stack[I].second;
301     emitBuildingModuleLocation(CurLoc,
302                                CurSM.getPresumedLoc(CurLoc,
303                                                     DiagOpts->ShowPresumedLoc),
304                                Stack[I].first,
305                                CurSM);
306   }
307 }
308 
309 /// A recursive function to trace all possible backtrace locations
310 /// to match the \p CaretLocFileID.
311 static SourceLocation retrieveMacroLocation(SourceLocation Loc,
312                                             FileID MacroFileID,
313                                             FileID CaretFileID,
314                                             bool getBeginLoc,
315                                             const SourceManager *SM) {
316   if (MacroFileID == CaretFileID) return Loc;
317   if (!Loc.isMacroID()) return SourceLocation();
318 
319   SourceLocation MacroLocation, MacroArgLocation;
320 
321   if (SM->isMacroArgExpansion(Loc)) {
322     MacroLocation = SM->getImmediateSpellingLoc(Loc);
323     MacroArgLocation = getBeginLoc ? SM->getImmediateExpansionRange(Loc).first
324                                    : SM->getImmediateExpansionRange(Loc).second;
325   } else {
326     MacroLocation = getBeginLoc ? SM->getImmediateExpansionRange(Loc).first
327                                 : SM->getImmediateExpansionRange(Loc).second;
328     MacroArgLocation = SM->getImmediateSpellingLoc(Loc);
329   }
330 
331   MacroFileID = SM->getFileID(MacroLocation);
332   MacroLocation = retrieveMacroLocation(MacroLocation, MacroFileID, CaretFileID,
333                                         getBeginLoc, SM);
334   if (MacroLocation.isValid()) return MacroLocation;
335 
336   MacroFileID = SM->getFileID(MacroArgLocation);
337   return retrieveMacroLocation(MacroArgLocation, MacroFileID, CaretFileID,
338                                getBeginLoc, SM);
339 }
340 
341 // Helper function to fix up source ranges.  It takes in an array of ranges,
342 // and outputs an array of ranges where we want to draw the range highlighting
343 // around the location specified by CaretLoc.
344 //
345 // To find locations which correspond to the caret, we crawl the macro caller
346 // chain for the beginning and end of each range.  If the caret location
347 // is in a macro expansion, we search each chain for a location
348 // in the same expansion as the caret; otherwise, we crawl to the top of
349 // each chain. Two locations are part of the same macro expansion
350 // iff the FileID is the same.
351 static void mapDiagnosticRanges(
352     SourceLocation CaretLoc,
353     ArrayRef<CharSourceRange> Ranges,
354     SmallVectorImpl<CharSourceRange> &SpellingRanges,
355     const SourceManager *SM) {
356   FileID CaretLocFileID = SM->getFileID(CaretLoc);
357 
358   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
359     if (I->isInvalid()) continue;
360 
361     SourceLocation Begin = I->getBegin(), End = I->getEnd();
362     bool IsTokenRange = I->isTokenRange();
363 
364     FileID BeginFileID = SM->getFileID(Begin);
365     FileID EndFileID = SM->getFileID(End);
366 
367     // Find the common parent for the beginning and end of the range.
368 
369     // First, crawl the expansion chain for the beginning of the range.
370     llvm::SmallDenseMap<FileID, SourceLocation> BeginLocsMap;
371     while (Begin.isMacroID() && BeginFileID != EndFileID) {
372       BeginLocsMap[BeginFileID] = Begin;
373       Begin = SM->getImmediateExpansionRange(Begin).first;
374       BeginFileID = SM->getFileID(Begin);
375     }
376 
377     // Then, crawl the expansion chain for the end of the range.
378     if (BeginFileID != EndFileID) {
379       while (End.isMacroID() && !BeginLocsMap.count(EndFileID)) {
380         End = SM->getImmediateExpansionRange(End).second;
381         EndFileID = SM->getFileID(End);
382       }
383       if (End.isMacroID()) {
384         Begin = BeginLocsMap[EndFileID];
385         BeginFileID = EndFileID;
386       }
387     }
388 
389     // Do the backtracking.
390     Begin = retrieveMacroLocation(Begin, BeginFileID, CaretLocFileID,
391                                   true /*getBeginLoc*/, SM);
392     End = retrieveMacroLocation(End, BeginFileID, CaretLocFileID,
393                                 false /*getBeginLoc*/, SM);
394     if (Begin.isInvalid() || End.isInvalid()) continue;
395 
396     // Return the spelling location of the beginning and end of the range.
397     Begin = SM->getSpellingLoc(Begin);
398     End = SM->getSpellingLoc(End);
399 
400     SpellingRanges.push_back(CharSourceRange(SourceRange(Begin, End),
401                                              IsTokenRange));
402   }
403 }
404 
405 void DiagnosticRenderer::emitCaret(SourceLocation Loc,
406                                    DiagnosticsEngine::Level Level,
407                                    ArrayRef<CharSourceRange> Ranges,
408                                    ArrayRef<FixItHint> Hints,
409                                    const SourceManager &SM) {
410   SmallVector<CharSourceRange, 4> SpellingRanges;
411   mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
412   emitCodeContext(Loc, Level, SpellingRanges, Hints, SM);
413 }
414 
415 /// \brief A helper function for emitMacroExpansion to print the
416 /// macro expansion message
417 void DiagnosticRenderer::emitSingleMacroExpansion(
418     SourceLocation Loc,
419     DiagnosticsEngine::Level Level,
420     ArrayRef<CharSourceRange> Ranges,
421     const SourceManager &SM) {
422   // Find the spelling location for the macro definition. We must use the
423   // spelling location here to avoid emitting a macro backtrace for the note.
424   SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
425 
426   // Map the ranges into the FileID of the diagnostic location.
427   SmallVector<CharSourceRange, 4> SpellingRanges;
428   mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
429 
430   SmallString<100> MessageStorage;
431   llvm::raw_svector_ostream Message(MessageStorage);
432   StringRef MacroName = getImmediateMacroName(Loc, SM, LangOpts);
433   if (MacroName.empty())
434     Message << "expanded from here";
435   else
436     Message << "expanded from macro '" << MacroName << "'";
437 
438   emitDiagnostic(SpellingLoc, DiagnosticsEngine::Note, Message.str(),
439                  SpellingRanges, None, &SM);
440 }
441 
442 /// Check that the macro argument location of Loc starts with ArgumentLoc.
443 /// The starting location of the macro expansions is used to differeniate
444 /// different macro expansions.
445 static bool checkLocForMacroArgExpansion(SourceLocation Loc,
446                                          const SourceManager &SM,
447                                          SourceLocation ArgumentLoc) {
448   SourceLocation MacroLoc;
449   if (SM.isMacroArgExpansion(Loc, &MacroLoc)) {
450     if (ArgumentLoc == MacroLoc) return true;
451   }
452 
453   return false;
454 }
455 
456 /// Check if all the locations in the range have the same macro argument
457 /// expansion, and that that expansion starts with ArgumentLoc.
458 static bool checkRangeForMacroArgExpansion(CharSourceRange Range,
459                                            const SourceManager &SM,
460                                            SourceLocation ArgumentLoc) {
461   SourceLocation BegLoc = Range.getBegin(), EndLoc = Range.getEnd();
462   while (BegLoc != EndLoc) {
463     if (!checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc))
464       return false;
465     BegLoc.getLocWithOffset(1);
466   }
467 
468   return checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc);
469 }
470 
471 /// A helper function to check if the current ranges are all inside the same
472 /// macro argument expansion as Loc.
473 static bool checkRangesForMacroArgExpansion(SourceLocation Loc,
474                                             ArrayRef<CharSourceRange> Ranges,
475                                             const SourceManager &SM) {
476   assert(Loc.isMacroID() && "Must be a macro expansion!");
477 
478   SmallVector<CharSourceRange, 4> SpellingRanges;
479   mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
480 
481   /// Count all valid ranges.
482   unsigned ValidCount = 0;
483   for (auto I : Ranges)
484     if (I.isValid()) ValidCount++;
485 
486   if (ValidCount > SpellingRanges.size())
487     return false;
488 
489   /// To store the source location of the argument location.
490   SourceLocation ArgumentLoc;
491 
492   /// Set the ArgumentLoc to the beginning location of the expansion of Loc
493   /// so to check if the ranges expands to the same beginning location.
494   if (!SM.isMacroArgExpansion(Loc,&ArgumentLoc))
495     return false;
496 
497   for (auto I = SpellingRanges.begin(), E = SpellingRanges.end(); I != E; ++I) {
498     if (!checkRangeForMacroArgExpansion(*I, SM, ArgumentLoc))
499       return false;
500   }
501 
502   return true;
503 }
504 
505 /// \brief Recursively emit notes for each macro expansion and caret
506 /// diagnostics where appropriate.
507 ///
508 /// Walks up the macro expansion stack printing expansion notes, the code
509 /// snippet, caret, underlines and FixItHint display as appropriate at each
510 /// level.
511 ///
512 /// \param Loc The location for this caret.
513 /// \param Level The diagnostic level currently being emitted.
514 /// \param Ranges The underlined ranges for this code snippet.
515 /// \param Hints The FixIt hints active for this diagnostic.
516 void DiagnosticRenderer::emitMacroExpansions(SourceLocation Loc,
517                                              DiagnosticsEngine::Level Level,
518                                              ArrayRef<CharSourceRange> Ranges,
519                                              ArrayRef<FixItHint> Hints,
520                                              const SourceManager &SM) {
521   assert(Loc.isValid() && "must have a valid source location here");
522 
523   // Produce a stack of macro backtraces.
524   SmallVector<SourceLocation, 8> LocationStack;
525   unsigned IgnoredEnd = 0;
526   while (Loc.isMacroID()) {
527     // If this is the expansion of a macro argument, point the caret at the
528     // use of the argument in the definition of the macro, not the expansion.
529     if (SM.isMacroArgExpansion(Loc))
530       LocationStack.push_back(SM.getImmediateExpansionRange(Loc).first);
531     else
532       LocationStack.push_back(Loc);
533 
534     if (checkRangesForMacroArgExpansion(Loc, Ranges, SM))
535       IgnoredEnd = LocationStack.size();
536 
537     Loc = SM.getImmediateMacroCallerLoc(Loc);
538 
539     // Once the location no longer points into a macro, try stepping through
540     // the last found location.  This sometimes produces additional useful
541     // backtraces.
542     if (Loc.isFileID())
543       Loc = SM.getImmediateMacroCallerLoc(LocationStack.back());
544     assert(Loc.isValid() && "must have a valid source location here");
545   }
546 
547   LocationStack.erase(LocationStack.begin(),
548                       LocationStack.begin() + IgnoredEnd);
549 
550   unsigned MacroDepth = LocationStack.size();
551   unsigned MacroLimit = DiagOpts->MacroBacktraceLimit;
552   if (MacroDepth <= MacroLimit || MacroLimit == 0) {
553     for (auto I = LocationStack.rbegin(), E = LocationStack.rend();
554          I != E; ++I)
555       emitSingleMacroExpansion(*I, Level, Ranges, SM);
556     return;
557   }
558 
559   unsigned MacroStartMessages = MacroLimit / 2;
560   unsigned MacroEndMessages = MacroLimit / 2 + MacroLimit % 2;
561 
562   for (auto I = LocationStack.rbegin(),
563             E = LocationStack.rbegin() + MacroStartMessages;
564        I != E; ++I)
565     emitSingleMacroExpansion(*I, Level, Ranges, SM);
566 
567   SmallString<200> MessageStorage;
568   llvm::raw_svector_ostream Message(MessageStorage);
569   Message << "(skipping " << (MacroDepth - MacroLimit)
570           << " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
571              "see all)";
572   emitBasicNote(Message.str());
573 
574   for (auto I = LocationStack.rend() - MacroEndMessages,
575             E = LocationStack.rend();
576        I != E; ++I)
577     emitSingleMacroExpansion(*I, Level, Ranges, SM);
578 }
579 
580 DiagnosticNoteRenderer::~DiagnosticNoteRenderer() {}
581 
582 void DiagnosticNoteRenderer::emitIncludeLocation(SourceLocation Loc,
583                                                  PresumedLoc PLoc,
584                                                  const SourceManager &SM) {
585   // Generate a note indicating the include location.
586   SmallString<200> MessageStorage;
587   llvm::raw_svector_ostream Message(MessageStorage);
588   Message << "in file included from " << PLoc.getFilename() << ':'
589           << PLoc.getLine() << ":";
590   emitNote(Loc, Message.str(), &SM);
591 }
592 
593 void DiagnosticNoteRenderer::emitImportLocation(SourceLocation Loc,
594                                                 PresumedLoc PLoc,
595                                                 StringRef ModuleName,
596                                                 const SourceManager &SM) {
597   // Generate a note indicating the include location.
598   SmallString<200> MessageStorage;
599   llvm::raw_svector_ostream Message(MessageStorage);
600   Message << "in module '" << ModuleName;
601   if (PLoc.isValid())
602     Message << "' imported from " << PLoc.getFilename() << ':'
603             << PLoc.getLine();
604   Message << ":";
605   emitNote(Loc, Message.str(), &SM);
606 }
607 
608 void
609 DiagnosticNoteRenderer::emitBuildingModuleLocation(SourceLocation Loc,
610                                                    PresumedLoc PLoc,
611                                                    StringRef ModuleName,
612                                                    const SourceManager &SM) {
613   // Generate a note indicating the include location.
614   SmallString<200> MessageStorage;
615   llvm::raw_svector_ostream Message(MessageStorage);
616   if (PLoc.getFilename())
617     Message << "while building module '" << ModuleName << "' imported from "
618             << PLoc.getFilename() << ':' << PLoc.getLine() << ":";
619   else
620     Message << "while building module '" << ModuleName << "':";
621   emitNote(Loc, Message.str(), &SM);
622 }
623