Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- VerifyDiagnosticConsumer.cpp - Verifying Diagnostic Client ---------===//
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
// This is a concrete diagnostic client, which buffers the diagnostic messages.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Frontend/VerifyDiagnosticConsumer.h"
14
#include "clang/Basic/CharInfo.h"
15
#include "clang/Basic/Diagnostic.h"
16
#include "clang/Basic/DiagnosticOptions.h"
17
#include "clang/Basic/FileManager.h"
18
#include "clang/Basic/LLVM.h"
19
#include "clang/Basic/SourceLocation.h"
20
#include "clang/Basic/SourceManager.h"
21
#include "clang/Basic/TokenKinds.h"
22
#include "clang/Frontend/FrontendDiagnostic.h"
23
#include "clang/Frontend/TextDiagnosticBuffer.h"
24
#include "clang/Lex/HeaderSearch.h"
25
#include "clang/Lex/Lexer.h"
26
#include "clang/Lex/PPCallbacks.h"
27
#include "clang/Lex/Preprocessor.h"
28
#include "clang/Lex/Token.h"
29
#include "llvm/ADT/STLExtras.h"
30
#include "llvm/ADT/SmallPtrSet.h"
31
#include "llvm/ADT/SmallString.h"
32
#include "llvm/ADT/StringRef.h"
33
#include "llvm/ADT/Twine.h"
34
#include "llvm/Support/ErrorHandling.h"
35
#include "llvm/Support/Regex.h"
36
#include "llvm/Support/raw_ostream.h"
37
#include <algorithm>
38
#include <cassert>
39
#include <cstddef>
40
#include <cstring>
41
#include <iterator>
42
#include <memory>
43
#include <string>
44
#include <utility>
45
#include <vector>
46
47
using namespace clang;
48
49
using Directive = VerifyDiagnosticConsumer::Directive;
50
using DirectiveList = VerifyDiagnosticConsumer::DirectiveList;
51
using ExpectedData = VerifyDiagnosticConsumer::ExpectedData;
52
53
#ifndef NDEBUG
54
55
namespace {
56
57
class VerifyFileTracker : public PPCallbacks {
58
  VerifyDiagnosticConsumer &Verify;
59
  SourceManager &SM;
60
61
public:
62
  VerifyFileTracker(VerifyDiagnosticConsumer &Verify, SourceManager &SM)
63
17.4k
      : Verify(Verify), SM(SM) {}
64
65
  /// Hook into the preprocessor and update the list of parsed
66
  /// files when the preprocessor indicates a new file is entered.
67
  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
68
                   SrcMgr::CharacteristicKind FileType,
69
107k
                   FileID PrevFID) override {
70
107k
    Verify.UpdateParsedFileStatus(SM, SM.getFileID(Loc),
71
107k
                                  VerifyDiagnosticConsumer::IsParsed);
72
107k
  }
73
};
74
75
} // namespace
76
77
#endif
78
79
//===----------------------------------------------------------------------===//
80
// Checking diagnostics implementation.
81
//===----------------------------------------------------------------------===//
82
83
using DiagList = TextDiagnosticBuffer::DiagList;
84
using const_diag_iterator = TextDiagnosticBuffer::const_iterator;
85
86
namespace {
87
88
/// StandardDirective - Directive with string matching.
89
class StandardDirective : public Directive {
90
public:
91
  StandardDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
92
                    bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text,
93
                    unsigned Min, unsigned Max)
94
      : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyFileAndLine,
95
304k
                  MatchAnyLine, Text, Min, Max) {}
96
97
304k
  bool isValid(std::string &Error) override {
98
    // all strings are considered valid; even empty ones
99
304k
    return true;
100
304k
  }
101
102
410k
  bool match(StringRef S) override {
103
410k
    return S.find(Text) != StringRef::npos;
104
410k
  }
105
};
106
107
/// RegexDirective - Directive with regular-expression matching.
108
class RegexDirective : public Directive {
109
public:
110
  RegexDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
111
                 bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text,
112
                 unsigned Min, unsigned Max, StringRef RegexStr)
113
      : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyFileAndLine,
114
                  MatchAnyLine, Text, Min, Max),
115
4.60k
        Regex(RegexStr) {}
116
117
4.60k
  bool isValid(std::string &Error) override {
118
4.60k
    return Regex.isValid(Error);
119
4.60k
  }
120
121
4.75k
  bool match(StringRef S) override {
122
4.75k
    return Regex.match(S);
123
4.75k
  }
124
125
private:
126
  llvm::Regex Regex;
