Coverage Report

Created: 2019-07-24 05:18

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