Bug Summary

File:llvm/lib/Analysis/AssumeBundleQueries.cpp
Warning:line 149, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name AssumeBundleQueries.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-26-161721-17566-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp

/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp

1//===- AssumeBundleQueries.cpp - tool to query assume bundles ---*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#define DEBUG_TYPE"assume-queries" "assume-queries"
10
11#include "llvm/Analysis/AssumeBundleQueries.h"
12#include "llvm/ADT/Statistic.h"
13#include "llvm/Analysis/AssumptionCache.h"
14#include "llvm/Analysis/ValueTracking.h"
15#include "llvm/IR/Function.h"
16#include "llvm/IR/InstIterator.h"
17#include "llvm/IR/IntrinsicInst.h"
18#include "llvm/IR/PatternMatch.h"
19#include "llvm/Support/DebugCounter.h"
20
21using namespace llvm;
22using namespace llvm::PatternMatch;
23
24STATISTIC(NumAssumeQueries, "Number of Queries into an assume assume bundles")static llvm::Statistic NumAssumeQueries = {"assume-queries", "NumAssumeQueries"
, "Number of Queries into an assume assume bundles"}
;
25STATISTIC(static llvm::Statistic NumUsefullAssumeQueries = {"assume-queries"
, "NumUsefullAssumeQueries", "Number of Queries into an assume assume bundles that were satisfied"
}
26 NumUsefullAssumeQueries,static llvm::Statistic NumUsefullAssumeQueries = {"assume-queries"
, "NumUsefullAssumeQueries", "Number of Queries into an assume assume bundles that were satisfied"
}
27 "Number of Queries into an assume assume bundles that were satisfied")static llvm::Statistic NumUsefullAssumeQueries = {"assume-queries"
, "NumUsefullAssumeQueries", "Number of Queries into an assume assume bundles that were satisfied"
}
;
28
29DEBUG_COUNTER(AssumeQueryCounter, "assume-queries-counter",static const unsigned AssumeQueryCounter = DebugCounter::registerCounter
("assume-queries-counter", "Controls which assumes gets created"
)
30 "Controls which assumes gets created")static const unsigned AssumeQueryCounter = DebugCounter::registerCounter
("assume-queries-counter", "Controls which assumes gets created"
)
;
31
32static bool bundleHasArgument(const CallBase::BundleOpInfo &BOI, unsigned Idx) {
33 return BOI.End - BOI.Begin > Idx;
34}
35
36static Value *getValueFromBundleOpInfo(CallInst &Assume,
37 const CallBase::BundleOpInfo &BOI,
38 unsigned Idx) {
39 assert(bundleHasArgument(BOI, Idx) && "index out of range")((bundleHasArgument(BOI, Idx) && "index out of range"
) ? static_cast<void> (0) : __assert_fail ("bundleHasArgument(BOI, Idx) && \"index out of range\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 39, __PRETTY_FUNCTION__))
;
40 return (Assume.op_begin() + BOI.Begin + Idx)->get();
41}
42
43bool llvm::hasAttributeInAssume(CallInst &AssumeCI, Value *IsOn,
44 StringRef AttrName, uint64_t *ArgVal) {
45 assert(isa<IntrinsicInst>(AssumeCI) &&((isa<IntrinsicInst>(AssumeCI) && "this function is intended to be used on llvm.assume"
) ? static_cast<void> (0) : __assert_fail ("isa<IntrinsicInst>(AssumeCI) && \"this function is intended to be used on llvm.assume\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 46, __PRETTY_FUNCTION__))
46 "this function is intended to be used on llvm.assume")((isa<IntrinsicInst>(AssumeCI) && "this function is intended to be used on llvm.assume"
) ? static_cast<void> (0) : __assert_fail ("isa<IntrinsicInst>(AssumeCI) && \"this function is intended to be used on llvm.assume\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 46, __PRETTY_FUNCTION__))
;
47 IntrinsicInst &Assume = cast<IntrinsicInst>(AssumeCI);
48 assert(Assume.getIntrinsicID() == Intrinsic::assume &&((Assume.getIntrinsicID() == Intrinsic::assume && "this function is intended to be used on llvm.assume"
) ? static_cast<void> (0) : __assert_fail ("Assume.getIntrinsicID() == Intrinsic::assume && \"this function is intended to be used on llvm.assume\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 49, __PRETTY_FUNCTION__))
49 "this function is intended to be used on llvm.assume")((Assume.getIntrinsicID() == Intrinsic::assume && "this function is intended to be used on llvm.assume"
) ? static_cast<void> (0) : __assert_fail ("Assume.getIntrinsicID() == Intrinsic::assume && \"this function is intended to be used on llvm.assume\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 49, __PRETTY_FUNCTION__))
;
50 assert(Attribute::isExistingAttribute(AttrName) &&((Attribute::isExistingAttribute(AttrName) && "this attribute doesn't exist"
) ? static_cast<void> (0) : __assert_fail ("Attribute::isExistingAttribute(AttrName) && \"this attribute doesn't exist\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 51, __PRETTY_FUNCTION__))
51 "this attribute doesn't exist")((Attribute::isExistingAttribute(AttrName) && "this attribute doesn't exist"
) ? static_cast<void> (0) : __assert_fail ("Attribute::isExistingAttribute(AttrName) && \"this attribute doesn't exist\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 51, __PRETTY_FUNCTION__))
;
52 assert((ArgVal == nullptr || Attribute::doesAttrKindHaveArgument((((ArgVal == nullptr || Attribute::doesAttrKindHaveArgument( Attribute
::getAttrKindFromName(AttrName))) && "requested value for an attribute that has no argument"
) ? static_cast<void> (0) : __assert_fail ("(ArgVal == nullptr || Attribute::doesAttrKindHaveArgument( Attribute::getAttrKindFromName(AttrName))) && \"requested value for an attribute that has no argument\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 54, __PRETTY_FUNCTION__))
53 Attribute::getAttrKindFromName(AttrName))) &&(((ArgVal == nullptr || Attribute::doesAttrKindHaveArgument( Attribute
::getAttrKindFromName(AttrName))) && "requested value for an attribute that has no argument"
) ? static_cast<void> (0) : __assert_fail ("(ArgVal == nullptr || Attribute::doesAttrKindHaveArgument( Attribute::getAttrKindFromName(AttrName))) && \"requested value for an attribute that has no argument\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 54, __PRETTY_FUNCTION__))
54 "requested value for an attribute that has no argument")(((ArgVal == nullptr || Attribute::doesAttrKindHaveArgument( Attribute
::getAttrKindFromName(AttrName))) && "requested value for an attribute that has no argument"
) ? static_cast<void> (0) : __assert_fail ("(ArgVal == nullptr || Attribute::doesAttrKindHaveArgument( Attribute::getAttrKindFromName(AttrName))) && \"requested value for an attribute that has no argument\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 54, __PRETTY_FUNCTION__))
;
55 if (Assume.bundle_op_infos().empty())
56 return false;
57
58 for (auto &BOI : Assume.bundle_op_infos()) {
59 if (BOI.Tag->getKey() != AttrName)
60 continue;
61 if (IsOn && (BOI.End - BOI.Begin <= ABA_WasOn ||
62 IsOn != getValueFromBundleOpInfo(Assume, BOI, ABA_WasOn)))
63 continue;
64 if (ArgVal) {
65 assert(BOI.End - BOI.Begin > ABA_Argument)((BOI.End - BOI.Begin > ABA_Argument) ? static_cast<void
> (0) : __assert_fail ("BOI.End - BOI.Begin > ABA_Argument"
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 65, __PRETTY_FUNCTION__))
;
66 *ArgVal =
67 cast<ConstantInt>(getValueFromBundleOpInfo(Assume, BOI, ABA_Argument))
68 ->getZExtValue();
69 }
70 return true;
71 }
72 return false;
73}
74
75void llvm::fillMapFromAssume(CallInst &AssumeCI, RetainedKnowledgeMap &Result) {
76 IntrinsicInst &Assume = cast<IntrinsicInst>(AssumeCI);
77 assert(Assume.getIntrinsicID() == Intrinsic::assume &&((Assume.getIntrinsicID() == Intrinsic::assume && "this function is intended to be used on llvm.assume"
) ? static_cast<void> (0) : __assert_fail ("Assume.getIntrinsicID() == Intrinsic::assume && \"this function is intended to be used on llvm.assume\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 78, __PRETTY_FUNCTION__))
78 "this function is intended to be used on llvm.assume")((Assume.getIntrinsicID() == Intrinsic::assume && "this function is intended to be used on llvm.assume"
) ? static_cast<void> (0) : __assert_fail ("Assume.getIntrinsicID() == Intrinsic::assume && \"this function is intended to be used on llvm.assume\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 78, __PRETTY_FUNCTION__))
;
79 for (auto &Bundles : Assume.bundle_op_infos()) {
80 std::pair<Value *, Attribute::AttrKind> Key{
81 nullptr, Attribute::getAttrKindFromName(Bundles.Tag->getKey())};
82 if (bundleHasArgument(Bundles, ABA_WasOn))
83 Key.first = getValueFromBundleOpInfo(Assume, Bundles, ABA_WasOn);
84
85 if (Key.first == nullptr && Key.second == Attribute::None)
86 continue;
87 if (!bundleHasArgument(Bundles, ABA_Argument)) {
88 Result[Key][&Assume] = {0, 0};
89 continue;
90 }
91 unsigned Val = cast<ConstantInt>(
92 getValueFromBundleOpInfo(Assume, Bundles, ABA_Argument))
93 ->getZExtValue();
94 auto Lookup = Result.find(Key);
95 if (Lookup == Result.end() || !Lookup->second.count(&Assume)) {
96 Result[Key][&Assume] = {Val, Val};
97 continue;
98 }
99 Lookup->second[&Assume].Min = std::min(Val, Lookup->second[&Assume].Min);
100 Lookup->second[&Assume].Max = std::max(Val, Lookup->second[&Assume].Max);
101 }
102}
103
104RetainedKnowledge
105llvm::getKnowledgeFromBundle(CallInst &Assume,
106 const CallBase::BundleOpInfo &BOI) {
107 RetainedKnowledge Result;
108 Result.AttrKind = Attribute::getAttrKindFromName(BOI.Tag->getKey());
109 if (bundleHasArgument(BOI, ABA_WasOn))
110 Result.WasOn = getValueFromBundleOpInfo(Assume, BOI, ABA_WasOn);
111 auto GetArgOr1 = [&](unsigned Idx) -> unsigned {
112 if (auto *ConstInt = dyn_cast<ConstantInt>(
113 getValueFromBundleOpInfo(Assume, BOI, ABA_Argument + Idx)))
114 return ConstInt->getZExtValue();
115 return 1;
116 };
117 if (BOI.End - BOI.Begin > ABA_Argument)
118 Result.ArgValue = GetArgOr1(0);
119 if (Result.AttrKind == Attribute::Alignment)
120 if (BOI.End - BOI.Begin > ABA_Argument + 1)
121 Result.ArgValue = MinAlign(Result.ArgValue, GetArgOr1(1));
122 return Result;
123}
124
125RetainedKnowledge llvm::getKnowledgeFromOperandInAssume(CallInst &AssumeCI,
126 unsigned Idx) {
127 IntrinsicInst &Assume = cast<IntrinsicInst>(AssumeCI);
128 assert(Assume.getIntrinsicID() == Intrinsic::assume &&((Assume.getIntrinsicID() == Intrinsic::assume && "this function is intended to be used on llvm.assume"
) ? static_cast<void> (0) : __assert_fail ("Assume.getIntrinsicID() == Intrinsic::assume && \"this function is intended to be used on llvm.assume\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 129, __PRETTY_FUNCTION__))
129 "this function is intended to be used on llvm.assume")((Assume.getIntrinsicID() == Intrinsic::assume && "this function is intended to be used on llvm.assume"
) ? static_cast<void> (0) : __assert_fail ("Assume.getIntrinsicID() == Intrinsic::assume && \"this function is intended to be used on llvm.assume\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 129, __PRETTY_FUNCTION__))
;
130 CallBase::BundleOpInfo BOI = Assume.getBundleOpInfoForOperand(Idx);
131 return getKnowledgeFromBundle(AssumeCI, BOI);
132}
133
134bool llvm::isAssumeWithEmptyBundle(CallInst &CI) {
135 IntrinsicInst &Assume = cast<IntrinsicInst>(CI);
136 assert(Assume.getIntrinsicID() == Intrinsic::assume &&((Assume.getIntrinsicID() == Intrinsic::assume && "this function is intended to be used on llvm.assume"
) ? static_cast<void> (0) : __assert_fail ("Assume.getIntrinsicID() == Intrinsic::assume && \"this function is intended to be used on llvm.assume\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 137, __PRETTY_FUNCTION__))
137 "this function is intended to be used on llvm.assume")((Assume.getIntrinsicID() == Intrinsic::assume && "this function is intended to be used on llvm.assume"
) ? static_cast<void> (0) : __assert_fail ("Assume.getIntrinsicID() == Intrinsic::assume && \"this function is intended to be used on llvm.assume\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Analysis/AssumeBundleQueries.cpp"
, 137, __PRETTY_FUNCTION__))
;
138 return none_of(Assume.bundle_op_infos(),
139 [](const CallBase::BundleOpInfo &BOI) {
140 return BOI.Tag->getKey() != IgnoreBundleTag;
141 });
142}
143
144static CallInst::BundleOpInfo *getBundleFromUse(const Use *U) {
145 auto *Intr = dyn_cast<IntrinsicInst>(U->getUser());
2
Assuming the object is not a 'IntrinsicInst'
3
'Intr' initialized to a null pointer value
146 if (!match(U->getUser(),
4
Calling 'match<llvm::User, llvm::PatternMatch::match_combine_and<llvm::PatternMatch::IntrinsicID_match, llvm::PatternMatch::Argument_match<llvm::PatternMatch::match_unless<llvm::PatternMatch::specificval_ty>>>>'
30
Returning from 'match<llvm::User, llvm::PatternMatch::match_combine_and<llvm::PatternMatch::IntrinsicID_match, llvm::PatternMatch::Argument_match<llvm::PatternMatch::match_unless<llvm::PatternMatch::specificval_ty>>>>'
31
Taking false branch
147 m_Intrinsic<Intrinsic::assume>(m_Unless(m_Specific(U->get())))))
148 return nullptr;
149 return &Intr->getBundleOpInfoForOperand(U->getOperandNo());
32
Called C++ object pointer is null
150}
151
152RetainedKnowledge
153llvm::getKnowledgeFromUse(const Use *U,
154 ArrayRef<Attribute::AttrKind> AttrKinds) {
155 CallInst::BundleOpInfo* Bundle = getBundleFromUse(U);
1
Calling 'getBundleFromUse'
156 if (!Bundle)
157 return RetainedKnowledge::none();
158 RetainedKnowledge RK =
159 getKnowledgeFromBundle(*cast<CallInst>(U->getUser()), *Bundle);
160 for (auto Attr : AttrKinds)
161 if (Attr == RK.AttrKind)
162 return RK;
163 return RetainedKnowledge::none();
164}
165
166RetainedKnowledge
167llvm::getKnowledgeForValue(const Value *V,
168 ArrayRef<Attribute::AttrKind> AttrKinds,
169 AssumptionCache *AC,
170 function_ref<bool(RetainedKnowledge, Instruction *,
171 const CallBase::BundleOpInfo *)>
172 Filter) {
173 NumAssumeQueries++;
174 if (!DebugCounter::shouldExecute(AssumeQueryCounter))
175 return RetainedKnowledge::none();
176 if (AC) {
177 for (AssumptionCache::ResultElem &Elem : AC->assumptionsFor(V)) {
178 IntrinsicInst *II = cast_or_null<IntrinsicInst>(Elem.Assume);
179 if (!II || Elem.Index == AssumptionCache::ExprResultIdx)
180 continue;
181 if (RetainedKnowledge RK = getKnowledgeFromBundle(
182 *II, II->bundle_op_info_begin()[Elem.Index])) {
183 if (V != RK.WasOn)
184 continue;
185 if (is_contained(AttrKinds, RK.AttrKind) &&
186 Filter(RK, II, &II->bundle_op_info_begin()[Elem.Index])) {
187 NumUsefullAssumeQueries++;
188 return RK;
189 }
190 }
191 }
192 return RetainedKnowledge::none();
193 }
194 for (const auto &U : V->uses()) {
195 CallInst::BundleOpInfo* Bundle = getBundleFromUse(&U);
196 if (!Bundle)
197 continue;
198 if (RetainedKnowledge RK =
199 getKnowledgeFromBundle(*cast<CallInst>(U.getUser()), *Bundle))
200 if (is_contained(AttrKinds, RK.AttrKind) &&
201 Filter(RK, cast<Instruction>(U.getUser()), Bundle)) {
202 NumUsefullAssumeQueries++;
203 return RK;
204 }
205 }
206 return RetainedKnowledge::none();
207}
208
209RetainedKnowledge llvm::getKnowledgeValidInContext(
210 const Value *V, ArrayRef<Attribute::AttrKind> AttrKinds,
211 const Instruction *CtxI, const DominatorTree *DT, AssumptionCache *AC) {
212 return getKnowledgeForValue(V, AttrKinds, AC,
213 [&](auto, Instruction *I, auto) {
214 return isValidAssumeForContext(I, CtxI, DT);
215 });
216}

/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/include/llvm/IR/PatternMatch.h

1//===- PatternMatch.h - Match on the LLVM IR --------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides a simple and efficient mechanism for performing general
10// tree-based pattern matches on the LLVM IR. The power of these routines is
11// that it allows you to write concise patterns that are expressive and easy to
12// understand. The other major advantage of this is that it allows you to
13// trivially capture/bind elements in the pattern to variables. For example,
14// you can do something like this:
15//
16// Value *Exp = ...
17// Value *X, *Y; ConstantInt *C1, *C2; // (X & C1) | (Y & C2)
18// if (match(Exp, m_Or(m_And(m_Value(X), m_ConstantInt(C1)),
19// m_And(m_Value(Y), m_ConstantInt(C2))))) {
20// ... Pattern is matched and variables are bound ...
21// }
22//
23// This is primarily useful to things like the instruction combiner, but can
24// also be useful for static analysis tools or code generators.
25//
26//===----------------------------------------------------------------------===//
27
28#ifndef LLVM_IR_PATTERNMATCH_H
29#define LLVM_IR_PATTERNMATCH_H
30
31#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/InstrTypes.h"
37#include "llvm/IR/Instruction.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/Operator.h"
42#include "llvm/IR/Value.h"
43#include "llvm/Support/Casting.h"
44#include <cstdint>
45
46namespace llvm {
47namespace PatternMatch {
48
49template <typename Val, typename Pattern> bool match(Val *V, const Pattern &P) {
50 return const_cast<Pattern &>(P).match(V);
5
Calling 'match_combine_and::match'
28
Returning from 'match_combine_and::match'
29
Returning the value 1, which participates in a condition later
51}
52
53template <typename Pattern> bool match(ArrayRef<int> Mask, const Pattern &P) {
54 return const_cast<Pattern &>(P).match(Mask);
55}
56
57template <typename SubPattern_t> struct OneUse_match {
58 SubPattern_t SubPattern;
59
60 OneUse_match(const SubPattern_t &SP) : SubPattern(SP) {}
61
62 template <typename OpTy> bool match(OpTy *V) {
63 return V->hasOneUse() && SubPattern.match(V);
64 }
65};
66
67template <typename T> inline OneUse_match<T> m_OneUse(const T &SubPattern) {
68 return SubPattern;
69}
70
71template <typename Class> struct class_match {
72 template <typename ITy> bool match(ITy *V) { return isa<Class>(V); }
73};
74
75/// Match an arbitrary value and ignore it.
76inline class_match<Value> m_Value() { return class_match<Value>(); }
77
78/// Match an arbitrary unary operation and ignore it.
79inline class_match<UnaryOperator> m_UnOp() {
80 return class_match<UnaryOperator>();
81}
82
83/// Match an arbitrary binary operation and ignore it.
84inline class_match<BinaryOperator> m_BinOp() {
85 return class_match<BinaryOperator>();
86}
87
88/// Matches any compare instruction and ignore it.
89inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); }
90
91/// Match an arbitrary ConstantInt and ignore it.
92inline class_match<ConstantInt> m_ConstantInt() {
93 return class_match<ConstantInt>();
94}
95
96/// Match an arbitrary undef constant.
97inline class_match<UndefValue> m_Undef() { return class_match<UndefValue>(); }
98
99/// Match an arbitrary Constant and ignore it.
100inline class_match<Constant> m_Constant() { return class_match<Constant>(); }
101
102/// Match an arbitrary basic block value and ignore it.
103inline class_match<BasicBlock> m_BasicBlock() {
104 return class_match<BasicBlock>();
105}
106
107/// Inverting matcher
108template <typename Ty> struct match_unless {
109 Ty M;
110
111 match_unless(const Ty &Matcher) : M(Matcher) {}
112
113 template <typename ITy> bool match(ITy *V) { return !M.match(V); }
18
Calling 'specificval_ty::match'
21
Returning from 'specificval_ty::match'
22
Returning the value 1, which participates in a condition later
114};
115
116/// Match if the inner matcher does *NOT* match.
117template <typename Ty> inline match_unless<Ty> m_Unless(const Ty &M) {
118 return match_unless<Ty>(M);
119}
120
121/// Matching combinators
122template <typename LTy, typename RTy> struct match_combine_or {
123 LTy L;
124 RTy R;
125
126 match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
127
128 template <typename ITy> bool match(ITy *V) {
129 if (L.match(V))
130 return true;
131 if (R.match(V))
132 return true;
133 return false;
134 }
135};
136
137template <typename LTy, typename RTy> struct match_combine_and {
138 LTy L;
139 RTy R;
140
141 match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
142
143 template <typename ITy> bool match(ITy *V) {
144 if (L.match(V))
6
Calling 'IntrinsicID_match::match'
12
Returning from 'IntrinsicID_match::match'
13
Taking true branch
145 if (R.match(V))
14
Calling 'Argument_match::match'
25
Returning from 'Argument_match::match'
26
Taking true branch
146 return true;
27
Returning the value 1, which participates in a condition later
147 return false;
148 }
149};
150
151/// Combine two pattern matchers matching L || R
152template <typename LTy, typename RTy>
153inline match_combine_or<LTy, RTy> m_CombineOr(const LTy &L, const RTy &R) {
154 return match_combine_or<LTy, RTy>(L, R);
155}
156
157/// Combine two pattern matchers matching L && R
158template <typename LTy, typename RTy>
159inline match_combine_and<LTy, RTy> m_CombineAnd(const LTy &L, const RTy &R) {
160 return match_combine_and<LTy, RTy>(L, R);
161}
162
163struct apint_match {
164 const APInt *&Res;
165 bool AllowUndef;
166
167 apint_match(const APInt *&Res, bool AllowUndef)
168 : Res(Res), AllowUndef(AllowUndef) {}
169
170 template <typename ITy> bool match(ITy *V) {
171 if (auto *CI = dyn_cast<ConstantInt>(V)) {
172 Res = &CI->getValue();
173 return true;
174 }
175 if (V->getType()->isVectorTy())
176 if (const auto *C = dyn_cast<Constant>(V))
177 if (auto *CI = dyn_cast_or_null<ConstantInt>(
178 C->getSplatValue(AllowUndef))) {
179 Res = &CI->getValue();
180 return true;
181 }
182 return false;
183 }
184};
185// Either constexpr if or renaming ConstantFP::getValueAPF to
186// ConstantFP::getValue is needed to do it via single template
187// function for both apint/apfloat.
188struct apfloat_match {
189 const APFloat *&Res;
190 bool AllowUndef;
191
192 apfloat_match(const APFloat *&Res, bool AllowUndef)
193 : Res(Res), AllowUndef(AllowUndef) {}
194
195 template <typename ITy> bool match(ITy *V) {
196 if (auto *CI = dyn_cast<ConstantFP>(V)) {
197 Res = &CI->getValueAPF();
198 return true;
199 }
200 if (V->getType()->isVectorTy())
201 if (const auto *C = dyn_cast<Constant>(V))
202 if (auto *CI = dyn_cast_or_null<ConstantFP>(
203 C->getSplatValue(AllowUndef))) {
204 Res = &CI->getValueAPF();
205 return true;
206 }
207 return false;
208 }
209};
210
211/// Match a ConstantInt or splatted ConstantVector, binding the
212/// specified pointer to the contained APInt.
213inline apint_match m_APInt(const APInt *&Res) {
214 // Forbid undefs by default to maintain previous behavior.
215 return apint_match(Res, /* AllowUndef */ false);
216}
217
218/// Match APInt while allowing undefs in splat vector constants.
219inline apint_match m_APIntAllowUndef(const APInt *&Res) {
220 return apint_match(Res, /* AllowUndef */ true);
221}
222
223/// Match APInt while forbidding undefs in splat vector constants.
224inline apint_match m_APIntForbidUndef(const APInt *&Res) {
225 return apint_match(Res, /* AllowUndef */ false);
226}
227
228/// Match a ConstantFP or splatted ConstantVector, binding the
229/// specified pointer to the contained APFloat.
230inline apfloat_match m_APFloat(const APFloat *&Res) {
231 // Forbid undefs by default to maintain previous behavior.
232 return apfloat_match(Res, /* AllowUndef */ false);
233}
234
235/// Match APFloat while allowing undefs in splat vector constants.
236inline apfloat_match m_APFloatAllowUndef(const APFloat *&Res) {
237 return apfloat_match(Res, /* AllowUndef */ true);
238}
239
240/// Match APFloat while forbidding undefs in splat vector constants.
241inline apfloat_match m_APFloatForbidUndef(const APFloat *&Res) {
242 return apfloat_match(Res, /* AllowUndef */ false);
243}
244
245template <int64_t Val> struct constantint_match {
246 template <typename ITy> bool match(ITy *V) {
247 if (const auto *CI = dyn_cast<ConstantInt>(V)) {
248 const APInt &CIV = CI->getValue();
249 if (Val >= 0)
250 return CIV == static_cast<uint64_t>(Val);
251 // If Val is negative, and CI is shorter than it, truncate to the right
252 // number of bits. If it is larger, then we have to sign extend. Just
253 // compare their negated values.
254 return -CIV == -Val;
255 }
256 return false;
257 }
258};
259
260/// Match a ConstantInt with a specific value.
261template <int64_t Val> inline constantint_match<Val> m_ConstantInt() {
262 return constantint_match<Val>();
263}
264
265/// This helper class is used to match constant scalars, vector splats,
266/// and fixed width vectors that satisfy a specified predicate.
267/// For fixed width vector constants, undefined elements are ignored.
268template <typename Predicate, typename ConstantVal>
269struct cstval_pred_ty : public Predicate {
270 template <typename ITy> bool match(ITy *V) {
271 if (const auto *CV = dyn_cast<ConstantVal>(V))
272 return this->isValue(CV->getValue());
273 if (const auto *VTy = dyn_cast<VectorType>(V->getType())) {
274 if (const auto *C = dyn_cast<Constant>(V)) {
275 if (const auto *CV = dyn_cast_or_null<ConstantVal>(C->getSplatValue()))
276 return this->isValue(CV->getValue());
277
278 // Number of elements of a scalable vector unknown at compile time
279 auto *FVTy = dyn_cast<FixedVectorType>(VTy);
280 if (!FVTy)
281 return false;
282
283 // Non-splat vector constant: check each element for a match.
284 unsigned NumElts = FVTy->getNumElements();
285 assert(NumElts != 0 && "Constant vector with no elements?")((NumElts != 0 && "Constant vector with no elements?"
) ? static_cast<void> (0) : __assert_fail ("NumElts != 0 && \"Constant vector with no elements?\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/include/llvm/IR/PatternMatch.h"
, 285, __PRETTY_FUNCTION__))
;
286 bool HasNonUndefElements = false;
287 for (unsigned i = 0; i != NumElts; ++i) {
288 Constant *Elt = C->getAggregateElement(i);
289 if (!Elt)
290 return false;
291 if (isa<UndefValue>(Elt))
292 continue;
293 auto *CV = dyn_cast<ConstantVal>(Elt);
294 if (!CV || !this->isValue(CV->getValue()))
295 return false;
296 HasNonUndefElements = true;
297 }
298 return HasNonUndefElements;
299 }
300 }
301 return false;
302 }
303};
304
305/// specialization of cstval_pred_ty for ConstantInt
306template <typename Predicate>
307using cst_pred_ty = cstval_pred_ty<Predicate, ConstantInt>;
308
309/// specialization of cstval_pred_ty for ConstantFP
310template <typename Predicate>
311using cstfp_pred_ty = cstval_pred_ty<Predicate, ConstantFP>;
312
313/// This helper class is used to match scalar and vector constants that
314/// satisfy a specified predicate, and bind them to an APInt.
315template <typename Predicate> struct api_pred_ty : public Predicate {
316 const APInt *&Res;
317
318 api_pred_ty(const APInt *&R) : Res(R) {}
319
320 template <typename ITy> bool match(ITy *V) {
321 if (const auto *CI = dyn_cast<ConstantInt>(V))
322 if (this->isValue(CI->getValue())) {
323 Res = &CI->getValue();
324 return true;
325 }
326 if (V->getType()->isVectorTy())
327 if (const auto *C = dyn_cast<Constant>(V))
328 if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
329 if (this->isValue(CI->getValue())) {
330 Res = &CI->getValue();
331 return true;
332 }
333
334 return false;
335 }
336};
337
338///////////////////////////////////////////////////////////////////////////////
339//
340// Encapsulate constant value queries for use in templated predicate matchers.
341// This allows checking if constants match using compound predicates and works
342// with vector constants, possibly with relaxed constraints. For example, ignore
343// undef values.
344//
345///////////////////////////////////////////////////////////////////////////////
346
347struct is_any_apint {
348 bool isValue(const APInt &C) { return true; }
349};
350/// Match an integer or vector with any integral constant.
351/// For vectors, this includes constants with undefined elements.
352inline cst_pred_ty<is_any_apint> m_AnyIntegralConstant() {
353 return cst_pred_ty<is_any_apint>();
354}
355
356struct is_all_ones {
357 bool isValue(const APInt &C) { return C.isAllOnesValue(); }
358};
359/// Match an integer or vector with all bits set.
360/// For vectors, this includes constants with undefined elements.
361inline cst_pred_ty<is_all_ones> m_AllOnes() {
362 return cst_pred_ty<is_all_ones>();
363}
364
365struct is_maxsignedvalue {
366 bool isValue(const APInt &C) { return C.isMaxSignedValue(); }
367};
368/// Match an integer or vector with values having all bits except for the high
369/// bit set (0x7f...).
370/// For vectors, this includes constants with undefined elements.
371inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() {
372 return cst_pred_ty<is_maxsignedvalue>();
373}
374inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) {
375 return V;
376}
377
378struct is_negative {
379 bool isValue(const APInt &C) { return C.isNegative(); }
380};
381/// Match an integer or vector of negative values.
382/// For vectors, this includes constants with undefined elements.
383inline cst_pred_ty<is_negative> m_Negative() {
384 return cst_pred_ty<is_negative>();
385}
386inline api_pred_ty<is_negative> m_Negative(const APInt *&V) {
387 return V;
388}
389
390struct is_nonnegative {
391 bool isValue(const APInt &C) { return C.isNonNegative(); }
392};
393/// Match an integer or vector of non-negative values.
394/// For vectors, this includes constants with undefined elements.
395inline cst_pred_ty<is_nonnegative> m_NonNegative() {
396 return cst_pred_ty<is_nonnegative>();
397}
398inline api_pred_ty<is_nonnegative> m_NonNegative(const APInt *&V) {
399 return V;
400}
401
402struct is_strictlypositive {
403 bool isValue(const APInt &C) { return C.isStrictlyPositive(); }
404};
405/// Match an integer or vector of strictly positive values.
406/// For vectors, this includes constants with undefined elements.
407inline cst_pred_ty<is_strictlypositive> m_StrictlyPositive() {
408 return cst_pred_ty<is_strictlypositive>();
409}
410inline api_pred_ty<is_strictlypositive> m_StrictlyPositive(const APInt *&V) {
411 return V;
412}
413
414struct is_nonpositive {
415 bool isValue(const APInt &C) { return C.isNonPositive(); }
416};
417/// Match an integer or vector of non-positive values.
418/// For vectors, this includes constants with undefined elements.
419inline cst_pred_ty<is_nonpositive> m_NonPositive() {
420 return cst_pred_ty<is_nonpositive>();
421}
422inline api_pred_ty<is_nonpositive> m_NonPositive(const APInt *&V) { return V; }
423
424struct is_one {
425 bool isValue(const APInt &C) { return C.isOneValue(); }
426};
427/// Match an integer 1 or a vector with all elements equal to 1.
428/// For vectors, this includes constants with undefined elements.
429inline cst_pred_ty<is_one> m_One() {
430 return cst_pred_ty<is_one>();
431}
432
433struct is_zero_int {
434 bool isValue(const APInt &C) { return C.isNullValue(); }
435};
436/// Match an integer 0 or a vector with all elements equal to 0.
437/// For vectors, this includes constants with undefined elements.
438inline cst_pred_ty<is_zero_int> m_ZeroInt() {
439 return cst_pred_ty<is_zero_int>();
440}
441
442struct is_zero {
443 template <typename ITy> bool match(ITy *V) {
444 auto *C = dyn_cast<Constant>(V);
445 // FIXME: this should be able to do something for scalable vectors
446 return C && (C->isNullValue() || cst_pred_ty<is_zero_int>().match(C));
447 }
448};
449/// Match any null constant or a vector with all elements equal to 0.
450/// For vectors, this includes constants with undefined elements.
451inline is_zero m_Zero() {
452 return is_zero();
453}
454
455struct is_power2 {
456 bool isValue(const APInt &C) { return C.isPowerOf2(); }
457};
458/// Match an integer or vector power-of-2.
459/// For vectors, this includes constants with undefined elements.
460inline cst_pred_ty<is_power2> m_Power2() {
461 return cst_pred_ty<is_power2>();
462}
463inline api_pred_ty<is_power2> m_Power2(const APInt *&V) {
464 return V;
465}
466
467struct is_negated_power2 {
468 bool isValue(const APInt &C) { return (-C).isPowerOf2(); }
469};
470/// Match a integer or vector negated power-of-2.
471/// For vectors, this includes constants with undefined elements.
472inline cst_pred_ty<is_negated_power2> m_NegatedPower2() {
473 return cst_pred_ty<is_negated_power2>();
474}
475inline api_pred_ty<is_negated_power2> m_NegatedPower2(const APInt *&V) {
476 return V;
477}
478
479struct is_power2_or_zero {
480 bool isValue(const APInt &C) { return !C || C.isPowerOf2(); }
481};
482/// Match an integer or vector of 0 or power-of-2 values.
483/// For vectors, this includes constants with undefined elements.
484inline cst_pred_ty<is_power2_or_zero> m_Power2OrZero() {
485 return cst_pred_ty<is_power2_or_zero>();
486}
487inline api_pred_ty<is_power2_or_zero> m_Power2OrZero(const APInt *&V) {
488 return V;
489}
490
491struct is_sign_mask {
492 bool isValue(const APInt &C) { return C.isSignMask(); }
493};
494/// Match an integer or vector with only the sign bit(s) set.
495/// For vectors, this includes constants with undefined elements.
496inline cst_pred_ty<is_sign_mask> m_SignMask() {
497 return cst_pred_ty<is_sign_mask>();
498}
499
500struct is_lowbit_mask {
501 bool isValue(const APInt &C) { return C.isMask(); }
502};
503/// Match an integer or vector with only the low bit(s) set.
504/// For vectors, this includes constants with undefined elements.
505inline cst_pred_ty<is_lowbit_mask> m_LowBitMask() {
506 return cst_pred_ty<is_lowbit_mask>();
507}
508
509struct icmp_pred_with_threshold {
510 ICmpInst::Predicate Pred;
511 const APInt *Thr;
512 bool isValue(const APInt &C) {
513 switch (Pred) {
514 case ICmpInst::Predicate::ICMP_EQ:
515 return C.eq(*Thr);
516 case ICmpInst::Predicate::ICMP_NE:
517 return C.ne(*Thr);
518 case ICmpInst::Predicate::ICMP_UGT:
519 return C.ugt(*Thr);
520 case ICmpInst::Predicate::ICMP_UGE:
521 return C.uge(*Thr);
522 case ICmpInst::Predicate::ICMP_ULT:
523 return C.ult(*Thr);
524 case ICmpInst::Predicate::ICMP_ULE:
525 return C.ule(*Thr);
526 case ICmpInst::Predicate::ICMP_SGT:
527 return C.sgt(*Thr);
528 case ICmpInst::Predicate::ICMP_SGE:
529 return C.sge(*Thr);
530 case ICmpInst::Predicate::ICMP_SLT:
531 return C.slt(*Thr);
532 case ICmpInst::Predicate::ICMP_SLE:
533 return C.sle(*Thr);
534 default:
535 llvm_unreachable("Unhandled ICmp predicate")::llvm::llvm_unreachable_internal("Unhandled ICmp predicate",
"/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/include/llvm/IR/PatternMatch.h"
, 535)
;
536 }
537 }
538};
539/// Match an integer or vector with every element comparing 'pred' (eg/ne/...)
540/// to Threshold. For vectors, this includes constants with undefined elements.
541inline cst_pred_ty<icmp_pred_with_threshold>
542m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold) {
543 cst_pred_ty<icmp_pred_with_threshold> P;
544 P.Pred = Predicate;
545 P.Thr = &Threshold;
546 return P;
547}
548
549struct is_nan {
550 bool isValue(const APFloat &C) { return C.isNaN(); }
551};
552/// Match an arbitrary NaN constant. This includes quiet and signalling nans.
553/// For vectors, this includes constants with undefined elements.
554inline cstfp_pred_ty<is_nan> m_NaN() {
555 return cstfp_pred_ty<is_nan>();
556}
557
558struct is_inf {
559 bool isValue(const APFloat &C) { return C.isInfinity(); }
560};
561/// Match a positive or negative infinity FP constant.
562/// For vectors, this includes constants with undefined elements.
563inline cstfp_pred_ty<is_inf> m_Inf() {
564 return cstfp_pred_ty<is_inf>();
565}
566
567struct is_any_zero_fp {
568 bool isValue(const APFloat &C) { return C.isZero(); }
569};
570/// Match a floating-point negative zero or positive zero.
571/// For vectors, this includes constants with undefined elements.
572inline cstfp_pred_ty<is_any_zero_fp> m_AnyZeroFP() {
573 return cstfp_pred_ty<is_any_zero_fp>();
574}
575
576struct is_pos_zero_fp {
577 bool isValue(const APFloat &C) { return C.isPosZero(); }
578};
579/// Match a floating-point positive zero.
580/// For vectors, this includes constants with undefined elements.
581inline cstfp_pred_ty<is_pos_zero_fp> m_PosZeroFP() {
582 return cstfp_pred_ty<is_pos_zero_fp>();
583}
584
585struct is_neg_zero_fp {
586 bool isValue(const APFloat &C) { return C.isNegZero(); }
587};
588/// Match a floating-point negative zero.
589/// For vectors, this includes constants with undefined elements.
590inline cstfp_pred_ty<is_neg_zero_fp> m_NegZeroFP() {
591 return cstfp_pred_ty<is_neg_zero_fp>();
592}
593
594///////////////////////////////////////////////////////////////////////////////
595
596template <typename Class> struct bind_ty {
597 Class *&VR;
598
599 bind_ty(Class *&V) : VR(V) {}
600
601 template <typename ITy> bool match(ITy *V) {
602 if (auto *CV = dyn_cast<Class>(V)) {
603 VR = CV;
604 return true;
605 }
606 return false;
607 }
608};
609
610/// Match a value, capturing it if we match.
611inline bind_ty<Value> m_Value(Value *&V) { return V; }
612inline bind_ty<const Value> m_Value(const Value *&V) { return V; }
613
614/// Match an instruction, capturing it if we match.
615inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; }
616/// Match a unary operator, capturing it if we match.
617inline bind_ty<UnaryOperator> m_UnOp(UnaryOperator *&I) { return I; }
618/// Match a binary operator, capturing it if we match.
619inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; }
620/// Match a with overflow intrinsic, capturing it if we match.
621inline bind_ty<WithOverflowInst> m_WithOverflowInst(WithOverflowInst *&I) { return I; }
622
623/// Match a ConstantInt, capturing the value if we match.
624inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; }
625
626/// Match a Constant, capturing the value if we match.
627inline bind_ty<Constant> m_Constant(Constant *&C) { return C; }
628
629/// Match a ConstantFP, capturing the value if we match.
630inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; }
631
632/// Match a basic block value, capturing it if we match.
633inline bind_ty<BasicBlock> m_BasicBlock(BasicBlock *&V) { return V; }
634inline bind_ty<const BasicBlock> m_BasicBlock(const BasicBlock *&V) {
635 return V;
636}
637
638/// Match a specified Value*.
639struct specificval_ty {
640 const Value *Val;
641
642 specificval_ty(const Value *V) : Val(V) {}
643
644 template <typename ITy> bool match(ITy *V) { return V == Val; }
19
Assuming 'V' is not equal to field 'Val'
20
Returning zero, which participates in a condition later
645};
646
647/// Match if we have a specific specified value.
648inline specificval_ty m_Specific(const Value *V) { return V; }
649
650/// Stores a reference to the Value *, not the Value * itself,
651/// thus can be used in commutative matchers.
652template <typename Class> struct deferredval_ty {
653 Class *const &Val;
654
655 deferredval_ty(Class *const &V) : Val(V) {}
656
657 template <typename ITy> bool match(ITy *const V) { return V == Val; }
658};
659
660/// A commutative-friendly version of m_Specific().
661inline deferredval_ty<Value> m_Deferred(Value *const &V) { return V; }
662inline deferredval_ty<const Value> m_Deferred(const Value *const &V) {
663 return V;
664}
665
666/// Match a specified floating point value or vector of all elements of
667/// that value.
668struct specific_fpval {
669 double Val;
670
671 specific_fpval(double V) : Val(V) {}
672
673 template <typename ITy> bool match(ITy *V) {
674 if (const auto *CFP = dyn_cast<ConstantFP>(V))
675 return CFP->isExactlyValue(Val);
676 if (V->getType()->isVectorTy())
677 if (const auto *C = dyn_cast<Constant>(V))
678 if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
679 return CFP->isExactlyValue(Val);
680 return false;
681 }
682};
683
684/// Match a specific floating point value or vector with all elements
685/// equal to the value.
686inline specific_fpval m_SpecificFP(double V) { return specific_fpval(V); }
687
688/// Match a float 1.0 or vector with all elements equal to 1.0.
689inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); }
690
691struct bind_const_intval_ty {
692 uint64_t &VR;
693
694 bind_const_intval_ty(uint64_t &V) : VR(V) {}
695
696 template <typename ITy> bool match(ITy *V) {
697 if (const auto *CV = dyn_cast<ConstantInt>(V))
698 if (CV->getValue().ule(UINT64_MAX(18446744073709551615UL))) {
699 VR = CV->getZExtValue();
700 return true;
701 }
702 return false;
703 }
704};
705
706/// Match a specified integer value or vector of all elements of that
707/// value.
708struct specific_intval {
709 APInt Val;
710
711 specific_intval(APInt V) : Val(std::move(V)) {}
712
713 template <typename ITy> bool match(ITy *V) {
714 const auto *CI = dyn_cast<ConstantInt>(V);
715 if (!CI && V->getType()->isVectorTy())
716 if (const auto *C = dyn_cast<Constant>(V))
717 CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue());
718
719 return CI && APInt::isSameValue(CI->getValue(), Val);
720 }
721};
722
723/// Match a specific integer value or vector with all elements equal to
724/// the value.
725inline specific_intval m_SpecificInt(APInt V) {
726 return specific_intval(std::move(V));
727}
728
729inline specific_intval m_SpecificInt(uint64_t V) {
730 return m_SpecificInt(APInt(64, V));
731}
732
733/// Match a ConstantInt and bind to its value. This does not match
734/// ConstantInts wider than 64-bits.
735inline bind_const_intval_ty m_ConstantInt(uint64_t &V) { return V; }
736
737/// Match a specified basic block value.
738struct specific_bbval {
739 BasicBlock *Val;
740
741 specific_bbval(BasicBlock *Val) : Val(Val) {}
742
743 template <typename ITy> bool match(ITy *V) {
744 const auto *BB = dyn_cast<BasicBlock>(V);
745 return BB && BB == Val;
746 }
747};
748
749/// Match a specific basic block value.
750inline specific_bbval m_SpecificBB(BasicBlock *BB) {
751 return specific_bbval(BB);
752}
753
754/// A commutative-friendly version of m_Specific().
755inline deferredval_ty<BasicBlock> m_Deferred(BasicBlock *const &BB) {
756 return BB;
757}
758inline deferredval_ty<const BasicBlock>
759m_Deferred(const BasicBlock *const &BB) {
760 return BB;
761}
762
763//===----------------------------------------------------------------------===//
764// Matcher for any binary operator.
765//
766template <typename LHS_t, typename RHS_t, bool Commutable = false>
767struct AnyBinaryOp_match {
768 LHS_t L;
769 RHS_t R;
770
771 // The evaluation order is always stable, regardless of Commutability.
772 // The LHS is always matched first.
773 AnyBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
774
775 template <typename OpTy> bool match(OpTy *V) {
776 if (auto *I = dyn_cast<BinaryOperator>(V))
777 return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
778 (Commutable && L.match(I->getOperand(1)) &&
779 R.match(I->getOperand(0)));
780 return false;
781 }
782};
783
784template <typename LHS, typename RHS>
785inline AnyBinaryOp_match<LHS, RHS> m_BinOp(const LHS &L, const RHS &R) {
786 return AnyBinaryOp_match<LHS, RHS>(L, R);
787}
788
789//===----------------------------------------------------------------------===//
790// Matcher for any unary operator.
791// TODO fuse unary, binary matcher into n-ary matcher
792//
793template <typename OP_t> struct AnyUnaryOp_match {
794 OP_t X;
795
796 AnyUnaryOp_match(const OP_t &X) : X(X) {}
797
798 template <typename OpTy> bool match(OpTy *V) {
799 if (auto *I = dyn_cast<UnaryOperator>(V))
800 return X.match(I->getOperand(0));
801 return false;
802 }
803};
804
805template <typename OP_t> inline AnyUnaryOp_match<OP_t> m_UnOp(const OP_t &X) {
806 return AnyUnaryOp_match<OP_t>(X);
807}
808
809//===----------------------------------------------------------------------===//
810// Matchers for specific binary operators.
811//
812
813template <typename LHS_t, typename RHS_t, unsigned Opcode,
814 bool Commutable = false>
815struct BinaryOp_match {
816 LHS_t L;
817 RHS_t R;
818
819 // The evaluation order is always stable, regardless of Commutability.
820 // The LHS is always matched first.
821 BinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
822
823 template <typename OpTy> bool match(OpTy *V) {
824 if (V->getValueID() == Value::InstructionVal + Opcode) {
825 auto *I = cast<BinaryOperator>(V);
826 return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
827 (Commutable && L.match(I->getOperand(1)) &&
828 R.match(I->getOperand(0)));
829 }
830 if (auto *CE = dyn_cast<ConstantExpr>(V))
831 return CE->getOpcode() == Opcode &&
832 ((L.match(CE->getOperand(0)) && R.match(CE->getOperand(1))) ||
833 (Commutable && L.match(CE->getOperand(1)) &&
834 R.match(CE->getOperand(0))));
835 return false;
836 }
837};
838
839template <typename LHS, typename RHS>
840inline BinaryOp_match<LHS, RHS, Instruction::Add> m_Add(const LHS &L,
841 const RHS &R) {
842 return BinaryOp_match<LHS, RHS, Instruction::Add>(L, R);
843}
844
845template <typename LHS, typename RHS>
846inline BinaryOp_match<LHS, RHS, Instruction::FAdd> m_FAdd(const LHS &L,
847 const RHS &R) {
848 return BinaryOp_match<LHS, RHS, Instruction::FAdd>(L, R);
849}
850
851template <typename LHS, typename RHS>
852inline BinaryOp_match<LHS, RHS, Instruction::Sub> m_Sub(const LHS &L,
853 const RHS &R) {
854 return BinaryOp_match<LHS, RHS, Instruction::Sub>(L, R);
855}
856
857template <typename LHS, typename RHS>
858inline BinaryOp_match<LHS, RHS, Instruction::FSub> m_FSub(const LHS &L,
859 const RHS &R) {
860 return BinaryOp_match<LHS, RHS, Instruction::FSub>(L, R);
861}
862
863template <typename Op_t> struct FNeg_match {
864 Op_t X;
865
866 FNeg_match(const Op_t &Op) : X(Op) {}
867 template <typename OpTy> bool match(OpTy *V) {
868 auto *FPMO = dyn_cast<FPMathOperator>(V);
869 if (!FPMO) return false;
870
871 if (FPMO->getOpcode() == Instruction::FNeg)
872 return X.match(FPMO->getOperand(0));
873
874 if (FPMO->getOpcode() == Instruction::FSub) {
875 if (FPMO->hasNoSignedZeros()) {
876 // With 'nsz', any zero goes.
877 if (!cstfp_pred_ty<is_any_zero_fp>().match(FPMO->getOperand(0)))
878 return false;
879 } else {
880 // Without 'nsz', we need fsub -0.0, X exactly.
881 if (!cstfp_pred_ty<is_neg_zero_fp>().match(FPMO->getOperand(0)))
882 return false;
883 }
884
885 return X.match(FPMO->getOperand(1));
886 }
887
888 return false;
889 }
890};
891
892/// Match 'fneg X' as 'fsub -0.0, X'.
893template <typename OpTy>
894inline FNeg_match<OpTy>
895m_FNeg(const OpTy &X) {
896 return FNeg_match<OpTy>(X);
897}
898
899/// Match 'fneg X' as 'fsub +-0.0, X'.
900template <typename RHS>
901inline BinaryOp_match<cstfp_pred_ty<is_any_zero_fp>, RHS, Instruction::FSub>
902m_FNegNSZ(const RHS &X) {
903 return m_FSub(m_AnyZeroFP(), X);
904}
905
906template <typename LHS, typename RHS>
907inline BinaryOp_match<LHS, RHS, Instruction::Mul> m_Mul(const LHS &L,
908 const RHS &R) {
909 return BinaryOp_match<LHS, RHS, Instruction::Mul>(L, R);
910}
911
912template <typename LHS, typename RHS>
913inline BinaryOp_match<LHS, RHS, Instruction::FMul> m_FMul(const LHS &L,
914 const RHS &R) {
915 return BinaryOp_match<LHS, RHS, Instruction::FMul>(L, R);
916}
917
918template <typename LHS, typename RHS>
919inline BinaryOp_match<LHS, RHS, Instruction::UDiv> m_UDiv(const LHS &L,
920 const RHS &R) {
921 return BinaryOp_match<LHS, RHS, Instruction::UDiv>(L, R);
922}
923
924template <typename LHS, typename RHS>
925inline BinaryOp_match<LHS, RHS, Instruction::SDiv> m_SDiv(const LHS &L,
926 const RHS &R) {
927 return BinaryOp_match<LHS, RHS, Instruction::SDiv>(L, R);
928}
929
930template <typename LHS, typename RHS>
931inline BinaryOp_match<LHS, RHS, Instruction::FDiv> m_FDiv(const LHS &L,
932 const RHS &R) {
933 return BinaryOp_match<LHS, RHS, Instruction::FDiv>(L, R);
934}
935
936template <typename LHS, typename RHS>
937inline BinaryOp_match<LHS, RHS, Instruction::URem> m_URem(const LHS &L,
938 const RHS &R) {
939 return BinaryOp_match<LHS, RHS, Instruction::URem>(L, R);
940}
941
942template <typename LHS, typename RHS>
943inline BinaryOp_match<LHS, RHS, Instruction::SRem> m_SRem(const LHS &L,
944 const RHS &R) {
945 return BinaryOp_match<LHS, RHS, Instruction::SRem>(L, R);
946}
947
948template <typename LHS, typename RHS>
949inline BinaryOp_match<LHS, RHS, Instruction::FRem> m_FRem(const LHS &L,
950 const RHS &R) {
951 return BinaryOp_match<LHS, RHS, Instruction::FRem>(L, R);
952}
953
954template <typename LHS, typename RHS>
955inline BinaryOp_match<LHS, RHS, Instruction::And> m_And(const LHS &L,
956 const RHS &R) {
957 return BinaryOp_match<LHS, RHS, Instruction::And>(L, R);
958}
959
960template <typename LHS, typename RHS>
961inline BinaryOp_match<LHS, RHS, Instruction::Or> m_Or(const LHS &L,
962 const RHS &R) {
963 return BinaryOp_match<LHS, RHS, Instruction::Or>(L, R);
964}
965
966template <typename LHS, typename RHS>
967inline BinaryOp_match<LHS, RHS, Instruction::Xor> m_Xor(const LHS &L,
968 const RHS &R) {
969 return BinaryOp_match<LHS, RHS, Instruction::Xor>(L, R);
970}
971
972template <typename LHS, typename RHS>
973inline BinaryOp_match<LHS, RHS, Instruction::Shl> m_Shl(const LHS &L,
974 const RHS &R) {
975 return BinaryOp_match<LHS, RHS, Instruction::Shl>(L, R);
976}
977
978template <typename LHS, typename RHS>
979inline BinaryOp_match<LHS, RHS, Instruction::LShr> m_LShr(const LHS &L,
980 const RHS &R) {
981 return BinaryOp_match<LHS, RHS, Instruction::LShr>(L, R);
982}
983
984template <typename LHS, typename RHS>
985inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L,
986 const RHS &R) {
987 return BinaryOp_match<LHS, RHS, Instruction::AShr>(L, R);
988}
989
990template <typename LHS_t, typename RHS_t, unsigned Opcode,
991 unsigned WrapFlags = 0>
992struct OverflowingBinaryOp_match {
993 LHS_t L;
994 RHS_t R;
995
996 OverflowingBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS)
997 : L(LHS), R(RHS) {}
998
999 template <typename OpTy> bool match(OpTy *V) {
1000 if (auto *Op = dyn_cast<OverflowingBinaryOperator>(V)) {
1001 if (Op->getOpcode() != Opcode)
1002 return false;
1003 if (WrapFlags & OverflowingBinaryOperator::NoUnsignedWrap &&
1004 !Op->hasNoUnsignedWrap())
1005 return false;
1006 if (WrapFlags & OverflowingBinaryOperator::NoSignedWrap &&
1007 !Op->hasNoSignedWrap())
1008 return false;
1009 return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1));
1010 }
1011 return false;
1012 }
1013};
1014
1015template <typename LHS, typename RHS>
1016inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1017 OverflowingBinaryOperator::NoSignedWrap>
1018m_NSWAdd(const LHS &L, const RHS &R) {
1019 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1020 OverflowingBinaryOperator::NoSignedWrap>(
1021 L, R);
1022}
1023template <typename LHS, typename RHS>
1024inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1025 OverflowingBinaryOperator::NoSignedWrap>
1026m_NSWSub(const LHS &L, const RHS &R) {
1027 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1028 OverflowingBinaryOperator::NoSignedWrap>(
1029 L, R);
1030}
1031template <typename LHS, typename RHS>
1032inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1033 OverflowingBinaryOperator::NoSignedWrap>
1034m_NSWMul(const LHS &L, const RHS &R) {
1035 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1036 OverflowingBinaryOperator::NoSignedWrap>(
1037 L, R);
1038}
1039template <typename LHS, typename RHS>
1040inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1041 OverflowingBinaryOperator::NoSignedWrap>
1042m_NSWShl(const LHS &L, const RHS &R) {
1043 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1044 OverflowingBinaryOperator::NoSignedWrap>(
1045 L, R);
1046}
1047
1048template <typename LHS, typename RHS>
1049inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1050 OverflowingBinaryOperator::NoUnsignedWrap>
1051m_NUWAdd(const LHS &L, const RHS &R) {
1052 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1053 OverflowingBinaryOperator::NoUnsignedWrap>(
1054 L, R);
1055}
1056template <typename LHS, typename RHS>
1057inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1058 OverflowingBinaryOperator::NoUnsignedWrap>
1059m_NUWSub(const LHS &L, const RHS &R) {
1060 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1061 OverflowingBinaryOperator::NoUnsignedWrap>(
1062 L, R);
1063}
1064template <typename LHS, typename RHS>
1065inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1066 OverflowingBinaryOperator::NoUnsignedWrap>
1067m_NUWMul(const LHS &L, const RHS &R) {
1068 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1069 OverflowingBinaryOperator::NoUnsignedWrap>(
1070 L, R);
1071}
1072template <typename LHS, typename RHS>
1073inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1074 OverflowingBinaryOperator::NoUnsignedWrap>
1075m_NUWShl(const LHS &L, const RHS &R) {
1076 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1077 OverflowingBinaryOperator::NoUnsignedWrap>(
1078 L, R);
1079}
1080
1081//===----------------------------------------------------------------------===//
1082// Class that matches a group of binary opcodes.
1083//
1084template <typename LHS_t, typename RHS_t, typename Predicate>
1085struct BinOpPred_match : Predicate {
1086 LHS_t L;
1087 RHS_t R;
1088
1089 BinOpPred_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1090
1091 template <typename OpTy> bool match(OpTy *V) {
1092 if (auto *I = dyn_cast<Instruction>(V))
1093 return this->isOpType(I->getOpcode()) && L.match(I->getOperand(0)) &&
1094 R.match(I->getOperand(1));
1095 if (auto *CE = dyn_cast<ConstantExpr>(V))
1096 return this->isOpType(CE->getOpcode()) && L.match(CE->getOperand(0)) &&
1097 R.match(CE->getOperand(1));
1098 return false;
1099 }
1100};
1101
1102struct is_shift_op {
1103 bool isOpType(unsigned Opcode) { return Instruction::isShift(Opcode); }
1104};
1105
1106struct is_right_shift_op {
1107 bool isOpType(unsigned Opcode) {
1108 return Opcode == Instruction::LShr || Opcode == Instruction::AShr;
1109 }
1110};
1111
1112struct is_logical_shift_op {
1113 bool isOpType(unsigned Opcode) {
1114 return Opcode == Instruction::LShr || Opcode == Instruction::Shl;
1115 }
1116};
1117
1118struct is_bitwiselogic_op {
1119 bool isOpType(unsigned Opcode) {
1120 return Instruction::isBitwiseLogicOp(Opcode);
1121 }
1122};
1123
1124struct is_idiv_op {
1125 bool isOpType(unsigned Opcode) {
1126 return Opcode == Instruction::SDiv || Opcode == Instruction::UDiv;
1127 }
1128};
1129
1130struct is_irem_op {
1131 bool isOpType(unsigned Opcode) {
1132 return Opcode == Instruction::SRem || Opcode == Instruction::URem;
1133 }
1134};
1135
1136/// Matches shift operations.
1137template <typename LHS, typename RHS>
1138inline BinOpPred_match<LHS, RHS, is_shift_op> m_Shift(const LHS &L,
1139 const RHS &R) {
1140 return BinOpPred_match<LHS, RHS, is_shift_op>(L, R);
1141}
1142
1143/// Matches logical shift operations.
1144template <typename LHS, typename RHS>
1145inline BinOpPred_match<LHS, RHS, is_right_shift_op> m_Shr(const LHS &L,
1146 const RHS &R) {
1147 return BinOpPred_match<LHS, RHS, is_right_shift_op>(L, R);
1148}
1149
1150/// Matches logical shift operations.
1151template <typename LHS, typename RHS>
1152inline BinOpPred_match<LHS, RHS, is_logical_shift_op>
1153m_LogicalShift(const LHS &L, const RHS &R) {
1154 return BinOpPred_match<LHS, RHS, is_logical_shift_op>(L, R);
1155}
1156
1157/// Matches bitwise logic operations.
1158template <typename LHS, typename RHS>
1159inline BinOpPred_match<LHS, RHS, is_bitwiselogic_op>
1160m_BitwiseLogic(const LHS &L, const RHS &R) {
1161 return BinOpPred_match<LHS, RHS, is_bitwiselogic_op>(L, R);
1162}
1163
1164/// Matches integer division operations.
1165template <typename LHS, typename RHS>
1166inline BinOpPred_match<LHS, RHS, is_idiv_op> m_IDiv(const LHS &L,
1167 const RHS &R) {
1168 return BinOpPred_match<LHS, RHS, is_idiv_op>(L, R);
1169}
1170
1171/// Matches integer remainder operations.
1172template <typename LHS, typename RHS>
1173inline BinOpPred_match<LHS, RHS, is_irem_op> m_IRem(const LHS &L,
1174 const RHS &R) {
1175 return BinOpPred_match<LHS, RHS, is_irem_op>(L, R);
1176}
1177
1178//===----------------------------------------------------------------------===//
1179// Class that matches exact binary ops.
1180//
1181template <typename SubPattern_t> struct Exact_match {
1182 SubPattern_t SubPattern;
1183
1184 Exact_match(const SubPattern_t &SP) : SubPattern(SP) {}
1185
1186 template <typename OpTy> bool match(OpTy *V) {
1187 if (auto *PEO = dyn_cast<PossiblyExactOperator>(V))
1188 return PEO->isExact() && SubPattern.match(V);
1189 return false;
1190 }
1191};
1192
1193template <typename T> inline Exact_match<T> m_Exact(const T &SubPattern) {
1194 return SubPattern;
1195}
1196
1197//===----------------------------------------------------------------------===//
1198// Matchers for CmpInst classes
1199//
1200
1201template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy,
1202 bool Commutable = false>
1203struct CmpClass_match {
1204 PredicateTy &Predicate;
1205 LHS_t L;
1206 RHS_t R;
1207
1208 // The evaluation order is always stable, regardless of Commutability.
1209 // The LHS is always matched first.
1210 CmpClass_match(PredicateTy &Pred, const LHS_t &LHS, const RHS_t &RHS)
1211 : Predicate(Pred), L(LHS), R(RHS) {}
1212
1213 template <typename OpTy> bool match(OpTy *V) {
1214 if (auto *I = dyn_cast<Class>(V)) {
1215 if (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) {
1216 Predicate = I->getPredicate();
1217 return true;
1218 } else if (Commutable && L.match(I->getOperand(1)) &&
1219 R.match(I->getOperand(0))) {
1220 Predicate = I->getSwappedPredicate();
1221 return true;
1222 }
1223 }
1224 return false;
1225 }
1226};
1227
1228template <typename LHS, typename RHS>
1229inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>
1230m_Cmp(CmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1231 return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(Pred, L, R);
1232}
1233
1234template <typename LHS, typename RHS>
1235inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>
1236m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1237 return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(Pred, L, R);
1238}
1239
1240template <typename LHS, typename RHS>
1241inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>
1242m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1243 return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(Pred, L, R);
1244}
1245
1246//===----------------------------------------------------------------------===//
1247// Matchers for instructions with a given opcode and number of operands.
1248//
1249
1250/// Matches instructions with Opcode and three operands.
1251template <typename T0, unsigned Opcode> struct OneOps_match {
1252 T0 Op1;
1253
1254 OneOps_match(const T0 &Op1) : Op1(Op1) {}
1255
1256 template <typename OpTy> bool match(OpTy *V) {
1257 if (V->getValueID() == Value::InstructionVal + Opcode) {
1258 auto *I = cast<Instruction>(V);
1259 return Op1.match(I->getOperand(0));
1260 }
1261 return false;
1262 }
1263};
1264
1265/// Matches instructions with Opcode and three operands.
1266template <typename T0, typename T1, unsigned Opcode> struct TwoOps_match {
1267 T0 Op1;
1268 T1 Op2;
1269
1270 TwoOps_match(const T0 &Op1, const T1 &Op2) : Op1(Op1), Op2(Op2) {}
1271
1272 template <typename OpTy> bool match(OpTy *V) {
1273 if (V->getValueID() == Value::InstructionVal + Opcode) {
1274 auto *I = cast<Instruction>(V);
1275 return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1));
1276 }
1277 return false;
1278 }
1279};
1280
1281/// Matches instructions with Opcode and three operands.
1282template <typename T0, typename T1, typename T2, unsigned Opcode>
1283struct ThreeOps_match {
1284 T0 Op1;
1285 T1 Op2;
1286 T2 Op3;
1287
1288 ThreeOps_match(const T0 &Op1, const T1 &Op2, const T2 &Op3)
1289 : Op1(Op1), Op2(Op2), Op3(Op3) {}
1290
1291 template <typename OpTy> bool match(OpTy *V) {
1292 if (V->getValueID() == Value::InstructionVal + Opcode) {
1293 auto *I = cast<Instruction>(V);
1294 return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1295 Op3.match(I->getOperand(2));
1296 }
1297 return false;
1298 }
1299};
1300
1301/// Matches SelectInst.
1302template <typename Cond, typename LHS, typename RHS>
1303inline ThreeOps_match<Cond, LHS, RHS, Instruction::Select>
1304m_Select(const Cond &C, const LHS &L, const RHS &R) {
1305 return ThreeOps_match<Cond, LHS, RHS, Instruction::Select>(C, L, R);
1306}
1307
1308/// This matches a select of two constants, e.g.:
1309/// m_SelectCst<-1, 0>(m_Value(V))
1310template <int64_t L, int64_t R, typename Cond>
1311inline ThreeOps_match<Cond, constantint_match<L>, constantint_match<R>,
1312 Instruction::Select>
1313m_SelectCst(const Cond &C) {
1314 return m_Select(C, m_ConstantInt<L>(), m_ConstantInt<R>());
1315}
1316
1317/// Matches FreezeInst.
1318template <typename OpTy>
1319inline OneOps_match<OpTy, Instruction::Freeze> m_Freeze(const OpTy &Op) {
1320 return OneOps_match<OpTy, Instruction::Freeze>(Op);
1321}
1322
1323/// Matches InsertElementInst.
1324template <typename Val_t, typename Elt_t, typename Idx_t>
1325inline ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>
1326m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx) {
1327 return ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>(
1328 Val, Elt, Idx);
1329}
1330
1331/// Matches ExtractElementInst.
1332template <typename Val_t, typename Idx_t>
1333inline TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>
1334m_ExtractElt(const Val_t &Val, const Idx_t &Idx) {
1335 return TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>(Val, Idx);
1336}
1337
1338/// Matches shuffle.
1339template <typename T0, typename T1, typename T2> struct Shuffle_match {
1340 T0 Op1;
1341 T1 Op2;
1342 T2 Mask;
1343
1344 Shuffle_match(const T0 &Op1, const T1 &Op2, const T2 &Mask)
1345 : Op1(Op1), Op2(Op2), Mask(Mask) {}
1346
1347 template <typename OpTy> bool match(OpTy *V) {
1348 if (auto *I = dyn_cast<ShuffleVectorInst>(V)) {
1349 return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1350 Mask.match(I->getShuffleMask());
1351 }
1352 return false;
1353 }
1354};
1355
1356struct m_Mask {
1357 ArrayRef<int> &MaskRef;
1358 m_Mask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {}
1359 bool match(ArrayRef<int> Mask) {
1360 MaskRef = Mask;
1361 return true;
1362 }
1363};
1364
1365struct m_ZeroMask {
1366 bool match(ArrayRef<int> Mask) {
1367 return all_of(Mask, [](int Elem) { return Elem == 0 || Elem == -1; });
1368 }
1369};
1370
1371struct m_SpecificMask {
1372 ArrayRef<int> &MaskRef;
1373 m_SpecificMask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {}
1374 bool match(ArrayRef<int> Mask) { return MaskRef == Mask; }
1375};
1376
1377struct m_SplatOrUndefMask {
1378 int &SplatIndex;
1379 m_SplatOrUndefMask(int &SplatIndex) : SplatIndex(SplatIndex) {}
1380 bool match(ArrayRef<int> Mask) {
1381 auto First = find_if(Mask, [](int Elem) { return Elem != -1; });
1382 if (First == Mask.end())
1383 return false;
1384 SplatIndex = *First;
1385 return all_of(Mask,
1386 [First](int Elem) { return Elem == *First || Elem == -1; });
1387 }
1388};
1389
1390/// Matches ShuffleVectorInst independently of mask value.
1391template <typename V1_t, typename V2_t>
1392inline TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>
1393m_Shuffle(const V1_t &v1, const V2_t &v2) {
1394 return TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>(v1, v2);
1395}
1396
1397template <typename V1_t, typename V2_t, typename Mask_t>
1398inline Shuffle_match<V1_t, V2_t, Mask_t>
1399m_Shuffle(const V1_t &v1, const V2_t &v2, const Mask_t &mask) {
1400 return Shuffle_match<V1_t, V2_t, Mask_t>(v1, v2, mask);
1401}
1402
1403/// Matches LoadInst.
1404template <typename OpTy>
1405inline OneOps_match<OpTy, Instruction::Load> m_Load(const OpTy &Op) {
1406 return OneOps_match<OpTy, Instruction::Load>(Op);
1407}
1408
1409/// Matches StoreInst.
1410template <typename ValueOpTy, typename PointerOpTy>
1411inline TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>
1412m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp) {
1413 return TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>(ValueOp,
1414 PointerOp);
1415}
1416
1417//===----------------------------------------------------------------------===//
1418// Matchers for CastInst classes
1419//
1420
1421template <typename Op_t, unsigned Opcode> struct CastClass_match {
1422 Op_t Op;
1423
1424 CastClass_match(const Op_t &OpMatch) : Op(OpMatch) {}
1425
1426 template <typename OpTy> bool match(OpTy *V) {
1427 if (auto *O = dyn_cast<Operator>(V))
1428 return O->getOpcode() == Opcode && Op.match(O->getOperand(0));
1429 return false;
1430 }
1431};
1432
1433/// Matches BitCast.
1434template <typename OpTy>
1435inline CastClass_match<OpTy, Instruction::BitCast> m_BitCast(const OpTy &Op) {
1436 return CastClass_match<OpTy, Instruction::BitCast>(Op);
1437}
1438
1439/// Matches PtrToInt.
1440template <typename OpTy>
1441inline CastClass_match<OpTy, Instruction::PtrToInt> m_PtrToInt(const OpTy &Op) {
1442 return CastClass_match<OpTy, Instruction::PtrToInt>(Op);
1443}
1444
1445/// Matches IntToPtr.
1446template <typename OpTy>
1447inline CastClass_match<OpTy, Instruction::IntToPtr> m_IntToPtr(const OpTy &Op) {
1448 return CastClass_match<OpTy, Instruction::IntToPtr>(Op);
1449}
1450
1451/// Matches Trunc.
1452template <typename OpTy>
1453inline CastClass_match<OpTy, Instruction::Trunc> m_Trunc(const OpTy &Op) {
1454 return CastClass_match<OpTy, Instruction::Trunc>(Op);
1455}
1456
1457template <typename OpTy>
1458inline match_combine_or<CastClass_match<OpTy, Instruction::Trunc>, OpTy>
1459m_TruncOrSelf(const OpTy &Op) {
1460 return m_CombineOr(m_Trunc(Op), Op);
1461}
1462
1463/// Matches SExt.
1464template <typename OpTy>
1465inline CastClass_match<OpTy, Instruction::SExt> m_SExt(const OpTy &Op) {
1466 return CastClass_match<OpTy, Instruction::SExt>(Op);
1467}
1468
1469/// Matches ZExt.
1470template <typename OpTy>
1471inline CastClass_match<OpTy, Instruction::ZExt> m_ZExt(const OpTy &Op) {
1472 return CastClass_match<OpTy, Instruction::ZExt>(Op);
1473}
1474
1475template <typename OpTy>
1476inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>, OpTy>
1477m_ZExtOrSelf(const OpTy &Op) {
1478 return m_CombineOr(m_ZExt(Op), Op);
1479}
1480
1481template <typename OpTy>
1482inline match_combine_or<CastClass_match<OpTy, Instruction::SExt>, OpTy>
1483m_SExtOrSelf(const OpTy &Op) {
1484 return m_CombineOr(m_SExt(Op), Op);
1485}
1486
1487template <typename OpTy>
1488inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>,
1489 CastClass_match<OpTy, Instruction::SExt>>
1490m_ZExtOrSExt(const OpTy &Op) {
1491 return m_CombineOr(m_ZExt(Op), m_SExt(Op));
1492}
1493
1494template <typename OpTy>
1495inline match_combine_or<
1496 match_combine_or<CastClass_match<OpTy, Instruction::ZExt>,
1497 CastClass_match<OpTy, Instruction::SExt>>,
1498 OpTy>
1499m_ZExtOrSExtOrSelf(const OpTy &Op) {
1500 return m_CombineOr(m_ZExtOrSExt(Op), Op);
1501}
1502
1503template <typename OpTy>
1504inline CastClass_match<OpTy, Instruction::UIToFP> m_UIToFP(const OpTy &Op) {
1505 return CastClass_match<OpTy, Instruction::UIToFP>(Op);
1506}
1507
1508template <typename OpTy>
1509inline CastClass_match<OpTy, Instruction::SIToFP> m_SIToFP(const OpTy &Op) {
1510 return CastClass_match<OpTy, Instruction::SIToFP>(Op);
1511}
1512
1513template <typename OpTy>
1514inline CastClass_match<OpTy, Instruction::FPToUI> m_FPToUI(const OpTy &Op) {
1515 return CastClass_match<OpTy, Instruction::FPToUI>(Op);
1516}
1517
1518template <typename OpTy>
1519inline CastClass_match<OpTy, Instruction::FPToSI> m_FPToSI(const OpTy &Op) {
1520 return CastClass_match<OpTy, Instruction::FPToSI>(Op);
1521}
1522
1523template <typename OpTy>
1524inline CastClass_match<OpTy, Instruction::FPTrunc> m_FPTrunc(const OpTy &Op) {
1525 return CastClass_match<OpTy, Instruction::FPTrunc>(Op);
1526}
1527
1528template <typename OpTy>
1529inline CastClass_match<OpTy, Instruction::FPExt> m_FPExt(const OpTy &Op) {
1530 return CastClass_match<OpTy, Instruction::FPExt>(Op);
1531}
1532
1533//===----------------------------------------------------------------------===//
1534// Matchers for control flow.
1535//
1536
1537struct br_match {
1538 BasicBlock *&Succ;
1539
1540 br_match(BasicBlock *&Succ) : Succ(Succ) {}
1541
1542 template <typename OpTy> bool match(OpTy *V) {
1543 if (auto *BI = dyn_cast<BranchInst>(V))
1544 if (BI->isUnconditional()) {
1545 Succ = BI->getSuccessor(0);
1546 return true;
1547 }
1548 return false;
1549 }
1550};
1551
1552inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); }
1553
1554template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
1555struct brc_match {
1556 Cond_t Cond;
1557 TrueBlock_t T;
1558 FalseBlock_t F;
1559
1560 brc_match(const Cond_t &C, const TrueBlock_t &t, const FalseBlock_t &f)
1561 : Cond(C), T(t), F(f) {}
1562
1563 template <typename OpTy> bool match(OpTy *V) {
1564 if (auto *BI = dyn_cast<BranchInst>(V))
1565 if (BI->isConditional() && Cond.match(BI->getCondition()))
1566 return T.match(BI->getSuccessor(0)) && F.match(BI->getSuccessor(1));
1567 return false;
1568 }
1569};
1570
1571template <typename Cond_t>
1572inline brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>
1573m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) {
1574 return brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>(
1575 C, m_BasicBlock(T), m_BasicBlock(F));
1576}
1577
1578template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
1579inline brc_match<Cond_t, TrueBlock_t, FalseBlock_t>
1580m_Br(const Cond_t &C, const TrueBlock_t &T, const FalseBlock_t &F) {
1581 return brc_match<Cond_t, TrueBlock_t, FalseBlock_t>(C, T, F);
1582}
1583
1584//===----------------------------------------------------------------------===//
1585// Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y).
1586//
1587
1588template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t,
1589 bool Commutable = false>
1590struct MaxMin_match {
1591 LHS_t L;
1592 RHS_t R;
1593
1594 // The evaluation order is always stable, regardless of Commutability.
1595 // The LHS is always matched first.
1596 MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1597
1598 template <typename OpTy> bool match(OpTy *V) {
1599 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1600 Intrinsic::ID IID = II->getIntrinsicID();
1601 if ((IID == Intrinsic::smax && Pred_t::match(ICmpInst::ICMP_SGT)) ||
1602 (IID == Intrinsic::smin && Pred_t::match(ICmpInst::ICMP_SLT)) ||
1603 (IID == Intrinsic::umax && Pred_t::match(ICmpInst::ICMP_UGT)) ||
1604 (IID == Intrinsic::umin && Pred_t::match(ICmpInst::ICMP_ULT))) {
1605 Value *LHS = II->getOperand(0), *RHS = II->getOperand(1);
1606 return (L.match(LHS) && R.match(RHS)) ||
1607 (Commutable && L.match(RHS) && R.match(LHS));
1608 }
1609 }
1610 // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x".
1611 auto *SI = dyn_cast<SelectInst>(V);
1612 if (!SI)
1613 return false;
1614 auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition());
1615 if (!Cmp)
1616 return false;
1617 // At this point we have a select conditioned on a comparison. Check that
1618 // it is the values returned by the select that are being compared.
1619 Value *TrueVal = SI->getTrueValue();
1620 Value *FalseVal = SI->getFalseValue();
1621 Value *LHS = Cmp->getOperand(0);
1622 Value *RHS = Cmp->getOperand(1);
1623 if ((TrueVal != LHS || FalseVal != RHS) &&
1624 (TrueVal != RHS || FalseVal != LHS))
1625 return false;
1626 typename CmpInst_t::Predicate Pred =
1627 LHS == TrueVal ? Cmp->getPredicate() : Cmp->getInversePredicate();
1628 // Does "(x pred y) ? x : y" represent the desired max/min operation?
1629 if (!Pred_t::match(Pred))
1630 return false;
1631 // It does! Bind the operands.
1632 return (L.match(LHS) && R.match(RHS)) ||
1633 (Commutable && L.match(RHS) && R.match(LHS));
1634 }
1635};
1636
1637/// Helper class for identifying signed max predicates.
1638struct smax_pred_ty {
1639 static bool match(ICmpInst::Predicate Pred) {
1640 return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE;
1641 }
1642};
1643
1644/// Helper class for identifying signed min predicates.
1645struct smin_pred_ty {
1646 static bool match(ICmpInst::Predicate Pred) {
1647 return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE;
1648 }
1649};
1650
1651/// Helper class for identifying unsigned max predicates.
1652struct umax_pred_ty {
1653 static bool match(ICmpInst::Predicate Pred) {
1654 return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE;
1655 }
1656};
1657
1658/// Helper class for identifying unsigned min predicates.
1659struct umin_pred_ty {
1660 static bool match(ICmpInst::Predicate Pred) {
1661 return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE;
1662 }
1663};
1664
1665/// Helper class for identifying ordered max predicates.
1666struct ofmax_pred_ty {
1667 static bool match(FCmpInst::Predicate Pred) {
1668 return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE;
1669 }
1670};
1671
1672/// Helper class for identifying ordered min predicates.
1673struct ofmin_pred_ty {
1674 static bool match(FCmpInst::Predicate Pred) {
1675 return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE;
1676 }
1677};
1678
1679/// Helper class for identifying unordered max predicates.
1680struct ufmax_pred_ty {
1681 static bool match(FCmpInst::Predicate Pred) {
1682 return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE;
1683 }
1684};
1685
1686/// Helper class for identifying unordered min predicates.
1687struct ufmin_pred_ty {
1688 static bool match(FCmpInst::Predicate Pred) {
1689 return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE;
1690 }
1691};
1692
1693template <typename LHS, typename RHS>
1694inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L,
1695 const RHS &R) {
1696 return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R);
1697}
1698
1699template <typename LHS, typename RHS>
1700inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L,
1701 const RHS &R) {
1702 return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R);
1703}
1704
1705template <typename LHS, typename RHS>
1706inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L,
1707 const RHS &R) {
1708 return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R);
1709}
1710
1711template <typename LHS, typename RHS>
1712inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L,
1713 const RHS &R) {
1714 return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R);
1715}
1716
1717template <typename LHS, typename RHS>
1718inline match_combine_or<
1719 match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>,
1720 MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>>,
1721 match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>,
1722 MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>>>
1723m_MaxOrMin(const LHS &L, const RHS &R) {
1724 return m_CombineOr(m_CombineOr(m_SMax(L, R), m_SMin(L, R)),
1725 m_CombineOr(m_UMax(L, R), m_UMin(L, R)));
1726}
1727
1728/// Match an 'ordered' floating point maximum function.
1729/// Floating point has one special value 'NaN'. Therefore, there is no total
1730/// order. However, if we can ignore the 'NaN' value (for example, because of a
1731/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1732/// semantics. In the presence of 'NaN' we have to preserve the original
1733/// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate.
1734///
1735/// max(L, R) iff L and R are not NaN
1736/// m_OrdFMax(L, R) = R iff L or R are NaN
1737template <typename LHS, typename RHS>
1738inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L,
1739 const RHS &R) {
1740 return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R);
1741}
1742
1743/// Match an 'ordered' floating point minimum function.
1744/// Floating point has one special value 'NaN'. Therefore, there is no total
1745/// order. However, if we can ignore the 'NaN' value (for example, because of a
1746/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1747/// semantics. In the presence of 'NaN' we have to preserve the original
1748/// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate.
1749///
1750/// min(L, R) iff L and R are not NaN
1751/// m_OrdFMin(L, R) = R iff L or R are NaN
1752template <typename LHS, typename RHS>
1753inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L,
1754 const RHS &R) {
1755 return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R);
1756}
1757
1758/// Match an 'unordered' floating point maximum function.
1759/// Floating point has one special value 'NaN'. Therefore, there is no total
1760/// order. However, if we can ignore the 'NaN' value (for example, because of a
1761/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1762/// semantics. In the presence of 'NaN' we have to preserve the original
1763/// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate.
1764///
1765/// max(L, R) iff L and R are not NaN
1766/// m_UnordFMax(L, R) = L iff L or R are NaN
1767template <typename LHS, typename RHS>
1768inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>
1769m_UnordFMax(const LHS &L, const RHS &R) {
1770 return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R);
1771}
1772
1773/// Match an 'unordered' floating point minimum function.
1774/// Floating point has one special value 'NaN'. Therefore, there is no total
1775/// order. However, if we can ignore the 'NaN' value (for example, because of a
1776/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1777/// semantics. In the presence of 'NaN' we have to preserve the original
1778/// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate.
1779///
1780/// min(L, R) iff L and R are not NaN
1781/// m_UnordFMin(L, R) = L iff L or R are NaN
1782template <typename LHS, typename RHS>
1783inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>
1784m_UnordFMin(const LHS &L, const RHS &R) {
1785 return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R);
1786}
1787
1788//===----------------------------------------------------------------------===//
1789// Matchers for overflow check patterns: e.g. (a + b) u< a, (a ^ -1) <u b
1790// Note that S might be matched to other instructions than AddInst.
1791//
1792
1793template <typename LHS_t, typename RHS_t, typename Sum_t>
1794struct UAddWithOverflow_match {
1795 LHS_t L;
1796 RHS_t R;
1797 Sum_t S;
1798
1799 UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S)
1800 : L(L), R(R), S(S) {}
1801
1802 template <typename OpTy> bool match(OpTy *V) {
1803 Value *ICmpLHS, *ICmpRHS;
1804 ICmpInst::Predicate Pred;
1805 if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V))
1806 return false;
1807
1808 Value *AddLHS, *AddRHS;
1809 auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS));
1810
1811 // (a + b) u< a, (a + b) u< b
1812 if (Pred == ICmpInst::ICMP_ULT)
1813 if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS))
1814 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
1815
1816 // a >u (a + b), b >u (a + b)
1817 if (Pred == ICmpInst::ICMP_UGT)
1818 if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS))
1819 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
1820
1821 Value *Op1;
1822 auto XorExpr = m_OneUse(m_Xor(m_Value(Op1), m_AllOnes()));
1823 // (a ^ -1) <u b
1824 if (Pred == ICmpInst::ICMP_ULT) {
1825 if (XorExpr.match(ICmpLHS))
1826 return L.match(Op1) && R.match(ICmpRHS) && S.match(ICmpLHS);
1827 }
1828 // b > u (a ^ -1)
1829 if (Pred == ICmpInst::ICMP_UGT) {
1830 if (XorExpr.match(ICmpRHS))
1831 return L.match(Op1) && R.match(ICmpLHS) && S.match(ICmpRHS);
1832 }
1833
1834 // Match special-case for increment-by-1.
1835 if (Pred == ICmpInst::ICMP_EQ) {
1836 // (a + 1) == 0
1837 // (1 + a) == 0
1838 if (AddExpr.match(ICmpLHS) && m_ZeroInt().match(ICmpRHS) &&
1839 (m_One().match(AddLHS) || m_One().match(AddRHS)))
1840 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
1841 // 0 == (a + 1)
1842 // 0 == (1 + a)
1843 if (m_ZeroInt().match(ICmpLHS) && AddExpr.match(ICmpRHS) &&
1844 (m_One().match(AddLHS) || m_One().match(AddRHS)))
1845 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
1846 }
1847
1848 return false;
1849 }
1850};
1851
1852/// Match an icmp instruction checking for unsigned overflow on addition.
1853///
1854/// S is matched to the addition whose result is being checked for overflow, and
1855/// L and R are matched to the LHS and RHS of S.
1856template <typename LHS_t, typename RHS_t, typename Sum_t>
1857UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>
1858m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) {
1859 return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S);
1860}
1861
1862template <typename Opnd_t> struct Argument_match {
1863 unsigned OpI;
1864 Opnd_t Val;
1865
1866 Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {}
1867
1868 template <typename OpTy> bool match(OpTy *V) {
1869 // FIXME: Should likely be switched to use `CallBase`.
1870 if (const auto *CI
15.1
'CI' is non-null
15.1
'CI' is non-null
= dyn_cast<CallInst>(V))
15
'V' is a 'CallInst'
16
Taking true branch
1871 return Val.match(CI->getArgOperand(OpI));
17
Calling 'match_unless::match'
23
Returning from 'match_unless::match'
24
Returning the value 1, which participates in a condition later
1872 return false;
1873 }
1874};
1875
1876/// Match an argument.
1877template <unsigned OpI, typename Opnd_t>
1878inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) {
1879 return Argument_match<Opnd_t>(OpI, Op);
1880}
1881
1882/// Intrinsic matchers.
1883struct IntrinsicID_match {
1884 unsigned ID;
1885
1886 IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {}
1887
1888 template <typename OpTy> bool match(OpTy *V) {
1889 if (const auto *CI
7.1
'CI' is non-null, which participates in a condition later
7.1
'CI' is non-null, which participates in a condition later
= dyn_cast<CallInst>(V))
7
Assuming 'V' is a 'CallInst'
8
Taking true branch
1890 if (const auto *F
8.1
'F' is non-null
8.1
'F' is non-null
= CI->getCalledFunction())
9
Taking true branch
1891 return F->getIntrinsicID() == ID;
10
Assuming the condition is true
11
Returning the value 1, which participates in a condition later
1892 return false;
1893 }
1894};
1895
1896/// Intrinsic matches are combinations of ID matchers, and argument
1897/// matchers. Higher arity matcher are defined recursively in terms of and-ing
1898/// them with lower arity matchers. Here's some convenient typedefs for up to
1899/// several arguments, and more can be added as needed
1900template <typename T0 = void, typename T1 = void, typename T2 = void,
1901 typename T3 = void, typename T4 = void, typename T5 = void,
1902 typename T6 = void, typename T7 = void, typename T8 = void,
1903 typename T9 = void, typename T10 = void>
1904struct m_Intrinsic_Ty;
1905template <typename T0> struct m_Intrinsic_Ty<T0> {
1906 using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>;
1907};
1908template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> {
1909 using Ty =
1910 match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>;
1911};
1912template <typename T0, typename T1, typename T2>
1913struct m_Intrinsic_Ty<T0, T1, T2> {
1914 using Ty =
1915 match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty,
1916 Argument_match<T2>>;
1917};
1918template <typename T0, typename T1, typename T2, typename T3>
1919struct m_Intrinsic_Ty<T0, T1, T2, T3> {
1920 using Ty =
1921 match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty,
1922 Argument_match<T3>>;
1923};
1924
1925template <typename T0, typename T1, typename T2, typename T3, typename T4>
1926struct m_Intrinsic_Ty<T0, T1, T2, T3, T4> {
1927 using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty,
1928 Argument_match<T4>>;
1929};
1930
1931template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5>
1932struct m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5> {
1933 using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty,
1934 Argument_match<T5>>;
1935};
1936
1937/// Match intrinsic calls like this:
1938/// m_Intrinsic<Intrinsic::fabs>(m_Value(X))
1939template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() {
1940 return IntrinsicID_match(IntrID);
1941}
1942
1943template <Intrinsic::ID IntrID, typename T0>
1944inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) {
1945 return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0));
1946}
1947
1948template <Intrinsic::ID IntrID, typename T0, typename T1>
1949inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0,
1950 const T1 &Op1) {
1951 return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1));
1952}
1953
1954template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2>
1955inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty
1956m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) {
1957 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2));
1958}
1959
1960template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
1961 typename T3>
1962inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty
1963m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) {
1964 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3));
1965}
1966
1967template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
1968 typename T3, typename T4>
1969inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty
1970m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3,
1971 const T4 &Op4) {
1972 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3),
1973 m_Argument<4>(Op4));
1974}
1975
1976template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
1977 typename T3, typename T4, typename T5>
1978inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5>::Ty
1979m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3,
1980 const T4 &Op4, const T5 &Op5) {
1981 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3, Op4),
1982 m_Argument<5>(Op5));
1983}
1984
1985// Helper intrinsic matching specializations.
1986template <typename Opnd0>
1987inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BitReverse(const Opnd0 &Op0) {
1988 return m_Intrinsic<Intrinsic::bitreverse>(Op0);
1989}
1990
1991template <typename Opnd0>
1992inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) {
1993 return m_Intrinsic<Intrinsic::bswap>(Op0);
1994}
1995
1996template <typename Opnd0>
1997inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FAbs(const Opnd0 &Op0) {
1998 return m_Intrinsic<Intrinsic::fabs>(Op0);
1999}
2000
2001template <typename Opnd0>
2002inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FCanonicalize(const Opnd0 &Op0) {
2003 return m_Intrinsic<Intrinsic::canonicalize>(Op0);
2004}
2005
2006template <typename Opnd0, typename Opnd1>
2007inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0,
2008 const Opnd1 &Op1) {
2009 return m_Intrinsic<Intrinsic::minnum>(Op0, Op1);
2010}
2011
2012template <typename Opnd0, typename Opnd1>
2013inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0,
2014 const Opnd1 &Op1) {
2015 return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1);
2016}
2017
2018//===----------------------------------------------------------------------===//
2019// Matchers for two-operands operators with the operators in either order
2020//
2021
2022/// Matches a BinaryOperator with LHS and RHS in either order.
2023template <typename LHS, typename RHS>
2024inline AnyBinaryOp_match<LHS, RHS, true> m_c_BinOp(const LHS &L, const RHS &R) {
2025 return AnyBinaryOp_match<LHS, RHS, true>(L, R);
2026}
2027
2028/// Matches an ICmp with a predicate over LHS and RHS in either order.
2029/// Swaps the predicate if operands are commuted.
2030template <typename LHS, typename RHS>
2031inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>
2032m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
2033 return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>(Pred, L,
2034 R);
2035}
2036
2037/// Matches a Add with LHS and RHS in either order.
2038template <typename LHS, typename RHS>
2039inline BinaryOp_match<LHS, RHS, Instruction::Add, true> m_c_Add(const LHS &L,
2040 const RHS &R) {
2041 return BinaryOp_match<LHS, RHS, Instruction::Add, true>(L, R);
2042}
2043
2044/// Matches a Mul with LHS and RHS in either order.
2045template <typename LHS, typename RHS>
2046inline BinaryOp_match<LHS, RHS, Instruction::Mul, true> m_c_Mul(const LHS &L,
2047 const RHS &R) {
2048 return BinaryOp_match<LHS, RHS, Instruction::Mul, true>(L, R);
2049}
2050
2051/// Matches an And with LHS and RHS in either order.
2052template <typename LHS, typename RHS>
2053inline BinaryOp_match<LHS, RHS, Instruction::And, true> m_c_And(const LHS &L,
2054 const RHS &R) {
2055 return BinaryOp_match<LHS, RHS, Instruction::And, true>(L, R);
2056}
2057
2058/// Matches an Or with LHS and RHS in either order.
2059template <typename LHS, typename RHS>
2060inline BinaryOp_match<LHS, RHS, Instruction::Or, true> m_c_Or(const LHS &L,
2061 const RHS &R) {
2062 return BinaryOp_match<LHS, RHS, Instruction::Or, true>(L, R);
2063}
2064
2065/// Matches an Xor with LHS and RHS in either order.
2066template <typename LHS, typename RHS>
2067inline BinaryOp_match<LHS, RHS, Instruction::Xor, true> m_c_Xor(const LHS &L,
2068 const RHS &R) {
2069 return BinaryOp_match<LHS, RHS, Instruction::Xor, true>(L, R);
2070}
2071
2072/// Matches a 'Neg' as 'sub 0, V'.
2073template <typename ValTy>
2074inline BinaryOp_match<cst_pred_ty<is_zero_int>, ValTy, Instruction::Sub>
2075m_Neg(const ValTy &V) {
2076 return m_Sub(m_ZeroInt(), V);
2077}
2078
2079/// Matches a 'Neg' as 'sub nsw 0, V'.
2080template <typename ValTy>
2081inline OverflowingBinaryOp_match<cst_pred_ty<is_zero_int>, ValTy,
2082 Instruction::Sub,
2083 OverflowingBinaryOperator::NoSignedWrap>
2084m_NSWNeg(const ValTy &V) {
2085 return m_NSWSub(m_ZeroInt(), V);
2086}
2087
2088/// Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
2089template <typename ValTy>
2090inline BinaryOp_match<ValTy, cst_pred_ty<is_all_ones>, Instruction::Xor, true>
2091m_Not(const ValTy &V) {
2092 return m_c_Xor(V, m_AllOnes());
2093}
2094
2095/// Matches an SMin with LHS and RHS in either order.
2096template <typename LHS, typename RHS>
2097inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>
2098m_c_SMin(const LHS &L, const RHS &R) {
2099 return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>(L, R);
2100}
2101/// Matches an SMax with LHS and RHS in either order.
2102template <typename LHS, typename RHS>
2103inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>
2104m_c_SMax(const LHS &L, const RHS &R) {
2105 return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>(L, R);
2106}
2107/// Matches a UMin with LHS and RHS in either order.
2108template <typename LHS, typename RHS>
2109inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>
2110m_c_UMin(const LHS &L, const RHS &R) {
2111 return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>(L, R);
2112}
2113/// Matches a UMax with LHS and RHS in either order.
2114template <typename LHS, typename RHS>
2115inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>
2116m_c_UMax(const LHS &L, const RHS &R) {
2117 return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>(L, R);
2118}
2119
2120template <typename LHS, typename RHS>
2121inline match_combine_or<
2122 match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>,
2123 MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>>,
2124 match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>,
2125 MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>>>
2126m_c_MaxOrMin(const LHS &L, const RHS &R) {
2127 return m_CombineOr(m_CombineOr(m_c_SMax(L, R), m_c_SMin(L, R)),
2128 m_CombineOr(m_c_UMax(L, R), m_c_UMin(L, R)));
2129}
2130
2131/// Matches FAdd with LHS and RHS in either order.
2132template <typename LHS, typename RHS>
2133inline BinaryOp_match<LHS, RHS, Instruction::FAdd, true>
2134m_c_FAdd(const LHS &L, const RHS &R) {
2135 return BinaryOp_match<LHS, RHS, Instruction::FAdd, true>(L, R);
2136}
2137
2138/// Matches FMul with LHS and RHS in either order.
2139template <typename LHS, typename RHS>
2140inline BinaryOp_match<LHS, RHS, Instruction::FMul, true>
2141m_c_FMul(const LHS &L, const RHS &R) {
2142 return BinaryOp_match<LHS, RHS, Instruction::FMul, true>(L, R);
2143}
2144
2145template <typename Opnd_t> struct Signum_match {
2146 Opnd_t Val;
2147 Signum_match(const Opnd_t &V) : Val(V) {}
2148
2149 template <typename OpTy> bool match(OpTy *V) {
2150 unsigned TypeSize = V->getType()->getScalarSizeInBits();
2151 if (TypeSize == 0)
2152 return false;
2153
2154 unsigned ShiftWidth = TypeSize - 1;
2155 Value *OpL = nullptr, *OpR = nullptr;
2156
2157 // This is the representation of signum we match:
2158 //
2159 // signum(x) == (x >> 63) | (-x >>u 63)
2160 //
2161 // An i1 value is its own signum, so it's correct to match
2162 //
2163 // signum(x) == (x >> 0) | (-x >>u 0)
2164 //
2165 // for i1 values.
2166
2167 auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth));
2168 auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth));
2169 auto Signum = m_Or(LHS, RHS);
2170
2171 return Signum.match(V) && OpL == OpR && Val.match(OpL);
2172 }
2173};
2174
2175/// Matches a signum pattern.
2176///
2177/// signum(x) =
2178/// x > 0 -> 1
2179/// x == 0 -> 0
2180/// x < 0 -> -1
2181template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) {
2182 return Signum_match<Val_t>(V);
2183}
2184
2185template <int Ind, typename Opnd_t> struct ExtractValue_match {
2186 Opnd_t Val;
2187 ExtractValue_match(const Opnd_t &V) : Val(V) {}
2188
2189 template <typename OpTy> bool match(OpTy *V) {
2190 if (auto *I = dyn_cast<ExtractValueInst>(V))
2191 return I->getNumIndices() == 1 && I->getIndices()[0] == Ind &&
2192 Val.match(I->getAggregateOperand());
2193 return false;
2194 }
2195};
2196
2197/// Match a single index ExtractValue instruction.
2198/// For example m_ExtractValue<1>(...)
2199template <int Ind, typename Val_t>
2200inline ExtractValue_match<Ind, Val_t> m_ExtractValue(const Val_t &V) {
2201 return ExtractValue_match<Ind, Val_t>(V);
2202}
2203
2204/// Matches patterns for `vscale`. This can either be a call to `llvm.vscale` or
2205/// the constant expression
2206/// `ptrtoint(gep <vscale x 1 x i8>, <vscale x 1 x i8>* null, i32 1>`
2207/// under the right conditions determined by DataLayout.
2208struct VScaleVal_match {
2209private:
2210 template <typename Base, typename Offset>
2211 inline BinaryOp_match<Base, Offset, Instruction::GetElementPtr>
2212 m_OffsetGep(const Base &B, const Offset &O) {
2213 return BinaryOp_match<Base, Offset, Instruction::GetElementPtr>(B, O);
2214 }
2215
2216public:
2217 const DataLayout &DL;
2218 VScaleVal_match(const DataLayout &DL) : DL(DL) {}
2219
2220 template <typename ITy> bool match(ITy *V) {
2221 if (m_Intrinsic<Intrinsic::vscale>().match(V))
2222 return true;
2223
2224 if (m_PtrToInt(m_OffsetGep(m_Zero(), m_SpecificInt(1))).match(V)) {
2225 Type *PtrTy = cast<Operator>(V)->getOperand(0)->getType();
2226 auto *DerefTy = PtrTy->getPointerElementType();
2227 if (isa<ScalableVectorType>(DerefTy) &&
2228 DL.getTypeAllocSizeInBits(DerefTy).getKnownMinSize() == 8)
2229 return true;
2230 }
2231
2232 return false;
2233 }
2234};
2235
2236inline VScaleVal_match m_VScale(const DataLayout &DL) {
2237 return VScaleVal_match(DL);
2238}
2239
2240} // end namespace PatternMatch
2241} // end namespace llvm
2242
2243#endif // LLVM_IR_PATTERNMATCH_H