127
};
128
129
class ParseHelper
130
{
131
public:
132
  ParseHelper(StringRef S)
133
43.5M
      : Begin(S.begin()), End(S.end()), C(Begin), P(Begin) {}
134
135
  // Return true if string literal is next.
136
1.66M
  bool Next(StringRef S) {
137
1.66M
    P = C;
138
1.66M
    PEnd = C + S.size();
139
1.66M
    if (PEnd > End)
140
0
      return false;
141
1.66M
    return memcmp(P, S.data(), S.size()) == 0;
142
1.66M
  }
143
144
  // Return true if number is next.
145
  // Output N only if number is next.
146
374k
  bool Next(unsigned &N) {
147
374k
    unsigned TMP = 0;
148
374k
    P = C;
149
374k
    PEnd = P;
150
474k
    for (; PEnd < End && *PEnd >= '0' && 
*PEnd <= '9'383k
;
++PEnd100k
) {
151
100k
      TMP *= 10;
152
100k
      TMP += *PEnd - '0';
153
100k
    }
154
374k
    if (PEnd == C)
155
275k
      return false;
156
98.5k
    N = TMP;
157
98.5k
    return true;
158
374k
  }
159
160
  // Return true if a marker is next.
161
  // A marker is the longest match for /#[A-Za-z0-9_-]+/.
162
655k
  bool NextMarker() {
163
655k
    P = C;
164
655k
    if (P == End || *P != '#')
165
2.08k
      return false;
166
653k
    PEnd = P;
167
653k
    ++PEnd;
168
744k
    while ((isAlphanumeric(*PEnd) || 
*PEnd == '-'653k
||
*PEnd == '_'653k
) &&
169
744k
           
PEnd < End91.8k
)
170
91.8k
      ++PEnd;
171
653k
    return PEnd > P + 1;
172
655k
  }
173
174
  // Return true if string literal S is matched in content.
175
  // When true, P marks begin-position of the match, and calling Advance sets C
176
  // to end-position of the match.
177
  // If S is the empty string, then search for any letter instead (makes sense
178
  // with FinishDirectiveToken=true).
179
  // If EnsureStartOfWord, then skip matches that don't start a new word.
180
  // If FinishDirectiveToken, then assume the match is the start of a comment
181
  // directive for -verify, and extend the match to include the entire first
182
  // token of that directive.
183
  bool Search(StringRef S, bool EnsureStartOfWord = false,
184
44.4M
              bool FinishDirectiveToken = false) {
185
45.3M
    do {
186
45.3M
      if (!S.empty()) {
187
44.1M
        P = std::search(C, End, S.begin(), S.end());
188
44.1M
        PEnd = P + S.size();
189
44.1M
      }
190
1.15M
      else {
191
1.15M
        P = C;
192
2.21M
        while (P != End && 
!isLetter(*P)2.19M
)
193
1.05M
          ++P;
194
1.15M
        PEnd = P + 1;
195
1.15M
      }
196
45.3M
      if (P == End)
197
43.3M
        break;
198
      // If not start of word but required, skip and search again.
199
2.00M
      if (EnsureStartOfWord
200
               // Check if string literal starts a new word.
201
2.00M
          && 
!(1.99M
P == Begin1.99M
||
isWhitespace(P[-1])1.99M
202
               // Or it could be preceded by the start of a comment.
203
1.99M
               || 
(889k
P > (Begin + 1)889k
&&
(889k
P[-1] == '/'889k
||
P[-1] == '*'884k
)
204
889k
                                   &&  
P[-2] == '/'5.28k
)))
205
884k
        continue;
206
1.11M
      if (FinishDirectiveToken) {
207
4.03M
        while (PEnd != End && 
(4.01M
isAlphanumeric(*PEnd)4.01M
208
4.01M
                               || 
*PEnd == '-'792k
||
*PEnd == '_'447k
))
209
3.56M
          ++PEnd;
210
        // Put back trailing digits and hyphens to be parsed later as a count
211
        // or count range.  Because -verify prefixes must start with letters,
212
        // we know the actual directive we found starts with a letter, so
213
        // we won't put back the entire directive word and thus record an empty
214
        // string.
215
461k
        assert(isLetter(*P) && "-verify prefix must start with a letter");
216
465k
        while (isDigit(PEnd[-1]) || 
PEnd[-1] == '-'461k
)
217
3.43k
          --PEnd;
218
461k
      }
219
0
      return true;
220
2.00M
    } while (
Advance()884k
);
221
43.3M
    return false;
222
44.4M
  }
223
224
  // Return true if a CloseBrace that closes the OpenBrace at the current nest
225
  // level is found. When true, P marks begin-position of CloseBrace.
226
308k
  bool SearchClosingBrace(StringRef OpenBrace, StringRef CloseBrace) {
227
308k
    unsigned Depth = 1;
228
308k
    P = C;
229
14.0M
    while (P < End) {
230
14.0M
      StringRef S(P, End - P);
231
14.0M
      if (S.startswith(OpenBrace)) {
232
5.78k
        ++Depth;
233
5.78k
        P += OpenBrace.size();
234
14.0M
      } else if (S.startswith(CloseBrace)) {
235
314k
        --Depth;
236
314k
        if (Depth == 0) {
237
308k
          PEnd = P + CloseBrace.size();
238
308k
          return true;
239
308k
        }
240
5.78k
        P += CloseBrace.size();
241
13.7M
      } else {
242
13.7M
        ++P;
243
13.7M
      }
244
14.0M
    }
245
0
    return false;
246
308k
  }
247
248
  // Advance 1-past previous next/search.
249
  // Behavior is undefined if previous next/search failed.
250
2.84M
  bool Advance() {
251
2.84M
    C = PEnd;
252
2.84M
    return C < End;
253
2.84M
  }
254
255
  // Return the text matched by the previous next/search.
256
  // Behavior is undefined if previous next/search failed.
257
492k
  StringRef Match() { return StringRef(P, PEnd - P); }
258
259
  // Skip zero or more whitespace.
260
617k
  void SkipWhitespace() {
261
916k
    for (; C < End && isWhitespace(*C); 
++C299k
)
262
299k
      ;
263
617k
  }
264
265
  // Return true if EOF reached.
266
44.6M
  bool Done() {
267
44.6M
    return !(C < End);
268
44.6M
  }
269
270
  // Beginning of expected content.
271
  const char * const Begin;
272
273
  // End of expected content (1-past).
274
  const char * const End;
275
276
  // Position of next char in content.
277
  const char *C;
278
279
  // Previous next/search subject start.
280
  const char *P;
281
282
private:
283
  // Previous next/search subject end (1-past).
284
  const char *PEnd = nullptr;
285
};
286
287
// The information necessary to create a directive.
288
struct UnattachedDirective {
289
  DirectiveList *DL = nullptr;
290
  bool RegexKind = false;
291
  SourceLocation DirectivePos, ContentBegin;
292
  std::string Text;
293
  unsigned Min = 1, Max = 1;
294
};
295
296
// Attach the specified directive to the line of code indicated by
297
// \p ExpectedLoc.
298
void attachDirective(DiagnosticsEngine &Diags, const UnattachedDirective &UD,
299
                     SourceLocation ExpectedLoc,
300
                     bool MatchAnyFileAndLine = false,
301
308k
                     bool MatchAnyLine = false) {
302
  // Construct new directive.
303
308k
  std::unique_ptr<Directive> D = Directive::create(
304
308k
      UD.RegexKind, UD.DirectivePos, ExpectedLoc, MatchAnyFileAndLine,
305
308k
      MatchAnyLine, UD.Text, UD.Min, UD.Max);
306
307
308k
  std::string Error;
308
308k
  if (!D->isValid(Error)) {
309
0
    Diags.Report(UD.ContentBegin, diag::err_verify_invalid_content)
310
0
      << (UD.RegexKind ? "regex" : "string") << Error;
311
0
  }
312
313
308k
  UD.DL->push_back(std::move(D));
314
308k
}
315
316
} // anonymous
317
318
// Tracker for markers in the input files. A marker is a comment of the form
319
//
320
//   n = 123; // #123
321
//
322
// ... that can be referred to by a later expected-* directive:
323
//
324
//   // expected-error@#123 {{undeclared identifier 'n'}}
325
//
326
// Marker declarations must be at the start of a comment or preceded by
327
// whitespace to distinguish them from uses of markers in directives.
328
class VerifyDiagnosticConsumer::MarkerTracker {
329
  DiagnosticsEngine &Diags;
330
331
  struct Marker {
332
    SourceLocation DefLoc;
333
    SourceLocation RedefLoc;
334
    SourceLocation UseLoc;
335
  };
336
  llvm::StringMap<Marker> Markers;
337
338
  // Directives that couldn't be created yet because they name an unknown
339
  // marker.
340
  llvm::StringMap<llvm::SmallVector<UnattachedDirective, 2>> DeferredDirectives;
341
342
public:
343
18.0k
  MarkerTracker(DiagnosticsEngine &Diags) : Diags(Diags) {}
344
345
  // Register a marker.
346
30.6k
  void addMarker(StringRef MarkerName, SourceLocation Pos) {
347
30.6k
    auto InsertResult = Markers.insert(
348
30.6k
        {MarkerName, Marker{Pos, SourceLocation(), SourceLocation()}});
349
350
30.6k
    Marker &M = InsertResult.first->second;
351
30.6k
    if (!InsertResult.second) {
352
      // Marker was redefined.
353
28.6k
      M.RedefLoc = Pos;
354
28.6k
    } else {
355
      // First definition: build any deferred directives.
356
1.99k
      auto Deferred = DeferredDirectives.find(MarkerName);
357
1.99k
      if (Deferred != DeferredDirectives.end()) {
358
42
        for (auto &UD : Deferred->second) {
359
42
          if (M.UseLoc.isInvalid())
360
26
            M.UseLoc = UD.DirectivePos;
361
42
          attachDirective(Diags, UD, Pos);
362
42
        }
363
26
        DeferredDirectives.erase(Deferred);
364
26
      }
365
1.99k
    }
366
30.6k
  }
367
368
  // Register a directive at the specified marker.
369
386
  void addDirective(StringRef MarkerName, const UnattachedDirective &UD) {
370
386
    auto MarkerIt = Markers.find(MarkerName);
371
386
    if (MarkerIt != Markers.end()) {
372
343
      Marker &M = MarkerIt->second;
373
343
      if (M.UseLoc.isInvalid())
374
205
        M.UseLoc = UD.DirectivePos;
375
343
      return attachDirective(Diags, UD, M.DefLoc);
376
343
    }
377
43
    DeferredDirectives[MarkerName].push_back(UD);
378
43
  }
379
380
  // Ensure we have no remaining deferred directives, and no
381
  // multiply-defined-and-used markers.
382
17.4k
  void finalize() {
383
17.4k
    for (auto &MarkerInfo : Markers) {
384
1.99k
      StringRef Name = MarkerInfo.first();
385
1.99k
      Marker &M = MarkerInfo.second;
386
1.99k
      if (M.RedefLoc.isValid() && 
M.UseLoc.isValid()944
) {
387
1
        Diags.Report(M.UseLoc, diag::err_verify_ambiguous_marker) << Name;
388
1
        Diags.Report(M.DefLoc, diag::note_verify_ambiguous_marker) << Name;
389
1
        Diags.Report(M.RedefLoc, diag::note_verify_ambiguous_marker) << Name;
390
1
      }
391
1.99k
    }
392
393
17.4k
    for (auto &DeferredPair : DeferredDirectives) {
394
1
      Diags.Report(DeferredPair.second.front().DirectivePos,
395
1
                   diag::err_verify_no_such_marker)
396
1
          << DeferredPair.first();
397
1
    }
398
17.4k
  }
399
};
400
401
/// ParseDirective - Go through the comment and see if it indicates expected
402
/// diagnostics. If so, then put them in the appropriate directive list.
403
///
404
/// Returns true if any valid directives were found.
405
static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM,
406
                           Preprocessor *PP, SourceLocation Pos,
