Bug Summary

File:llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp
Warning:line 204, column 33
Called C++ object pointer is uninitialized

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name InstCombineShifts.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 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/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-10/lib/clang/10.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-10~+201911111502510600c19528f1809/build-llvm/lib/Transforms/InstCombine -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-11-181444-25759-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp

1//===- InstCombineShifts.cpp ----------------------------------------------===//
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 implements the visitShl, visitLShr, and visitAShr functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/Analysis/ConstantFolding.h"
15#include "llvm/Analysis/InstructionSimplify.h"
16#include "llvm/IR/IntrinsicInst.h"
17#include "llvm/IR/PatternMatch.h"
18using namespace llvm;
19using namespace PatternMatch;
20
21#define DEBUG_TYPE"instcombine" "instcombine"
22
23// Given pattern:
24// (x shiftopcode Q) shiftopcode K
25// we should rewrite it as
26// x shiftopcode (Q+K) iff (Q+K) u< bitwidth(x)
27// This is valid for any shift, but they must be identical.
28//
29// AnalyzeForSignBitExtraction indicates that we will only analyze whether this
30// pattern has any 2 right-shifts that sum to 1 less than original bit width.
31Value *InstCombiner::reassociateShiftAmtsOfTwoSameDirectionShifts(
32 BinaryOperator *Sh0, const SimplifyQuery &SQ,
33 bool AnalyzeForSignBitExtraction) {
34 // Look for a shift of some instruction, ignore zext of shift amount if any.
35 Instruction *Sh0Op0;
36 Value *ShAmt0;
37 if (!match(Sh0,
38 m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(ShAmt0)))))
39 return nullptr;
40
41 // If there is a truncation between the two shifts, we must make note of it
42 // and look through it. The truncation imposes additional constraints on the
43 // transform.
44 Instruction *Sh1;
45 Value *Trunc = nullptr;
46 match(Sh0Op0,
47 m_CombineOr(m_CombineAnd(m_Trunc(m_Instruction(Sh1)), m_Value(Trunc)),
48 m_Instruction(Sh1)));
49
50 // Inner shift: (x shiftopcode ShAmt1)
51 // Like with other shift, ignore zext of shift amount if any.
52 Value *X, *ShAmt1;
53 if (!match(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(ShAmt1)))))
54 return nullptr;
55
56 // We have two shift amounts from two different shifts. The types of those
57 // shift amounts may not match. If that's the case let's bailout now..
58 if (ShAmt0->getType() != ShAmt1->getType())
59 return nullptr;
60
61 // We are only looking for signbit extraction if we have two right shifts.
62 bool HadTwoRightShifts = match(Sh0, m_Shr(m_Value(), m_Value())) &&
63 match(Sh1, m_Shr(m_Value(), m_Value()));
64 // ... and if it's not two right-shifts, we know the answer already.
65 if (AnalyzeForSignBitExtraction && !HadTwoRightShifts)
66 return nullptr;
67
68 // The shift opcodes must be identical, unless we are just checking whether
69 // this pattern can be interpreted as a sign-bit-extraction.
70 Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode();
71 bool IdenticalShOpcodes = Sh0->getOpcode() == Sh1->getOpcode();
72 if (!IdenticalShOpcodes && !AnalyzeForSignBitExtraction)
73 return nullptr;
74
75 // If we saw truncation, we'll need to produce extra instruction,
76 // and for that one of the operands of the shift must be one-use,
77 // unless of course we don't actually plan to produce any instructions here.
78 if (Trunc && !AnalyzeForSignBitExtraction &&
79 !match(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
80 return nullptr;
81
82 // Can we fold (ShAmt0+ShAmt1) ?
83 auto *NewShAmt = dyn_cast_or_null<Constant>(
84 SimplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false,
85 SQ.getWithInstruction(Sh0)));
86 if (!NewShAmt)
87 return nullptr; // Did not simplify.
88 unsigned NewShAmtBitWidth = NewShAmt->getType()->getScalarSizeInBits();
89 unsigned XBitWidth = X->getType()->getScalarSizeInBits();
90 // Is the new shift amount smaller than the bit width of inner/new shift?
91 if (!match(NewShAmt, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
92 APInt(NewShAmtBitWidth, XBitWidth))))
93 return nullptr; // FIXME: could perform constant-folding.
94
95 // If there was a truncation, and we have a right-shift, we can only fold if
96 // we are left with the original sign bit. Likewise, if we were just checking
97 // that this is a sighbit extraction, this is the place to check it.
98 // FIXME: zero shift amount is also legal here, but we can't *easily* check
99 // more than one predicate so it's not really worth it.
100 if (HadTwoRightShifts && (Trunc || AnalyzeForSignBitExtraction)) {
101 // If it's not a sign bit extraction, then we're done.
102 if (!match(NewShAmt,
103 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
104 APInt(NewShAmtBitWidth, XBitWidth - 1))))
105 return nullptr;
106 // If it is, and that was the question, return the base value.
107 if (AnalyzeForSignBitExtraction)
108 return X;
109 }
110
111 assert(IdenticalShOpcodes && "Should not get here with different shifts.")((IdenticalShOpcodes && "Should not get here with different shifts."
) ? static_cast<void> (0) : __assert_fail ("IdenticalShOpcodes && \"Should not get here with different shifts.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 111, __PRETTY_FUNCTION__))
;
112
113 // All good, we can do this fold.
114 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, X->getType());
115
116 BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt);
117
118 // The flags can only be propagated if there wasn't a trunc.
119 if (!Trunc) {
120 // If the pattern did not involve trunc, and both of the original shifts
121 // had the same flag set, preserve the flag.
122 if (ShiftOpcode == Instruction::BinaryOps::Shl) {
123 NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
124 Sh1->hasNoUnsignedWrap());
125 NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
126 Sh1->hasNoSignedWrap());
127 } else {
128 NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
129 }
130 }
131
132 Instruction *Ret = NewShift;
133 if (Trunc) {
134 Builder.Insert(NewShift);
135 Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType());
136 }
137
138 return Ret;
139}
140
141// If we have some pattern that leaves only some low bits set, and then performs
142// left-shift of those bits, if none of the bits that are left after the final
143// shift are modified by the mask, we can omit the mask.
144//
145// There are many variants to this pattern:
146// a) (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
147// b) (x & (~(-1 << MaskShAmt))) << ShiftShAmt
148// c) (x & (-1 >> MaskShAmt)) << ShiftShAmt
149// d) (x & ((-1 << MaskShAmt) >> MaskShAmt)) << ShiftShAmt
150// e) ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
151// f) ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
152// All these patterns can be simplified to just:
153// x << ShiftShAmt
154// iff:
155// a,b) (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
156// c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
157static Instruction *
158dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
159 const SimplifyQuery &Q,
160 InstCombiner::BuilderTy &Builder) {
161 assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&((OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
"The input must be 'shl'!") ? static_cast<void> (0) : __assert_fail
("OuterShift->getOpcode() == Instruction::BinaryOps::Shl && \"The input must be 'shl'!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 162, __PRETTY_FUNCTION__))
8
Assuming the condition is true
9
'?' condition is true
162 "The input must be 'shl'!")((OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
"The input must be 'shl'!") ? static_cast<void> (0) : __assert_fail
("OuterShift->getOpcode() == Instruction::BinaryOps::Shl && \"The input must be 'shl'!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 162, __PRETTY_FUNCTION__))
;
163
164 Value *Masked, *ShiftShAmt;
10
'ShiftShAmt' declared without an initial value
165 match(OuterShift,
166 m_Shift(m_Value(Masked), m_ZExtOrSelf(m_Value(ShiftShAmt))));
11
Calling 'm_Value'
15
Returning from 'm_Value'
16
Calling 'm_ZExtOrSelf<llvm::PatternMatch::bind_ty<llvm::Value>>'
24
Returning from 'm_ZExtOrSelf<llvm::PatternMatch::bind_ty<llvm::Value>>'
25
Calling 'm_Shift<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::bind_ty<llvm::Value>, 40>, llvm::PatternMatch::bind_ty<llvm::Value> >>'
27
Returning from 'm_Shift<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::bind_ty<llvm::Value>, 40>, llvm::PatternMatch::bind_ty<llvm::Value> >>'
167
168 // *If* there is a truncation between an outer shift and a possibly-mask,
169 // then said truncation *must* be one-use, else we can't perform the fold.
170 Value *Trunc;
171 if (match(Masked, m_CombineAnd(m_Trunc(m_Value(Masked)), m_Value(Trunc))) &&
28
Taking false branch
172 !Trunc->hasOneUse())
173 return nullptr;
174
175 Type *NarrowestTy = OuterShift->getType();
176 Type *WidestTy = Masked->getType();
177 bool HadTrunc = WidestTy != NarrowestTy;
29
Assuming 'WidestTy' is equal to 'NarrowestTy'
178
179 // The mask must be computed in a type twice as wide to ensure
180 // that no bits are lost if the sum-of-shifts is wider than the base type.
181 Type *ExtendedTy = WidestTy->getExtendedType();
182
183 Value *MaskShAmt;
184
185 // ((1 << MaskShAmt) - 1)
186 auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
187 // (~(-1 << maskNbits))
188 auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes());
189 // (-1 >> MaskShAmt)
190 auto MaskC = m_Shr(m_AllOnes(), m_Value(MaskShAmt));
191 // ((-1 << MaskShAmt) >> MaskShAmt)
192 auto MaskD =
193 m_Shr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
194
195 Value *X;
196 Constant *NewMask;
197
198 if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
30
Calling 'match<llvm::Value, llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_one>, llvm::PatternMatch::bind_ty<llvm::Value>, 26, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 14, false>, llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, llvm::PatternMatch::bind_ty<llvm::Value>, 26, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 31, false> >, llvm::PatternMatch::bind_ty<llvm::Value>, 29, true>>'
38
Returning from 'match<llvm::Value, llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_one>, llvm::PatternMatch::bind_ty<llvm::Value>, 26, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 14, false>, llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, llvm::PatternMatch::bind_ty<llvm::Value>, 26, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 31, false> >, llvm::PatternMatch::bind_ty<llvm::Value>, 29, true>>'
39
Taking true branch
199 // Peek through an optional zext of the shift amount.
200 match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
201
202 // We have two shift amounts from two different shifts. The types of those
203 // shift amounts may not match. If that's the case let's bailout now.
204 if (MaskShAmt->getType() != ShiftShAmt->getType())
40
Called C++ object pointer is uninitialized
205 return nullptr;
206
207 // Can we simplify (MaskShAmt+ShiftShAmt) ?
208 auto *SumOfShAmts = dyn_cast_or_null<Constant>(SimplifyAddInst(
209 MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
210 if (!SumOfShAmts)
211 return nullptr; // Did not simplify.
212 // In this pattern SumOfShAmts correlates with the number of low bits
213 // that shall remain in the root value (OuterShift).
214
215 // An extend of an undef value becomes zero because the high bits are never
216 // completely unknown. Replace the the `undef` shift amounts with final
217 // shift bitwidth to ensure that the value remains undef when creating the
218 // subsequent shift op.
219 SumOfShAmts = Constant::replaceUndefsWith(
220 SumOfShAmts, ConstantInt::get(SumOfShAmts->getType()->getScalarType(),
221 ExtendedTy->getScalarSizeInBits()));
222 auto *ExtendedSumOfShAmts = ConstantExpr::getZExt(SumOfShAmts, ExtendedTy);
223 // And compute the mask as usual: ~(-1 << (SumOfShAmts))
224 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
225 auto *ExtendedInvertedMask =
226 ConstantExpr::getShl(ExtendedAllOnes, ExtendedSumOfShAmts);
227 NewMask = ConstantExpr::getNot(ExtendedInvertedMask);
228 } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
229 match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
230 m_Deferred(MaskShAmt)))) {
231 // Peek through an optional zext of the shift amount.
232 match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
233
234 // We have two shift amounts from two different shifts. The types of those
235 // shift amounts may not match. If that's the case let's bailout now.
236 if (MaskShAmt->getType() != ShiftShAmt->getType())
237 return nullptr;
238
239 // Can we simplify (ShiftShAmt-MaskShAmt) ?
240 auto *ShAmtsDiff = dyn_cast_or_null<Constant>(SimplifySubInst(
241 ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
242 if (!ShAmtsDiff)
243 return nullptr; // Did not simplify.
244 // In this pattern ShAmtsDiff correlates with the number of high bits that
245 // shall be unset in the root value (OuterShift).
246
247 // An extend of an undef value becomes zero because the high bits are never
248 // completely unknown. Replace the the `undef` shift amounts with negated
249 // bitwidth of innermost shift to ensure that the value remains undef when
250 // creating the subsequent shift op.
251 unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits();
252 ShAmtsDiff = Constant::replaceUndefsWith(
253 ShAmtsDiff, ConstantInt::get(ShAmtsDiff->getType()->getScalarType(),
254 -WidestTyBitWidth));
255 auto *ExtendedNumHighBitsToClear = ConstantExpr::getZExt(
256 ConstantExpr::getSub(ConstantInt::get(ShAmtsDiff->getType(),
257 WidestTyBitWidth,
258 /*isSigned=*/false),
259 ShAmtsDiff),
260 ExtendedTy);
261 // And compute the mask as usual: (-1 l>> (NumHighBitsToClear))
262 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
263 NewMask =
264 ConstantExpr::getLShr(ExtendedAllOnes, ExtendedNumHighBitsToClear);
265 } else
266 return nullptr; // Don't know anything about this pattern.
267
268 NewMask = ConstantExpr::getTrunc(NewMask, NarrowestTy);
269
270 // Does this mask has any unset bits? If not then we can just not apply it.
271 bool NeedMask = !match(NewMask, m_AllOnes());
272
273 // If we need to apply a mask, there are several more restrictions we have.
274 if (NeedMask) {
275 // The old masking instruction must go away.
276 if (!Masked->hasOneUse())
277 return nullptr;
278 // The original "masking" instruction must not have been`ashr`.
279 if (match(Masked, m_AShr(m_Value(), m_Value())))
280 return nullptr;
281 }
282
283 // If we need to apply truncation, let's do it first, since we can.
284 // We have already ensured that the old truncation will go away.
285 if (HadTrunc)
286 X = Builder.CreateTrunc(X, NarrowestTy);
287
288 // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits.
289 // We didn't change the Type of this outermost shift, so we can just do it.
290 auto *NewShift = BinaryOperator::Create(OuterShift->getOpcode(), X,
291 OuterShift->getOperand(1));
292 if (!NeedMask)
293 return NewShift;
294
295 Builder.Insert(NewShift);
296 return BinaryOperator::Create(Instruction::And, NewShift, NewMask);
297}
298
299/// If we have a shift-by-constant of a bitwise logic op that itself has a
300/// shift-by-constant operand with identical opcode, we may be able to convert
301/// that into 2 independent shifts followed by the logic op. This eliminates a
302/// a use of an intermediate value (reduces dependency chain).
303static Instruction *foldShiftOfShiftedLogic(BinaryOperator &I,
304 InstCombiner::BuilderTy &Builder) {
305 assert(I.isShift() && "Expected a shift as input")((I.isShift() && "Expected a shift as input") ? static_cast
<void> (0) : __assert_fail ("I.isShift() && \"Expected a shift as input\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 305, __PRETTY_FUNCTION__))
;
306 auto *LogicInst = dyn_cast<BinaryOperator>(I.getOperand(0));
307 if (!LogicInst || !LogicInst->isBitwiseLogicOp() || !LogicInst->hasOneUse())
308 return nullptr;
309
310 const APInt *C0, *C1;
311 if (!match(I.getOperand(1), m_APInt(C1)))
312 return nullptr;
313
314 Instruction::BinaryOps ShiftOpcode = I.getOpcode();
315 Type *Ty = I.getType();
316
317 // Find a matching one-use shift by constant. The fold is not valid if the sum
318 // of the shift values equals or exceeds bitwidth.
319 // TODO: Remove the one-use check if the other logic operand (Y) is constant.
320 Value *X, *Y;
321 auto matchFirstShift = [&](Value *V) {
322 return match(V, m_OneUse(m_Shift(m_Value(X), m_APInt(C0)))) &&
323 cast<BinaryOperator>(V)->getOpcode() == ShiftOpcode &&
324 (*C0 + *C1).ult(Ty->getScalarSizeInBits());
325 };
326
327 // Logic ops are commutative, so check each operand for a match.
328 if (matchFirstShift(LogicInst->getOperand(0)))
329 Y = LogicInst->getOperand(1);
330 else if (matchFirstShift(LogicInst->getOperand(1)))
331 Y = LogicInst->getOperand(0);
332 else
333 return nullptr;
334
335 // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
336 Constant *ShiftSumC = ConstantInt::get(Ty, *C0 + *C1);
337 Value *NewShift1 = Builder.CreateBinOp(ShiftOpcode, X, ShiftSumC);
338 Value *NewShift2 = Builder.CreateBinOp(ShiftOpcode, Y, I.getOperand(1));
339 return BinaryOperator::Create(LogicInst->getOpcode(), NewShift1, NewShift2);
340}
341
342Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
343 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
344 assert(Op0->getType() == Op1->getType())((Op0->getType() == Op1->getType()) ? static_cast<void
> (0) : __assert_fail ("Op0->getType() == Op1->getType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 344, __PRETTY_FUNCTION__))
;
345
346 // If the shift amount is a one-use `sext`, we can demote it to `zext`.
347 Value *Y;
348 if (match(Op1, m_OneUse(m_SExt(m_Value(Y))))) {
349 Value *NewExt = Builder.CreateZExt(Y, I.getType(), Op1->getName());
350 return BinaryOperator::Create(I.getOpcode(), Op0, NewExt);
351 }
352
353 // See if we can fold away this shift.
354 if (SimplifyDemandedInstructionBits(I))
355 return &I;
356
357 // Try to fold constant and into select arguments.
358 if (isa<Constant>(Op0))
359 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
360 if (Instruction *R = FoldOpIntoSelect(I, SI))
361 return R;
362
363 if (Constant *CUI = dyn_cast<Constant>(Op1))
364 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
365 return Res;
366
367 if (auto *NewShift = cast_or_null<Instruction>(
368 reassociateShiftAmtsOfTwoSameDirectionShifts(&I, SQ)))
369 return NewShift;
370
371 // (C1 shift (A add C2)) -> (C1 shift C2) shift A)
372 // iff A and C2 are both positive.
373 Value *A;
374 Constant *C;
375 if (match(Op0, m_Constant()) && match(Op1, m_Add(m_Value(A), m_Constant(C))))
376 if (isKnownNonNegative(A, DL, 0, &AC, &I, &DT) &&
377 isKnownNonNegative(C, DL, 0, &AC, &I, &DT))
378 return BinaryOperator::Create(
379 I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), Op0, C), A);
380
381 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
382 // Because shifts by negative values (which could occur if A were negative)
383 // are undefined.
384 const APInt *B;
385 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
386 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
387 // demand the sign bit (and many others) here??
388 Value *Rem = Builder.CreateAnd(A, ConstantInt::get(I.getType(), *B - 1),
389 Op1->getName());
390 I.setOperand(1, Rem);
391 return &I;
392 }
393
394 if (Instruction *Logic = foldShiftOfShiftedLogic(I, Builder))
395 return Logic;
396
397 return nullptr;
398}
399
400/// Return true if we can simplify two logical (either left or right) shifts
401/// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
402static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
403 Instruction *InnerShift, InstCombiner &IC,
404 Instruction *CxtI) {
405 assert(InnerShift->isLogicalShift() && "Unexpected instruction type")((InnerShift->isLogicalShift() && "Unexpected instruction type"
) ? static_cast<void> (0) : __assert_fail ("InnerShift->isLogicalShift() && \"Unexpected instruction type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 405, __PRETTY_FUNCTION__))
;
406
407 // We need constant scalar or constant splat shifts.
408 const APInt *InnerShiftConst;
409 if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
410 return false;
411
412 // Two logical shifts in the same direction:
413 // shl (shl X, C1), C2 --> shl X, C1 + C2
414 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
415 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
416 if (IsInnerShl == IsOuterShl)
417 return true;
418
419 // Equal shift amounts in opposite directions become bitwise 'and':
420 // lshr (shl X, C), C --> and X, C'
421 // shl (lshr X, C), C --> and X, C'
422 if (*InnerShiftConst == OuterShAmt)
423 return true;
424
425 // If the 2nd shift is bigger than the 1st, we can fold:
426 // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3
427 // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
428 // but it isn't profitable unless we know the and'd out bits are already zero.
429 // Also, check that the inner shift is valid (less than the type width) or
430 // we'll crash trying to produce the bit mask for the 'and'.
431 unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
432 if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
433 unsigned InnerShAmt = InnerShiftConst->getZExtValue();
434 unsigned MaskShift =
435 IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
436 APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
437 if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
438 return true;
439 }
440
441 return false;
442}
443
444/// See if we can compute the specified value, but shifted logically to the left
445/// or right by some number of bits. This should return true if the expression
446/// can be computed for the same cost as the current expression tree. This is
447/// used to eliminate extraneous shifting from things like:
448/// %C = shl i128 %A, 64
449/// %D = shl i128 %B, 96
450/// %E = or i128 %C, %D
451/// %F = lshr i128 %E, 64
452/// where the client will ask if E can be computed shifted right by 64-bits. If
453/// this succeeds, getShiftedValue() will be called to produce the value.
454static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
455 InstCombiner &IC, Instruction *CxtI) {
456 // We can always evaluate constants shifted.
457 if (isa<Constant>(V))
458 return true;
459
460 Instruction *I = dyn_cast<Instruction>(V);
461 if (!I) return false;
462
463 // If this is the opposite shift, we can directly reuse the input of the shift
464 // if the needed bits are already zero in the input. This allows us to reuse
465 // the value which means that we don't care if the shift has multiple uses.
466 // TODO: Handle opposite shift by exact value.
467 ConstantInt *CI = nullptr;
468 if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
469 (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
470 if (CI->getValue() == NumBits) {
471 // TODO: Check that the input bits are already zero with MaskedValueIsZero
472#if 0
473 // If this is a truncate of a logical shr, we can truncate it to a smaller
474 // lshr iff we know that the bits we would otherwise be shifting in are
475 // already zeros.
476 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
477 uint32_t BitWidth = Ty->getScalarSizeInBits();
478 if (MaskedValueIsZero(I->getOperand(0),
479 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
480 CI->getLimitedValue(BitWidth) < BitWidth) {
481 return CanEvaluateTruncated(I->getOperand(0), Ty);
482 }
483#endif
484
485 }
486 }
487
488 // We can't mutate something that has multiple uses: doing so would
489 // require duplicating the instruction in general, which isn't profitable.
490 if (!I->hasOneUse()) return false;
491
492 switch (I->getOpcode()) {
493 default: return false;
494 case Instruction::And:
495 case Instruction::Or:
496 case Instruction::Xor:
497 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
498 return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
499 canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
500
501 case Instruction::Shl:
502 case Instruction::LShr:
503 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
504
505 case Instruction::Select: {
506 SelectInst *SI = cast<SelectInst>(I);
507 Value *TrueVal = SI->getTrueValue();
508 Value *FalseVal = SI->getFalseValue();
509 return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
510 canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
511 }
512 case Instruction::PHI: {
513 // We can change a phi if we can change all operands. Note that we never
514 // get into trouble with cyclic PHIs here because we only consider
515 // instructions with a single use.
516 PHINode *PN = cast<PHINode>(I);
517 for (Value *IncValue : PN->incoming_values())
518 if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
519 return false;
520 return true;
521 }
522 }
523}
524
525/// Fold OuterShift (InnerShift X, C1), C2.
526/// See canEvaluateShiftedShift() for the constraints on these instructions.
527static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
528 bool IsOuterShl,
529 InstCombiner::BuilderTy &Builder) {
530 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
531 Type *ShType = InnerShift->getType();
532 unsigned TypeWidth = ShType->getScalarSizeInBits();
533
534 // We only accept shifts-by-a-constant in canEvaluateShifted().
535 const APInt *C1;
536 match(InnerShift->getOperand(1), m_APInt(C1));
537 unsigned InnerShAmt = C1->getZExtValue();
538
539 // Change the shift amount and clear the appropriate IR flags.
540 auto NewInnerShift = [&](unsigned ShAmt) {
541 InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
542 if (IsInnerShl) {
543 InnerShift->setHasNoUnsignedWrap(false);
544 InnerShift->setHasNoSignedWrap(false);
545 } else {
546 InnerShift->setIsExact(false);
547 }
548 return InnerShift;
549 };
550
551 // Two logical shifts in the same direction:
552 // shl (shl X, C1), C2 --> shl X, C1 + C2
553 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
554 if (IsInnerShl == IsOuterShl) {
555 // If this is an oversized composite shift, then unsigned shifts get 0.
556 if (InnerShAmt + OuterShAmt >= TypeWidth)
557 return Constant::getNullValue(ShType);
558
559 return NewInnerShift(InnerShAmt + OuterShAmt);
560 }
561
562 // Equal shift amounts in opposite directions become bitwise 'and':
563 // lshr (shl X, C), C --> and X, C'
564 // shl (lshr X, C), C --> and X, C'
565 if (InnerShAmt == OuterShAmt) {
566 APInt Mask = IsInnerShl
567 ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
568 : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
569 Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
570 ConstantInt::get(ShType, Mask));
571 if (auto *AndI = dyn_cast<Instruction>(And)) {
572 AndI->moveBefore(InnerShift);
573 AndI->takeName(InnerShift);
574 }
575 return And;
576 }
577
578 assert(InnerShAmt > OuterShAmt &&((InnerShAmt > OuterShAmt && "Unexpected opposite direction logical shift pair"
) ? static_cast<void> (0) : __assert_fail ("InnerShAmt > OuterShAmt && \"Unexpected opposite direction logical shift pair\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 579, __PRETTY_FUNCTION__))
579 "Unexpected opposite direction logical shift pair")((InnerShAmt > OuterShAmt && "Unexpected opposite direction logical shift pair"
) ? static_cast<void> (0) : __assert_fail ("InnerShAmt > OuterShAmt && \"Unexpected opposite direction logical shift pair\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 579, __PRETTY_FUNCTION__))
;
580
581 // In general, we would need an 'and' for this transform, but
582 // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
583 // lshr (shl X, C1), C2 --> shl X, C1 - C2
584 // shl (lshr X, C1), C2 --> lshr X, C1 - C2
585 return NewInnerShift(InnerShAmt - OuterShAmt);
586}
587
588/// When canEvaluateShifted() returns true for an expression, this function
589/// inserts the new computation that produces the shifted value.
590static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
591 InstCombiner &IC, const DataLayout &DL) {
592 // We can always evaluate constants shifted.
593 if (Constant *C = dyn_cast<Constant>(V)) {
594 if (isLeftShift)
595 V = IC.Builder.CreateShl(C, NumBits);
596 else
597 V = IC.Builder.CreateLShr(C, NumBits);
598 // If we got a constantexpr back, try to simplify it with TD info.
599 if (auto *C = dyn_cast<Constant>(V))
600 if (auto *FoldedC =
601 ConstantFoldConstant(C, DL, &IC.getTargetLibraryInfo()))
602 V = FoldedC;
603 return V;
604 }
605
606 Instruction *I = cast<Instruction>(V);
607 IC.Worklist.Add(I);
608
609 switch (I->getOpcode()) {
610 default: llvm_unreachable("Inconsistency with CanEvaluateShifted")::llvm::llvm_unreachable_internal("Inconsistency with CanEvaluateShifted"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 610)
;
611 case Instruction::And:
612 case Instruction::Or:
613 case Instruction::Xor:
614 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
615 I->setOperand(
616 0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
617 I->setOperand(
618 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
619 return I;
620
621 case Instruction::Shl:
622 case Instruction::LShr:
623 return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
624 IC.Builder);
625
626 case Instruction::Select:
627 I->setOperand(
628 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
629 I->setOperand(
630 2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
631 return I;
632 case Instruction::PHI: {
633 // We can change a phi if we can change all operands. Note that we never
634 // get into trouble with cyclic PHIs here because we only consider
635 // instructions with a single use.
636 PHINode *PN = cast<PHINode>(I);
637 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
638 PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
639 isLeftShift, IC, DL));
640 return PN;
641 }
642 }
643}
644
645// If this is a bitwise operator or add with a constant RHS we might be able
646// to pull it through a shift.
647static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift,
648 BinaryOperator *BO) {
649 switch (BO->getOpcode()) {
650 default:
651 return false; // Do not perform transform!
652 case Instruction::Add:
653 return Shift.getOpcode() == Instruction::Shl;
654 case Instruction::Or:
655 case Instruction::Xor:
656 case Instruction::And:
657 return true;
658 }
659}
660
661Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
662 BinaryOperator &I) {
663 bool isLeftShift = I.getOpcode() == Instruction::Shl;
664
665 const APInt *Op1C;
666 if (!match(Op1, m_APInt(Op1C)))
667 return nullptr;
668
669 // See if we can propagate this shift into the input, this covers the trivial
670 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
671 if (I.getOpcode() != Instruction::AShr &&
672 canEvaluateShifted(Op0, Op1C->getZExtValue(), isLeftShift, *this, &I)) {
673 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "ICE: GetShiftedValue propagating shift through expression"
" to eliminate shift:\n IN: " << *Op0 << "\n SH: "
<< I << "\n"; } } while (false)
674 dbgs() << "ICE: GetShiftedValue propagating shift through expression"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "ICE: GetShiftedValue propagating shift through expression"
" to eliminate shift:\n IN: " << *Op0 << "\n SH: "
<< I << "\n"; } } while (false)
675 " to eliminate shift:\n IN: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "ICE: GetShiftedValue propagating shift through expression"
" to eliminate shift:\n IN: " << *Op0 << "\n SH: "
<< I << "\n"; } } while (false)
676 << *Op0 << "\n SH: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "ICE: GetShiftedValue propagating shift through expression"
" to eliminate shift:\n IN: " << *Op0 << "\n SH: "
<< I << "\n"; } } while (false)
;
677
678 return replaceInstUsesWith(
679 I, getShiftedValue(Op0, Op1C->getZExtValue(), isLeftShift, *this, DL));
680 }
681
682 // See if we can simplify any instructions used by the instruction whose sole
683 // purpose is to compute bits we don't care about.
684 unsigned TypeBits = Op0->getType()->getScalarSizeInBits();
685
686 assert(!Op1C->uge(TypeBits) &&((!Op1C->uge(TypeBits) && "Shift over the type width should have been removed already"
) ? static_cast<void> (0) : __assert_fail ("!Op1C->uge(TypeBits) && \"Shift over the type width should have been removed already\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 687, __PRETTY_FUNCTION__))
687 "Shift over the type width should have been removed already")((!Op1C->uge(TypeBits) && "Shift over the type width should have been removed already"
) ? static_cast<void> (0) : __assert_fail ("!Op1C->uge(TypeBits) && \"Shift over the type width should have been removed already\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 687, __PRETTY_FUNCTION__))
;
688
689 if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
690 return FoldedShift;
691
692 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
693 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
694 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
695 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
696 // place. Don't try to do this transformation in this case. Also, we
697 // require that the input operand is a shift-by-constant so that we have
698 // confidence that the shifts will get folded together. We could do this
699 // xform in more cases, but it is unlikely to be profitable.
700 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
701 isa<ConstantInt>(TrOp->getOperand(1))) {
702 // Okay, we'll do this xform. Make the shift of shift.
703 Constant *ShAmt =
704 ConstantExpr::getZExt(cast<Constant>(Op1), TrOp->getType());
705 // (shift2 (shift1 & 0x00FF), c2)
706 Value *NSh = Builder.CreateBinOp(I.getOpcode(), TrOp, ShAmt, I.getName());
707
708 // For logical shifts, the truncation has the effect of making the high
709 // part of the register be zeros. Emulate this by inserting an AND to
710 // clear the top bits as needed. This 'and' will usually be zapped by
711 // other xforms later if dead.
712 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
713 unsigned DstSize = TI->getType()->getScalarSizeInBits();
714 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
715
716 // The mask we constructed says what the trunc would do if occurring
717 // between the shifts. We want to know the effect *after* the second
718 // shift. We know that it is a logical shift by a constant, so adjust the
719 // mask as appropriate.
720 if (I.getOpcode() == Instruction::Shl)
721 MaskV <<= Op1C->getZExtValue();
722 else {
723 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift")((I.getOpcode() == Instruction::LShr && "Unknown logical shift"
) ? static_cast<void> (0) : __assert_fail ("I.getOpcode() == Instruction::LShr && \"Unknown logical shift\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 723, __PRETTY_FUNCTION__))
;
724 MaskV.lshrInPlace(Op1C->getZExtValue());
725 }
726
727 // shift1 & 0x00FF
728 Value *And = Builder.CreateAnd(NSh,
729 ConstantInt::get(I.getContext(), MaskV),
730 TI->getName());
731
732 // Return the value truncated to the interesting size.
733 return new TruncInst(And, I.getType());
734 }
735 }
736
737 if (Op0->hasOneUse()) {
738 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
739 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
740 Value *V1, *V2;
741 ConstantInt *CC;
742 switch (Op0BO->getOpcode()) {
743 default: break;
744 case Instruction::Add:
745 case Instruction::And:
746 case Instruction::Or:
747 case Instruction::Xor: {
748 // These operators commute.
749 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
750 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
751 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
752 m_Specific(Op1)))) {
753 Value *YS = // (Y << C)
754 Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
755 // (X + (Y << C))
756 Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), YS, V1,
757 Op0BO->getOperand(1)->getName());
758 unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
759
760 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
761 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
762 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
763 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
764 return BinaryOperator::CreateAnd(X, Mask);
765 }
766
767 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
768 Value *Op0BOOp1 = Op0BO->getOperand(1);
769 if (isLeftShift && Op0BOOp1->hasOneUse() &&
770 match(Op0BOOp1,
771 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
772 m_ConstantInt(CC)))) {
773 Value *YS = // (Y << C)
774 Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
775 // X & (CC << C)
776 Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
777 V1->getName()+".mask");
778 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
779 }
780 LLVM_FALLTHROUGH[[gnu::fallthrough]];
781 }
782
783 case Instruction::Sub: {
784 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
785 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
786 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
787 m_Specific(Op1)))) {
788 Value *YS = // (Y << C)
789 Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
790 // (X + (Y << C))
791 Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), V1, YS,
792 Op0BO->getOperand(0)->getName());
793 unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
794
795 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
796 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
797 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
798 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
799 return BinaryOperator::CreateAnd(X, Mask);
800 }
801
802 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
803 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
804 match(Op0BO->getOperand(0),
805 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
806 m_ConstantInt(CC))) && V2 == Op1) {
807 Value *YS = // (Y << C)
808 Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
809 // X & (CC << C)
810 Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
811 V1->getName()+".mask");
812
813 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
814 }
815
816 break;
817 }
818 }
819
820
821 // If the operand is a bitwise operator with a constant RHS, and the
822 // shift is the only use, we can pull it out of the shift.
823 const APInt *Op0C;
824 if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
825 if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
826 Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
827 cast<Constant>(Op0BO->getOperand(1)), Op1);
828
829 Value *NewShift =
830 Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
831 NewShift->takeName(Op0BO);
832
833 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
834 NewRHS);
835 }
836 }
837
838 // If the operand is a subtract with a constant LHS, and the shift
839 // is the only use, we can pull it out of the shift.
840 // This folds (shl (sub C1, X), C2) -> (sub (C1 << C2), (shl X, C2))
841 if (isLeftShift && Op0BO->getOpcode() == Instruction::Sub &&
842 match(Op0BO->getOperand(0), m_APInt(Op0C))) {
843 Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
844 cast<Constant>(Op0BO->getOperand(0)), Op1);
845
846 Value *NewShift = Builder.CreateShl(Op0BO->getOperand(1), Op1);
847 NewShift->takeName(Op0BO);
848
849 return BinaryOperator::CreateSub(NewRHS, NewShift);
850 }
851 }
852
853 // If we have a select that conditionally executes some binary operator,
854 // see if we can pull it the select and operator through the shift.
855 //
856 // For example, turning:
857 // shl (select C, (add X, C1), X), C2
858 // Into:
859 // Y = shl X, C2
860 // select C, (add Y, C1 << C2), Y
861 Value *Cond;
862 BinaryOperator *TBO;
863 Value *FalseVal;
864 if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
865 m_Value(FalseVal)))) {
866 const APInt *C;
867 if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
868 match(TBO->getOperand(1), m_APInt(C)) &&
869 canShiftBinOpWithConstantRHS(I, TBO)) {
870 Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
871 cast<Constant>(TBO->getOperand(1)), Op1);
872
873 Value *NewShift =
874 Builder.CreateBinOp(I.getOpcode(), FalseVal, Op1);
875 Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift,
876 NewRHS);
877 return SelectInst::Create(Cond, NewOp, NewShift);
878 }
879 }
880
881 BinaryOperator *FBO;
882 Value *TrueVal;
883 if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
884 m_OneUse(m_BinOp(FBO))))) {
885 const APInt *C;
886 if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
887 match(FBO->getOperand(1), m_APInt(C)) &&
888 canShiftBinOpWithConstantRHS(I, FBO)) {
889 Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
890 cast<Constant>(FBO->getOperand(1)), Op1);
891
892 Value *NewShift =
893 Builder.CreateBinOp(I.getOpcode(), TrueVal, Op1);
894 Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift,
895 NewRHS);
896 return SelectInst::Create(Cond, NewShift, NewOp);
897 }
898 }
899 }
900
901 return nullptr;
902}
903
904Instruction *InstCombiner::visitShl(BinaryOperator &I) {
905 const SimplifyQuery Q = SQ.getWithInstruction(&I);
906
907 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
1
Assuming 'V' is null
2
Taking false branch
908 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q))
909 return replaceInstUsesWith(I, V);
910
911 if (Instruction *X = foldVectorBinop(I))
3
Assuming 'X' is null
4
Taking false branch
912 return X;
913
914 if (Instruction *V = commonShiftTransforms(I))
5
Assuming 'V' is null
6
Taking false branch
915 return V;
916
917 if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, Q, Builder))
7
Calling 'dropRedundantMaskingOfLeftShiftInput'
918 return V;
919
920 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
921 Type *Ty = I.getType();
922 unsigned BitWidth = Ty->getScalarSizeInBits();
923
924 const APInt *ShAmtAPInt;
925 if (match(Op1, m_APInt(ShAmtAPInt))) {
926 unsigned ShAmt = ShAmtAPInt->getZExtValue();
927
928 // shl (zext X), ShAmt --> zext (shl X, ShAmt)
929 // This is only valid if X would have zeros shifted out.
930 Value *X;
931 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
932 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
933 if (ShAmt < SrcWidth &&
934 MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I))
935 return new ZExtInst(Builder.CreateShl(X, ShAmt), Ty);
936 }
937
938 // (X >> C) << C --> X & (-1 << C)
939 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
940 APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt));
941 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
942 }
943
944 // FIXME: we do not yet transform non-exact shr's. The backend (DAGCombine)
945 // needs a few fixes for the rotate pattern recognition first.
946 const APInt *ShOp1;
947 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(ShOp1))))) {
948 unsigned ShrAmt = ShOp1->getZExtValue();
949 if (ShrAmt < ShAmt) {
950 // If C1 < C2: (X >>?,exact C1) << C2 --> X << (C2 - C1)
951 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShrAmt);
952 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
953 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
954 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
955 return NewShl;
956 }
957 if (ShrAmt > ShAmt) {
958 // If C1 > C2: (X >>?exact C1) << C2 --> X >>?exact (C1 - C2)
959 Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmt);
960 auto *NewShr = BinaryOperator::Create(
961 cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
962 NewShr->setIsExact(true);
963 return NewShr;
964 }
965 }
966
967 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1)))) {
968 unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
969 // Oversized shifts are simplified to zero in InstSimplify.
970 if (AmtSum < BitWidth)
971 // (X << C1) << C2 --> X << (C1 + C2)
972 return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
973 }
974
975 // If the shifted-out value is known-zero, then this is a NUW shift.
976 if (!I.hasNoUnsignedWrap() &&
977 MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmt), 0, &I)) {
978 I.setHasNoUnsignedWrap();
979 return &I;
980 }
981
982 // If the shifted-out value is all signbits, then this is a NSW shift.
983 if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) {
984 I.setHasNoSignedWrap();
985 return &I;
986 }
987 }
988
989 // Transform (x >> y) << y to x & (-1 << y)
990 // Valid for any type of right-shift.
991 Value *X;
992 if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
993 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
994 Value *Mask = Builder.CreateShl(AllOnes, Op1);
995 return BinaryOperator::CreateAnd(Mask, X);
996 }
997
998 Constant *C1;
999 if (match(Op1, m_Constant(C1))) {
1000 Constant *C2;
1001 Value *X;
1002 // (C2 << X) << C1 --> (C2 << C1) << X
1003 if (match(Op0, m_OneUse(m_Shl(m_Constant(C2), m_Value(X)))))
1004 return BinaryOperator::CreateShl(ConstantExpr::getShl(C2, C1), X);
1005
1006 // (X * C2) << C1 --> X * (C2 << C1)
1007 if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
1008 return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1));
1009
1010 // shl (zext i1 X), C1 --> select (X, 1 << C1, 0)
1011 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1012 auto *NewC = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C1);
1013 return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty));
1014 }
1015 }
1016
1017 // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
1018 if (match(Op0, m_One()) &&
1019 match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
1020 return BinaryOperator::CreateLShr(
1021 ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
1022
1023 return nullptr;
1024}
1025
1026Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
1027 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1028 SQ.getWithInstruction(&I)))
1029 return replaceInstUsesWith(I, V);
1030
1031 if (Instruction *X = foldVectorBinop(I))
1032 return X;
1033
1034 if (Instruction *R = commonShiftTransforms(I))
1035 return R;
1036
1037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1038 Type *Ty = I.getType();
1039 const APInt *ShAmtAPInt;
1040 if (match(Op1, m_APInt(ShAmtAPInt))) {
1041 unsigned ShAmt = ShAmtAPInt->getZExtValue();
1042 unsigned BitWidth = Ty->getScalarSizeInBits();
1043 auto *II = dyn_cast<IntrinsicInst>(Op0);
1044 if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt &&
1045 (II->getIntrinsicID() == Intrinsic::ctlz ||
1046 II->getIntrinsicID() == Intrinsic::cttz ||
1047 II->getIntrinsicID() == Intrinsic::ctpop)) {
1048 // ctlz.i32(x)>>5 --> zext(x == 0)
1049 // cttz.i32(x)>>5 --> zext(x == 0)
1050 // ctpop.i32(x)>>5 --> zext(x == -1)
1051 bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
1052 Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
1053 Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
1054 return new ZExtInst(Cmp, Ty);
1055 }
1056
1057 Value *X;
1058 const APInt *ShOp1;
1059 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1))) && ShOp1->ult(BitWidth)) {
1060 if (ShOp1->ult(ShAmt)) {
1061 unsigned ShlAmt = ShOp1->getZExtValue();
1062 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1063 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1064 // (X <<nuw C1) >>u C2 --> X >>u (C2 - C1)
1065 auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
1066 NewLShr->setIsExact(I.isExact());
1067 return NewLShr;
1068 }
1069 // (X << C1) >>u C2 --> (X >>u (C2 - C1)) & (-1 >> C2)
1070 Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
1071 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
1072 return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
1073 }
1074 if (ShOp1->ugt(ShAmt)) {
1075 unsigned ShlAmt = ShOp1->getZExtValue();
1076 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1077 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1078 // (X <<nuw C1) >>u C2 --> X <<nuw (C1 - C2)
1079 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1080 NewShl->setHasNoUnsignedWrap(true);
1081 return NewShl;
1082 }
1083 // (X << C1) >>u C2 --> X << (C1 - C2) & (-1 >> C2)
1084 Value *NewShl = Builder.CreateShl(X, ShiftDiff);
1085 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
1086 return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1087 }
1088 assert(*ShOp1 == ShAmt)((*ShOp1 == ShAmt) ? static_cast<void> (0) : __assert_fail
("*ShOp1 == ShAmt", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 1088, __PRETTY_FUNCTION__))
;
1089 // (X << C) >>u C --> X & (-1 >>u C)
1090 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
1091 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
1092 }
1093
1094 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
1095 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1096 assert(ShAmt < X->getType()->getScalarSizeInBits() &&((ShAmt < X->getType()->getScalarSizeInBits() &&
"Big shift not simplified to zero?") ? static_cast<void>
(0) : __assert_fail ("ShAmt < X->getType()->getScalarSizeInBits() && \"Big shift not simplified to zero?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 1097, __PRETTY_FUNCTION__))
1097 "Big shift not simplified to zero?")((ShAmt < X->getType()->getScalarSizeInBits() &&
"Big shift not simplified to zero?") ? static_cast<void>
(0) : __assert_fail ("ShAmt < X->getType()->getScalarSizeInBits() && \"Big shift not simplified to zero?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 1097, __PRETTY_FUNCTION__))
;
1098 // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
1099 Value *NewLShr = Builder.CreateLShr(X, ShAmt);
1100 return new ZExtInst(NewLShr, Ty);
1101 }
1102
1103 if (match(Op0, m_SExt(m_Value(X))) &&
1104 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1105 // Are we moving the sign bit to the low bit and widening with high zeros?
1106 unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
1107 if (ShAmt == BitWidth - 1) {
1108 // lshr (sext i1 X to iN), N-1 --> zext X to iN
1109 if (SrcTyBitWidth == 1)
1110 return new ZExtInst(X, Ty);
1111
1112 // lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
1113 if (Op0->hasOneUse()) {
1114 Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
1115 return new ZExtInst(NewLShr, Ty);
1116 }
1117 }
1118
1119 // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
1120 if (ShAmt == BitWidth - SrcTyBitWidth && Op0->hasOneUse()) {
1121 // The new shift amount can't be more than the narrow source type.
1122 unsigned NewShAmt = std::min(ShAmt, SrcTyBitWidth - 1);
1123 Value *AShr = Builder.CreateAShr(X, NewShAmt);
1124 return new ZExtInst(AShr, Ty);
1125 }
1126 }
1127
1128 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShOp1)))) {
1129 unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1130 // Oversized shifts are simplified to zero in InstSimplify.
1131 if (AmtSum < BitWidth)
1132 // (X >>u C1) >>u C2 --> X >>u (C1 + C2)
1133 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
1134 }
1135
1136 // If the shifted-out value is known-zero, then this is an exact shift.
1137 if (!I.isExact() &&
1138 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1139 I.setIsExact();
1140 return &I;
1141 }
1142 }
1143
1144 // Transform (x << y) >> y to x & (-1 >> y)
1145 Value *X;
1146 if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
1147 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1148 Value *Mask = Builder.CreateLShr(AllOnes, Op1);
1149 return BinaryOperator::CreateAnd(Mask, X);
1150 }
1151
1152 return nullptr;
1153}
1154
1155Instruction *
1156InstCombiner::foldVariableSignZeroExtensionOfVariableHighBitExtract(
1157 BinaryOperator &OldAShr) {
1158 assert(OldAShr.getOpcode() == Instruction::AShr &&((OldAShr.getOpcode() == Instruction::AShr && "Must be called with arithmetic right-shift instruction only."
) ? static_cast<void> (0) : __assert_fail ("OldAShr.getOpcode() == Instruction::AShr && \"Must be called with arithmetic right-shift instruction only.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 1159, __PRETTY_FUNCTION__))
1159 "Must be called with arithmetic right-shift instruction only.")((OldAShr.getOpcode() == Instruction::AShr && "Must be called with arithmetic right-shift instruction only."
) ? static_cast<void> (0) : __assert_fail ("OldAShr.getOpcode() == Instruction::AShr && \"Must be called with arithmetic right-shift instruction only.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp"
, 1159, __PRETTY_FUNCTION__))
;
1160
1161 // Check that constant C is a splat of the element-wise bitwidth of V.
1162 auto BitWidthSplat = [](Constant *C, Value *V) {
1163 return match(
1164 C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1165 APInt(C->getType()->getScalarSizeInBits(),
1166 V->getType()->getScalarSizeInBits())));
1167 };
1168
1169 // It should look like variable-length sign-extension on the outside:
1170 // (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits)
1171 Value *NBits;
1172 Instruction *MaybeTrunc;
1173 Constant *C1, *C2;
1174 if (!match(&OldAShr,
1175 m_AShr(m_Shl(m_Instruction(MaybeTrunc),
1176 m_ZExtOrSelf(m_Sub(m_Constant(C1),
1177 m_ZExtOrSelf(m_Value(NBits))))),
1178 m_ZExtOrSelf(m_Sub(m_Constant(C2),
1179 m_ZExtOrSelf(m_Deferred(NBits)))))) ||
1180 !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr))
1181 return nullptr;
1182
1183 // There may or may not be a truncation after outer two shifts.
1184 Instruction *HighBitExtract;
1185 match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract)));
1186 bool HadTrunc = MaybeTrunc != HighBitExtract;
1187
1188 // And finally, the innermost part of the pattern must be a right-shift.
1189 Value *X, *NumLowBitsToSkip;
1190 if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip))))
1191 return nullptr;
1192
1193 // Said right-shift must extract high NBits bits - C0 must be it's bitwidth.
1194 Constant *C0;
1195 if (!match(NumLowBitsToSkip,
1196 m_ZExtOrSelf(
1197 m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) ||
1198 !BitWidthSplat(C0, HighBitExtract))
1199 return nullptr;
1200
1201 // Since the NBits is identical for all shifts, if the outermost and
1202 // innermost shifts are identical, then outermost shifts are redundant.
1203 // If we had truncation, do keep it though.
1204 if (HighBitExtract->getOpcode() == OldAShr.getOpcode())
1205 return replaceInstUsesWith(OldAShr, MaybeTrunc);
1206
1207 // Else, if there was a truncation, then we need to ensure that one
1208 // instruction will go away.
1209 if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1210 return nullptr;
1211
1212 // Finally, bypass two innermost shifts, and perform the outermost shift on
1213 // the operands of the innermost shift.
1214 Instruction *NewAShr =
1215 BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip);
1216 NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness.
1217 if (!HadTrunc)
1218 return NewAShr;
1219
1220 Builder.Insert(NewAShr);
1221 return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType());
1222}
1223
1224Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
1225 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1226 SQ.getWithInstruction(&I)))
1227 return replaceInstUsesWith(I, V);
1228
1229 if (Instruction *X = foldVectorBinop(I))
1230 return X;
1231
1232 if (Instruction *R = commonShiftTransforms(I))
1233 return R;
1234
1235 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1236 Type *Ty = I.getType();
1237 unsigned BitWidth = Ty->getScalarSizeInBits();
1238 const APInt *ShAmtAPInt;
1239 if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1240 unsigned ShAmt = ShAmtAPInt->getZExtValue();
1241
1242 // If the shift amount equals the difference in width of the destination
1243 // and source scalar types:
1244 // ashr (shl (zext X), C), C --> sext X
1245 Value *X;
1246 if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1247 ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1248 return new SExtInst(X, Ty);
1249
1250 // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1251 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1252 const APInt *ShOp1;
1253 if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1254 ShOp1->ult(BitWidth)) {
1255 unsigned ShlAmt = ShOp1->getZExtValue();
1256 if (ShlAmt < ShAmt) {
1257 // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1258 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1259 auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1260 NewAShr->setIsExact(I.isExact());
1261 return NewAShr;
1262 }
1263 if (ShlAmt > ShAmt) {
1264 // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1265 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1266 auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1267 NewShl->setHasNoSignedWrap(true);
1268 return NewShl;
1269 }
1270 }
1271
1272 if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1273 ShOp1->ult(BitWidth)) {
1274 unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1275 // Oversized arithmetic shifts replicate the sign bit.
1276 AmtSum = std::min(AmtSum, BitWidth - 1);
1277 // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1278 return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1279 }
1280
1281 if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1282 (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1283 // ashr (sext X), C --> sext (ashr X, C')
1284 Type *SrcTy = X->getType();
1285 ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1286 Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1287 return new SExtInst(NewSh, Ty);
1288 }
1289
1290 // If the shifted-out value is known-zero, then this is an exact shift.
1291 if (!I.isExact() &&
1292 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1293 I.setIsExact();
1294 return &I;
1295 }
1296 }
1297
1298 if (Instruction *R = foldVariableSignZeroExtensionOfVariableHighBitExtract(I))
1299 return R;
1300
1301 // See if we can turn a signed shr into an unsigned shr.
1302 if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I))
1303 return BinaryOperator::CreateLShr(Op0, Op1);
1304
1305 return nullptr;
1306}

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