1ee3c74fbSChris Lattner //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2ee3c74fbSChris Lattner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ee3c74fbSChris Lattner //
7ee3c74fbSChris Lattner //===----------------------------------------------------------------------===//
8ee3c74fbSChris Lattner //
9ee3c74fbSChris Lattner // FileCheck does a line-by line check of a file that validates whether it
10ee3c74fbSChris Lattner // contains the expected content.  This is useful for regression tests etc.
11ee3c74fbSChris Lattner //
12b5ecceffSJames Henderson // This program exits with an exit status of 2 on error, exit status of 0 if
13ee3c74fbSChris Lattner // the file matched the expected contents, and exit status of 1 if it did not
14ee3c74fbSChris Lattner // contain the expected contents.
15ee3c74fbSChris Lattner //
16ee3c74fbSChris Lattner //===----------------------------------------------------------------------===//
17ee3c74fbSChris Lattner 
18ee3c74fbSChris Lattner #include "llvm/Support/CommandLine.h"
19197194b6SRui Ueyama #include "llvm/Support/InitLLVM.h"
203e66509fSJoel E. Denny #include "llvm/Support/Process.h"
213c5d267eSJoel E. Denny #include "llvm/Support/WithColor.h"
22ee3c74fbSChris Lattner #include "llvm/Support/raw_ostream.h"
23ffa9d2e4SAditya Nandakumar #include "llvm/Support/FileCheck.h"
24010982f7SRainer Orth #include <cmath>
25ee3c74fbSChris Lattner using namespace llvm;
26ee3c74fbSChris Lattner 
27dbb757f4SJoel E. Denny static cl::extrahelp FileCheckOptsEnv(
28dbb757f4SJoel E. Denny     "\nOptions are parsed from the environment variable FILECHECK_OPTS and\n"
29dbb757f4SJoel E. Denny     "from the command line.\n");
30dbb757f4SJoel E. Denny 
31ee3c74fbSChris Lattner static cl::opt<std::string>
323c5d267eSJoel E. Denny     CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Optional);
33ee3c74fbSChris Lattner 
34ee3c74fbSChris Lattner static cl::opt<std::string>
35ee3c74fbSChris Lattner     InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
36ee3c74fbSChris Lattner                   cl::init("-"), cl::value_desc("filename"));
37ee3c74fbSChris Lattner 
38e8f2fb20SChandler Carruth static cl::list<std::string> CheckPrefixes(
39e8f2fb20SChandler Carruth     "check-prefix",
40ee3c74fbSChris Lattner     cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
41fd557cb0SDaniel Sanders static cl::alias CheckPrefixesAlias(
42fd557cb0SDaniel Sanders     "check-prefixes", cl::aliasopt(CheckPrefixes), cl::CommaSeparated,
43fd557cb0SDaniel Sanders     cl::NotHidden,
44fd557cb0SDaniel Sanders     cl::desc(
45fd557cb0SDaniel Sanders         "Alias for -check-prefix permitting multiple comma separated values"));
46ee3c74fbSChris Lattner 
47a1fd1882SJoel E. Denny static cl::list<std::string> CommentPrefixes(
48a1fd1882SJoel E. Denny     "comment-prefixes", cl::CommaSeparated, cl::Hidden,
49a1fd1882SJoel E. Denny     cl::desc("Comma-separated list of comment prefixes to use from check file\n"
50a1fd1882SJoel E. Denny              "(defaults to 'COM,RUN'). Please avoid using this feature in\n"
51a1fd1882SJoel E. Denny              "LLVM's LIT-based test suites, which should be easier to\n"
52a1fd1882SJoel E. Denny              "maintain if they all follow a consistent comment style. This\n"
53a1fd1882SJoel E. Denny              "feature is meant for non-LIT test suites using FileCheck."));
54a1fd1882SJoel E. Denny 
55e8f2fb20SChandler Carruth static cl::opt<bool> NoCanonicalizeWhiteSpace(
56e8f2fb20SChandler Carruth     "strict-whitespace",
572c3e5cdfSChris Lattner     cl::desc("Do not treat all horizontal whitespace as equivalent"));
582c3e5cdfSChris Lattner 
595b5b2fd2SKai Nacke static cl::opt<bool> IgnoreCase(
605b5b2fd2SKai Nacke     "ignore-case",
615b5b2fd2SKai Nacke     cl::desc("Use case-insensitive matching"));
625b5b2fd2SKai Nacke 
6356ccdbbdSAlexander Kornienko static cl::list<std::string> ImplicitCheckNot(
6456ccdbbdSAlexander Kornienko     "implicit-check-not",
6556ccdbbdSAlexander Kornienko     cl::desc("Add an implicit negative check with this pattern to every\n"
6656ccdbbdSAlexander Kornienko              "positive check. This can be used to ensure that no instances of\n"
6756ccdbbdSAlexander Kornienko              "this pattern occur which are not matched by a positive pattern"),
6856ccdbbdSAlexander Kornienko     cl::value_desc("pattern"));
6956ccdbbdSAlexander Kornienko 
70a5e233bfSThomas Preud'homme static cl::list<std::string>
71a5e233bfSThomas Preud'homme     GlobalDefines("D", cl::AlwaysPrefix,
7246e1fd61SAlexander Richardson                   cl::desc("Define a variable to be used in capture patterns."),
7346e1fd61SAlexander Richardson                   cl::value_desc("VAR=VALUE"));
7446e1fd61SAlexander Richardson 
751b9f936fSJustin Bogner static cl::opt<bool> AllowEmptyInput(
761b9f936fSJustin Bogner     "allow-empty", cl::init(false),
771b9f936fSJustin Bogner     cl::desc("Allow the input file to be empty. This is useful when making\n"
781b9f936fSJustin Bogner              "checks that some error message does not occur, for example."));
791b9f936fSJustin Bogner 
8085913ccaSJames Y Knight static cl::opt<bool> MatchFullLines(
8185913ccaSJames Y Knight     "match-full-lines", cl::init(false),
8285913ccaSJames Y Knight     cl::desc("Require all positive matches to cover an entire input line.\n"
8385913ccaSJames Y Knight              "Allows leading and trailing whitespace if --strict-whitespace\n"
8485913ccaSJames Y Knight              "is not also passed."));
8585913ccaSJames Y Knight 
86f55e72a5SArtem Belevich static cl::opt<bool> EnableVarScope(
87f55e72a5SArtem Belevich     "enable-var-scope", cl::init(false),
88f55e72a5SArtem Belevich     cl::desc("Enables scope for regex variables. Variables with names that\n"
89f55e72a5SArtem Belevich              "do not start with '$' will be reset at the beginning of\n"
90f55e72a5SArtem Belevich              "each CHECK-LABEL block."));
91f55e72a5SArtem Belevich 
92bcf5b441SJoel E. Denny static cl::opt<bool> AllowDeprecatedDagOverlap(
93bcf5b441SJoel E. Denny     "allow-deprecated-dag-overlap", cl::init(false),
94bcf5b441SJoel E. Denny     cl::desc("Enable overlapping among matches in a group of consecutive\n"
95bcf5b441SJoel E. Denny              "CHECK-DAG directives.  This option is deprecated and is only\n"
96bcf5b441SJoel E. Denny              "provided for convenience as old tests are migrated to the new\n"
97bcf5b441SJoel E. Denny              "non-overlapping CHECK-DAG implementation.\n"));
98bcf5b441SJoel E. Denny 
99352695c3SJoel E. Denny static cl::opt<bool> Verbose(
100*782585a2SJoel E. Denny     "v", cl::init(false), cl::ZeroOrMore,
101352695c3SJoel E. Denny     cl::desc("Print directive pattern matches, or add them to the input dump\n"
102352695c3SJoel E. Denny              "if enabled.\n"));
103dc5ba317SJoel E. Denny 
104dc5ba317SJoel E. Denny static cl::opt<bool> VerboseVerbose(
105*782585a2SJoel E. Denny     "vv", cl::init(false), cl::ZeroOrMore,
106dc5ba317SJoel E. Denny     cl::desc("Print information helpful in diagnosing internal FileCheck\n"
107352695c3SJoel E. Denny              "issues, or add it to the input dump if enabled.  Implies\n"
108352695c3SJoel E. Denny              "-v.\n"));
1093c5d267eSJoel E. Denny 
110fdde18a7SJoel E. Denny // The order of DumpInputValue members affects their precedence, as documented
111fdde18a7SJoel E. Denny // for -dump-input below.
1123c5d267eSJoel E. Denny enum DumpInputValue {
1133c5d267eSJoel E. Denny   DumpInputNever,
1143c5d267eSJoel E. Denny   DumpInputFail,
115fdde18a7SJoel E. Denny   DumpInputAlways,
116fdde18a7SJoel E. Denny   DumpInputHelp
1173c5d267eSJoel E. Denny };
1183c5d267eSJoel E. Denny 
119fdde18a7SJoel E. Denny static cl::list<DumpInputValue> DumpInputs(
120fdde18a7SJoel E. Denny     "dump-input",
1213c5d267eSJoel E. Denny     cl::desc("Dump input to stderr, adding annotations representing\n"
122fdde18a7SJoel E. Denny              "currently enabled diagnostics.  When there are multiple\n"
123fdde18a7SJoel E. Denny              "occurrences of this option, the <value> that appears earliest\n"
124fdde18a7SJoel E. Denny              "in the list below has precedence.\n"),
1253c5d267eSJoel E. Denny     cl::value_desc("mode"),
1263c5d267eSJoel E. Denny     cl::values(clEnumValN(DumpInputHelp, "help",
1273c5d267eSJoel E. Denny                           "Explain dump format and quit"),
128fdde18a7SJoel E. Denny                clEnumValN(DumpInputAlways, "always", "Always dump input"),
1293c5d267eSJoel E. Denny                clEnumValN(DumpInputFail, "fail", "Dump input on failure"),
130fdde18a7SJoel E. Denny                clEnumValN(DumpInputNever, "never", "Never dump input")));
131dc5ba317SJoel E. Denny 
13213df4626SMatt Arsenault typedef cl::list<std::string>::const_iterator prefix_iterator;
13313df4626SMatt Arsenault 
13413df4626SMatt Arsenault 
13513df4626SMatt Arsenault 
136726774cbSChandler Carruth 
137726774cbSChandler Carruth 
138726774cbSChandler Carruth 
139c2735158SRui Ueyama 
1402bd4f8b6SXinliang David Li static void DumpCommandLine(int argc, char **argv) {
1412bd4f8b6SXinliang David Li   errs() << "FileCheck command line: ";
1422bd4f8b6SXinliang David Li   for (int I = 0; I < argc; I++)
1432bd4f8b6SXinliang David Li     errs() << " " << argv[I];
1442bd4f8b6SXinliang David Li   errs() << "\n";
1452bd4f8b6SXinliang David Li }
1462bd4f8b6SXinliang David Li 
1473c5d267eSJoel E. Denny struct MarkerStyle {
1483c5d267eSJoel E. Denny   /// The starting char (before tildes) for marking the line.
1493c5d267eSJoel E. Denny   char Lead;
1503c5d267eSJoel E. Denny   /// What color to use for this annotation.
1514d41c332SRui Ueyama   raw_ostream::Colors Color;
1523c5d267eSJoel E. Denny   /// A note to follow the marker, or empty string if none.
1533c5d267eSJoel E. Denny   std::string Note;
1543c5d267eSJoel E. Denny   MarkerStyle() {}
1554d41c332SRui Ueyama   MarkerStyle(char Lead, raw_ostream::Colors Color,
1564d41c332SRui Ueyama               const std::string &Note = "")
1573c5d267eSJoel E. Denny       : Lead(Lead), Color(Color), Note(Note) {}
1583c5d267eSJoel E. Denny };
1593c5d267eSJoel E. Denny 
1603c5d267eSJoel E. Denny static MarkerStyle GetMarker(FileCheckDiag::MatchType MatchTy) {
1613c5d267eSJoel E. Denny   switch (MatchTy) {
162e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundAndExpected:
1637df86967SJoel E. Denny     return MarkerStyle('^', raw_ostream::GREEN);
164e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundButExcluded:
1650e7e3fa0SJoel E. Denny     return MarkerStyle('!', raw_ostream::RED, "error: no match expected");
166e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundButWrongLine:
167cadfcef4SJoel E. Denny     return MarkerStyle('!', raw_ostream::RED, "error: match on wrong line");
168e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundButDiscarded:
169f7c1c4d8SJoel E. Denny     return MarkerStyle('!', raw_ostream::CYAN,
170f7c1c4d8SJoel E. Denny                        "discard: overlaps earlier match");
17196f0e84cSJoel E. Denny   case FileCheckDiag::MatchNoneAndExcluded:
17296f0e84cSJoel E. Denny     return MarkerStyle('X', raw_ostream::GREEN);
1733c5d267eSJoel E. Denny   case FileCheckDiag::MatchNoneButExpected:
1743c5d267eSJoel E. Denny     return MarkerStyle('X', raw_ostream::RED, "error: no match found");
1752c007c80SJoel E. Denny   case FileCheckDiag::MatchFuzzy:
1762c007c80SJoel E. Denny     return MarkerStyle('?', raw_ostream::MAGENTA, "possible intended match");
1773c5d267eSJoel E. Denny   }
1783c5d267eSJoel E. Denny   llvm_unreachable_internal("unexpected match type");
1793c5d267eSJoel E. Denny }
1803c5d267eSJoel E. Denny 
1813c5d267eSJoel E. Denny static void DumpInputAnnotationHelp(raw_ostream &OS) {
1823c5d267eSJoel E. Denny   OS << "The following description was requested by -dump-input=help to\n"
1833c5d267eSJoel E. Denny      << "explain the input annotations printed by -dump-input=always and\n"
1843c5d267eSJoel E. Denny      << "-dump-input=fail:\n\n";
1853c5d267eSJoel E. Denny 
1863c5d267eSJoel E. Denny   // Labels for input lines.
1873c5d267eSJoel E. Denny   OS << "  - ";
1883c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "L:";
1893c5d267eSJoel E. Denny   OS << "     labels line number L of the input file\n";
1903c5d267eSJoel E. Denny 
1913c5d267eSJoel E. Denny   // Labels for annotation lines.
1923c5d267eSJoel E. Denny   OS << "  - ";
1933c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L";
194b5a24610SJoel E. Denny   OS << "    labels the only match result for either (1) a pattern of type T"
195b5a24610SJoel E. Denny      << " from\n"
196b5a24610SJoel E. Denny      << "           line L of the check file if L is an integer or (2) the"
197b5a24610SJoel E. Denny      << " I-th implicit\n"
198b5a24610SJoel E. Denny      << "           pattern if L is \"imp\" followed by an integer "
199b5a24610SJoel E. Denny      << "I (index origin one)\n";
2002c007c80SJoel E. Denny   OS << "  - ";
2012c007c80SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L'N";
202b5a24610SJoel E. Denny   OS << "  labels the Nth match result for such a pattern\n";
2033c5d267eSJoel E. Denny 
2043c5d267eSJoel E. Denny   // Markers on annotation lines.
2053c5d267eSJoel E. Denny   OS << "  - ";
2067df86967SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "^~~";
2077df86967SJoel E. Denny   OS << "    marks good match (reported if -v)\n"
2087df86967SJoel E. Denny      << "  - ";
209cadfcef4SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "!~~";
210cadfcef4SJoel E. Denny   OS << "    marks bad match, such as:\n"
211cadfcef4SJoel E. Denny      << "           - CHECK-NEXT on same line as previous match (error)\n"
2120e7e3fa0SJoel E. Denny      << "           - CHECK-NOT found (error)\n"
213f7c1c4d8SJoel E. Denny      << "           - CHECK-DAG overlapping match (discarded, reported if "
214f7c1c4d8SJoel E. Denny      << "-vv)\n"
215cadfcef4SJoel E. Denny      << "  - ";
2163c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "X~~";
217cadfcef4SJoel E. Denny   OS << "    marks search range when no match is found, such as:\n"
218cadfcef4SJoel E. Denny      << "           - CHECK-NEXT not found (error)\n"
21996f0e84cSJoel E. Denny      << "           - CHECK-NOT not found (success, reported if -vv)\n"
220f7c1c4d8SJoel E. Denny      << "           - CHECK-DAG not found after discarded matches (error)\n"
2212c007c80SJoel E. Denny      << "  - ";
2222c007c80SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "?";
2232c007c80SJoel E. Denny   OS << "      marks fuzzy match when no match is found\n";
2243c5d267eSJoel E. Denny 
2253c5d267eSJoel E. Denny   // Colors.
2263c5d267eSJoel E. Denny   OS << "  - colors ";
2277df86967SJoel E. Denny   WithColor(OS, raw_ostream::GREEN, true) << "success";
2287df86967SJoel E. Denny   OS << ", ";
2293c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::RED, true) << "error";
2302c007c80SJoel E. Denny   OS << ", ";
2312c007c80SJoel E. Denny   WithColor(OS, raw_ostream::MAGENTA, true) << "fuzzy match";
2327df86967SJoel E. Denny   OS << ", ";
233f7c1c4d8SJoel E. Denny   WithColor(OS, raw_ostream::CYAN, true, false) << "discarded match";
234f7c1c4d8SJoel E. Denny   OS << ", ";
2357df86967SJoel E. Denny   WithColor(OS, raw_ostream::CYAN, true, true) << "unmatched input";
2363c5d267eSJoel E. Denny   OS << "\n\n"
2373c5d267eSJoel E. Denny      << "If you are not seeing color above or in input dumps, try: -color\n";
2383c5d267eSJoel E. Denny }
2393c5d267eSJoel E. Denny 
2403c5d267eSJoel E. Denny /// An annotation for a single input line.
2413c5d267eSJoel E. Denny struct InputAnnotation {
242ce685455SJoel E. Denny   /// The index of the match result across all checks
243ce685455SJoel E. Denny   unsigned DiagIndex;
2443c5d267eSJoel E. Denny   /// The label for this annotation.
2453c5d267eSJoel E. Denny   std::string Label;
2463c5d267eSJoel E. Denny   /// What input line (one-origin indexing) this annotation marks.  This might
2473c5d267eSJoel E. Denny   /// be different from the starting line of the original diagnostic if this is
2483c5d267eSJoel E. Denny   /// a non-initial fragment of a diagnostic that has been broken across
2493c5d267eSJoel E. Denny   /// multiple lines.
2503c5d267eSJoel E. Denny   unsigned InputLine;
251ce685455SJoel E. Denny   /// The column range (one-origin indexing, open end) in which to mark the
2523c5d267eSJoel E. Denny   /// input line.  If InputEndCol is UINT_MAX, treat it as the last column
2533c5d267eSJoel E. Denny   /// before the newline.
2543c5d267eSJoel E. Denny   unsigned InputStartCol, InputEndCol;
2553c5d267eSJoel E. Denny   /// The marker to use.
2563c5d267eSJoel E. Denny   MarkerStyle Marker;
257e2afb614SJoel E. Denny   /// Whether this annotation represents a good match for an expected pattern.
258e2afb614SJoel E. Denny   bool FoundAndExpectedMatch;
2593c5d267eSJoel E. Denny };
2603c5d267eSJoel E. Denny 
2613c5d267eSJoel E. Denny /// Get an abbreviation for the check type.
2623c5d267eSJoel E. Denny std::string GetCheckTypeAbbreviation(Check::FileCheckType Ty) {
2633c5d267eSJoel E. Denny   switch (Ty) {
2643c5d267eSJoel E. Denny   case Check::CheckPlain:
2653c5d267eSJoel E. Denny     if (Ty.getCount() > 1)
2663c5d267eSJoel E. Denny       return "count";
2673c5d267eSJoel E. Denny     return "check";
2683c5d267eSJoel E. Denny   case Check::CheckNext:
2693c5d267eSJoel E. Denny     return "next";
2703c5d267eSJoel E. Denny   case Check::CheckSame:
2713c5d267eSJoel E. Denny     return "same";
2723c5d267eSJoel E. Denny   case Check::CheckNot:
2733c5d267eSJoel E. Denny     return "not";
2743c5d267eSJoel E. Denny   case Check::CheckDAG:
2753c5d267eSJoel E. Denny     return "dag";
2763c5d267eSJoel E. Denny   case Check::CheckLabel:
2773c5d267eSJoel E. Denny     return "label";
2783c5d267eSJoel E. Denny   case Check::CheckEmpty:
2793c5d267eSJoel E. Denny     return "empty";
280a1fd1882SJoel E. Denny   case Check::CheckComment:
281a1fd1882SJoel E. Denny     return "com";
2823c5d267eSJoel E. Denny   case Check::CheckEOF:
2833c5d267eSJoel E. Denny     return "eof";
2843c5d267eSJoel E. Denny   case Check::CheckBadNot:
2853c5d267eSJoel E. Denny     return "bad-not";
2863c5d267eSJoel E. Denny   case Check::CheckBadCount:
2873c5d267eSJoel E. Denny     return "bad-count";
2883c5d267eSJoel E. Denny   case Check::CheckNone:
2893c5d267eSJoel E. Denny     llvm_unreachable("invalid FileCheckType");
2903c5d267eSJoel E. Denny   }
2913c5d267eSJoel E. Denny   llvm_unreachable("unknown FileCheckType");
2923c5d267eSJoel E. Denny }
2933c5d267eSJoel E. Denny 
294b5a24610SJoel E. Denny static void
295b5a24610SJoel E. Denny BuildInputAnnotations(const SourceMgr &SM, unsigned CheckFileBufferID,
296b5a24610SJoel E. Denny                       const std::pair<unsigned, unsigned> &ImpPatBufferIDRange,
297b5a24610SJoel E. Denny                       const std::vector<FileCheckDiag> &Diags,
2983c5d267eSJoel E. Denny                       std::vector<InputAnnotation> &Annotations,
2993c5d267eSJoel E. Denny                       unsigned &LabelWidth) {
300ce685455SJoel E. Denny   // How many diagnostics have we seen so far?
301ce685455SJoel E. Denny   unsigned DiagCount = 0;
3022c007c80SJoel E. Denny   // How many diagnostics has the current check seen so far?
3032c007c80SJoel E. Denny   unsigned CheckDiagCount = 0;
3043c5d267eSJoel E. Denny   // What's the widest label?
3053c5d267eSJoel E. Denny   LabelWidth = 0;
3063c5d267eSJoel E. Denny   for (auto DiagItr = Diags.begin(), DiagEnd = Diags.end(); DiagItr != DiagEnd;
3073c5d267eSJoel E. Denny        ++DiagItr) {
3083c5d267eSJoel E. Denny     InputAnnotation A;
309ce685455SJoel E. Denny     A.DiagIndex = DiagCount++;
3103c5d267eSJoel E. Denny 
3113c5d267eSJoel E. Denny     // Build label, which uniquely identifies this check result.
312b5a24610SJoel E. Denny     unsigned CheckBufferID = SM.FindBufferContainingLoc(DiagItr->CheckLoc);
313b5a24610SJoel E. Denny     auto CheckLineAndCol =
314b5a24610SJoel E. Denny         SM.getLineAndColumn(DiagItr->CheckLoc, CheckBufferID);
3153c5d267eSJoel E. Denny     llvm::raw_string_ostream Label(A.Label);
316b5a24610SJoel E. Denny     Label << GetCheckTypeAbbreviation(DiagItr->CheckTy) << ":";
317b5a24610SJoel E. Denny     if (CheckBufferID == CheckFileBufferID)
318b5a24610SJoel E. Denny       Label << CheckLineAndCol.first;
319b5a24610SJoel E. Denny     else if (ImpPatBufferIDRange.first <= CheckBufferID &&
320b5a24610SJoel E. Denny              CheckBufferID < ImpPatBufferIDRange.second)
321b5a24610SJoel E. Denny       Label << "imp" << (CheckBufferID - ImpPatBufferIDRange.first + 1);
322b5a24610SJoel E. Denny     else
323b5a24610SJoel E. Denny       llvm_unreachable("expected diagnostic's check location to be either in "
324b5a24610SJoel E. Denny                        "the check file or for an implicit pattern");
325ce685455SJoel E. Denny     unsigned CheckDiagIndex = UINT_MAX;
3262c007c80SJoel E. Denny     auto DiagNext = std::next(DiagItr);
3272c007c80SJoel E. Denny     if (DiagNext != DiagEnd && DiagItr->CheckTy == DiagNext->CheckTy &&
328b5a24610SJoel E. Denny         DiagItr->CheckLoc == DiagNext->CheckLoc)
329ce685455SJoel E. Denny       CheckDiagIndex = CheckDiagCount++;
3302c007c80SJoel E. Denny     else if (CheckDiagCount) {
331ce685455SJoel E. Denny       CheckDiagIndex = CheckDiagCount;
3322c007c80SJoel E. Denny       CheckDiagCount = 0;
3332c007c80SJoel E. Denny     }
334ce685455SJoel E. Denny     if (CheckDiagIndex != UINT_MAX)
335ce685455SJoel E. Denny       Label << "'" << CheckDiagIndex;
3363c5d267eSJoel E. Denny     Label.flush();
3373c5d267eSJoel E. Denny     LabelWidth = std::max((std::string::size_type)LabelWidth, A.Label.size());
3383c5d267eSJoel E. Denny 
339608f2bfdSJoel E. Denny     A.Marker = GetMarker(DiagItr->MatchTy);
340e2afb614SJoel E. Denny     A.FoundAndExpectedMatch =
341e2afb614SJoel E. Denny         DiagItr->MatchTy == FileCheckDiag::MatchFoundAndExpected;
3423c5d267eSJoel E. Denny 
3433c5d267eSJoel E. Denny     // Compute the mark location, and break annotation into multiple
3443c5d267eSJoel E. Denny     // annotations if it spans multiple lines.
3453c5d267eSJoel E. Denny     A.InputLine = DiagItr->InputStartLine;
3463c5d267eSJoel E. Denny     A.InputStartCol = DiagItr->InputStartCol;
3473c5d267eSJoel E. Denny     if (DiagItr->InputStartLine == DiagItr->InputEndLine) {
3483c5d267eSJoel E. Denny       // Sometimes ranges are empty in order to indicate a specific point, but
3493c5d267eSJoel E. Denny       // that would mean nothing would be marked, so adjust the range to
3503c5d267eSJoel E. Denny       // include the following character.
3513c5d267eSJoel E. Denny       A.InputEndCol =
3523c5d267eSJoel E. Denny           std::max(DiagItr->InputStartCol + 1, DiagItr->InputEndCol);
3533c5d267eSJoel E. Denny       Annotations.push_back(A);
3543c5d267eSJoel E. Denny     } else {
3553c5d267eSJoel E. Denny       assert(DiagItr->InputStartLine < DiagItr->InputEndLine &&
3563c5d267eSJoel E. Denny              "expected input range not to be inverted");
3573c5d267eSJoel E. Denny       A.InputEndCol = UINT_MAX;
3583c5d267eSJoel E. Denny       Annotations.push_back(A);
3593c5d267eSJoel E. Denny       for (unsigned L = DiagItr->InputStartLine + 1, E = DiagItr->InputEndLine;
3603c5d267eSJoel E. Denny            L <= E; ++L) {
3613c5d267eSJoel E. Denny         // If a range ends before the first column on a line, then it has no
3623c5d267eSJoel E. Denny         // characters on that line, so there's nothing to render.
363608f2bfdSJoel E. Denny         if (DiagItr->InputEndCol == 1 && L == E)
3643c5d267eSJoel E. Denny           break;
3653c5d267eSJoel E. Denny         InputAnnotation B;
366ce685455SJoel E. Denny         B.DiagIndex = A.DiagIndex;
3673c5d267eSJoel E. Denny         B.Label = A.Label;
3683c5d267eSJoel E. Denny         B.InputLine = L;
369608f2bfdSJoel E. Denny         B.Marker = A.Marker;
3703c5d267eSJoel E. Denny         B.Marker.Lead = '~';
3713c5d267eSJoel E. Denny         B.Marker.Note = "";
372608f2bfdSJoel E. Denny         B.InputStartCol = 1;
373608f2bfdSJoel E. Denny         if (L != E)
374608f2bfdSJoel E. Denny           B.InputEndCol = UINT_MAX;
375608f2bfdSJoel E. Denny         else
3763c5d267eSJoel E. Denny           B.InputEndCol = DiagItr->InputEndCol;
377e2afb614SJoel E. Denny         B.FoundAndExpectedMatch = A.FoundAndExpectedMatch;
3783c5d267eSJoel E. Denny         Annotations.push_back(B);
3793c5d267eSJoel E. Denny       }
3803c5d267eSJoel E. Denny     }
3813c5d267eSJoel E. Denny   }
3823c5d267eSJoel E. Denny }
3833c5d267eSJoel E. Denny 
3847df86967SJoel E. Denny static void DumpAnnotatedInput(raw_ostream &OS, const FileCheckRequest &Req,
3857df86967SJoel E. Denny                                StringRef InputFileText,
3867df86967SJoel E. Denny                                std::vector<InputAnnotation> &Annotations,
3877df86967SJoel E. Denny                                unsigned LabelWidth) {
3883c5d267eSJoel E. Denny   OS << "Full input was:\n<<<<<<\n";
3893c5d267eSJoel E. Denny 
3903c5d267eSJoel E. Denny   // Sort annotations.
3913c5d267eSJoel E. Denny   std::sort(Annotations.begin(), Annotations.end(),
3923c5d267eSJoel E. Denny             [](const InputAnnotation &A, const InputAnnotation &B) {
393ce685455SJoel E. Denny               // 1. Sort annotations in the order of the input lines.
394ce685455SJoel E. Denny               //
395ce685455SJoel E. Denny               // This makes it easier to find relevant annotations while
396ce685455SJoel E. Denny               // iterating input lines in the implementation below.  FileCheck
397ce685455SJoel E. Denny               // does not always produce diagnostics in the order of input
398ce685455SJoel E. Denny               // lines due to, for example, CHECK-DAG and CHECK-NOT.
3993c5d267eSJoel E. Denny               if (A.InputLine != B.InputLine)
4003c5d267eSJoel E. Denny                 return A.InputLine < B.InputLine;
401ce685455SJoel E. Denny               // 2. Sort annotations in the temporal order FileCheck produced
402ce685455SJoel E. Denny               // their associated diagnostics.
403ce685455SJoel E. Denny               //
404ce685455SJoel E. Denny               // This sort offers several benefits:
405ce685455SJoel E. Denny               //
406ce685455SJoel E. Denny               // A. On a single input line, the order of annotations reflects
407ce685455SJoel E. Denny               //    the FileCheck logic for processing directives/patterns.
408ce685455SJoel E. Denny               //    This can be helpful in understanding cases in which the
409ce685455SJoel E. Denny               //    order of the associated directives/patterns in the check
410ce685455SJoel E. Denny               //    file or on the command line either (i) does not match the
411ce685455SJoel E. Denny               //    temporal order in which FileCheck looks for matches for the
412ce685455SJoel E. Denny               //    directives/patterns (due to, for example, CHECK-LABEL,
413ce685455SJoel E. Denny               //    CHECK-NOT, or `--implicit-check-not`) or (ii) does match
414ce685455SJoel E. Denny               //    that order but does not match the order of those
415ce685455SJoel E. Denny               //    diagnostics along an input line (due to, for example,
416ce685455SJoel E. Denny               //    CHECK-DAG).
417ce685455SJoel E. Denny               //
418ce685455SJoel E. Denny               //    On the other hand, because our presentation format presents
419ce685455SJoel E. Denny               //    input lines in order, there's no clear way to offer the
420ce685455SJoel E. Denny               //    same benefit across input lines.  For consistency, it might
421ce685455SJoel E. Denny               //    then seem worthwhile to have annotations on a single line
422ce685455SJoel E. Denny               //    also sorted in input order (that is, by input column).
423ce685455SJoel E. Denny               //    However, in practice, this appears to be more confusing
424ce685455SJoel E. Denny               //    than helpful.  Perhaps it's intuitive to expect annotations
425ce685455SJoel E. Denny               //    to be listed in the temporal order in which they were
426ce685455SJoel E. Denny               //    produced except in cases the presentation format obviously
427ce685455SJoel E. Denny               //    and inherently cannot support it (that is, across input
428ce685455SJoel E. Denny               //    lines).
429ce685455SJoel E. Denny               //
430ce685455SJoel E. Denny               // B. When diagnostics' annotations are split among multiple
431ce685455SJoel E. Denny               //    input lines, the user must track them from one input line
432ce685455SJoel E. Denny               //    to the next.  One property of the sort chosen here is that
433ce685455SJoel E. Denny               //    it facilitates the user in this regard by ensuring the
434ce685455SJoel E. Denny               //    following: when comparing any two input lines, a
435ce685455SJoel E. Denny               //    diagnostic's annotations are sorted in the same position
436ce685455SJoel E. Denny               //    relative to all other diagnostics' annotations.
437ce685455SJoel E. Denny               return A.DiagIndex < B.DiagIndex;
4383c5d267eSJoel E. Denny             });
4393c5d267eSJoel E. Denny 
4403c5d267eSJoel E. Denny   // Compute the width of the label column.
4413c5d267eSJoel E. Denny   const unsigned char *InputFilePtr = InputFileText.bytes_begin(),
4423c5d267eSJoel E. Denny                       *InputFileEnd = InputFileText.bytes_end();
4433c5d267eSJoel E. Denny   unsigned LineCount = InputFileText.count('\n');
4443c5d267eSJoel E. Denny   if (InputFileEnd[-1] != '\n')
4453c5d267eSJoel E. Denny     ++LineCount;
446010982f7SRainer Orth   unsigned LineNoWidth = std::log10(LineCount) + 1;
4473c5d267eSJoel E. Denny   // +3 below adds spaces (1) to the left of the (right-aligned) line numbers
4483c5d267eSJoel E. Denny   // on input lines and (2) to the right of the (left-aligned) labels on
4493c5d267eSJoel E. Denny   // annotation lines so that input lines and annotation lines are more
4503c5d267eSJoel E. Denny   // visually distinct.  For example, the spaces on the annotation lines ensure
4513c5d267eSJoel E. Denny   // that input line numbers and check directive line numbers never align
4523c5d267eSJoel E. Denny   // horizontally.  Those line numbers might not even be for the same file.
4533c5d267eSJoel E. Denny   // One space would be enough to achieve that, but more makes it even easier
4543c5d267eSJoel E. Denny   // to see.
4553c5d267eSJoel E. Denny   LabelWidth = std::max(LabelWidth, LineNoWidth) + 3;
4563c5d267eSJoel E. Denny 
4573c5d267eSJoel E. Denny   // Print annotated input lines.
4583c5d267eSJoel E. Denny   auto AnnotationItr = Annotations.begin(), AnnotationEnd = Annotations.end();
4593c5d267eSJoel E. Denny   for (unsigned Line = 1;
4603c5d267eSJoel E. Denny        InputFilePtr != InputFileEnd || AnnotationItr != AnnotationEnd;
4613c5d267eSJoel E. Denny        ++Line) {
4623c5d267eSJoel E. Denny     const unsigned char *InputFileLine = InputFilePtr;
4633c5d267eSJoel E. Denny 
4643c5d267eSJoel E. Denny     // Print right-aligned line number.
4653c5d267eSJoel E. Denny     WithColor(OS, raw_ostream::BLACK, true)
4663c5d267eSJoel E. Denny         << format_decimal(Line, LabelWidth) << ": ";
4673c5d267eSJoel E. Denny 
468e2afb614SJoel E. Denny     // For the case where -v and colors are enabled, find the annotations for
469e2afb614SJoel E. Denny     // good matches for expected patterns in order to highlight everything
470e2afb614SJoel E. Denny     // else in the line.  There are no such annotations if -v is disabled.
471e2afb614SJoel E. Denny     std::vector<InputAnnotation> FoundAndExpectedMatches;
4727df86967SJoel E. Denny     if (Req.Verbose && WithColor(OS).colorsEnabled()) {
4737df86967SJoel E. Denny       for (auto I = AnnotationItr; I != AnnotationEnd && I->InputLine == Line;
4747df86967SJoel E. Denny            ++I) {
475e2afb614SJoel E. Denny         if (I->FoundAndExpectedMatch)
476e2afb614SJoel E. Denny           FoundAndExpectedMatches.push_back(*I);
4777df86967SJoel E. Denny       }
4787df86967SJoel E. Denny     }
4797df86967SJoel E. Denny 
4807df86967SJoel E. Denny     // Print numbered line with highlighting where there are no matches for
4817df86967SJoel E. Denny     // expected patterns.
4823c5d267eSJoel E. Denny     bool Newline = false;
4837df86967SJoel E. Denny     {
4847df86967SJoel E. Denny       WithColor COS(OS);
4857df86967SJoel E. Denny       bool InMatch = false;
4867df86967SJoel E. Denny       if (Req.Verbose)
4877df86967SJoel E. Denny         COS.changeColor(raw_ostream::CYAN, true, true);
4887df86967SJoel E. Denny       for (unsigned Col = 1; InputFilePtr != InputFileEnd && !Newline; ++Col) {
4897df86967SJoel E. Denny         bool WasInMatch = InMatch;
4907df86967SJoel E. Denny         InMatch = false;
491e2afb614SJoel E. Denny         for (auto M : FoundAndExpectedMatches) {
4927df86967SJoel E. Denny           if (M.InputStartCol <= Col && Col < M.InputEndCol) {
4937df86967SJoel E. Denny             InMatch = true;
4947df86967SJoel E. Denny             break;
4957df86967SJoel E. Denny           }
4967df86967SJoel E. Denny         }
4977df86967SJoel E. Denny         if (!WasInMatch && InMatch)
4987df86967SJoel E. Denny           COS.resetColor();
4997df86967SJoel E. Denny         else if (WasInMatch && !InMatch)
5007df86967SJoel E. Denny           COS.changeColor(raw_ostream::CYAN, true, true);
5013c5d267eSJoel E. Denny         if (*InputFilePtr == '\n')
5023c5d267eSJoel E. Denny           Newline = true;
5033c5d267eSJoel E. Denny         else
5047df86967SJoel E. Denny           COS << *InputFilePtr;
5053c5d267eSJoel E. Denny         ++InputFilePtr;
5063c5d267eSJoel E. Denny       }
5077df86967SJoel E. Denny     }
5083c5d267eSJoel E. Denny     OS << '\n';
5093c5d267eSJoel E. Denny     unsigned InputLineWidth = InputFilePtr - InputFileLine - Newline;
5103c5d267eSJoel E. Denny 
5113c5d267eSJoel E. Denny     // Print any annotations.
5123c5d267eSJoel E. Denny     while (AnnotationItr != AnnotationEnd &&
5133c5d267eSJoel E. Denny            AnnotationItr->InputLine == Line) {
5143c5d267eSJoel E. Denny       WithColor COS(OS, AnnotationItr->Marker.Color, true);
5153c5d267eSJoel E. Denny       // The two spaces below are where the ": " appears on input lines.
5163c5d267eSJoel E. Denny       COS << left_justify(AnnotationItr->Label, LabelWidth) << "  ";
5173c5d267eSJoel E. Denny       unsigned Col;
5183c5d267eSJoel E. Denny       for (Col = 1; Col < AnnotationItr->InputStartCol; ++Col)
5193c5d267eSJoel E. Denny         COS << ' ';
5203c5d267eSJoel E. Denny       COS << AnnotationItr->Marker.Lead;
5213c5d267eSJoel E. Denny       // If InputEndCol=UINT_MAX, stop at InputLineWidth.
5223c5d267eSJoel E. Denny       for (++Col; Col < AnnotationItr->InputEndCol && Col <= InputLineWidth;
5233c5d267eSJoel E. Denny            ++Col)
5243c5d267eSJoel E. Denny         COS << '~';
5253c5d267eSJoel E. Denny       const std::string &Note = AnnotationItr->Marker.Note;
5263c5d267eSJoel E. Denny       if (!Note.empty()) {
5273c5d267eSJoel E. Denny         // Put the note at the end of the input line.  If we were to instead
5283c5d267eSJoel E. Denny         // put the note right after the marker, subsequent annotations for the
5293c5d267eSJoel E. Denny         // same input line might appear to mark this note instead of the input
5303c5d267eSJoel E. Denny         // line.
5313c5d267eSJoel E. Denny         for (; Col <= InputLineWidth; ++Col)
5323c5d267eSJoel E. Denny           COS << ' ';
5333c5d267eSJoel E. Denny         COS << ' ' << Note;
5343c5d267eSJoel E. Denny       }
5353c5d267eSJoel E. Denny       COS << '\n';
5363c5d267eSJoel E. Denny       ++AnnotationItr;
5373c5d267eSJoel E. Denny     }
5383c5d267eSJoel E. Denny   }
5393c5d267eSJoel E. Denny 
5403c5d267eSJoel E. Denny   OS << ">>>>>>\n";
5413c5d267eSJoel E. Denny }
5423c5d267eSJoel E. Denny 
543ee3c74fbSChris Lattner int main(int argc, char **argv) {
5443e66509fSJoel E. Denny   // Enable use of ANSI color codes because FileCheck is using them to
5453e66509fSJoel E. Denny   // highlight text.
5463e66509fSJoel E. Denny   llvm::sys::Process::UseANSIEscapeCodes(true);
5473e66509fSJoel E. Denny 
548197194b6SRui Ueyama   InitLLVM X(argc, argv);
54924994d77SJoel E. Denny   cl::ParseCommandLineOptions(argc, argv, /*Overview*/ "", /*Errs*/ nullptr,
55024994d77SJoel E. Denny                               "FILECHECK_OPTS");
551fdde18a7SJoel E. Denny   DumpInputValue DumpInput =
552fdde18a7SJoel E. Denny       DumpInputs.empty()
5533b83501cSJoel E. Denny           ? DumpInputFail
554fdde18a7SJoel E. Denny           : *std::max_element(DumpInputs.begin(), DumpInputs.end());
5553c5d267eSJoel E. Denny   if (DumpInput == DumpInputHelp) {
5563c5d267eSJoel E. Denny     DumpInputAnnotationHelp(outs());
5573c5d267eSJoel E. Denny     return 0;
5583c5d267eSJoel E. Denny   }
5593c5d267eSJoel E. Denny   if (CheckFilename.empty()) {
5603c5d267eSJoel E. Denny     errs() << "<check-file> not specified\n";
5613c5d267eSJoel E. Denny     return 2;
5623c5d267eSJoel E. Denny   }
563ee3c74fbSChris Lattner 
564ffa9d2e4SAditya Nandakumar   FileCheckRequest Req;
56576e0ab23SGeorgii Rymar   for (StringRef Prefix : CheckPrefixes)
566ffa9d2e4SAditya Nandakumar     Req.CheckPrefixes.push_back(Prefix);
567ffa9d2e4SAditya Nandakumar 
568a1fd1882SJoel E. Denny   for (StringRef Prefix : CommentPrefixes)
569a1fd1882SJoel E. Denny     Req.CommentPrefixes.push_back(Prefix);
570a1fd1882SJoel E. Denny 
57176e0ab23SGeorgii Rymar   for (StringRef CheckNot : ImplicitCheckNot)
572ffa9d2e4SAditya Nandakumar     Req.ImplicitCheckNot.push_back(CheckNot);
573ffa9d2e4SAditya Nandakumar 
574a5e233bfSThomas Preud'homme   bool GlobalDefineError = false;
57576e0ab23SGeorgii Rymar   for (StringRef G : GlobalDefines) {
576a5e233bfSThomas Preud'homme     size_t EqIdx = G.find('=');
577a5e233bfSThomas Preud'homme     if (EqIdx == std::string::npos) {
578a5e233bfSThomas Preud'homme       errs() << "Missing equal sign in command-line definition '-D" << G
579a5e233bfSThomas Preud'homme              << "'\n";
580a5e233bfSThomas Preud'homme       GlobalDefineError = true;
581a5e233bfSThomas Preud'homme       continue;
582a5e233bfSThomas Preud'homme     }
583a5e233bfSThomas Preud'homme     if (EqIdx == 0) {
5841a944d27SThomas Preud'homme       errs() << "Missing variable name in command-line definition '-D" << G
5851a944d27SThomas Preud'homme              << "'\n";
586a5e233bfSThomas Preud'homme       GlobalDefineError = true;
587a5e233bfSThomas Preud'homme       continue;
588a5e233bfSThomas Preud'homme     }
589ffa9d2e4SAditya Nandakumar     Req.GlobalDefines.push_back(G);
590a5e233bfSThomas Preud'homme   }
591a5e233bfSThomas Preud'homme   if (GlobalDefineError)
592a5e233bfSThomas Preud'homme     return 2;
593ffa9d2e4SAditya Nandakumar 
594ffa9d2e4SAditya Nandakumar   Req.AllowEmptyInput = AllowEmptyInput;
595ffa9d2e4SAditya Nandakumar   Req.EnableVarScope = EnableVarScope;
596ffa9d2e4SAditya Nandakumar   Req.AllowDeprecatedDagOverlap = AllowDeprecatedDagOverlap;
597ffa9d2e4SAditya Nandakumar   Req.Verbose = Verbose;
598ffa9d2e4SAditya Nandakumar   Req.VerboseVerbose = VerboseVerbose;
599ffa9d2e4SAditya Nandakumar   Req.NoCanonicalizeWhiteSpace = NoCanonicalizeWhiteSpace;
600ffa9d2e4SAditya Nandakumar   Req.MatchFullLines = MatchFullLines;
6015b5b2fd2SKai Nacke   Req.IgnoreCase = IgnoreCase;
602ffa9d2e4SAditya Nandakumar 
603ffa9d2e4SAditya Nandakumar   if (VerboseVerbose)
604ffa9d2e4SAditya Nandakumar     Req.Verbose = true;
605ffa9d2e4SAditya Nandakumar 
606ffa9d2e4SAditya Nandakumar   FileCheck FC(Req);
6072aa0217aSJoel E. Denny   if (!FC.ValidateCheckPrefixes())
608c2735158SRui Ueyama     return 2;
609c2735158SRui Ueyama 
610ffa9d2e4SAditya Nandakumar   Regex PrefixRE = FC.buildCheckPrefixRegex();
611726774cbSChandler Carruth   std::string REError;
612726774cbSChandler Carruth   if (!PrefixRE.isValid(REError)) {
613726774cbSChandler Carruth     errs() << "Unable to combine check-prefix strings into a prefix regular "
614726774cbSChandler Carruth               "expression! This is likely a bug in FileCheck's verification of "
615726774cbSChandler Carruth               "the check-prefix strings. Regular expression parsing failed "
616726774cbSChandler Carruth               "with the following error: "
617726774cbSChandler Carruth            << REError << "\n";
618726774cbSChandler Carruth     return 2;
619726774cbSChandler Carruth   }
62013df4626SMatt Arsenault 
621ee3c74fbSChris Lattner   SourceMgr SM;
622ee3c74fbSChris Lattner 
623ee3c74fbSChris Lattner   // Read the expected strings from the check file.
62420247900SChandler Carruth   ErrorOr<std::unique_ptr<MemoryBuffer>> CheckFileOrErr =
62520247900SChandler Carruth       MemoryBuffer::getFileOrSTDIN(CheckFilename);
62620247900SChandler Carruth   if (std::error_code EC = CheckFileOrErr.getError()) {
62720247900SChandler Carruth     errs() << "Could not open check file '" << CheckFilename
62820247900SChandler Carruth            << "': " << EC.message() << '\n';
62920247900SChandler Carruth     return 2;
63020247900SChandler Carruth   }
63120247900SChandler Carruth   MemoryBuffer &CheckFile = *CheckFileOrErr.get();
63220247900SChandler Carruth 
63320247900SChandler Carruth   SmallString<4096> CheckFileBuffer;
634ffa9d2e4SAditya Nandakumar   StringRef CheckFileText = FC.CanonicalizeFile(CheckFile, CheckFileBuffer);
63520247900SChandler Carruth 
636b5a24610SJoel E. Denny   unsigned CheckFileBufferID =
63720247900SChandler Carruth       SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
63820247900SChandler Carruth                                 CheckFileText, CheckFile.getBufferIdentifier()),
63920247900SChandler Carruth                             SMLoc());
64020247900SChandler Carruth 
641b5a24610SJoel E. Denny   std::pair<unsigned, unsigned> ImpPatBufferIDRange;
642b5a24610SJoel E. Denny   if (FC.readCheckFile(SM, CheckFileText, PrefixRE, &ImpPatBufferIDRange))
643ee3c74fbSChris Lattner     return 2;
644ee3c74fbSChris Lattner 
645ee3c74fbSChris Lattner   // Open the file to check and add it to SourceMgr.
64620247900SChandler Carruth   ErrorOr<std::unique_ptr<MemoryBuffer>> InputFileOrErr =
647adf21f2aSRafael Espindola       MemoryBuffer::getFileOrSTDIN(InputFilename);
6486e01cd67SDavid Bozier   if (InputFilename == "-")
6496e01cd67SDavid Bozier     InputFilename = "<stdin>"; // Overwrite for improved diagnostic messages
65020247900SChandler Carruth   if (std::error_code EC = InputFileOrErr.getError()) {
651adf21f2aSRafael Espindola     errs() << "Could not open input file '" << InputFilename
652adf21f2aSRafael Espindola            << "': " << EC.message() << '\n';
6538e1c6477SEli Bendersky     return 2;
654ee3c74fbSChris Lattner   }
65520247900SChandler Carruth   MemoryBuffer &InputFile = *InputFileOrErr.get();
6562c3e5cdfSChris Lattner 
65720247900SChandler Carruth   if (InputFile.getBufferSize() == 0 && !AllowEmptyInput) {
658b692bed7SChris Lattner     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
6592bd4f8b6SXinliang David Li     DumpCommandLine(argc, argv);
6608e1c6477SEli Bendersky     return 2;
661b692bed7SChris Lattner   }
662b692bed7SChris Lattner 
66320247900SChandler Carruth   SmallString<4096> InputFileBuffer;
664ffa9d2e4SAditya Nandakumar   StringRef InputFileText = FC.CanonicalizeFile(InputFile, InputFileBuffer);
6652c3e5cdfSChris Lattner 
666e8f2fb20SChandler Carruth   SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
667e8f2fb20SChandler Carruth                             InputFileText, InputFile.getBufferIdentifier()),
668e8f2fb20SChandler Carruth                         SMLoc());
669ee3c74fbSChris Lattner 
6703c5d267eSJoel E. Denny   std::vector<FileCheckDiag> Diags;
67102ada9bdSThomas Preud'homme   int ExitCode = FC.checkInput(SM, InputFileText,
6723c5d267eSJoel E. Denny                                DumpInput == DumpInputNever ? nullptr : &Diags)
6733c5d267eSJoel E. Denny                      ? EXIT_SUCCESS
6743c5d267eSJoel E. Denny                      : 1;
6753c5d267eSJoel E. Denny   if (DumpInput == DumpInputAlways ||
6763c5d267eSJoel E. Denny       (ExitCode == 1 && DumpInput == DumpInputFail)) {
6773c5d267eSJoel E. Denny     errs() << "\n"
6783c5d267eSJoel E. Denny            << "Input file: "
6796e01cd67SDavid Bozier            << InputFilename
6803c5d267eSJoel E. Denny            << "\n"
6813c5d267eSJoel E. Denny            << "Check file: " << CheckFilename << "\n"
6823c5d267eSJoel E. Denny            << "\n"
6833c5d267eSJoel E. Denny            << "-dump-input=help describes the format of the following dump.\n"
6843c5d267eSJoel E. Denny            << "\n";
6853c5d267eSJoel E. Denny     std::vector<InputAnnotation> Annotations;
6863c5d267eSJoel E. Denny     unsigned LabelWidth;
687b5a24610SJoel E. Denny     BuildInputAnnotations(SM, CheckFileBufferID, ImpPatBufferIDRange, Diags,
688b5a24610SJoel E. Denny                           Annotations, LabelWidth);
6897df86967SJoel E. Denny     DumpAnnotatedInput(errs(), Req, InputFileText, Annotations, LabelWidth);
6903c5d267eSJoel E. Denny   }
691346dfbe2SGeorge Karpenkov 
692346dfbe2SGeorge Karpenkov   return ExitCode;
693ee3c74fbSChris Lattner }
694