407
                           VerifyDiagnosticConsumer::DirectiveStatus &Status,
408
21.7M
                           VerifyDiagnosticConsumer::MarkerTracker &Markers) {
409
21.7M
  DiagnosticsEngine &Diags = PP ? 
PP->getDiagnostics()21.7M
:
SM.getDiagnostics()635
;
410
411
  // First, scan the comment looking for markers.
412
22.4M
  for (ParseHelper PH(S); !PH.Done();) {
413
22.4M
    if (!PH.Search("#", true))
414
21.7M
      break;
415
652k
    PH.C = PH.P;
416
652k
    if (!PH.NextMarker()) {
417
622k
      PH.Next("#");
418
622k
      PH.Advance();
419
622k
      continue;
420
622k
    }
421
30.6k
    PH.Advance();
422
30.6k
    Markers.addMarker(PH.Match(), Pos);
423
30.6k
  }
424
425
  // A single comment may contain multiple directives.
426
21.7M
  bool FoundDirective = false;
427
22.2M
  for (ParseHelper PH(S); !PH.Done();) {
428
    // Search for the initial directive token.
429
    // If one prefix, save time by searching only for its directives.
430
    // Otherwise, search for any potential directive token and check it later.
431
21.9M
    const auto &Prefixes = Diags.getDiagnosticOptions().VerifyPrefixes;
432
21.9M
    if (!(Prefixes.size() == 1 ? 
PH.Search(*Prefixes.begin(), true, true)21.6M
433
21.9M
                               : 
PH.Search("", true, true)297k
))
434
21.5M
      break;
435
436
461k
    StringRef DToken = PH.Match();
437
461k
    PH.Advance();
438
439
    // Default directive kind.
440
461k
    UnattachedDirective D;
441
461k
    const char *KindStr = "string";
442
443
    // Parse the initial directive token in reverse so we can easily determine
444
    // its exact actual prefix.  If we were to parse it from the front instead,
445
    // it would be harder to determine where the prefix ends because there
446
    // might be multiple matching -verify prefixes because some might prefix
447
    // others.
448
449
    // Regex in initial directive token: -re
450
461k
    if (DToken.endswith("-re")) {
451
4.64k
      D.RegexKind = true;
452
4.64k
      KindStr = "regex";
453
4.64k
      DToken = DToken.substr(0, DToken.size()-3);
454
4.64k
    }
455
456
    // Type in initial directive token: -{error|warning|note|no-diagnostics}
457
461k
    bool NoDiag = false;
458
461k
    StringRef DType;
459
461k
    if (DToken.endswith(DType="-error"))
460
173k
      D.DL = ED ? 
&ED->Errors173k
:
nullptr34
;
461
288k
    else if (DToken.endswith(DType="-warning"))
462
60.0k
      D.DL = ED ? 
&ED->Warnings60.0k
:
nullptr7
;
463
228k
    else if (DToken.endswith(DType="-remark"))
464
94
      D.DL = ED ? &ED->Remarks : 
nullptr0
;
465
228k
    else if (DToken.endswith(DType="-note"))
466
86.6k
      D.DL = ED ? 
&ED->Notes86.6k
:
nullptr10
;
467
141k
    else if (DToken.endswith(DType="-no-diagnostics")) {
468
8.29k
      NoDiag = true;
469
8.29k
      if (D.RegexKind)
470
0
        continue;
471
8.29k
    }
472
133k
    else
473
133k
      continue;
474
328k
    DToken = DToken.substr(0, DToken.size()-DType.size());
475
476
    // What's left in DToken is the actual prefix.  That might not be a -verify
477
    // prefix even if there is only one -verify prefix (for example, the full
478
    // DToken is foo-bar-warning, but foo is the only -verify prefix).
479
328k
    if (!std::binary_search(Prefixes.begin(), Prefixes.end(), DToken))
480
11.4k
      continue;
481
482
316k
    if (NoDiag) {
483
8.19k
      if (Status == VerifyDiagnosticConsumer::HasOtherExpectedDirectives)
484
1
        Diags.Report(Pos, diag::err_verify_invalid_no_diags)
485
1
          << /*IsExpectedNoDiagnostics=*/true;
486
8.18k
      else
487
8.18k
        Status = VerifyDiagnosticConsumer::HasExpectedNoDiagnostics;
488
8.19k
      continue;
489
8.19k
    }
490
308k
    if (Status == VerifyDiagnosticConsumer::HasExpectedNoDiagnostics) {
491
1
      Diags.Report(Pos, diag::err_verify_invalid_no_diags)
492
1
        << /*IsExpectedNoDiagnostics=*/false;
493
1
      continue;
494
1
    }
495
308k
    Status = VerifyDiagnosticConsumer::HasOtherExpectedDirectives;
496
497
    // If a directive has been found but we're not interested
498
    // in storing the directive information, return now.
499
308k
    if (!D.DL)
500
51
      return true;
501
502
    // Next optional token: @
503
308k
    SourceLocation ExpectedLoc;
504
308k
    StringRef Marker;
505
308k
    bool MatchAnyFileAndLine = false;
506
308k
    bool MatchAnyLine = false;
507
308k
    if (!PH.Next("@")) {
508
246k
      ExpectedLoc = Pos;
509
246k
    } else {
510
62.6k
      PH.Advance();
511
62.6k
      unsigned Line = 0;
512
62.6k
      bool FoundPlus = PH.Next("+");
513
62.6k
      if (FoundPlus || 
PH.Next("-")18.8k
) {
514
        // Relative to current line.
515
59.5k
        PH.Advance();
516
59.5k
        bool Invalid = false;
517
59.5k
        unsigned ExpectedLine = SM.getSpellingLineNumber(Pos, &Invalid);
518
59.5k
        if (!Invalid && PH.Next(Line) && (FoundPlus || 
Line < ExpectedLine15.8k
)) {
519
59.5k
          if (FoundPlus) 
ExpectedLine += Line43.7k
;
520
15.7k
          else ExpectedLine -= Line;
521
59.5k
          ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), ExpectedLine, 1);
522
59.5k
        }
523
59.5k
      } else 
if (3.05k
PH.Next(Line)3.05k
) {
524
        // Absolute line number.
525
591
        if (Line > 0)
526
585
          ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), Line, 1);
