33 return make_error<UndefVarError>(Name);
42 if (!LeftOp || !RightOp) {
48 return std::move(Err);
51 return EvalBinop(*LeftOp, *RightOp);
58 return utostr(*EvaluatedValue);
76 bool ParsedOneChar =
false;
78 bool IsPseudo = Str[0] ==
'@';
81 if (Str[0] ==
'$' || IsPseudo)
84 for (
unsigned E = Str.
size(); I !=
E; ++
I) {
85 if (!ParsedOneChar && !isValidVarNameStart(Str[I]))
89 if (Str[I] !=
'_' && !isalnum(Str[I]))
122 if (ParseVarResult->IsPseudo)
124 SM, Name,
"definition of pseudo numeric variable unsupported");
128 if (Context->DefinedVariableTable.
find(Name) !=
129 Context->DefinedVariableTable.
end())
131 SM, Name,
"string variable with name '" + Name +
"' already exists");
136 SM, Expr,
"unexpected characters after numeric variable name");
139 auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
140 if (VarTableIter != Context->GlobalNumericVariableTable.end())
141 DefinedNumericVariable = VarTableIter->second;
143 DefinedNumericVariable = Context->makeNumericVariable(Name, LineNumber);
145 return DefinedNumericVariable;
151 if (IsPseudo && !Name.
equals(
"@LINE"))
153 SM, Name,
"invalid pseudo numeric variable '" + Name +
"'");
163 auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
165 if (VarTableIter != Context->GlobalNumericVariableTable.end())
166 NumericVariable = VarTableIter->second;
168 NumericVariable = Context->makeNumericVariable(Name);
169 Context->GlobalNumericVariableTable[Name] = NumericVariable;
173 if (DefLineNumber && LineNumber && *DefLineNumber == *LineNumber)
176 "numeric variable '" + Name +
177 "' defined earlier in the same CHECK directive");
188 parseVariable(Expr, SM);
190 return parseNumericVariableUse(ParseVarResult->Name,
191 ParseVarResult->IsPseudo, LineNumber,
193 if (AO == AllowedOperand::LineVar)
200 uint64_t LiteralValue;
202 return std::make_unique<ExpressionLiteral>(LiteralValue);
205 "invalid operand format '" + Expr +
"'");
208 static uint64_t
add(uint64_t LeftOp, uint64_t RightOp) {
209 return LeftOp + RightOp;
212 static uint64_t
sub(uint64_t LeftOp, uint64_t RightOp) {
213 return LeftOp - RightOp;
217 Pattern::parseBinop(
StringRef &Expr, std::unique_ptr<ExpressionAST> LeftOp,
222 return std::move(LeftOp);
238 SM, OpLoc,
Twine(
"unsupported operation '") +
Twine(Operator) +
"'");
249 parseNumericOperand(Expr, AO, LineNumber, Context, SM);
251 return RightOpResult;
254 return std::make_unique<BinaryOperation>(EvalBinop, std::move(LeftOp),
255 std::move(*RightOpResult));
262 std::unique_ptr<ExpressionAST> ExpressionASTPointer =
nullptr;
264 DefinedNumericVariable =
None;
266 size_t DefEnd = Expr.
find(
':');
268 DefExpr = Expr.
substr(0, DefEnd);
269 Expr = Expr.
substr(DefEnd + 1);
280 parseNumericOperand(Expr, AO, LineNumber, Context, SM);
281 while (ParseResult && !Expr.
empty()) {
282 ParseResult = parseBinop(Expr, std::move(*ParseResult), IsLegacyLineExpr,
283 LineNumber, Context, SM);
285 if (ParseResult && IsLegacyLineExpr && !Expr.
empty())
288 "unexpected characters at end of expression '" + Expr +
"'");
292 ExpressionASTPointer = std::move(*ParseResult);
299 parseNumericVariableDefinition(DefExpr, Context, LineNumber, SM);
303 DefinedNumericVariable = *ParseResult;
306 return std::move(ExpressionASTPointer);
318 while (!PatternStr.
empty() &&
319 (PatternStr.
back() ==
' ' || PatternStr.
back() ==
'\t'))
320 PatternStr = PatternStr.
substr(0, PatternStr.
size() - 1);
325 "found empty check string with prefix '" + Prefix +
":'");
332 "found non-empty check string for empty check with prefix '" + Prefix +
343 if (!MatchFullLinesHere &&
346 FixedStr = PatternStr;
350 if (MatchFullLinesHere) {
358 unsigned CurParen = 1;
362 while (!PatternStr.
empty()) {
366 size_t End = PatternStr.
find(
"}}");
370 "found start of regex string with no end '}}'");
381 if (AddRegExToRegEx(PatternStr.
substr(2, End - 2), CurParen, SM))
385 PatternStr = PatternStr.
substr(End + 2);
402 size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
409 "Invalid substitution block, no ]] found");
415 PatternStr = UnparsedPatternStr.
substr(End + 2);
417 bool IsDefinition =
false;
418 bool SubstNeeded =
false;
421 bool IsLegacyLineExpr =
false;
425 size_t SubstInsertIdx = RegExStr.
size();
429 size_t VarEndIdx = MatchStr.
find(
":");
440 parseVariable(MatchStr, SM);
441 if (!ParseVarResult) {
446 bool IsPseudo = ParseVarResult->IsPseudo;
449 SubstNeeded = !IsDefinition;
454 "invalid name in string variable definition");
460 if (Context->GlobalNumericVariableTable.find(Name) !=
461 Context->GlobalNumericVariableTable.end()) {
464 "numeric variable with name '" + Name +
"' already exists");
468 MatchRegexp = MatchStr;
471 MatchStr = OrigMatchStr;
472 IsLegacyLineExpr = IsNumBlock =
true;
479 std::unique_ptr<ExpressionAST> ExpressionASTPointer;
483 parseNumericSubstitutionBlock(MatchStr, DefinedNumericVariable,
484 IsLegacyLineExpr, LineNumber, Context,
490 ExpressionASTPointer = std::move(*ParseResult);
491 SubstNeeded = ExpressionASTPointer !=
nullptr;
492 if (DefinedNumericVariable) {
494 DefName = (*DefinedNumericVariable)->getName();
499 MatchRegexp =
"[0-9]+";
508 NumericVariableMatch NumericVariableDefinition = {
509 *DefinedNumericVariable, CurParen};
510 NumericVariableDefs[DefName] = NumericVariableDefinition;
515 Context->GlobalNumericVariableTable[DefName] =
516 *DefinedNumericVariable;
518 VariableDefs[DefName] = CurParen;
525 Context->DefinedVariableTable[DefName] =
true;
531 if (!MatchRegexp.
empty() && AddRegExToRegEx(MatchRegexp, CurParen, SM))
542 if (!IsNumBlock && VariableDefs.find(SubstStr) != VariableDefs.end()) {
543 unsigned CaptureParenGroup = VariableDefs[SubstStr];
544 if (CaptureParenGroup < 1 || CaptureParenGroup > 9) {
547 "Can't back-reference more than 9 variables");
550 AddBackrefToRegEx(CaptureParenGroup);
556 ? Context->makeNumericSubstitution(
557 SubstStr, std::move(ExpressionASTPointer),
559 : Context->makeStringSubstitution(SubstStr, SubstInsertIdx);
560 Substitutions.push_back(Substitution);
567 size_t FixedMatchEnd = PatternStr.
find(
"{{");
568 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.
find(
"[["));
570 PatternStr = PatternStr.
substr(FixedMatchEnd);
573 if (MatchFullLinesHere) {
587 "invalid regex: " + Error);
591 RegExStr += RS.
str();
596 void Pattern::AddBackrefToRegEx(
unsigned BackrefNum) {
597 assert(BackrefNum >= 1 && BackrefNum <= 9 &&
"Invalid backref number");
598 std::string Backref = std::string(
"\\") + std::string(1,
'0' + BackrefNum);
607 return Buffer.
size();
611 if (!FixedStr.empty()) {
612 MatchLen = FixedStr.size();
616 return make_error<NotFoundError>();
626 if (!Substitutions.empty()) {
629 Context->LineVariable->
setValue(*LineNumber);
631 size_t InsertOffset = 0;
643 Value->begin(), Value->end());
644 InsertOffset += Value->size();
648 RegExToMatch = TmpStr;
655 if (!
Regex(RegExToMatch, Flags).
match(Buffer, &MatchInfo))
656 return make_error<NotFoundError>();
659 assert(!MatchInfo.
empty() &&
"Didn't get any match");
663 for (
const auto &VariableDef : VariableDefs) {
664 assert(VariableDef.second < MatchInfo.
size() &&
"Internal paren error");
665 Context->GlobalVariableTable[VariableDef.first] =
666 MatchInfo[VariableDef.second];
670 for (
const auto &NumericVariableDef : NumericVariableDefs) {
671 const NumericVariableMatch &NumericVariableMatch =
672 NumericVariableDef.getValue();
673 unsigned CaptureParenGroup = NumericVariableMatch.CaptureParenGroup;
674 assert(CaptureParenGroup < MatchInfo.
size() &&
"Internal paren error");
676 NumericVariableMatch.DefinedNumericVariable;
678 StringRef MatchedValue = MatchInfo[CaptureParenGroup];
682 "Unable to represent numeric value");
683 DefinedNumericVariable->setValue(Val);
690 MatchLen = FullMatch.size() - MatchStartSkip;
691 return FullMatch.data() - Buffer.
data() + MatchStartSkip;
694 unsigned Pattern::computeMatchDistance(
StringRef Buffer)
const {
702 if (ExampleString.
empty())
703 ExampleString = RegExStr;
707 BufferPrefix = BufferPrefix.
split(
'\n').first;
714 if (!Substitutions.empty()) {
723 bool UndefSeen =
false;
729 OS <<
"uses undefined variable(s):";
755 StringRef Buffer,
size_t Pos,
size_t Len,
756 std::vector<FileCheckDiag> *Diags,
757 bool AdjustPrevDiag =
false) {
763 Diags->rbegin()->MatchTy = MatchTy;
765 Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
771 std::vector<FileCheckDiag> *Diags)
const {
776 size_t NumLinesForward = 0;
778 double BestQuality = 0;
781 for (
size_t i = 0,
e = std::min(
size_t(4096), Buffer.
size()); i !=
e; ++i) {
782 if (Buffer[i] ==
'\n')
787 if (Buffer[i] ==
' ' || Buffer[i] ==
'\t')
792 unsigned Distance = computeMatchDistance(Buffer.
substr(i));
793 double Quality = Distance + (NumLinesForward / 100.);
797 BestQuality = Quality;
807 getCheckTy(), Buffer, Best, 0, Diags);
809 "possible intended match here");
818 auto VarIter = GlobalVariableTable.find(VarName);
819 if (VarIter == GlobalVariableTable.end())
820 return make_error<UndefVarError>(VarName);
822 return VarIter->second;
825 template <
class... Types>
826 NumericVariable *FileCheckPatternContext::makeNumericVariable(Types... args) {
827 NumericVariables.push_back(std::make_unique<NumericVariable>(args...));
828 return NumericVariables.back().get();
834 Substitutions.push_back(
835 std::make_unique<StringSubstitution>(
this, VarName, InsertIdx));
836 return Substitutions.back().get();
839 Substitution *FileCheckPatternContext::makeNumericSubstitution(
841 std::unique_ptr<ExpressionAST> ExpressionASTPointer,
size_t InsertIdx) {
842 Substitutions.push_back(std::make_unique<NumericSubstitution>(
843 this, ExpressionStr, std::move(ExpressionASTPointer), InsertIdx));
844 return Substitutions.back().get();
851 size_t BracketDepth = 0;
853 while (!Str.
empty()) {
854 if (Str.
startswith(
"]]") && BracketDepth == 0)
856 if (Str[0] ==
'\\') {
868 if (BracketDepth == 0) {
871 "missing closing \"]\" for regex variable");
892 if (Ptr <= End - 2 && Ptr[0] ==
'\r' && Ptr[1] ==
'\n') {
898 if (Req.NoCanonicalizeWhiteSpace || (*Ptr !=
' ' && *Ptr !=
'\t')) {
905 while (Ptr + 1 != End && (Ptr[1] ==
' ' || Ptr[1] ==
'\t'))
918 : CheckTy(CheckTy), MatchTy(MatchTy) {
931 return (isalnum(c) || c ==
'-' || c ==
'_');
935 assert(Count > 0 &&
"zero and negative counts are not supported");
937 "count supported only for plain CHECK directives");
948 return Prefix.
str() +
"-COUNT";
951 return Prefix.
str() +
"-NEXT";
953 return Prefix.
str() +
"-SAME";
955 return Prefix.
str() +
"-NOT";
957 return Prefix.
str() +
"-DAG";
959 return Prefix.
str() +
"-LABEL";
961 return Prefix.
str() +
"-EMPTY";
963 return "implicit EOF";
972 static std::pair<Check::FileCheckType, StringRef>
977 char NextChar = Buffer[Prefix.
size()];
987 if (Rest.consume_front(
"COUNT-")) {
989 if (Rest.consumeInteger(10, Count))
992 if (Count <= 0 || Count > INT32_MAX)
994 if (!Rest.consume_front(
":"))
999 if (Rest.consume_front(
"NEXT:"))
1002 if (Rest.consume_front(
"SAME:"))
1005 if (Rest.consume_front(
"NOT:"))
1008 if (Rest.consume_front(
"DAG:"))
1011 if (Rest.consume_front(
"LABEL:"))
1014 if (Rest.consume_front(
"EMPTY:"))
1018 if (Rest.startswith(
"DAG-NOT:") || Rest.startswith(
"NOT-DAG:") ||
1019 Rest.startswith(
"NEXT-NOT:") || Rest.startswith(
"NOT-NEXT:") ||
1020 Rest.startswith(
"SAME-NOT:") || Rest.startswith(
"NOT-SAME:") ||
1021 Rest.startswith(
"EMPTY-NOT:") || Rest.startswith(
"NOT-EMPTY:"))
1057 static std::pair<StringRef, StringRef>
1062 while (!Buffer.
empty()) {
1064 if (!PrefixRE.
match(Buffer, &Matches))
1073 "Prefix doesn't start inside of buffer!");
1074 size_t Loc = Prefix.
data() - Buffer.
data();
1077 LineNumber += Skipped.
count(
'\n');
1087 std::tie(CheckTy, AfterSuffix) =
FindCheckType(Buffer, Prefix);
1091 return {
Prefix, AfterSuffix};
1105 assert(!LineVariable &&
"@LINE pseudo numeric variable already created");
1107 LineVariable = makeNumericVariable(LineName);
1108 GlobalNumericVariableTable[LineName] = LineVariable;
1120 PatternContext->defineCmdlineVariables(Req.
GlobalDefines, SM);
1126 PatternContext->createLineVariable();
1128 std::vector<Pattern> ImplicitNegativeChecks;
1132 std::string
Prefix =
"-implicit-check-not='";
1133 std::string Suffix =
"'";
1135 Prefix + PatternString + Suffix,
"command line");
1138 CmdLine->getBuffer().
substr(Prefix.size(), PatternString.size());
1141 ImplicitNegativeChecks.push_back(
1143 ImplicitNegativeChecks.back().parsePattern(PatternInBuffer,
1144 "IMPLICIT-CHECK", SM, Req);
1147 std::vector<Pattern> DagNotMatches = ImplicitNegativeChecks;
1151 unsigned LineNumber = 1;
1159 std::tie(UsedPrefix, AfterSuffix) =
1161 if (UsedPrefix.
empty())
1164 "Failed to move Buffer's start forward, or pointed prefix outside " 1168 "Parsing after suffix doesn't start inside of buffer!");
1171 const char *UsedPrefixStart = UsedPrefix.
data();
1181 "unsupported -NOT combo on prefix '" + UsedPrefix +
"'");
1188 "invalid count in -COUNT specification on prefix '" +
1205 Pattern P(CheckTy, PatternContext.get(), LineNumber);
1206 if (
P.parsePattern(Buffer.
substr(0, EOL), UsedPrefix, SM, Req))
1213 "found '" + UsedPrefix +
"-LABEL:'" 1214 " with variable definition or use");
1218 Buffer = Buffer.
substr(EOL);
1223 CheckStrings->empty()) {
1229 "found '" + UsedPrefix +
"-" + Type +
1230 "' without previous '" + UsedPrefix +
": line");
1236 DagNotMatches.push_back(
P);
1241 CheckStrings->emplace_back(
P, UsedPrefix, PatternLoc);
1242 std::swap(DagNotMatches, CheckStrings->back().DagNotStrings);
1243 DagNotMatches = ImplicitNegativeChecks;
1248 if (!DagNotMatches.empty()) {
1249 CheckStrings->emplace_back(
1252 std::swap(DagNotMatches, CheckStrings->back().DagNotStrings);
1255 if (CheckStrings->empty()) {
1256 errs() <<
"error: no check strings found with prefix" 1261 errs() <<
"\'" << *
I <<
":'";
1265 errs() <<
", \'" << *
I <<
":'";
1276 int MatchedCount,
StringRef Buffer,
size_t MatchPos,
1278 std::vector<FileCheckDiag> *Diags) {
1279 bool PrintDiag =
true;
1280 if (ExpectedMatch) {
1293 SM, Loc, Pat.
getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
1297 std::string Message =
formatv(
"{0}: {1} string found in input",
1299 (ExpectedMatch ?
"expected" :
"excluded"))
1302 Message +=
formatv(
" ({0} out of {1})", MatchedCount, Pat.
getCount()).str();
1313 StringRef Buffer,
size_t MatchPos,
size_t MatchLen,
1315 std::vector<FileCheckDiag> *Diags) {
1317 MatchedCount, Buffer, MatchPos, MatchLen, Req, Diags);
1323 bool VerboseVerbose, std::vector<FileCheckDiag> *Diags,
1324 Error MatchErrors) {
1325 assert(MatchErrors &&
"Called on successful match");
1326 bool PrintDiag =
true;
1327 if (!ExpectedMatch) {
1328 if (!VerboseVerbose) {
1359 std::string Message =
formatv(
"{0}: {1} string not found in input",
1361 (ExpectedMatch ?
"expected" :
"excluded"))
1364 Message +=
formatv(
" ({0} out of {1})", MatchedCount, Pat.
getCount()).str();
1381 std::vector<FileCheckDiag> *Diags,
Error MatchErrors) {
1383 MatchedCount, Buffer, VerboseVerbose, Diags,
1384 std::move(MatchErrors));
1389 const char *&FirstNewLine) {
1390 unsigned NumNewLines = 0;
1400 if (Range.
size() > 1 && (Range[1] ==
'\n' || Range[1] ==
'\r') &&
1401 (Range[0] != Range[1]))
1405 if (NumNewLines == 1)
1406 FirstNewLine = Range.
begin();
1411 bool IsLabelScanMode,
size_t &MatchLen,
1413 std::vector<FileCheckDiag> *Diags)
const {
1415 std::vector<const Pattern *> NotStrings;
1421 if (!IsLabelScanMode) {
1423 LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
1429 size_t LastMatchEnd = LastPos;
1430 size_t FirstMatchPos = 0;
1433 assert(Pat.getCount() != 0 &&
"pattern count can not be zero");
1434 for (
int i = 1; i <= Pat.getCount(); i++) {
1436 size_t CurrentMatchLen;
1438 Expected<size_t> MatchResult = Pat.match(MatchBuffer, CurrentMatchLen, SM);
1446 size_t MatchPos = *MatchResult;
1447 PrintMatch(
true, SM, *
this, i, MatchBuffer, MatchPos, CurrentMatchLen, Req,
1450 FirstMatchPos = LastPos + MatchPos;
1453 LastMatchEnd += MatchPos + CurrentMatchLen;
1456 MatchLen = LastMatchEnd - FirstMatchPos;
1460 if (!IsLabelScanMode) {
1461 size_t MatchPos = FirstMatchPos - LastPos;
1469 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
1478 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
1485 if (
CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
1489 return FirstMatchPos;
1502 const char *FirstNewLine =
nullptr;
1505 if (NumNewLines == 0) {
1507 CheckName +
": is on the same line as previous match");
1509 "'next' match was here");
1511 "previous match ended here");
1515 if (NumNewLines != 1) {
1518 ": is not on the line after the previous match");
1520 "'next' match was here");
1522 "previous match ended here");
1524 "non-matching line after previous match is here");
1536 const char *FirstNewLine =
nullptr;
1539 if (NumNewLines != 0) {
1542 "-SAME: is not on the same line as the previous match");
1544 "'next' match was here");
1546 "previous match ended here");
1554 const std::vector<const Pattern *> &NotStrings,
1556 std::vector<FileCheckDiag> *Diags)
const {
1557 for (
const Pattern *Pat : NotStrings) {
1560 size_t MatchLen = 0;
1568 size_t Pos = *MatchResult;
1570 PrintMatch(
false, SM,
Prefix, Pat->getLoc(), *Pat, 1, Buffer, Pos, MatchLen,
1580 std::vector<const Pattern *> &NotStrings,
1582 std::vector<FileCheckDiag> *Diags)
const {
1583 if (DagNotStrings.empty())
1587 size_t StartPos = 0;
1596 std::list<MatchRange> MatchRanges;
1600 for (
auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
1601 PatItr != PatEnd; ++PatItr) {
1605 "Invalid CHECK-DAG or CHECK-NOT!");
1608 NotStrings.push_back(&Pat);
1615 size_t MatchLen = 0, MatchPos = StartPos;
1619 for (
auto MI = MatchRanges.begin(), ME = MatchRanges.end();
true; ++
MI) {
1629 size_t MatchPosBuf = *MatchResult;
1631 MatchPos += MatchPosBuf;
1634 MatchLen, Req, Diags);
1635 MatchRange M{MatchPos, MatchPos + MatchLen};
1636 if (Req.AllowDeprecatedDagOverlap) {
1640 if (MatchRanges.empty())
1641 MatchRanges.insert(MatchRanges.end(), M);
1643 auto Block = MatchRanges.begin();
1644 Block->Pos = std::min(Block->Pos, M.Pos);
1645 Block->End =
std::max(Block->End, M.End);
1650 bool Overlap =
false;
1651 for (;
MI != ME; ++
MI) {
1652 if (M.Pos <
MI->End) {
1655 Overlap =
MI->Pos < M.End;
1661 MatchRanges.insert(
MI, M);
1664 if (Req.VerboseVerbose) {
1671 SMRange OldRange(OldStart, OldEnd);
1673 "match discarded, overlaps earlier DAG match here",
1682 MatchLen, Req, Diags);
1685 if (std::next(PatItr) == PatEnd ||
1687 if (!NotStrings.empty()) {
1692 Buffer.
slice(StartPos, MatchRanges.begin()->Pos);
1693 if (
CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
1700 StartPos = MatchRanges.rbegin()->End;
1702 MatchRanges.clear();
1711 static const Regex Validator(
"^[a-zA-Z0-9_-]*$");
1712 return Validator.
match(CheckPrefix);
1723 if (!PrefixSet.
insert(Prefix).second)
1736 if (Req.CheckPrefixes.empty())
1737 Req.CheckPrefixes.push_back(
"CHECK");
1743 if (Prefix != Req.CheckPrefixes.
front())
1746 PrefixRegexStr.
append(Prefix);
1749 return Regex(PrefixRegexStr);
1753 std::vector<std::string> &CmdlineDefines,
SourceMgr &SM) {
1754 assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
1755 "Overriding defined variable with command-line variable definitions");
1757 if (CmdlineDefines.empty())
1765 std::string CmdlineDefsDiag;
1767 for (
StringRef CmdlineDef : CmdlineDefines) {
1768 std::string DefPrefix = (
"Global define #" +
Twine(++I) +
": ").str();
1769 size_t EqIdx = CmdlineDef.find(
'=');
1771 CmdlineDefsIndices.
push_back(std::make_pair(CmdlineDefsDiag.size(), 0));
1775 if (CmdlineDef[0] ==
'#') {
1779 CmdlineDefsDiag += (DefPrefix + CmdlineDef +
" (parsed as: [[").str();
1780 std::string SubstitutionStr = CmdlineDef;
1781 SubstitutionStr[EqIdx] =
':';
1783 std::make_pair(CmdlineDefsDiag.size(), SubstitutionStr.size()));
1784 CmdlineDefsDiag += (SubstitutionStr +
Twine(
"]])\n")).str();
1786 CmdlineDefsDiag += DefPrefix;
1788 std::make_pair(CmdlineDefsDiag.size(), CmdlineDef.size()));
1789 CmdlineDefsDiag += (CmdlineDef +
"\n").str();
1796 std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
1798 StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
1801 for (std::pair<size_t, size_t> CmdlineDefIndices : CmdlineDefsIndices) {
1802 StringRef CmdlineDef = CmdlineDefsDiagRef.
substr(CmdlineDefIndices.first,
1803 CmdlineDefIndices.second);
1804 if (CmdlineDef.
empty()) {
1808 "missing equal sign in global definition"));
1813 if (CmdlineDef[0] ==
'#') {
1820 CmdlineDefExpr, DefinedNumericVariable,
false,
None,
this, SM);
1821 if (!ExpressionASTResult) {
1825 std::unique_ptr<ExpressionAST> ExpressionASTPointer =
1826 std::move(*ExpressionASTResult);
1837 assert(DefinedNumericVariable &&
"No variable defined");
1838 (*DefinedNumericVariable)->setValue(*Value);
1841 GlobalNumericVariableTable[(*DefinedNumericVariable)->getName()] =
1842 *DefinedNumericVariable;
1845 std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.
split(
'=');
1846 StringRef CmdlineName = CmdlineNameVal.first;
1847 StringRef OrigCmdlineName = CmdlineName;
1850 if (!ParseVarResult) {
1857 if (ParseVarResult->IsPseudo || !CmdlineName.
empty()) {
1860 SM, OrigCmdlineName,
1861 "invalid name in string variable definition '" +
1862 OrigCmdlineName +
"'"));
1869 if (GlobalNumericVariableTable.find(Name) !=
1870 GlobalNumericVariableTable.end()) {
1873 "numeric variable with name '" +
1874 Name +
"' already exists"));
1877 GlobalVariableTable.insert(CmdlineNameVal);
1884 DefinedVariableTable[
Name] =
true;
1894 if (Var.first()[0] !=
'$')
1895 LocalPatternVars.
push_back(Var.first());
1903 for (
const auto &Var : GlobalNumericVariableTable)
1904 if (Var.first()[0] !=
'$') {
1905 Var.getValue()->clearValue();
1906 LocalNumericVars.
push_back(Var.first());
1909 for (
const auto &Var : LocalPatternVars)
1910 GlobalVariableTable.erase(Var);
1911 for (
const auto &Var : LocalNumericVars)
1912 GlobalNumericVariableTable.erase(Var);
1916 std::vector<FileCheckDiag> *Diags) {
1917 bool ChecksFailed =
false;
1919 unsigned i = 0, j = 0,
e = CheckStrings->size();
1923 CheckRegion = Buffer;
1932 size_t MatchLabelLen = 0;
1933 size_t MatchLabelPos =
1934 CheckLabelStr.
Check(SM, Buffer,
true, MatchLabelLen, Req, Diags);
1939 CheckRegion = Buffer.
substr(0, MatchLabelPos + MatchLabelLen);
1940 Buffer = Buffer.
substr(MatchLabelPos + MatchLabelLen);
1947 if (i != 0 && Req.EnableVarScope)
1948 PatternContext->clearLocalVars();
1950 for (; i != j; ++i) {
1955 size_t MatchLen = 0;
1957 CheckStr.
Check(SM, CheckRegion,
false, MatchLen, Req, Diags);
1960 ChecksFailed =
true;
1965 CheckRegion = CheckRegion.
substr(MatchPos + MatchLen);
1973 return !ChecksFailed;
Represents a range in source code.
Check::FileCheckType getCheckTy() const
LLVM_NODISCARD StringRef take_front(size_t N=1) const
Return a StringRef equal to 'this' but with only the first N elements remaining.
Indicates a good match for an expected pattern.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Indicates no match for an excluded pattern.
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
This class represents lattice values for constants.
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
std::vector< std::string > ImplicitCheckNot
Indicates a discarded match for an expected pattern.
Expected< std::string > getResult() const override
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
void push_back(const T &Elt)
Class representing a substitution to perform in the RegExStr string.
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
bool CheckSame(const SourceMgr &SM, StringRef Buffer) const
Verifies that there is no newline in the given Buffer.
static std::string escape(StringRef String)
Turn String into a regex by escaping its special characters.
iterator find(StringRef Key)
A raw_ostream that writes to an SmallVector or SmallString.
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
std::string getDescription(StringRef Prefix) const
Marks when parsing found a -NOT check combined with another CHECK suffix.
size_t getBufferSize() const
Regex buildCheckPrefixRegex()
LLVM_NODISCARD StringRef ltrim(char Char) const
Return string with consecutive Char characters starting from the the left removed.
Class to represent an error holding a diagnostic with location information used when printing it...
Error takeError()
Take ownership of the stored error.
void reserve(size_type N)
std::pair< unsigned, unsigned > getLineAndColumn(SMLoc Loc, unsigned BufferID=0) const
Find the line and column number for the specified location in the specified file. ...
LLVM_NODISCARD unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
bool CheckNext(const SourceMgr &SM, StringRef Buffer) const
Verifies that there is a single line in the given Buffer.
Class representing a numeric variable and its associated current value.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode *>> &RecordedNodes)
CheckSame - Implements OP_CheckSame.
static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM, StringRef Prefix, SMLoc Loc, const Pattern &Pat, int MatchedCount, StringRef Buffer, size_t MatchPos, size_t MatchLen, const FileCheckRequest &Req, std::vector< FileCheckDiag > *Diags)
StringRef Prefix
Which prefix name this check matched.
bool match(Val *V, const Pattern &P)
Expected< std::string > getResult() const override
Compile for matching that ignores upper/lower case distinctions.
void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges=None, ArrayRef< SMFixIt > FixIts=None, bool ShowColors=true) const
Emit a message about the specified location with the specified string.
bool NoCanonicalizeWhiteSpace
Class holding the Pattern global state, shared by all patterns: tables holding values of variables an...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
LLVM_NODISCARD size_t count(char C) const
Return the number of occurrences of C in the string.
SMLoc Loc
The location in the match file that the check string was specified.
Check::FileCheckType CheckTy
What is the FileCheck directive for this diagnostic?
Indicates a match for an expected pattern, but the match is on the wrong line.
LLVM_NODISCARD StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Tagged union holding either a T or a Error.
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Marks when parsing found a -COUNT directive with invalid count value.
std::vector< std::string > CheckPrefixes
bool match(StringRef String, SmallVectorImpl< StringRef > *Matches=nullptr, std::string *Error=nullptr) const
matches - Match the regex against a given String.
static std::pair< Check::FileCheckType, StringRef > FindCheckType(StringRef Buffer, StringRef Prefix)
void setValue(uint64_t NewValue)
Sets value of this numeric variable to NewValue.
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type consumeInteger(unsigned Radix, T &Result)
Parse the current string as an integer of the specified radix.
static unsigned CountNumNewlinesBetween(StringRef Range, const char *&FirstNewLine)
Counts the number of newlines in the specified range.
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Contains info about various FileCheck options.
static bool ValidateCheckPrefix(StringRef CheckPrefix)
LLVM_NODISCARD size_t size() const
size - Get the string size.
static Expected< VariableProperties > parseVariable(StringRef &Str, const SourceMgr &SM)
Parses the string at the start of Str for a variable name.
std::vector< std::string > GlobalDefines
Expected< size_t > match(StringRef Buffer, size_t &MatchLen, const SourceMgr &SM) const
Matches the pattern string against the input buffer Buffer.
size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode, size_t &MatchLen, FileCheckRequest &Req, std::vector< FileCheckDiag > *Diags) const
Matches check string and its "not strings" and/or "dag strings".
void append(in_iter S, in_iter E)
Append from an iterator pair.
static bool isValidVarNameStart(char C)
bool ValidateCheckPrefixes()
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
A check that we found in the input file.
StringRef getFromString() const
void clearLocalVars()
Undefines local variables (variables whose name does not start with a '$' sign), i.e.
FileCheckDiag(const SourceMgr &SM, const Check::FileCheckType &CheckTy, SMLoc CheckLoc, MatchType MatchTy, SMRange InputRange)
The instances of the Type class are immutable: once they are created, they are never changed...
void printFuzzyMatch(const SourceMgr &SM, StringRef Buffer, std::vector< FileCheckDiag > *Diags) const
StringRef CanonicalizeFile(MemoryBuffer &MB, SmallVectorImpl< char > &OutputBuffer)
Canonicalizes whitespaces in the file.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_NODISCARD size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
static Error get(const SourceMgr &SM, SMLoc Loc, const Twine &ErrMsg)
bool checkInput(SourceMgr &SM, StringRef Buffer, std::vector< FileCheckDiag > *Diags=nullptr)
Checks the input to FileCheck provided in the Buffer against the expected strings read from the check...
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
unsigned CheckLine
Where is the FileCheck directive for this diagnostic?
bool parsePattern(StringRef PatternStr, StringRef Prefix, SourceMgr &SM, const FileCheckRequest &Req)
Parses the pattern in PatternStr and initializes this Pattern instance accordingly.
Class to represent an undefined variable error, which quotes that variable's name when printed...
void createLineVariable()
Create pseudo variable.
Optional< uint64_t > getValue() const
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_NODISCARD char back() const
back - Get the last character in the string.
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::pair< typename base::iterator, bool > insert(StringRef Key)
void log(raw_ostream &OS) const override
Print diagnostic associated with this error when printing the error.
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Indicates the pattern only matches the end of file.
static size_t SkipWord(StringRef Str, size_t Loc)
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
raw_ostream & write_escaped(StringRef Str, bool UseHexEscapes=false)
Output Str, turning '\', '', ' ', '"', and anything that doesn't satisfy llvm::isPrint into an escape...
static ErrorSuccess success()
Create a success value.
Indicates a fuzzy match that serves as a suggestion for the next intended match for an expected patte...
size_t CheckDag(const SourceMgr &SM, StringRef Buffer, std::vector< const Pattern *> &NotStrings, const FileCheckRequest &Req, std::vector< FileCheckDiag > *Diags) const
Matches "dag strings" and their mixed "not strings".
Align max(MaybeAlign Lhs, Align Rhs)
static std::pair< StringRef, StringRef > FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer, unsigned &LineNumber, Check::FileCheckType &CheckTy)
Searches the buffer for the first prefix in the prefix regular expression.
constexpr StringLiteral SpaceChars
static uint64_t add(uint64_t LeftOp, uint64_t RightOp)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
This is a utility class that provides an abstraction for the common functionality between Instruction...
Indicates no match for an expected pattern, but this might follow good matches when multiple matches ...
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
bool readCheckFile(SourceMgr &SM, StringRef Buffer, Regex &PrefixRE)
Reads the check file from Buffer and records the expected strings it contains.
void printSubstitutions(const SourceMgr &SM, StringRef Buffer, SMRange MatchRange=None) const
Prints the value of successful substitutions or the name of the undefined string or numeric variables...
bool isValid(std::string &Error) const
isValid - returns the error encountered during regex compilation, if any.
Expected< uint64_t > eval() const override
Evaluates the value of the binary operation represented by this AST, using EvalBinop on the result of...
LLVM_NODISCARD size_t find_lower(char C, size_t From=0) const
Search for the first character C in the string, ignoring case.
StringRef str()
Return a StringRef for the vector contents.
uint64_t(*)(uint64_t, uint64_t) binop_eval_t
Type of functions evaluating a given binary operation.
std::string utostr(uint64_t X, bool isNeg=false)
This interface provides simple read-only access to a block of memory, and provides simple methods for...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it...
static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy, const SourceMgr &SM, SMLoc Loc, Check::FileCheckType CheckTy, StringRef Buffer, size_t Pos, size_t Len, std::vector< FileCheckDiag > *Diags, bool AdjustPrevDiag=false)
unsigned getNumMatches() const
getNumMatches - In a valid regex, return the number of parenthesized matches it contains.
Expected< StringRef > getPatternVarValue(StringRef VarName)
static SMLoc getFromPointer(const char *Ptr)
Expected< uint64_t > eval() const override
unsigned InputStartLine
The search range if MatchTy is MatchNoneAndExcluded or MatchNoneButExpected, or the match range other...
LLVM_NODISCARD bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
Indicates a match for an excluded pattern.
const char * getBufferEnd() const
FileCheckType & setCount(int C)
pointer data()
Return a pointer to the vector's buffer, even if empty().
LLVM_NODISCARD bool empty() const
bool CheckNot(const SourceMgr &SM, StringRef Buffer, const std::vector< const Pattern *> &NotStrings, const FileCheckRequest &Req, std::vector< FileCheckDiag > *Diags) const
Verifies that none of the strings in NotStrings are found in the given Buffer.
FileCheck(FileCheckRequest Req)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
static Expected< std::unique_ptr< ExpressionAST > > parseNumericSubstitutionBlock(StringRef Expr, Optional< NumericVariable *> &DefinedNumericVariable, bool IsLegacyLineExpr, Optional< size_t > LineNumber, FileCheckPatternContext *Context, const SourceMgr &SM)
Parses Expr for a numeric substitution block at line LineNumber, or before input is parsed if LineNum...
Pattern Pat
The pattern to match.
const char * getBufferStart() const
virtual Expected< std::string > getResult() const =0
static bool IsPartOfWord(char c)
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM_NODISCARD char front() const
front - Get the first character in the string.
Error defineCmdlineVariables(std::vector< std::string > &CmdlineDefines, SourceMgr &SM)
Defines string and numeric variables from definitions given on the command line, passed as a vector o...
LLVM Value Representation.
static char popFront(StringRef &S)
Lightweight error class with error context and mandatory checking.
StringSet - A wrapper for StringMap that provides set-like functionality.
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
static uint64_t sub(uint64_t LeftOp, uint64_t RightOp)
Compile for newline-sensitive matching.
StringRef - Represent a constant reference to a string, i.e.
Parsing information about a variable.
MatchType
What type of match result does this diagnostic describe?
Represents a location in source code.
static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM, StringRef Prefix, SMLoc Loc, const Pattern &Pat, int MatchedCount, StringRef Buffer, bool VerboseVerbose, std::vector< FileCheckDiag > *Diags, Error MatchErrors)
Optional< size_t > getDefLineNumber() const