xref: /llvm-project/llvm/utils/FileCheck/FileCheck.cpp (revision 614717388cfccd6a6d34ed17a4680181e22cab22)
1 //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
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 // FileCheck does a line-by line check of a file that validates whether it
11 // contains the expected content.  This is useful for regression tests etc.
12 //
13 // This program exits with an error status of 2 on error, exit status of 0 if
14 // the file matched the expected contents, and exit status of 1 if it did not
15 // contain the expected contents.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringSet.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/Regex.h"
27 #include "llvm/Support/Signals.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <cctype>
32 #include <map>
33 #include <string>
34 #include <system_error>
35 #include <vector>
36 using namespace llvm;
37 
38 static cl::opt<std::string>
39 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
40 
41 static cl::opt<std::string>
42 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
43               cl::init("-"), cl::value_desc("filename"));
44 
45 static cl::list<std::string>
46 CheckPrefixes("check-prefix",
47               cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
48 
49 static cl::opt<bool>
50 NoCanonicalizeWhiteSpace("strict-whitespace",
51               cl::desc("Do not treat all horizontal whitespace as equivalent"));
52 
53 typedef cl::list<std::string>::const_iterator prefix_iterator;
54 
55 //===----------------------------------------------------------------------===//
56 // Pattern Handling Code.
57 //===----------------------------------------------------------------------===//
58 
59 namespace Check {
60   enum CheckType {
61     CheckNone = 0,
62     CheckPlain,
63     CheckNext,
64     CheckNot,
65     CheckDAG,
66     CheckLabel,
67 
68     /// MatchEOF - When set, this pattern only matches the end of file. This is
69     /// used for trailing CHECK-NOTs.
70     CheckEOF
71   };
72 }
73 
74 class Pattern {
75   SMLoc PatternLoc;
76 
77   Check::CheckType CheckTy;
78 
79   /// FixedStr - If non-empty, this pattern is a fixed string match with the
80   /// specified fixed string.
81   StringRef FixedStr;
82 
83   /// RegEx - If non-empty, this is a regex pattern.
84   std::string RegExStr;
85 
86   /// \brief Contains the number of line this pattern is in.
87   unsigned LineNumber;
88 
89   /// VariableUses - Entries in this vector map to uses of a variable in the
90   /// pattern, e.g. "foo[[bar]]baz".  In this case, the RegExStr will contain
91   /// "foobaz" and we'll get an entry in this vector that tells us to insert the
92   /// value of bar at offset 3.
93   std::vector<std::pair<StringRef, unsigned> > VariableUses;
94 
95   /// VariableDefs - Maps definitions of variables to their parenthesized
96   /// capture numbers.
97   /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
98   std::map<StringRef, unsigned> VariableDefs;
99 
100 public:
101 
102   Pattern(Check::CheckType Ty)
103     : CheckTy(Ty) { }
104 
105   /// getLoc - Return the location in source code.
106   SMLoc getLoc() const { return PatternLoc; }
107 
108   /// ParsePattern - Parse the given string into the Pattern. Prefix provides
109   /// which prefix is being matched, SM provides the SourceMgr used for error
110   /// reports, and LineNumber is the line number in the input file from which
111   /// the pattern string was read.  Returns true in case of an error, false
112   /// otherwise.
113   bool ParsePattern(StringRef PatternStr,
114                     StringRef Prefix,
115                     SourceMgr &SM,
116                     unsigned LineNumber);
117 
118   /// Match - Match the pattern string against the input buffer Buffer.  This
119   /// returns the position that is matched or npos if there is no match.  If
120   /// there is a match, the size of the matched string is returned in MatchLen.
121   ///
122   /// The VariableTable StringMap provides the current values of filecheck
123   /// variables and is updated if this match defines new values.
124   size_t Match(StringRef Buffer, size_t &MatchLen,
125                StringMap<StringRef> &VariableTable) const;
126 
127   /// PrintFailureInfo - Print additional information about a failure to match
128   /// involving this pattern.
129   void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
130                         const StringMap<StringRef> &VariableTable) const;
131 
132   bool hasVariable() const { return !(VariableUses.empty() &&
133                                       VariableDefs.empty()); }
134 
135   Check::CheckType getCheckTy() const { return CheckTy; }
136 
137 private:
138   bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
139   void AddBackrefToRegEx(unsigned BackrefNum);
140 
141   /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
142   /// matching this pattern at the start of \arg Buffer; a distance of zero
143   /// should correspond to a perfect match.
144   unsigned ComputeMatchDistance(StringRef Buffer,
145                                const StringMap<StringRef> &VariableTable) const;
146 
147   /// \brief Evaluates expression and stores the result to \p Value.
148   /// \return true on success. false when the expression has invalid syntax.
149   bool EvaluateExpression(StringRef Expr, std::string &Value) const;
150 
151   /// \brief Finds the closing sequence of a regex variable usage or
152   /// definition. Str has to point in the beginning of the definition
153   /// (right after the opening sequence).
154   /// \return offset of the closing sequence within Str, or npos if it was not
155   /// found.
156   size_t FindRegexVarEnd(StringRef Str, SourceMgr &SM);
157 };
158 
159 
160 bool Pattern::ParsePattern(StringRef PatternStr,
161                            StringRef Prefix,
162                            SourceMgr &SM,
163                            unsigned LineNumber) {
164   this->LineNumber = LineNumber;
165   PatternLoc = SMLoc::getFromPointer(PatternStr.data());
166 
167   // Ignore trailing whitespace.
168   while (!PatternStr.empty() &&
169          (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
170     PatternStr = PatternStr.substr(0, PatternStr.size()-1);
171 
172   // Check that there is something on the line.
173   if (PatternStr.empty()) {
174     SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
175                     "found empty check string with prefix '" +
176                     Prefix + ":'");
177     return true;
178   }
179 
180   // Check to see if this is a fixed string, or if it has regex pieces.
181   if (PatternStr.size() < 2 ||
182       (PatternStr.find("{{") == StringRef::npos &&
183        PatternStr.find("[[") == StringRef::npos)) {
184     FixedStr = PatternStr;
185     return false;
186   }
187 
188   // Paren value #0 is for the fully matched string.  Any new parenthesized
189   // values add from there.
190   unsigned CurParen = 1;
191 
192   // Otherwise, there is at least one regex piece.  Build up the regex pattern
193   // by escaping scary characters in fixed strings, building up one big regex.
194   while (!PatternStr.empty()) {
195     // RegEx matches.
196     if (PatternStr.startswith("{{")) {
197       // This is the start of a regex match.  Scan for the }}.
198       size_t End = PatternStr.find("}}");
199       if (End == StringRef::npos) {
200         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
201                         SourceMgr::DK_Error,
202                         "found start of regex string with no end '}}'");
203         return true;
204       }
205 
206       // Enclose {{}} patterns in parens just like [[]] even though we're not
207       // capturing the result for any purpose.  This is required in case the
208       // expression contains an alternation like: CHECK:  abc{{x|z}}def.  We
209       // want this to turn into: "abc(x|z)def" not "abcx|zdef".
210       RegExStr += '(';
211       ++CurParen;
212 
213       if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
214         return true;
215       RegExStr += ')';
216 
217       PatternStr = PatternStr.substr(End+2);
218       continue;
219     }
220 
221     // Named RegEx matches.  These are of two forms: [[foo:.*]] which matches .*
222     // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
223     // second form is [[foo]] which is a reference to foo.  The variable name
224     // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
225     // it.  This is to catch some common errors.
226     if (PatternStr.startswith("[[")) {
227       // Find the closing bracket pair ending the match.  End is going to be an
228       // offset relative to the beginning of the match string.
229       size_t End = FindRegexVarEnd(PatternStr.substr(2), SM);
230 
231       if (End == StringRef::npos) {
232         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
233                         SourceMgr::DK_Error,
234                         "invalid named regex reference, no ]] found");
235         return true;
236       }
237 
238       StringRef MatchStr = PatternStr.substr(2, End);
239       PatternStr = PatternStr.substr(End+4);
240 
241       // Get the regex name (e.g. "foo").
242       size_t NameEnd = MatchStr.find(':');
243       StringRef Name = MatchStr.substr(0, NameEnd);
244 
245       if (Name.empty()) {
246         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
247                         "invalid name in named regex: empty name");
248         return true;
249       }
250 
251       // Verify that the name/expression is well formed. FileCheck currently
252       // supports @LINE, @LINE+number, @LINE-number expressions. The check here
253       // is relaxed, more strict check is performed in \c EvaluateExpression.
254       bool IsExpression = false;
255       for (unsigned i = 0, e = Name.size(); i != e; ++i) {
256         if (i == 0 && Name[i] == '@') {
257           if (NameEnd != StringRef::npos) {
258             SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
259                             SourceMgr::DK_Error,
260                             "invalid name in named regex definition");
261             return true;
262           }
263           IsExpression = true;
264           continue;
265         }
266         if (Name[i] != '_' && !isalnum(Name[i]) &&
267             (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
268           SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
269                           SourceMgr::DK_Error, "invalid name in named regex");
270           return true;
271         }
272       }
273 
274       // Name can't start with a digit.
275       if (isdigit(static_cast<unsigned char>(Name[0]))) {
276         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
277                         "invalid name in named regex");
278         return true;
279       }
280 
281       // Handle [[foo]].
282       if (NameEnd == StringRef::npos) {
283         // Handle variables that were defined earlier on the same line by
284         // emitting a backreference.
285         if (VariableDefs.find(Name) != VariableDefs.end()) {
286           unsigned VarParenNum = VariableDefs[Name];
287           if (VarParenNum < 1 || VarParenNum > 9) {
288             SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
289                             SourceMgr::DK_Error,
290                             "Can't back-reference more than 9 variables");
291             return true;
292           }
293           AddBackrefToRegEx(VarParenNum);
294         } else {
295           VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
296         }
297         continue;
298       }
299 
300       // Handle [[foo:.*]].
301       VariableDefs[Name] = CurParen;
302       RegExStr += '(';
303       ++CurParen;
304 
305       if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
306         return true;
307 
308       RegExStr += ')';
309     }
310 
311     // Handle fixed string matches.
312     // Find the end, which is the start of the next regex.
313     size_t FixedMatchEnd = PatternStr.find("{{");
314     FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
315     RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
316     PatternStr = PatternStr.substr(FixedMatchEnd);
317   }
318 
319   return false;
320 }
321 
322 bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
323                               SourceMgr &SM) {
324   Regex R(RS);
325   std::string Error;
326   if (!R.isValid(Error)) {
327     SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
328                     "invalid regex: " + Error);
329     return true;
330   }
331 
332   RegExStr += RS.str();
333   CurParen += R.getNumMatches();
334   return false;
335 }
336 
337 void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
338   assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
339   std::string Backref = std::string("\\") +
340                         std::string(1, '0' + BackrefNum);
341   RegExStr += Backref;
342 }
343 
344 bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
345   // The only supported expression is @LINE([\+-]\d+)?
346   if (!Expr.startswith("@LINE"))
347     return false;
348   Expr = Expr.substr(StringRef("@LINE").size());
349   int Offset = 0;
350   if (!Expr.empty()) {
351     if (Expr[0] == '+')
352       Expr = Expr.substr(1);
353     else if (Expr[0] != '-')
354       return false;
355     if (Expr.getAsInteger(10, Offset))
356       return false;
357   }
358   Value = llvm::itostr(LineNumber + Offset);
359   return true;
360 }
361 
362 /// Match - Match the pattern string against the input buffer Buffer.  This
363 /// returns the position that is matched or npos if there is no match.  If
364 /// there is a match, the size of the matched string is returned in MatchLen.
365 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
366                       StringMap<StringRef> &VariableTable) const {
367   // If this is the EOF pattern, match it immediately.
368   if (CheckTy == Check::CheckEOF) {
369     MatchLen = 0;
370     return Buffer.size();
371   }
372 
373   // If this is a fixed string pattern, just match it now.
374   if (!FixedStr.empty()) {
375     MatchLen = FixedStr.size();
376     return Buffer.find(FixedStr);
377   }
378 
379   // Regex match.
380 
381   // If there are variable uses, we need to create a temporary string with the
382   // actual value.
383   StringRef RegExToMatch = RegExStr;
384   std::string TmpStr;
385   if (!VariableUses.empty()) {
386     TmpStr = RegExStr;
387 
388     unsigned InsertOffset = 0;
389     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
390       std::string Value;
391 
392       if (VariableUses[i].first[0] == '@') {
393         if (!EvaluateExpression(VariableUses[i].first, Value))
394           return StringRef::npos;
395       } else {
396         StringMap<StringRef>::iterator it =
397           VariableTable.find(VariableUses[i].first);
398         // If the variable is undefined, return an error.
399         if (it == VariableTable.end())
400           return StringRef::npos;
401 
402         // Look up the value and escape it so that we can put it into the regex.
403         Value += Regex::escape(it->second);
404       }
405 
406       // Plop it into the regex at the adjusted offset.
407       TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
408                     Value.begin(), Value.end());
409       InsertOffset += Value.size();
410     }
411 
412     // Match the newly constructed regex.
413     RegExToMatch = TmpStr;
414   }
415 
416 
417   SmallVector<StringRef, 4> MatchInfo;
418   if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
419     return StringRef::npos;
420 
421   // Successful regex match.
422   assert(!MatchInfo.empty() && "Didn't get any match");
423   StringRef FullMatch = MatchInfo[0];
424 
425   // If this defines any variables, remember their values.
426   for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
427                                                      E = VariableDefs.end();
428        I != E; ++I) {
429     assert(I->second < MatchInfo.size() && "Internal paren error");
430     VariableTable[I->first] = MatchInfo[I->second];
431   }
432 
433   MatchLen = FullMatch.size();
434   return FullMatch.data()-Buffer.data();
435 }
436 
437 unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
438                               const StringMap<StringRef> &VariableTable) const {
439   // Just compute the number of matching characters. For regular expressions, we
440   // just compare against the regex itself and hope for the best.
441   //
442   // FIXME: One easy improvement here is have the regex lib generate a single
443   // example regular expression which matches, and use that as the example
444   // string.
445   StringRef ExampleString(FixedStr);
446   if (ExampleString.empty())
447     ExampleString = RegExStr;
448 
449   // Only compare up to the first line in the buffer, or the string size.
450   StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
451   BufferPrefix = BufferPrefix.split('\n').first;
452   return BufferPrefix.edit_distance(ExampleString);
453 }
454 
455 void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
456                                const StringMap<StringRef> &VariableTable) const{
457   // If this was a regular expression using variables, print the current
458   // variable values.
459   if (!VariableUses.empty()) {
460     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
461       small_string_ostream<256> OS;
462       StringRef Var = VariableUses[i].first;
463       if (Var[0] == '@') {
464         std::string Value;
465         if (EvaluateExpression(Var, Value)) {
466           OS << "with expression \"";
467           OS.write_escaped(Var) << "\" equal to \"";
468           OS.write_escaped(Value) << "\"";
469         } else {
470           OS << "uses incorrect expression \"";
471           OS.write_escaped(Var) << "\"";
472         }
473       } else {
474         StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
475 
476         // Check for undefined variable references.
477         if (it == VariableTable.end()) {
478           OS << "uses undefined variable \"";
479           OS.write_escaped(Var) << "\"";
480         } else {
481           OS << "with variable \"";
482           OS.write_escaped(Var) << "\" equal to \"";
483           OS.write_escaped(it->second) << "\"";
484         }
485       }
486 
487       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
488                       OS.str());
489     }
490   }
491 
492   // Attempt to find the closest/best fuzzy match.  Usually an error happens
493   // because some string in the output didn't exactly match. In these cases, we
494   // would like to show the user a best guess at what "should have" matched, to
495   // save them having to actually check the input manually.
496   size_t NumLinesForward = 0;
497   size_t Best = StringRef::npos;
498   double BestQuality = 0;
499 
500   // Use an arbitrary 4k limit on how far we will search.
501   for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
502     if (Buffer[i] == '\n')
503       ++NumLinesForward;
504 
505     // Patterns have leading whitespace stripped, so skip whitespace when
506     // looking for something which looks like a pattern.
507     if (Buffer[i] == ' ' || Buffer[i] == '\t')
508       continue;
509 
510     // Compute the "quality" of this match as an arbitrary combination of the
511     // match distance and the number of lines skipped to get to this match.
512     unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
513     double Quality = Distance + (NumLinesForward / 100.);
514 
515     if (Quality < BestQuality || Best == StringRef::npos) {
516       Best = i;
517       BestQuality = Quality;
518     }
519   }
520 
521   // Print the "possible intended match here" line if we found something
522   // reasonable and not equal to what we showed in the "scanning from here"
523   // line.
524   if (Best && Best != StringRef::npos && BestQuality < 50) {
525       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
526                       SourceMgr::DK_Note, "possible intended match here");
527 
528     // FIXME: If we wanted to be really friendly we would show why the match
529     // failed, as it can be hard to spot simple one character differences.
530   }
531 }
532 
533 size_t Pattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
534   // Offset keeps track of the current offset within the input Str
535   size_t Offset = 0;
536   // [...] Nesting depth
537   size_t BracketDepth = 0;
538 
539   while (!Str.empty()) {
540     if (Str.startswith("]]") && BracketDepth == 0)
541       return Offset;
542     if (Str[0] == '\\') {
543       // Backslash escapes the next char within regexes, so skip them both.
544       Str = Str.substr(2);
545       Offset += 2;
546     } else {
547       switch (Str[0]) {
548         default:
549           break;
550         case '[':
551           BracketDepth++;
552           break;
553         case ']':
554           if (BracketDepth == 0) {
555             SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
556                             SourceMgr::DK_Error,
557                             "missing closing \"]\" for regex variable");
558             exit(1);
559           }
560           BracketDepth--;
561           break;
562       }
563       Str = Str.substr(1);
564       Offset++;
565     }
566   }
567 
568   return StringRef::npos;
569 }
570 
571 
572 //===----------------------------------------------------------------------===//
573 // Check Strings.
574 //===----------------------------------------------------------------------===//
575 
576 /// CheckString - This is a check that we found in the input file.
577 struct CheckString {
578   /// Pat - The pattern to match.
579   Pattern Pat;
580 
581   /// Prefix - Which prefix name this check matched.
582   StringRef Prefix;
583 
584   /// Loc - The location in the match file that the check string was specified.
585   SMLoc Loc;
586 
587   /// CheckTy - Specify what kind of check this is. e.g. CHECK-NEXT: directive,
588   /// as opposed to a CHECK: directive.
589   Check::CheckType CheckTy;
590 
591   /// DagNotStrings - These are all of the strings that are disallowed from
592   /// occurring between this match string and the previous one (or start of
593   /// file).
594   std::vector<Pattern> DagNotStrings;
595 
596 
597   CheckString(const Pattern &P,
598               StringRef S,
599               SMLoc L,
600               Check::CheckType Ty)
601     : Pat(P), Prefix(S), Loc(L), CheckTy(Ty) {}
602 
603   /// Check - Match check string and its "not strings" and/or "dag strings".
604   size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode,
605                size_t &MatchLen, StringMap<StringRef> &VariableTable) const;
606 
607   /// CheckNext - Verify there is a single line in the given buffer.
608   bool CheckNext(const SourceMgr &SM, StringRef Buffer) const;
609 
610   /// CheckNot - Verify there's no "not strings" in the given buffer.
611   bool CheckNot(const SourceMgr &SM, StringRef Buffer,
612                 const std::vector<const Pattern *> &NotStrings,
613                 StringMap<StringRef> &VariableTable) const;
614 
615   /// CheckDag - Match "dag strings" and their mixed "not strings".
616   size_t CheckDag(const SourceMgr &SM, StringRef Buffer,
617                   std::vector<const Pattern *> &NotStrings,
618                   StringMap<StringRef> &VariableTable) const;
619 };
620 
621 /// Canonicalize whitespaces in the input file. Line endings are replaced
622 /// with UNIX-style '\n'.
623 ///
624 /// \param PreserveHorizontal Don't squash consecutive horizontal whitespace
625 /// characters to a single space.
626 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB,
627                                            bool PreserveHorizontal) {
628   SmallString<128> NewFile;
629   NewFile.reserve(MB->getBufferSize());
630 
631   for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
632        Ptr != End; ++Ptr) {
633     // Eliminate trailing dosish \r.
634     if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
635       continue;
636     }
637 
638     // If current char is not a horizontal whitespace or if horizontal
639     // whitespace canonicalization is disabled, dump it to output as is.
640     if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) {
641       NewFile.push_back(*Ptr);
642       continue;
643     }
644 
645     // Otherwise, add one space and advance over neighboring space.
646     NewFile.push_back(' ');
647     while (Ptr+1 != End &&
648            (Ptr[1] == ' ' || Ptr[1] == '\t'))
649       ++Ptr;
650   }
651 
652   // Free the old buffer and return a new one.
653   MemoryBuffer *MB2 =
654     MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
655 
656   delete MB;
657   return MB2;
658 }
659 
660 static bool IsPartOfWord(char c) {
661   return (isalnum(c) || c == '-' || c == '_');
662 }
663 
664 // Get the size of the prefix extension.
665 static size_t CheckTypeSize(Check::CheckType Ty) {
666   switch (Ty) {
667   case Check::CheckNone:
668     return 0;
669 
670   case Check::CheckPlain:
671     return sizeof(":") - 1;
672 
673   case Check::CheckNext:
674     return sizeof("-NEXT:") - 1;
675 
676   case Check::CheckNot:
677     return sizeof("-NOT:") - 1;
678 
679   case Check::CheckDAG:
680     return sizeof("-DAG:") - 1;
681 
682   case Check::CheckLabel:
683     return sizeof("-LABEL:") - 1;
684 
685   case Check::CheckEOF:
686     llvm_unreachable("Should not be using EOF size");
687   }
688 
689   llvm_unreachable("Bad check type");
690 }
691 
692 static Check::CheckType FindCheckType(StringRef Buffer, StringRef Prefix) {
693   char NextChar = Buffer[Prefix.size()];
694 
695   // Verify that the : is present after the prefix.
696   if (NextChar == ':')
697     return Check::CheckPlain;
698 
699   if (NextChar != '-')
700     return Check::CheckNone;
701 
702   StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
703   if (Rest.startswith("NEXT:"))
704     return Check::CheckNext;
705 
706   if (Rest.startswith("NOT:"))
707     return Check::CheckNot;
708 
709   if (Rest.startswith("DAG:"))
710     return Check::CheckDAG;
711 
712   if (Rest.startswith("LABEL:"))
713     return Check::CheckLabel;
714 
715   return Check::CheckNone;
716 }
717 
718 // From the given position, find the next character after the word.
719 static size_t SkipWord(StringRef Str, size_t Loc) {
720   while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
721     ++Loc;
722   return Loc;
723 }
724 
725 // Try to find the first match in buffer for any prefix. If a valid match is
726 // found, return that prefix and set its type and location.  If there are almost
727 // matches (e.g. the actual prefix string is found, but is not an actual check
728 // string), but no valid match, return an empty string and set the position to
729 // resume searching from. If no partial matches are found, return an empty
730 // string and the location will be StringRef::npos. If one prefix is a substring
731 // of another, the maximal match should be found. e.g. if "A" and "AA" are
732 // prefixes then AA-CHECK: should match the second one.
733 static StringRef FindFirstCandidateMatch(StringRef &Buffer,
734                                          Check::CheckType &CheckTy,
735                                          size_t &CheckLoc) {
736   StringRef FirstPrefix;
737   size_t FirstLoc = StringRef::npos;
738   size_t SearchLoc = StringRef::npos;
739   Check::CheckType FirstTy = Check::CheckNone;
740 
741   CheckTy = Check::CheckNone;
742   CheckLoc = StringRef::npos;
743 
744   for (prefix_iterator I = CheckPrefixes.begin(), E = CheckPrefixes.end();
745        I != E; ++I) {
746     StringRef Prefix(*I);
747     size_t PrefixLoc = Buffer.find(Prefix);
748 
749     if (PrefixLoc == StringRef::npos)
750       continue;
751 
752     // Track where we are searching for invalid prefixes that look almost right.
753     // We need to only advance to the first partial match on the next attempt
754     // since a partial match could be a substring of a later, valid prefix.
755     // Need to skip to the end of the word, otherwise we could end up
756     // matching a prefix in a substring later.
757     if (PrefixLoc < SearchLoc)
758       SearchLoc = SkipWord(Buffer, PrefixLoc);
759 
760     // We only want to find the first match to avoid skipping some.
761     if (PrefixLoc > FirstLoc)
762       continue;
763     // If one matching check-prefix is a prefix of another, choose the
764     // longer one.
765     if (PrefixLoc == FirstLoc && Prefix.size() < FirstPrefix.size())
766       continue;
767 
768     StringRef Rest = Buffer.drop_front(PrefixLoc);
769     // Make sure we have actually found the prefix, and not a word containing
770     // it. This should also prevent matching the wrong prefix when one is a
771     // substring of another.
772     if (PrefixLoc != 0 && IsPartOfWord(Buffer[PrefixLoc - 1]))
773       FirstTy = Check::CheckNone;
774     else
775       FirstTy = FindCheckType(Rest, Prefix);
776 
777     FirstLoc = PrefixLoc;
778     FirstPrefix = Prefix;
779   }
780 
781   // If the first prefix is invalid, we should continue the search after it.
782   if (FirstTy == Check::CheckNone) {
783     CheckLoc = SearchLoc;
784     return "";
785   }
786 
787   CheckTy = FirstTy;
788   CheckLoc = FirstLoc;
789   return FirstPrefix;
790 }
791 
792 static StringRef FindFirstMatchingPrefix(StringRef &Buffer,
793                                          unsigned &LineNumber,
794                                          Check::CheckType &CheckTy,
795                                          size_t &CheckLoc) {
796   while (!Buffer.empty()) {
797     StringRef Prefix = FindFirstCandidateMatch(Buffer, CheckTy, CheckLoc);
798     // If we found a real match, we are done.
799     if (!Prefix.empty()) {
800       LineNumber += Buffer.substr(0, CheckLoc).count('\n');
801       return Prefix;
802     }
803 
804     // We didn't find any almost matches either, we are also done.
805     if (CheckLoc == StringRef::npos)
806       return StringRef();
807 
808     LineNumber += Buffer.substr(0, CheckLoc + 1).count('\n');
809 
810     // Advance to the last possible match we found and try again.
811     Buffer = Buffer.drop_front(CheckLoc + 1);
812   }
813 
814   return StringRef();
815 }
816 
817 /// ReadCheckFile - Read the check file, which specifies the sequence of
818 /// expected strings.  The strings are added to the CheckStrings vector.
819 /// Returns true in case of an error, false otherwise.
820 static bool ReadCheckFile(SourceMgr &SM,
821                           std::vector<CheckString> &CheckStrings) {
822   std::unique_ptr<MemoryBuffer> File;
823   if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) {
824     errs() << "Could not open check file '" << CheckFilename << "': "
825            << ec.message() << '\n';
826     return true;
827   }
828 
829   // If we want to canonicalize whitespace, strip excess whitespace from the
830   // buffer containing the CHECK lines. Remove DOS style line endings.
831   MemoryBuffer *F =
832     CanonicalizeInputFile(File.release(), NoCanonicalizeWhiteSpace);
833 
834   SM.AddNewSourceBuffer(F, SMLoc());
835 
836   // Find all instances of CheckPrefix followed by : in the file.
837   StringRef Buffer = F->getBuffer();
838   std::vector<Pattern> DagNotMatches;
839 
840   // LineNumber keeps track of the line on which CheckPrefix instances are
841   // found.
842   unsigned LineNumber = 1;
843 
844   while (1) {
845     Check::CheckType CheckTy;
846     size_t PrefixLoc;
847 
848     // See if a prefix occurs in the memory buffer.
849     StringRef UsedPrefix = FindFirstMatchingPrefix(Buffer,
850                                                    LineNumber,
851                                                    CheckTy,
852                                                    PrefixLoc);
853     if (UsedPrefix.empty())
854       break;
855 
856     Buffer = Buffer.drop_front(PrefixLoc);
857 
858     // Location to use for error messages.
859     const char *UsedPrefixStart = Buffer.data() + (PrefixLoc == 0 ? 0 : 1);
860 
861     // PrefixLoc is to the start of the prefix. Skip to the end.
862     Buffer = Buffer.drop_front(UsedPrefix.size() + CheckTypeSize(CheckTy));
863 
864     // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
865     // leading and trailing whitespace.
866     Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
867 
868     // Scan ahead to the end of line.
869     size_t EOL = Buffer.find_first_of("\n\r");
870 
871     // Remember the location of the start of the pattern, for diagnostics.
872     SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
873 
874     // Parse the pattern.
875     Pattern P(CheckTy);
876     if (P.ParsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, LineNumber))
877       return true;
878 
879     // Verify that CHECK-LABEL lines do not define or use variables
880     if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
881       SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
882                       SourceMgr::DK_Error,
883                       "found '" + UsedPrefix + "-LABEL:'"
884                       " with variable definition or use");
885       return true;
886     }
887 
888     Buffer = Buffer.substr(EOL);
889 
890     // Verify that CHECK-NEXT lines have at least one CHECK line before them.
891     if ((CheckTy == Check::CheckNext) && CheckStrings.empty()) {
892       SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
893                       SourceMgr::DK_Error,
894                       "found '" + UsedPrefix + "-NEXT:' without previous '"
895                       + UsedPrefix + ": line");
896       return true;
897     }
898 
899     // Handle CHECK-DAG/-NOT.
900     if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
901       DagNotMatches.push_back(P);
902       continue;
903     }
904 
905     // Okay, add the string we captured to the output vector and move on.
906     CheckStrings.push_back(CheckString(P,
907                                        UsedPrefix,
908                                        PatternLoc,
909                                        CheckTy));
910     std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
911   }
912 
913   // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
914   // prefix as a filler for the error message.
915   if (!DagNotMatches.empty()) {
916     CheckStrings.push_back(CheckString(Pattern(Check::CheckEOF),
917                                        CheckPrefixes[0],
918                                        SMLoc::getFromPointer(Buffer.data()),
919                                        Check::CheckEOF));
920     std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
921   }
922 
923   if (CheckStrings.empty()) {
924     errs() << "error: no check strings found with prefix"
925            << (CheckPrefixes.size() > 1 ? "es " : " ");
926     for (size_t I = 0, N = CheckPrefixes.size(); I != N; ++I) {
927       StringRef Prefix(CheckPrefixes[I]);
928       errs() << '\'' << Prefix << ":'";
929       if (I != N - 1)
930         errs() << ", ";
931     }
932 
933     errs() << '\n';
934     return true;
935   }
936 
937   return false;
938 }
939 
940 static void PrintCheckFailed(const SourceMgr &SM, const SMLoc &Loc,
941                              const Pattern &Pat, StringRef Buffer,
942                              StringMap<StringRef> &VariableTable) {
943   // Otherwise, we have an error, emit an error message.
944   SM.PrintMessage(Loc, SourceMgr::DK_Error,
945                   "expected string not found in input");
946 
947   // Print the "scanning from here" line.  If the current position is at the
948   // end of a line, advance to the start of the next line.
949   Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
950 
951   SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
952                   "scanning from here");
953 
954   // Allow the pattern to print additional information if desired.
955   Pat.PrintFailureInfo(SM, Buffer, VariableTable);
956 }
957 
958 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
959                              StringRef Buffer,
960                              StringMap<StringRef> &VariableTable) {
961   PrintCheckFailed(SM, CheckStr.Loc, CheckStr.Pat, Buffer, VariableTable);
962 }
963 
964 /// CountNumNewlinesBetween - Count the number of newlines in the specified
965 /// range.
966 static unsigned CountNumNewlinesBetween(StringRef Range,
967                                         const char *&FirstNewLine) {
968   unsigned NumNewLines = 0;
969   while (1) {
970     // Scan for newline.
971     Range = Range.substr(Range.find_first_of("\n\r"));
972     if (Range.empty()) return NumNewLines;
973 
974     ++NumNewLines;
975 
976     // Handle \n\r and \r\n as a single newline.
977     if (Range.size() > 1 &&
978         (Range[1] == '\n' || Range[1] == '\r') &&
979         (Range[0] != Range[1]))
980       Range = Range.substr(1);
981     Range = Range.substr(1);
982 
983     if (NumNewLines == 1)
984       FirstNewLine = Range.begin();
985   }
986 }
987 
988 size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer,
989                           bool IsLabelScanMode, size_t &MatchLen,
990                           StringMap<StringRef> &VariableTable) const {
991   size_t LastPos = 0;
992   std::vector<const Pattern *> NotStrings;
993 
994   // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
995   // bounds; we have not processed variable definitions within the bounded block
996   // yet so cannot handle any final CHECK-DAG yet; this is handled when going
997   // over the block again (including the last CHECK-LABEL) in normal mode.
998   if (!IsLabelScanMode) {
999     // Match "dag strings" (with mixed "not strings" if any).
1000     LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable);
1001     if (LastPos == StringRef::npos)
1002       return StringRef::npos;
1003   }
1004 
1005   // Match itself from the last position after matching CHECK-DAG.
1006   StringRef MatchBuffer = Buffer.substr(LastPos);
1007   size_t MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
1008   if (MatchPos == StringRef::npos) {
1009     PrintCheckFailed(SM, *this, MatchBuffer, VariableTable);
1010     return StringRef::npos;
1011   }
1012   MatchPos += LastPos;
1013 
1014   // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1015   // or CHECK-NOT
1016   if (!IsLabelScanMode) {
1017     StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1018 
1019     // If this check is a "CHECK-NEXT", verify that the previous match was on
1020     // the previous line (i.e. that there is one newline between them).
1021     if (CheckNext(SM, SkippedRegion))
1022       return StringRef::npos;
1023 
1024     // If this match had "not strings", verify that they don't exist in the
1025     // skipped region.
1026     if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
1027       return StringRef::npos;
1028   }
1029 
1030   return MatchPos;
1031 }
1032 
1033 bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1034   if (CheckTy != Check::CheckNext)
1035     return false;
1036 
1037   // Count the number of newlines between the previous match and this one.
1038   assert(Buffer.data() !=
1039          SM.getMemoryBuffer(
1040            SM.FindBufferContainingLoc(
1041              SMLoc::getFromPointer(Buffer.data())))->getBufferStart() &&
1042          "CHECK-NEXT can't be the first check in a file");
1043 
1044   const char *FirstNewLine = nullptr;
1045   unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1046 
1047   if (NumNewLines == 0) {
1048     SM.PrintMessage(Loc, SourceMgr::DK_Error, Prefix +
1049                     "-NEXT: is on the same line as previous match");
1050     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
1051                     SourceMgr::DK_Note, "'next' match was here");
1052     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1053                     "previous match ended here");
1054     return true;
1055   }
1056 
1057   if (NumNewLines != 1) {
1058     SM.PrintMessage(Loc, SourceMgr::DK_Error, Prefix +
1059                     "-NEXT: is not on the line after the previous match");
1060     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
1061                     SourceMgr::DK_Note, "'next' match was here");
1062     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1063                     "previous match ended here");
1064     SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
1065                     "non-matching line after previous match is here");
1066     return true;
1067   }
1068 
1069   return false;
1070 }
1071 
1072 bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer,
1073                            const std::vector<const Pattern *> &NotStrings,
1074                            StringMap<StringRef> &VariableTable) const {
1075   for (unsigned ChunkNo = 0, e = NotStrings.size();
1076        ChunkNo != e; ++ChunkNo) {
1077     const Pattern *Pat = NotStrings[ChunkNo];
1078     assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1079 
1080     size_t MatchLen = 0;
1081     size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);
1082 
1083     if (Pos == StringRef::npos) continue;
1084 
1085     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos),
1086                     SourceMgr::DK_Error,
1087                     Prefix + "-NOT: string occurred!");
1088     SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note,
1089                     Prefix + "-NOT: pattern specified here");
1090     return true;
1091   }
1092 
1093   return false;
1094 }
1095 
1096 size_t CheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1097                              std::vector<const Pattern *> &NotStrings,
1098                              StringMap<StringRef> &VariableTable) const {
1099   if (DagNotStrings.empty())
1100     return 0;
1101 
1102   size_t LastPos = 0;
1103   size_t StartPos = LastPos;
1104 
1105   for (unsigned ChunkNo = 0, e = DagNotStrings.size();
1106        ChunkNo != e; ++ChunkNo) {
1107     const Pattern &Pat = DagNotStrings[ChunkNo];
1108 
1109     assert((Pat.getCheckTy() == Check::CheckDAG ||
1110             Pat.getCheckTy() == Check::CheckNot) &&
1111            "Invalid CHECK-DAG or CHECK-NOT!");
1112 
1113     if (Pat.getCheckTy() == Check::CheckNot) {
1114       NotStrings.push_back(&Pat);
1115       continue;
1116     }
1117 
1118     assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1119 
1120     size_t MatchLen = 0, MatchPos;
1121 
1122     // CHECK-DAG always matches from the start.
1123     StringRef MatchBuffer = Buffer.substr(StartPos);
1124     MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
1125     // With a group of CHECK-DAGs, a single mismatching means the match on
1126     // that group of CHECK-DAGs fails immediately.
1127     if (MatchPos == StringRef::npos) {
1128       PrintCheckFailed(SM, Pat.getLoc(), Pat, MatchBuffer, VariableTable);
1129       return StringRef::npos;
1130     }
1131     // Re-calc it as the offset relative to the start of the original string.
1132     MatchPos += StartPos;
1133 
1134     if (!NotStrings.empty()) {
1135       if (MatchPos < LastPos) {
1136         // Reordered?
1137         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + MatchPos),
1138                         SourceMgr::DK_Error,
1139                         Prefix + "-DAG: found a match of CHECK-DAG"
1140                         " reordering across a CHECK-NOT");
1141         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + LastPos),
1142                         SourceMgr::DK_Note,
1143                         Prefix + "-DAG: the farthest match of CHECK-DAG"
1144                         " is found here");
1145         SM.PrintMessage(NotStrings[0]->getLoc(), SourceMgr::DK_Note,
1146                         Prefix + "-NOT: the crossed pattern specified"
1147                         " here");
1148         SM.PrintMessage(Pat.getLoc(), SourceMgr::DK_Note,
1149                         Prefix + "-DAG: the reordered pattern specified"
1150                         " here");
1151         return StringRef::npos;
1152       }
1153       // All subsequent CHECK-DAGs should be matched from the farthest
1154       // position of all precedent CHECK-DAGs (including this one.)
1155       StartPos = LastPos;
1156       // If there's CHECK-NOTs between two CHECK-DAGs or from CHECK to
1157       // CHECK-DAG, verify that there's no 'not' strings occurred in that
1158       // region.
1159       StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1160       if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
1161         return StringRef::npos;
1162       // Clear "not strings".
1163       NotStrings.clear();
1164     }
1165 
1166     // Update the last position with CHECK-DAG matches.
1167     LastPos = std::max(MatchPos + MatchLen, LastPos);
1168   }
1169 
1170   return LastPos;
1171 }
1172 
1173 // A check prefix must contain only alphanumeric, hyphens and underscores.
1174 static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1175   Regex Validator("^[a-zA-Z0-9_-]*$");
1176   return Validator.match(CheckPrefix);
1177 }
1178 
1179 static bool ValidateCheckPrefixes() {
1180   StringSet<> PrefixSet;
1181 
1182   for (prefix_iterator I = CheckPrefixes.begin(), E = CheckPrefixes.end();
1183        I != E; ++I) {
1184     StringRef Prefix(*I);
1185 
1186     if (!PrefixSet.insert(Prefix))
1187       return false;
1188 
1189     if (!ValidateCheckPrefix(Prefix))
1190       return false;
1191   }
1192 
1193   return true;
1194 }
1195 
1196 // I don't think there's a way to specify an initial value for cl::list,
1197 // so if nothing was specified, add the default
1198 static void AddCheckPrefixIfNeeded() {
1199   if (CheckPrefixes.empty())
1200     CheckPrefixes.push_back("CHECK");
1201 }
1202 
1203 int main(int argc, char **argv) {
1204   sys::PrintStackTraceOnErrorSignal();
1205   PrettyStackTraceProgram X(argc, argv);
1206   cl::ParseCommandLineOptions(argc, argv);
1207 
1208   if (!ValidateCheckPrefixes()) {
1209     errs() << "Supplied check-prefix is invalid! Prefixes must be unique and "
1210               "start with a letter and contain only alphanumeric characters, "
1211               "hyphens and underscores\n";
1212     return 2;
1213   }
1214 
1215   AddCheckPrefixIfNeeded();
1216 
1217   SourceMgr SM;
1218 
1219   // Read the expected strings from the check file.
1220   std::vector<CheckString> CheckStrings;
1221   if (ReadCheckFile(SM, CheckStrings))
1222     return 2;
1223 
1224   // Open the file to check and add it to SourceMgr.
1225   std::unique_ptr<MemoryBuffer> File;
1226   if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, File)) {
1227     errs() << "Could not open input file '" << InputFilename << "': "
1228            << ec.message() << '\n';
1229     return 2;
1230   }
1231 
1232   if (File->getBufferSize() == 0) {
1233     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
1234     return 2;
1235   }
1236 
1237   // Remove duplicate spaces in the input file if requested.
1238   // Remove DOS style line endings.
1239   MemoryBuffer *F =
1240     CanonicalizeInputFile(File.release(), NoCanonicalizeWhiteSpace);
1241 
1242   SM.AddNewSourceBuffer(F, SMLoc());
1243 
1244   /// VariableTable - This holds all the current filecheck variables.
1245   StringMap<StringRef> VariableTable;
1246 
1247   // Check that we have all of the expected strings, in order, in the input
1248   // file.
1249   StringRef Buffer = F->getBuffer();
1250 
1251   bool hasError = false;
1252 
1253   unsigned i = 0, j = 0, e = CheckStrings.size();
1254 
1255   while (true) {
1256     StringRef CheckRegion;
1257     if (j == e) {
1258       CheckRegion = Buffer;
1259     } else {
1260       const CheckString &CheckLabelStr = CheckStrings[j];
1261       if (CheckLabelStr.CheckTy != Check::CheckLabel) {
1262         ++j;
1263         continue;
1264       }
1265 
1266       // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1267       size_t MatchLabelLen = 0;
1268       size_t MatchLabelPos = CheckLabelStr.Check(SM, Buffer, true,
1269                                                  MatchLabelLen, VariableTable);
1270       if (MatchLabelPos == StringRef::npos) {
1271         hasError = true;
1272         break;
1273       }
1274 
1275       CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1276       Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1277       ++j;
1278     }
1279 
1280     for ( ; i != j; ++i) {
1281       const CheckString &CheckStr = CheckStrings[i];
1282 
1283       // Check each string within the scanned region, including a second check
1284       // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1285       size_t MatchLen = 0;
1286       size_t MatchPos = CheckStr.Check(SM, CheckRegion, false, MatchLen,
1287                                        VariableTable);
1288 
1289       if (MatchPos == StringRef::npos) {
1290         hasError = true;
1291         i = j;
1292         break;
1293       }
1294 
1295       CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1296     }
1297 
1298     if (j == e)
1299       break;
1300   }
1301 
1302   return hasError ? 1 : 0;
1303 }
1304