527
2.46k
      } else if (PH.NextMarker()) {
528
386
        Marker = PH.Match();
529
2.08k
      } else if (PP && PH.Search(":")) {
530
        // Specific source file.
531
1.63k
        StringRef Filename(PH.C, PH.P-PH.C);
532
1.63k
        PH.Advance();
533
534
1.63k
        if (Filename == "*") {
535
3
          MatchAnyFileAndLine = true;
536
3
          if (!PH.Next("*")) {
537
1
            Diags.Report(Pos.getLocWithOffset(PH.C - PH.Begin),
538
1
                         diag::err_verify_missing_line)
539
1
                << "'*'";
540
1
            continue;
541
1
          }
542
2
          MatchAnyLine = true;
543
2
          ExpectedLoc = SourceLocation();
544
1.63k
        } else {
545
          // Lookup file via Preprocessor, like a #include.
546
1.63k
          const DirectoryLookup *CurDir;
547
1.63k
          Optional<FileEntryRef> File =
548
1.63k
              PP->LookupFile(Pos, Filename, false, nullptr, nullptr, CurDir,
549
1.63k
                             nullptr, nullptr, nullptr, nullptr, nullptr);
550
1.63k
          if (!File) {
551
1
            Diags.Report(Pos.getLocWithOffset(PH.C - PH.Begin),
552
1
                         diag::err_verify_missing_file)
553
1
                << Filename << KindStr;
554
1
            continue;
555
1
          }
556
557
1.63k
          FileID FID = SM.translateFile(*File);
558
1.63k
          if (FID.isInvalid())
559
47
            FID = SM.createFileID(*File, Pos, SrcMgr::C_User);
560
561
1.63k
          if (PH.Next(Line) && 
Line > 0589
)
562
587
            ExpectedLoc = SM.translateLineCol(FID, Line, 1);
563
1.04k
          else if (PH.Next("*")) {
564
1.04k
            MatchAnyLine = true;
565
1.04k
            ExpectedLoc = SM.translateLineCol(FID, 1, 1);
566
1.04k
          }
567
1.63k
        }
568
1.63k
      } else 
if (442
PH.Next("*")442
) {
569
436
        MatchAnyLine = true;
570
436
        ExpectedLoc = SourceLocation();
571
436
      }
572
573
62.6k
      if (ExpectedLoc.isInvalid() && 
!MatchAnyLine845
&&
Marker.empty()407
) {
574
21
        Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
575
21
                     diag::err_verify_missing_line) << KindStr;
576
21
        continue;
577
21
      }
578
62.5k
      PH.Advance();
579
62.5k
    }
580
581
    // Skip optional whitespace.
582
308k
    PH.SkipWhitespace();
583
584
    // Next optional token: positive integer or a '+'.
585
308k
    if (PH.Next(D.Min)) {
586
36.5k
      PH.Advance();
587
      // A positive integer can be followed by a '+' meaning min
588
      // or more, or by a '-' meaning a range from min to max.
589
36.5k
      if (PH.Next("+")) {
590
2.51k
        D.Max = Directive::MaxCount;
591
2.51k
        PH.Advance();
592
34.0k
      } else if (PH.Next("-")) {
593
1.27k
        PH.Advance();
594
1.27k
        if (!PH.Next(D.Max) || D.Max < D.Min) {
595
0
          Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
596
0
                       diag::err_verify_invalid_range) << KindStr;
597
0
          continue;
598
0
        }
599
1.27k
        PH.Advance();
600
32.7k
      } else {
601
32.7k
        D.Max = D.Min;
602
32.7k
      }
603
272k
    } else if (PH.Next("+")) {
604
      // '+' on its own means "1 or more".
605
701
      D.Max = Directive::MaxCount;
606
701
      PH.Advance();
607
701
    }
608
609
    // Skip optional whitespace.
610
308k
    PH.SkipWhitespace();
611
612
    // Next token: {{
613
308k
    if (!PH.Next("{{")) {
614
7
      Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
615
7
                   diag::err_verify_missing_start) << KindStr;
616
7
      continue;
617
7
    }
618
308k
    PH.Advance();
619
308k
    const char* const ContentBegin = PH.C; // mark content begin
620
    // Search for token: }}
621
308k
    if (!PH.SearchClosingBrace("{{", "}}")) {
622
0
      Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
623
0
                   diag::err_verify_missing_end) << KindStr;
624
0
      continue;
625
0
    }
626
308k
    const char* const ContentEnd = PH.P; // mark content end
627
308k
    PH.Advance();
628
629
308k
    D.DirectivePos = Pos;
630
308k
    D.ContentBegin = Pos.getLocWithOffset(ContentBegin - PH.Begin);
631
632
    // Build directive text; convert \n to newlines.
633
308k
    StringRef NewlineStr = "\\n";
634
308k
    StringRef Content(ContentBegin, ContentEnd-ContentBegin);
635
308k
    size_t CPos = 0;
636
308k
    size_t FPos;
637
308k
    while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
638
86
      D.Text += Content.substr(CPos, FPos-CPos);
639
86
      D.Text += '\n';
640
86
      CPos = FPos + NewlineStr.size();
641
86
    }
642
308k
    if (D.Text.empty())
643
308k
      D.Text.assign(ContentBegin, ContentEnd);
644
645
    // Check that regex directives contain at least one regex.
646
308k
    if (D.RegexKind && 
D.Text.find("{{") == StringRef::npos4.60k
) {
647
0
      Diags.Report(D.ContentBegin, diag::err_verify_missing_regex) << D.Text;
648
0
      return false;
649
0
    }
650
651
308k
    if (Marker.empty())
652
308k
      attachDirective(Diags, D, ExpectedLoc, MatchAnyFileAndLine, MatchAnyLine);
653
386
    else
654
386
      Markers.addDirective(Marker, D);
655
308k
    FoundDirective = true;
656
308k
  }
657
658
21.7M
  return FoundDirective;
659
21.7M
}
660
661
VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &Diags_)
662
    : Diags(Diags_), PrimaryClient(Diags.getClient()),
663
      PrimaryClientOwner(Diags.takeClient()),
664
      Buffer(new TextDiagnosticBuffer()), Markers(new MarkerTracker(Diags)),
665
17.4k
      Status(HasNoDirectives) {
666
17.4k
  if (Diags.hasSourceManager())
667
0
    setSourceManager(Diags.getSourceManager());
668
17.4k
}
669
670
17.3k
VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() {
671
17.3k
  assert(!ActiveSourceFiles && "Incomplete parsing of source files!");
672
0
  assert(!CurrentPreprocessor && "CurrentPreprocessor should be invalid!");
673
0
  SrcManager = nullptr;
674
17.3k
  CheckDiagnostics();
675
17.3k
  assert(!Diags.ownsClient() &&
676
17.3k
         "The VerifyDiagnosticConsumer takes over ownership of the client!");
677
17.3k
}
678
679
// DiagnosticConsumer interface.
680
681
void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
682
17.4k
                                               const Preprocessor *PP) {
683
  // Attach comment handler on first invocation.
684
17.4k
  if (++ActiveSourceFiles == 1) {
685
17.4k
    if (PP) {
686
17.4k
      CurrentPreprocessor = PP;
687
17.4k
      this->LangOpts = &LangOpts;
688
17.4k
      setSourceManager(PP->getSourceManager());
689
17.4k
      const_cast<Preprocessor *>(PP)->addCommentHandler(this);
690
17.4k
#ifndef NDEBUG
691
      // Debug build tracks parsed files.
692
17.4k
      const_cast<Preprocessor *>(PP)->addPPCallbacks(
693
17.4k
                      std::make_unique<VerifyFileTracker>(*this, *SrcManager));
694
17.4k
#endif
695
17.4k
    }
696
17.4k
  }
697
698
17.4k
  assert((!PP || CurrentPreprocessor == PP) && "Preprocessor changed!");
699
0
  PrimaryClient->BeginSourceFile(LangOpts, PP);
700
17.4k
}
701
702
17.4k
void VerifyDiagnosticConsumer::EndSourceFile() {
703
17.4k
  assert(ActiveSourceFiles && "No active source files!");
704
0
  PrimaryClient->EndSourceFile();
705
706
  // Detach comment handler once last active source file completed.
707
17.4k
  if (--ActiveSourceFiles == 0) {
708
17.4k
    if (CurrentPreprocessor)
709
17.4k
      const_cast<Preprocessor *>(CurrentPreprocessor)->
710
17.4k
          removeCommentHandler(this);
711
712
    // Diagnose any used-but-not-defined markers.
713
17.4k
    Markers->finalize();
714
715
    // Check diagnostics once last file completed.
716
17.4k
    CheckDiagnostics();
717
17.4k
    CurrentPreprocessor = nullptr;
718
17.4k
    LangOpts = nullptr;
719
17.4k
  }
720
17.4k
}
721
722
void VerifyDiagnosticConsumer::HandleDiagnostic(
723
362k
      DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
724
362k
  if (Info.hasSourceManager()) {
725
    // If this diagnostic is for a different source manager, ignore it.
726
362k
    if (SrcManager && &Info.getSourceManager() != SrcManager)
727
277
      return;
728
729
362k
    setSourceManager(Info.getSourceManager());
730
362k
  }
731
732
362k
#ifndef NDEBUG
733
  // Debug build tracks unparsed files for possible
734
  // unparsed expected-* directives.
735
362k
  if (SrcManager) {
736
362k
    SourceLocation Loc = Info.getLocation();
737
362k
    if (Loc.isValid()) {
738
362k
      ParsedStatus PS = IsUnparsed;
739
740
362k
      Loc = SrcManager->getExpansionLoc(Loc);
741
362k
      FileID FID = SrcManager->getFileID(Loc);
742
743
362k
      const FileEntry *FE = SrcManager->getFileEntryForID(FID);
744
362k
      if (FE && 
CurrentPreprocessor362k
&&
SrcManager->isLoadedFileID(FID)362k
) {
745
        // If the file is a modules header file it shall not be parsed
746
        // for expected-* directives.
747
1.51k
        HeaderSearch &HS = CurrentPreprocessor->getHeaderSearchInfo();
748
1.51k
        if (HS.findModuleForHeader(FE))
749
1.12k
          PS = IsUnparsedNoDirectives;
750
1.51k
      }
751
752
362k
      UpdateParsedFileStatus(*SrcManager, FID, PS);
753
362k
    }
754
362k
  }
755
362k
#endif
756
757
  // Send the diagnostic to the buffer, we will check it once we reach the end
758
  // of the source file (or are destructed).
759
362k
  Buffer->HandleDiagnostic(DiagLevel, Info);
760
362k
}
761
762
/// HandleComment - Hook into the preprocessor and extract comments containing
763
///  expected errors and warnings.
764
bool VerifyDiagnosticConsumer::HandleComment(Preprocessor &PP,
765
21.7M
                                             SourceRange Comment) {
766
21.7M
  SourceManager &SM = PP.getSourceManager();
767
768
  // If this comment is for a different source manager, ignore it.
769
21.7M
  if (SrcManager && &SM != SrcManager)
770
0
    return false;
771
772
21.7M
  SourceLocation CommentBegin = Comment.getBegin();
773
774
21.7M
  const char *CommentRaw = SM.getCharacterData(CommentBegin);
775
21.7M
  StringRef C(CommentRaw, SM.getCharacterData(Comment.getEnd()) - CommentRaw);
776
777
21.7M
  if (C.empty())
778
2
    return false;
779
780
  // Fold any "\<EOL>" sequences
781
21.7M
  size_t loc = C.find('\\');
782
21.7M
  if (loc == StringRef::npos) {
783
21.6M
    ParseDirective(C, &ED, SM, &PP, CommentBegin, Status, *Markers);
784
21.6M
    return false;
785
21.6M
  }
786
787
137k
  std::string C2;
788
137k
  C2.reserve(C.size());
789
790
291k
  for (size_t last = 0;; 
loc = C.find('\\', last)153k
) {
791
291k
    if (loc == StringRef::npos || 
loc == C.size()153k
) {
792
137k
      C2 += C.substr(last);
793
137k
      break;
794
137k
    }
795
153k
    C2 += C.substr(last, loc-last);
796
153k
    last = loc + 1;
797
798
153k
    if (C[last] == '\n' || 
C[last] == '\r'140k
) {
799
12.9k
      ++last;
800
801
      // Escape \r\n  or \n\r, but not \n\n.
802
12.9k
      if (last < C.size())
803
12.9k
        if (C[last] == '\n' || C[last] == '\r')
804
0
          if (C[last] != C[last-1])
805
0
            ++last;
806
140k
    } else {
807
      // This was just a normal backslash.
808
140k
      C2 += '\\';
809
140k
    }
810
153k
  }
811
812
137k
  if (!C2.empty())
813
137k
    ParseDirective(C2, &ED, SM, &PP, CommentBegin, Status, *Markers);
814
137k
  return false;
815
21.7M
}
816
817
#ifndef NDEBUG
818
/// Lex the specified source file to determine whether it contains
819
/// any expected-* directives.  As a Lexer is used rather than a full-blown
820
/// Preprocessor, directives inside skipped #if blocks will still be found.
821
///
822
/// \return true if any directives were found.
823
static bool findDirectives(SourceManager &SM, FileID FID,
824
125
                           const LangOptions &LangOpts) {
825
  // Create a raw lexer to pull all the comments out of FID.
826
125
  if (FID.isInvalid())
827
0
    return false;
828
829
  // Create a lexer to lex all the tokens of the main file in raw mode.
830
125
  llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(FID);
831
125
  Lexer RawLex(FID, FromFile, SM, LangOpts);
832
833
  // Return comments as tokens, this is how we find expected diagnostics.
834
125
  RawLex.SetCommentRetentionState(true);
835
836
125
  Token Tok;
837
125
  Tok.setKind(tok::comment);
838
125
  VerifyDiagnosticConsumer::DirectiveStatus Status =
839
125
    VerifyDiagnosticConsumer::HasNoDirectives;
840
29.2k
  while (Tok.isNot(tok::eof)) {
841
29.2k
    RawLex.LexFromRawLexer(Tok);
842
29.2k
    if (!Tok.is(tok::comment)) 
continue28.5k
;
843
844
635
    std::string Comment = RawLex.getSpelling(Tok, SM, LangOpts);
845
635
    if (Comment.empty()) 
continue0
;
846
847
    // We don't care about tracking markers for this phase.
848
635
    VerifyDiagnosticConsumer::MarkerTracker Markers(SM.getDiagnostics());
849
850
    // Find first directive.
851
635
    if (ParseDirective(Comment, nullptr, SM, nullptr, Tok.getLocation(),
852
635
                       Status, Markers))
853
51
      return true;
854
635
  }
855
74
  return false;
856
125
}
857
#endif // !NDEBUG
858
859
/// Takes a list of diagnostics that have been generated but not matched
860
/// by an expected-* directive and produces a diagnostic to the user from this.
861
static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
862
                                const_diag_iterator diag_begin,
863
                                const_diag_iterator diag_end,
864
138k
                                const char *Kind) {
865
138k
  if (diag_begin == diag_end) 
return 0138k
;
866
867
79
  SmallString<256> Fmt;
868
79
  llvm::raw_svector_ostream OS(Fmt);
869
199
  for (const_diag_iterator I = diag_begin, E = diag_end; I != E; 
++I120
) {
870
120
    if (I->first.isInvalid() || 
!SourceMgr86
)
871
34
      OS << "\n  (frontend)";
872
86
    else {
873
86
      OS << "\n ";
874
86
      if (const FileEntry *File = SourceMgr->getFileEntryForID(
875
86
                                                SourceMgr->getFileID(I->first)))
876
86
        OS << " File " << File->getName();
877
86
      OS << " Line " << SourceMgr->getPresumedLineNumber(I->first);
878
86
    }
879
120
    OS << ": " << I->second;
880
120
  }
881
882
79
  Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
883
79
    << Kind << /*Unexpected=*/true << OS.str();
884
79
  return std::distance(diag_begin, diag_end);
885
138k
}
886
887
/// Takes a list of diagnostics that were expected to have been generated
888
/// but were not and produces a diagnostic to the user from this.
889
static unsigned PrintExpected(DiagnosticsEngine &Diags,
890
                              SourceManager &SourceMgr,
891
69.6k
                              std::vector<Directive *> &DL, const char *Kind) {
892
69.6k
  if (DL.empty())
893
69.6k
    return 0;
894
895
25
  SmallString<256> Fmt;
896
25
  llvm::raw_svector_ostream OS(Fmt);
897
175
  for (const auto *D : DL) {
898
175
    if (D->DiagnosticLoc.isInvalid() || 
D->MatchAnyFileAndLine174
)
899
1
      OS << "\n  File *";
900
174
    else
901
174
      OS << "\n  File " << SourceMgr.getFilename(D->DiagnosticLoc);
902
175
    if (D->MatchAnyLine)
903
2
      OS << " Line *";
904
173
    else
905
173
      OS << " Line " << SourceMgr.getPresumedLineNumber(D->DiagnosticLoc);
906
175
    if (D->DirectiveLoc != D->DiagnosticLoc)
907
20
      OS << " (directive at "
908
20
         << SourceMgr.getFilename(D->DirectiveLoc) << ':'
909
20
         << SourceMgr.getPresumedLineNumber(D->DirectiveLoc) << ')';
910
175
    OS << ": " << D->Text;
911
175
  }
912
913
25
  Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
914
25
    << Kind << /*Unexpected=*/false << OS.str();
915
25
  return DL.size();
916
69.6k
}
917
918
/// Determine whether two source locations come from the same file.
919
static bool IsFromSameFile(SourceManager &SM, SourceLocation DirectiveLoc,
920
383k
                           SourceLocation DiagnosticLoc) {
921
397k
  while (DiagnosticLoc.isMacroID())
922
14.5k
    DiagnosticLoc = SM.getImmediateMacroCallerLoc(DiagnosticLoc);
923
924
383k
  if (SM.isWrittenInSameFile(DirectiveLoc, DiagnosticLoc))
925
380k
    return true;
926
927
2.59k
  const FileEntry *DiagFile = SM.getFileEntryForID(SM.getFileID(DiagnosticLoc));
928
2.59k
  if (!DiagFile && 
SM.isWrittenInMainFile(DirectiveLoc)13
)
929
13
    return true;
930
931
2.58k
  return (DiagFile == SM.getFileEntryForID(SM.getFileID(DirectiveLoc)));
932
2.59k
}
933
934
/// CheckLists - Compare expected to seen diagnostic lists and return the
935
/// the difference between them.
936
static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
937
                           const char *Label,
938
                           DirectiveList &Left,
939
                           const_diag_iterator d2_begin,
940
                           const_diag_iterator d2_end,
941
69.6k
                           bool IgnoreUnexpected) {
942
69.6k
  std::vector<Directive *> LeftOnly;
943
69.6k
  DiagList Right(d2_begin, d2_end);
944
945
308k
  for (auto &Owner : Left) {
946
308k
    Directive &D = *Owner;
947
308k
    unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
948
949
666k
    for (unsigned i = 0; i < D.Max; 
++i357k
) {
950
361k
      DiagList::iterator II, IE;
951
2.25M
      for (II = Right.begin(), IE = Right.end(); II != IE; 
++II1.89M
) {
952
2.25M
        if (!D.MatchAnyLine) {
953
2.20M
          unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
954
2.20M
          if (LineNo1 != LineNo2)
955
1.83M
            continue;
956
2.20M
        }
957
958
417k
        if (!D.DiagnosticLoc.isInvalid() && 
!D.MatchAnyFileAndLine383k
&&
959
417k
            
!IsFromSameFile(SourceMgr, D.DiagnosticLoc, II->first)383k
)
960
2.28k
          continue;
961
962
415k
        const std::string &RightText = II->second;
963
415k
        if (D.match(RightText))
964
357k
          break;
965
415k
      }
966
361k
      if (II == IE) {
967
        // Not found.
968
4.19k
        if (i >= D.Min) 
break4.02k
;
969
175
        LeftOnly.push_back(&D);
970
357k
      } else {
971
        // Found. The same cannot be found twice.
972
357k
        Right.erase(II);
973
357k
      }
974
361k
    }
975
308k
  }
976
  // Now all that's left in Right are those that were not matched.
977
69.6k
  unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label);
978
69.6k
  if (!IgnoreUnexpected)
979
69.2k
    num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label);
980
69.6k
  return num;
981
69.6k
}
982
983
/// CheckResults - This compares the expected results to those that
984
/// were actually reported. It emits any discrepencies. Return "true" if there
985
/// were problems. Return "false" otherwise.
986
static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
987
                             const TextDiagnosticBuffer &Buffer,
988
17.4k
                             ExpectedData &ED) {
989
  // We want to capture the delta between what was expected and what was
990
  // seen.
991
  //
992
  //   Expected \ Seen - set expected but not seen
993
  //   Seen \ Expected - set seen but not expected
994
17.4k
  unsigned NumProblems = 0;
995
996
17.4k
  const DiagnosticLevelMask DiagMask =
997
17.4k
    Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected();
998
999
  // See if there are error mismatches.
1000
17.4k
  NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
1001
17.4k
                            Buffer.err_begin(), Buffer.err_end(),
1002
17.4k
                            bool(DiagnosticLevelMask::Error & DiagMask));
1003
1004
  // See if there are warning mismatches.
1005
17.4k
  NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
1006
17.4k
                            Buffer.warn_begin(), Buffer.warn_end(),
1007
17.4k
                            bool(DiagnosticLevelMask::Warning & DiagMask));
1008
1009
  // See if there are remark mismatches.
1010
17.4k
  NumProblems += CheckLists(Diags, SourceMgr, "remark", ED.Remarks,
1011
17.4k
                            Buffer.remark_begin(), Buffer.remark_end(),
1012
17.4k
                            bool(DiagnosticLevelMask::Remark & DiagMask));
1013
1014
  // See if there are note mismatches.
1015
17.4k
  NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
1016
17.4k
                            Buffer.note_begin(), Buffer.note_end(),
1017
17.4k
                            bool(DiagnosticLevelMask::Note & DiagMask));
1018
1019
17.4k
  return NumProblems;
1020
17.4k
}
1021
1022
void VerifyDiagnosticConsumer::UpdateParsedFileStatus(SourceManager &SM,
1023
                                                      FileID FID,
1024
469k
                                                      ParsedStatus PS) {
1025
  // Check SourceManager hasn't changed.
1026
469k
  setSourceManager(SM);
1027
1028
469k
#ifndef NDEBUG
1029
469k
  if (FID.isInvalid())
1030
0
    return;
1031
1032
469k
  const FileEntry *FE = SM.getFileEntryForID(FID);
1033
1034
469k
  if (PS == IsParsed) {
1035
    // Move the FileID from the unparsed set to the parsed set.
1036
107k
    UnparsedFiles.erase(FID);
1037
107k
    ParsedFiles.insert(std::make_pair(FID, FE));
1038
362k
  } else if (!ParsedFiles.count(FID) && 
!UnparsedFiles.count(FID)1.57k
) {
1039
    // Add the FileID to the unparsed set if we haven't seen it before.
1040
1041
    // Check for directives.
1042
311
    bool FoundDirectives;
1043
311
    if (PS == IsUnparsedNoDirectives)
1044
186
      FoundDirectives = false;
1045
125
    else
1046
125
      FoundDirectives = !LangOpts || findDirectives(SM, FID, *LangOpts);
1047
1048
    // Add the FileID to the unparsed set.
1049
311
    UnparsedFiles.insert(std::make_pair(FID,
1050
311
                                      UnparsedFileStatus(FE, FoundDirectives)));
1051
311
  }
1052
469k
#endif
1053
469k
}
1054
1055
34.7k
void VerifyDiagnosticConsumer::CheckDiagnostics() {
1056
  // Ensure any diagnostics go to the primary client.
1057
34.7k
  DiagnosticConsumer *CurClient = Diags.getClient();
1058
34.7k
  std::unique_ptr<DiagnosticConsumer> Owner = Diags.takeClient();
1059
34.7k
  Diags.setClient(PrimaryClient, false);
1060
1061
34.7k
#ifndef NDEBUG
1062
  // In a debug build, scan through any files that may have been missed
1063
  // during parsing and issue a fatal error if directives are contained
1064
  // within these files.  If a fatal error occurs, this suggests that
1065
  // this file is being parsed separately from the main file, in which
1066
  // case consider moving the directives to the correct place, if this
1067
  // is applicable.
1068
34.7k
  if (!UnparsedFiles.empty()) {
1069
    // Generate a cache of parsed FileEntry pointers for alias lookups.
1070
220
    llvm::SmallPtrSet<const FileEntry *, 8> ParsedFileCache;
1071
220
    for (const auto &I : ParsedFiles)
1072
464
      if (const FileEntry *FE = I.second)
1073
244
        ParsedFileCache.insert(FE);
1074
1075
    // Iterate through list of unparsed files.
1076
308
    for (const auto &I : UnparsedFiles) {
1077
308
      const UnparsedFileStatus &Status = I.second;
1078
308
      const FileEntry *FE = Status.getFile();
1079
1080
      // Skip files that have been parsed via an alias.
1081
308
      if (FE && 
ParsedFileCache.count(FE)304
)
1082
56
        continue;
1083
1084
      // Report a fatal error if this file contained directives.
1085
252
      if (Status.foundDirectives()) {
1086
0
        llvm::report_fatal_error(Twine("-verify directives found after rather"
1087
0
                                       " than during normal parsing of ",
1088
0
                                 StringRef(FE ? FE->getName() : "(unknown)")));
1089
0
      }
1090
252
    }
1091
1092
    // UnparsedFiles has been processed now, so clear it.
1093
220
    UnparsedFiles.clear();
1094
220
  }
1095
34.7k
#endif // !NDEBUG
1096
1097
34.7k
  if (SrcManager) {
1098
    // Produce an error if no expected-* directives could be found in the
1099
    // source file(s) processed.
1100
17.4k
    if (Status == HasNoDirectives) {
1101
24
      Diags.Report(diag::err_verify_no_directives).setForceEmit();
1102
24
      ++NumErrors;
1103
24
      Status = HasNoDirectivesReported;
1104
24
    }
1105
1106
    // Check that the expected diagnostics occurred.
1107
17.4k
    NumErrors += CheckResults(Diags, *SrcManager, *Buffer, ED);
1108
17.4k
  } else {
1109
17.3k
    const DiagnosticLevelMask DiagMask =
1110
17.3k
        ~Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected();
1111
17.3k
    if (bool(DiagnosticLevelMask::Error & DiagMask))
1112
17.0k
      NumErrors += PrintUnexpected(Diags, nullptr, Buffer->err_begin(),
1113
17.0k
                                   Buffer->err_end(), "error");
1114
17.3k
    if (bool(DiagnosticLevelMask::Warning & DiagMask))
1115
17.3k
      NumErrors += PrintUnexpected(Diags, nullptr, Buffer->warn_begin(),
1116
17.3k
                                   Buffer->warn_end(), "warn");
1117
17.3k
    if (bool(DiagnosticLevelMask::Remark & DiagMask))
1118
17.3k
      NumErrors += PrintUnexpected(Diags, nullptr, Buffer->remark_begin(),
1119
17.3k
                                   Buffer->remark_end(), "remark");
1120
17.3k
    if (bool(DiagnosticLevelMask::Note & DiagMask))
1121
17.2k
      NumErrors += PrintUnexpected(Diags, nullptr, Buffer->note_begin(),
1122
17.2k
                                   Buffer->note_end(), "note");
1123
17.3k
  }
1124
1125
34.7k
  Diags.setClient(CurClient, Owner.release() != nullptr);
1126
1127
  // Reset the buffer, we have processed all the diagnostics in it.
1128
34.7k
  Buffer.reset(new TextDiagnosticBuffer());
1129
34.7k
  ED.Reset();
1130
34.7k
}
1131
1132
std::unique_ptr<Directive> Directive::create(bool RegexKind,
1133
                                             SourceLocation DirectiveLoc,
1134
                                             SourceLocation DiagnosticLoc,
1135
                                             bool MatchAnyFileAndLine,
1136
                                             bool MatchAnyLine, StringRef Text,
1137
308k
                                             unsigned Min, unsigned Max) {
1138
308k
  if (!RegexKind)
1139
304k
    return std::make_unique<StandardDirective>(DirectiveLoc, DiagnosticLoc,
1140
304k
                                               MatchAnyFileAndLine,
1141
304k
                                               MatchAnyLine, Text, Min, Max);
1142
1143
  // Parse the directive into a regular expression.
1144
4.60k
  std::string RegexStr;
1145
4.60k
  StringRef S = Text;
1146
17.8k
  while (!S.empty()) {
1147
13.2k
    if (S.startswith("{{")) {
1148
5.77k
      S = S.drop_front(2);
1149
5.77k
      size_t RegexMatchLength = S.find("}}");
1150
5.77k
      assert(RegexMatchLength != StringRef::npos);
1151
      // Append the regex, enclosed in parentheses.
1152
0
      RegexStr += "(";
1153
5.77k
      RegexStr.append(S.data(), RegexMatchLength);
1154
5.77k
      RegexStr += ")";
1155
5.77k
      S = S.drop_front(RegexMatchLength + 2);
1156
7.48k
    } else {
1157
7.48k
      size_t VerbatimMatchLength = S.find("{{");
1158
7.48k
      if (VerbatimMatchLength == StringRef::npos)
1159
2.52k
        VerbatimMatchLength = S.size();
1160
      // Escape and append the fixed string.
1161
7.48k
      RegexStr += llvm::Regex::escape(S.substr(0, VerbatimMatchLength));
1162
7.48k
      S = S.drop_front(VerbatimMatchLength);
1163
7.48k
    }
1164
13.2k
  }
1165
1166
4.60k
  return std::make_unique<RegexDirective>(DirectiveLoc, DiagnosticLoc,
1167
4.60k
                                          MatchAnyFileAndLine, MatchAnyLine,
1168
4.60k
                                          Text, Min, Max, RegexStr);
1169
308k
}