Bug Summary

File:llvm/include/llvm/IR/PatternMatch.h
Warning:line 1271, column 9
Called C++ object pointer is null

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 InstCombineAddSub.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 -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/lib/Transforms/InstCombine -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -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-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp

1//===- InstCombineAddSub.cpp ------------------------------------*- 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 implements the visit functions for add, fadd, sub, and fsub.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Operator.h"
26#include "llvm/IR/PatternMatch.h"
27#include "llvm/IR/Type.h"
28#include "llvm/IR/Value.h"
29#include "llvm/Support/AlignOf.h"
30#include "llvm/Support/Casting.h"
31#include "llvm/Support/KnownBits.h"
32#include <cassert>
33#include <utility>
34
35using namespace llvm;
36using namespace PatternMatch;
37
38#define DEBUG_TYPE"instcombine" "instcombine"
39
40namespace {
41
42 /// Class representing coefficient of floating-point addend.
43 /// This class needs to be highly efficient, which is especially true for
44 /// the constructor. As of I write this comment, the cost of the default
45 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
46 /// perform write-merging).
47 ///
48 class FAddendCoef {
49 public:
50 // The constructor has to initialize a APFloat, which is unnecessary for
51 // most addends which have coefficient either 1 or -1. So, the constructor
52 // is expensive. In order to avoid the cost of the constructor, we should
53 // reuse some instances whenever possible. The pre-created instances
54 // FAddCombine::Add[0-5] embodies this idea.
55 FAddendCoef() = default;
56 ~FAddendCoef();
57
58 // If possible, don't define operator+/operator- etc because these
59 // operators inevitably call FAddendCoef's constructor which is not cheap.
60 void operator=(const FAddendCoef &A);
61 void operator+=(const FAddendCoef &A);
62 void operator*=(const FAddendCoef &S);
63
64 void set(short C) {
65 assert(!insaneIntVal(C) && "Insane coefficient")((!insaneIntVal(C) && "Insane coefficient") ? static_cast
<void> (0) : __assert_fail ("!insaneIntVal(C) && \"Insane coefficient\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 65, __PRETTY_FUNCTION__))
;
66 IsFp = false; IntVal = C;
67 }
68
69 void set(const APFloat& C);
70
71 void negate();
72
73 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
74 Value *getValue(Type *) const;
75
76 bool isOne() const { return isInt() && IntVal == 1; }
77 bool isTwo() const { return isInt() && IntVal == 2; }
78 bool isMinusOne() const { return isInt() && IntVal == -1; }
79 bool isMinusTwo() const { return isInt() && IntVal == -2; }
80
81 private:
82 bool insaneIntVal(int V) { return V > 4 || V < -4; }
83
84 APFloat *getFpValPtr()
85 { return reinterpret_cast<APFloat *>(&FpValBuf.buffer[0]); }
86
87 const APFloat *getFpValPtr() const
88 { return reinterpret_cast<const APFloat *>(&FpValBuf.buffer[0]); }
89
90 const APFloat &getFpVal() const {
91 assert(IsFp && BufHasFpVal && "Incorret state")((IsFp && BufHasFpVal && "Incorret state") ? static_cast
<void> (0) : __assert_fail ("IsFp && BufHasFpVal && \"Incorret state\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 91, __PRETTY_FUNCTION__))
;
92 return *getFpValPtr();
93 }
94
95 APFloat &getFpVal() {
96 assert(IsFp && BufHasFpVal && "Incorret state")((IsFp && BufHasFpVal && "Incorret state") ? static_cast
<void> (0) : __assert_fail ("IsFp && BufHasFpVal && \"Incorret state\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 96, __PRETTY_FUNCTION__))
;
97 return *getFpValPtr();
98 }
99
100 bool isInt() const { return !IsFp; }
101
102 // If the coefficient is represented by an integer, promote it to a
103 // floating point.
104 void convertToFpType(const fltSemantics &Sem);
105
106 // Construct an APFloat from a signed integer.
107 // TODO: We should get rid of this function when APFloat can be constructed
108 // from an *SIGNED* integer.
109 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
110
111 bool IsFp = false;
112
113 // True iff FpValBuf contains an instance of APFloat.
114 bool BufHasFpVal = false;
115
116 // The integer coefficient of an individual addend is either 1 or -1,
117 // and we try to simplify at most 4 addends from neighboring at most
118 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
119 // is overkill of this end.
120 short IntVal = 0;
121
122 AlignedCharArrayUnion<APFloat> FpValBuf;
123 };
124
125 /// FAddend is used to represent floating-point addend. An addend is
126 /// represented as <C, V>, where the V is a symbolic value, and C is a
127 /// constant coefficient. A constant addend is represented as <C, 0>.
128 class FAddend {
129 public:
130 FAddend() = default;
131
132 void operator+=(const FAddend &T) {
133 assert((Val == T.Val) && "Symbolic-values disagree")(((Val == T.Val) && "Symbolic-values disagree") ? static_cast
<void> (0) : __assert_fail ("(Val == T.Val) && \"Symbolic-values disagree\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 133, __PRETTY_FUNCTION__))
;
134 Coeff += T.Coeff;
135 }
136
137 Value *getSymVal() const { return Val; }
138 const FAddendCoef &getCoef() const { return Coeff; }
139
140 bool isConstant() const { return Val == nullptr; }
141 bool isZero() const { return Coeff.isZero(); }
142
143 void set(short Coefficient, Value *V) {
144 Coeff.set(Coefficient);
145 Val = V;
146 }
147 void set(const APFloat &Coefficient, Value *V) {
148 Coeff.set(Coefficient);
149 Val = V;
150 }
151 void set(const ConstantFP *Coefficient, Value *V) {
152 Coeff.set(Coefficient->getValueAPF());
153 Val = V;
154 }
155
156 void negate() { Coeff.negate(); }
157
158 /// Drill down the U-D chain one step to find the definition of V, and
159 /// try to break the definition into one or two addends.
160 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
161
162 /// Similar to FAddend::drillDownOneStep() except that the value being
163 /// splitted is the addend itself.
164 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
165
166 private:
167 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
168
169 // This addend has the value of "Coeff * Val".
170 Value *Val = nullptr;
171 FAddendCoef Coeff;
172 };
173
174 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
175 /// with its neighboring at most two instructions.
176 ///
177 class FAddCombine {
178 public:
179 FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
180
181 Value *simplify(Instruction *FAdd);
182
183 private:
184 using AddendVect = SmallVector<const FAddend *, 4>;
185
186 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
187
188 /// Convert given addend to a Value
189 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
190
191 /// Return the number of instructions needed to emit the N-ary addition.
192 unsigned calcInstrNumber(const AddendVect& Vect);
193
194 Value *createFSub(Value *Opnd0, Value *Opnd1);
195 Value *createFAdd(Value *Opnd0, Value *Opnd1);
196 Value *createFMul(Value *Opnd0, Value *Opnd1);
197 Value *createFNeg(Value *V);
198 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
199 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
200
201 // Debugging stuff are clustered here.
202 #ifndef NDEBUG
203 unsigned CreateInstrNum;
204 void initCreateInstNum() { CreateInstrNum = 0; }
205 void incCreateInstNum() { CreateInstrNum++; }
206 #else
207 void initCreateInstNum() {}
208 void incCreateInstNum() {}
209 #endif
210
211 InstCombiner::BuilderTy &Builder;
212 Instruction *Instr = nullptr;
213 };
214
215} // end anonymous namespace
216
217//===----------------------------------------------------------------------===//
218//
219// Implementation of
220// {FAddendCoef, FAddend, FAddition, FAddCombine}.
221//
222//===----------------------------------------------------------------------===//
223FAddendCoef::~FAddendCoef() {
224 if (BufHasFpVal)
225 getFpValPtr()->~APFloat();
226}
227
228void FAddendCoef::set(const APFloat& C) {
229 APFloat *P = getFpValPtr();
230
231 if (isInt()) {
232 // As the buffer is meanless byte stream, we cannot call
233 // APFloat::operator=().
234 new(P) APFloat(C);
235 } else
236 *P = C;
237
238 IsFp = BufHasFpVal = true;
239}
240
241void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
242 if (!isInt())
243 return;
244
245 APFloat *P = getFpValPtr();
246 if (IntVal > 0)
247 new(P) APFloat(Sem, IntVal);
248 else {
249 new(P) APFloat(Sem, 0 - IntVal);
250 P->changeSign();
251 }
252 IsFp = BufHasFpVal = true;
253}
254
255APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
256 if (Val >= 0)
257 return APFloat(Sem, Val);
258
259 APFloat T(Sem, 0 - Val);
260 T.changeSign();
261
262 return T;
263}
264
265void FAddendCoef::operator=(const FAddendCoef &That) {
266 if (That.isInt())
267 set(That.IntVal);
268 else
269 set(That.getFpVal());
270}
271
272void FAddendCoef::operator+=(const FAddendCoef &That) {
273 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
274 if (isInt() == That.isInt()) {
275 if (isInt())
276 IntVal += That.IntVal;
277 else
278 getFpVal().add(That.getFpVal(), RndMode);
279 return;
280 }
281
282 if (isInt()) {
283 const APFloat &T = That.getFpVal();
284 convertToFpType(T.getSemantics());
285 getFpVal().add(T, RndMode);
286 return;
287 }
288
289 APFloat &T = getFpVal();
290 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
291}
292
293void FAddendCoef::operator*=(const FAddendCoef &That) {
294 if (That.isOne())
295 return;
296
297 if (That.isMinusOne()) {
298 negate();
299 return;
300 }
301
302 if (isInt() && That.isInt()) {
303 int Res = IntVal * (int)That.IntVal;
304 assert(!insaneIntVal(Res) && "Insane int value")((!insaneIntVal(Res) && "Insane int value") ? static_cast
<void> (0) : __assert_fail ("!insaneIntVal(Res) && \"Insane int value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 304, __PRETTY_FUNCTION__))
;
305 IntVal = Res;
306 return;
307 }
308
309 const fltSemantics &Semantic =
310 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
311
312 if (isInt())
313 convertToFpType(Semantic);
314 APFloat &F0 = getFpVal();
315
316 if (That.isInt())
317 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
318 APFloat::rmNearestTiesToEven);
319 else
320 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
321}
322
323void FAddendCoef::negate() {
324 if (isInt())
325 IntVal = 0 - IntVal;
326 else
327 getFpVal().changeSign();
328}
329
330Value *FAddendCoef::getValue(Type *Ty) const {
331 return isInt() ?
332 ConstantFP::get(Ty, float(IntVal)) :
333 ConstantFP::get(Ty->getContext(), getFpVal());
334}
335
336// The definition of <Val> Addends
337// =========================================
338// A + B <1, A>, <1,B>
339// A - B <1, A>, <1,B>
340// 0 - B <-1, B>
341// C * A, <C, A>
342// A + C <1, A> <C, NULL>
343// 0 +/- 0 <0, NULL> (corner case)
344//
345// Legend: A and B are not constant, C is constant
346unsigned FAddend::drillValueDownOneStep
347 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
348 Instruction *I = nullptr;
349 if (!Val || !(I = dyn_cast<Instruction>(Val)))
350 return 0;
351
352 unsigned Opcode = I->getOpcode();
353
354 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
355 ConstantFP *C0, *C1;
356 Value *Opnd0 = I->getOperand(0);
357 Value *Opnd1 = I->getOperand(1);
358 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
359 Opnd0 = nullptr;
360
361 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
362 Opnd1 = nullptr;
363
364 if (Opnd0) {
365 if (!C0)
366 Addend0.set(1, Opnd0);
367 else
368 Addend0.set(C0, nullptr);
369 }
370
371 if (Opnd1) {
372 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
373 if (!C1)
374 Addend.set(1, Opnd1);
375 else
376 Addend.set(C1, nullptr);
377 if (Opcode == Instruction::FSub)
378 Addend.negate();
379 }
380
381 if (Opnd0 || Opnd1)
382 return Opnd0 && Opnd1 ? 2 : 1;
383
384 // Both operands are zero. Weird!
385 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
386 return 1;
387 }
388
389 if (I->getOpcode() == Instruction::FMul) {
390 Value *V0 = I->getOperand(0);
391 Value *V1 = I->getOperand(1);
392 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
393 Addend0.set(C, V1);
394 return 1;
395 }
396
397 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
398 Addend0.set(C, V0);
399 return 1;
400 }
401 }
402
403 return 0;
404}
405
406// Try to break *this* addend into two addends. e.g. Suppose this addend is
407// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
408// i.e. <2.3, X> and <2.3, Y>.
409unsigned FAddend::drillAddendDownOneStep
410 (FAddend &Addend0, FAddend &Addend1) const {
411 if (isConstant())
412 return 0;
413
414 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
415 if (!BreakNum || Coeff.isOne())
416 return BreakNum;
417
418 Addend0.Scale(Coeff);
419
420 if (BreakNum == 2)
421 Addend1.Scale(Coeff);
422
423 return BreakNum;
424}
425
426Value *FAddCombine::simplify(Instruction *I) {
427 assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&((I->hasAllowReassoc() && I->hasNoSignedZeros()
&& "Expected 'reassoc'+'nsz' instruction") ? static_cast
<void> (0) : __assert_fail ("I->hasAllowReassoc() && I->hasNoSignedZeros() && \"Expected 'reassoc'+'nsz' instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 428, __PRETTY_FUNCTION__))
428 "Expected 'reassoc'+'nsz' instruction")((I->hasAllowReassoc() && I->hasNoSignedZeros()
&& "Expected 'reassoc'+'nsz' instruction") ? static_cast
<void> (0) : __assert_fail ("I->hasAllowReassoc() && I->hasNoSignedZeros() && \"Expected 'reassoc'+'nsz' instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 428, __PRETTY_FUNCTION__))
;
429
430 // Currently we are not able to handle vector type.
431 if (I->getType()->isVectorTy())
432 return nullptr;
433
434 assert((I->getOpcode() == Instruction::FAdd ||(((I->getOpcode() == Instruction::FAdd || I->getOpcode(
) == Instruction::FSub) && "Expect add/sub") ? static_cast
<void> (0) : __assert_fail ("(I->getOpcode() == Instruction::FAdd || I->getOpcode() == Instruction::FSub) && \"Expect add/sub\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 435, __PRETTY_FUNCTION__))
435 I->getOpcode() == Instruction::FSub) && "Expect add/sub")(((I->getOpcode() == Instruction::FAdd || I->getOpcode(
) == Instruction::FSub) && "Expect add/sub") ? static_cast
<void> (0) : __assert_fail ("(I->getOpcode() == Instruction::FAdd || I->getOpcode() == Instruction::FSub) && \"Expect add/sub\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 435, __PRETTY_FUNCTION__))
;
436
437 // Save the instruction before calling other member-functions.
438 Instr = I;
439
440 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
441
442 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
443
444 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
445 unsigned Opnd0_ExpNum = 0;
446 unsigned Opnd1_ExpNum = 0;
447
448 if (!Opnd0.isConstant())
449 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
450
451 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
452 if (OpndNum == 2 && !Opnd1.isConstant())
453 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
454
455 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
456 if (Opnd0_ExpNum && Opnd1_ExpNum) {
457 AddendVect AllOpnds;
458 AllOpnds.push_back(&Opnd0_0);
459 AllOpnds.push_back(&Opnd1_0);
460 if (Opnd0_ExpNum == 2)
461 AllOpnds.push_back(&Opnd0_1);
462 if (Opnd1_ExpNum == 2)
463 AllOpnds.push_back(&Opnd1_1);
464
465 // Compute instruction quota. We should save at least one instruction.
466 unsigned InstQuota = 0;
467
468 Value *V0 = I->getOperand(0);
469 Value *V1 = I->getOperand(1);
470 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
471 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
472
473 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
474 return R;
475 }
476
477 if (OpndNum != 2) {
478 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
479 // splitted into two addends, say "V = X - Y", the instruction would have
480 // been optimized into "I = Y - X" in the previous steps.
481 //
482 const FAddendCoef &CE = Opnd0.getCoef();
483 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
484 }
485
486 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
487 if (Opnd1_ExpNum) {
488 AddendVect AllOpnds;
489 AllOpnds.push_back(&Opnd0);
490 AllOpnds.push_back(&Opnd1_0);
491 if (Opnd1_ExpNum == 2)
492 AllOpnds.push_back(&Opnd1_1);
493
494 if (Value *R = simplifyFAdd(AllOpnds, 1))
495 return R;
496 }
497
498 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
499 if (Opnd0_ExpNum) {
500 AddendVect AllOpnds;
501 AllOpnds.push_back(&Opnd1);
502 AllOpnds.push_back(&Opnd0_0);
503 if (Opnd0_ExpNum == 2)
504 AllOpnds.push_back(&Opnd0_1);
505
506 if (Value *R = simplifyFAdd(AllOpnds, 1))
507 return R;
508 }
509
510 return nullptr;
511}
512
513Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
514 unsigned AddendNum = Addends.size();
515 assert(AddendNum <= 4 && "Too many addends")((AddendNum <= 4 && "Too many addends") ? static_cast
<void> (0) : __assert_fail ("AddendNum <= 4 && \"Too many addends\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 515, __PRETTY_FUNCTION__))
;
516
517 // For saving intermediate results;
518 unsigned NextTmpIdx = 0;
519 FAddend TmpResult[3];
520
521 // Points to the constant addend of the resulting simplified expression.
522 // If the resulting expr has constant-addend, this constant-addend is
523 // desirable to reside at the top of the resulting expression tree. Placing
524 // constant close to supper-expr(s) will potentially reveal some optimization
525 // opportunities in super-expr(s).
526 const FAddend *ConstAdd = nullptr;
527
528 // Simplified addends are placed <SimpVect>.
529 AddendVect SimpVect;
530
531 // The outer loop works on one symbolic-value at a time. Suppose the input
532 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
533 // The symbolic-values will be processed in this order: x, y, z.
534 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
535
536 const FAddend *ThisAddend = Addends[SymIdx];
537 if (!ThisAddend) {
538 // This addend was processed before.
539 continue;
540 }
541
542 Value *Val = ThisAddend->getSymVal();
543 unsigned StartIdx = SimpVect.size();
544 SimpVect.push_back(ThisAddend);
545
546 // The inner loop collects addends sharing same symbolic-value, and these
547 // addends will be later on folded into a single addend. Following above
548 // example, if the symbolic value "y" is being processed, the inner loop
549 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
550 // be later on folded into "<b1+b2, y>".
551 for (unsigned SameSymIdx = SymIdx + 1;
552 SameSymIdx < AddendNum; SameSymIdx++) {
553 const FAddend *T = Addends[SameSymIdx];
554 if (T && T->getSymVal() == Val) {
555 // Set null such that next iteration of the outer loop will not process
556 // this addend again.
557 Addends[SameSymIdx] = nullptr;
558 SimpVect.push_back(T);
559 }
560 }
561
562 // If multiple addends share same symbolic value, fold them together.
563 if (StartIdx + 1 != SimpVect.size()) {
564 FAddend &R = TmpResult[NextTmpIdx ++];
565 R = *SimpVect[StartIdx];
566 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
567 R += *SimpVect[Idx];
568
569 // Pop all addends being folded and push the resulting folded addend.
570 SimpVect.resize(StartIdx);
571 if (Val) {
572 if (!R.isZero()) {
573 SimpVect.push_back(&R);
574 }
575 } else {
576 // Don't push constant addend at this time. It will be the last element
577 // of <SimpVect>.
578 ConstAdd = &R;
579 }
580 }
581 }
582
583 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&(((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
"out-of-bound access") ? static_cast<void> (0) : __assert_fail
("(NextTmpIdx <= array_lengthof(TmpResult) + 1) && \"out-of-bound access\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 584, __PRETTY_FUNCTION__))
584 "out-of-bound access")(((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
"out-of-bound access") ? static_cast<void> (0) : __assert_fail
("(NextTmpIdx <= array_lengthof(TmpResult) + 1) && \"out-of-bound access\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 584, __PRETTY_FUNCTION__))
;
585
586 if (ConstAdd)
587 SimpVect.push_back(ConstAdd);
588
589 Value *Result;
590 if (!SimpVect.empty())
591 Result = createNaryFAdd(SimpVect, InstrQuota);
592 else {
593 // The addition is folded to 0.0.
594 Result = ConstantFP::get(Instr->getType(), 0.0);
595 }
596
597 return Result;
598}
599
600Value *FAddCombine::createNaryFAdd
601 (const AddendVect &Opnds, unsigned InstrQuota) {
602 assert(!Opnds.empty() && "Expect at least one addend")((!Opnds.empty() && "Expect at least one addend") ? static_cast
<void> (0) : __assert_fail ("!Opnds.empty() && \"Expect at least one addend\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 602, __PRETTY_FUNCTION__))
;
603
604 // Step 1: Check if the # of instructions needed exceeds the quota.
605
606 unsigned InstrNeeded = calcInstrNumber(Opnds);
607 if (InstrNeeded > InstrQuota)
608 return nullptr;
609
610 initCreateInstNum();
611
612 // step 2: Emit the N-ary addition.
613 // Note that at most three instructions are involved in Fadd-InstCombine: the
614 // addition in question, and at most two neighboring instructions.
615 // The resulting optimized addition should have at least one less instruction
616 // than the original addition expression tree. This implies that the resulting
617 // N-ary addition has at most two instructions, and we don't need to worry
618 // about tree-height when constructing the N-ary addition.
619
620 Value *LastVal = nullptr;
621 bool LastValNeedNeg = false;
622
623 // Iterate the addends, creating fadd/fsub using adjacent two addends.
624 for (const FAddend *Opnd : Opnds) {
625 bool NeedNeg;
626 Value *V = createAddendVal(*Opnd, NeedNeg);
627 if (!LastVal) {
628 LastVal = V;
629 LastValNeedNeg = NeedNeg;
630 continue;
631 }
632
633 if (LastValNeedNeg == NeedNeg) {
634 LastVal = createFAdd(LastVal, V);
635 continue;
636 }
637
638 if (LastValNeedNeg)
639 LastVal = createFSub(V, LastVal);
640 else
641 LastVal = createFSub(LastVal, V);
642
643 LastValNeedNeg = false;
644 }
645
646 if (LastValNeedNeg) {
647 LastVal = createFNeg(LastVal);
648 }
649
650#ifndef NDEBUG
651 assert(CreateInstrNum == InstrNeeded &&((CreateInstrNum == InstrNeeded && "Inconsistent in instruction numbers"
) ? static_cast<void> (0) : __assert_fail ("CreateInstrNum == InstrNeeded && \"Inconsistent in instruction numbers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 652, __PRETTY_FUNCTION__))
652 "Inconsistent in instruction numbers")((CreateInstrNum == InstrNeeded && "Inconsistent in instruction numbers"
) ? static_cast<void> (0) : __assert_fail ("CreateInstrNum == InstrNeeded && \"Inconsistent in instruction numbers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 652, __PRETTY_FUNCTION__))
;
653#endif
654
655 return LastVal;
656}
657
658Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
659 Value *V = Builder.CreateFSub(Opnd0, Opnd1);
660 if (Instruction *I = dyn_cast<Instruction>(V))
661 createInstPostProc(I);
662 return V;
663}
664
665Value *FAddCombine::createFNeg(Value *V) {
666 Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
667 Value *NewV = createFSub(Zero, V);
668 if (Instruction *I = dyn_cast<Instruction>(NewV))
669 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
670 return NewV;
671}
672
673Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
674 Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
675 if (Instruction *I = dyn_cast<Instruction>(V))
676 createInstPostProc(I);
677 return V;
678}
679
680Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
681 Value *V = Builder.CreateFMul(Opnd0, Opnd1);
682 if (Instruction *I = dyn_cast<Instruction>(V))
683 createInstPostProc(I);
684 return V;
685}
686
687void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
688 NewInstr->setDebugLoc(Instr->getDebugLoc());
689
690 // Keep track of the number of instruction created.
691 if (!NoNumber)
692 incCreateInstNum();
693
694 // Propagate fast-math flags
695 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
696}
697
698// Return the number of instruction needed to emit the N-ary addition.
699// NOTE: Keep this function in sync with createAddendVal().
700unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
701 unsigned OpndNum = Opnds.size();
702 unsigned InstrNeeded = OpndNum - 1;
703
704 // The number of addends in the form of "(-1)*x".
705 unsigned NegOpndNum = 0;
706
707 // Adjust the number of instructions needed to emit the N-ary add.
708 for (const FAddend *Opnd : Opnds) {
709 if (Opnd->isConstant())
710 continue;
711
712 // The constant check above is really for a few special constant
713 // coefficients.
714 if (isa<UndefValue>(Opnd->getSymVal()))
715 continue;
716
717 const FAddendCoef &CE = Opnd->getCoef();
718 if (CE.isMinusOne() || CE.isMinusTwo())
719 NegOpndNum++;
720
721 // Let the addend be "c * x". If "c == +/-1", the value of the addend
722 // is immediately available; otherwise, it needs exactly one instruction
723 // to evaluate the value.
724 if (!CE.isMinusOne() && !CE.isOne())
725 InstrNeeded++;
726 }
727 if (NegOpndNum == OpndNum)
728 InstrNeeded++;
729 return InstrNeeded;
730}
731
732// Input Addend Value NeedNeg(output)
733// ================================================================
734// Constant C C false
735// <+/-1, V> V coefficient is -1
736// <2/-2, V> "fadd V, V" coefficient is -2
737// <C, V> "fmul V, C" false
738//
739// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
740Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
741 const FAddendCoef &Coeff = Opnd.getCoef();
742
743 if (Opnd.isConstant()) {
744 NeedNeg = false;
745 return Coeff.getValue(Instr->getType());
746 }
747
748 Value *OpndVal = Opnd.getSymVal();
749
750 if (Coeff.isMinusOne() || Coeff.isOne()) {
751 NeedNeg = Coeff.isMinusOne();
752 return OpndVal;
753 }
754
755 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
756 NeedNeg = Coeff.isMinusTwo();
757 return createFAdd(OpndVal, OpndVal);
758 }
759
760 NeedNeg = false;
761 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
762}
763
764// Checks if any operand is negative and we can convert add to sub.
765// This function checks for following negative patterns
766// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
767// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
768// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
769static Value *checkForNegativeOperand(BinaryOperator &I,
770 InstCombiner::BuilderTy &Builder) {
771 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
772
773 // This function creates 2 instructions to replace ADD, we need at least one
774 // of LHS or RHS to have one use to ensure benefit in transform.
775 if (!LHS->hasOneUse() && !RHS->hasOneUse())
776 return nullptr;
777
778 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
779 const APInt *C1 = nullptr, *C2 = nullptr;
780
781 // if ONE is on other side, swap
782 if (match(RHS, m_Add(m_Value(X), m_One())))
783 std::swap(LHS, RHS);
784
785 if (match(LHS, m_Add(m_Value(X), m_One()))) {
786 // if XOR on other side, swap
787 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
788 std::swap(X, RHS);
789
790 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
791 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
792 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
793 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
794 Value *NewAnd = Builder.CreateAnd(Z, *C1);
795 return Builder.CreateSub(RHS, NewAnd, "sub");
796 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
797 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
798 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
799 Value *NewOr = Builder.CreateOr(Z, ~(*C1));
800 return Builder.CreateSub(RHS, NewOr, "sub");
801 }
802 }
803 }
804
805 // Restore LHS and RHS
806 LHS = I.getOperand(0);
807 RHS = I.getOperand(1);
808
809 // if XOR is on other side, swap
810 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
811 std::swap(LHS, RHS);
812
813 // C2 is ODD
814 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
815 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
816 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
817 if (C1->countTrailingZeros() == 0)
818 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
819 Value *NewOr = Builder.CreateOr(Z, ~(*C2));
820 return Builder.CreateSub(RHS, NewOr, "sub");
821 }
822 return nullptr;
823}
824
825/// Wrapping flags may allow combining constants separated by an extend.
826static Instruction *foldNoWrapAdd(BinaryOperator &Add,
827 InstCombiner::BuilderTy &Builder) {
828 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
829 Type *Ty = Add.getType();
830 Constant *Op1C;
831 if (!match(Op1, m_Constant(Op1C)))
832 return nullptr;
833
834 // Try this match first because it results in an add in the narrow type.
835 // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
836 Value *X;
837 const APInt *C1, *C2;
838 if (match(Op1, m_APInt(C1)) &&
839 match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
840 C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
841 Constant *NewC =
842 ConstantInt::get(X->getType(), *C2 + C1->trunc(C2->getBitWidth()));
843 return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
844 }
845
846 // More general combining of constants in the wide type.
847 // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
848 Constant *NarrowC;
849 if (match(Op0, m_OneUse(m_SExt(m_NSWAdd(m_Value(X), m_Constant(NarrowC)))))) {
850 Constant *WideC = ConstantExpr::getSExt(NarrowC, Ty);
851 Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
852 Value *WideX = Builder.CreateSExt(X, Ty);
853 return BinaryOperator::CreateAdd(WideX, NewC);
854 }
855 // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
856 if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_Constant(NarrowC)))))) {
857 Constant *WideC = ConstantExpr::getZExt(NarrowC, Ty);
858 Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
859 Value *WideX = Builder.CreateZExt(X, Ty);
860 return BinaryOperator::CreateAdd(WideX, NewC);
861 }
862
863 return nullptr;
864}
865
866Instruction *InstCombiner::foldAddWithConstant(BinaryOperator &Add) {
867 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
868 Constant *Op1C;
869 if (!match(Op1, m_Constant(Op1C)))
870 return nullptr;
871
872 if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
873 return NV;
874
875 Value *X;
876 Constant *Op00C;
877
878 // add (sub C1, X), C2 --> sub (add C1, C2), X
879 if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
880 return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
881
882 Value *Y;
883
884 // add (sub X, Y), -1 --> add (not Y), X
885 if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
886 match(Op1, m_AllOnes()))
887 return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
888
889 // zext(bool) + C -> bool ? C + 1 : C
890 if (match(Op0, m_ZExt(m_Value(X))) &&
891 X->getType()->getScalarSizeInBits() == 1)
892 return SelectInst::Create(X, AddOne(Op1C), Op1);
893 // sext(bool) + C -> bool ? C - 1 : C
894 if (match(Op0, m_SExt(m_Value(X))) &&
895 X->getType()->getScalarSizeInBits() == 1)
896 return SelectInst::Create(X, SubOne(Op1C), Op1);
897
898 // ~X + C --> (C-1) - X
899 if (match(Op0, m_Not(m_Value(X))))
900 return BinaryOperator::CreateSub(SubOne(Op1C), X);
901
902 const APInt *C;
903 if (!match(Op1, m_APInt(C)))
904 return nullptr;
905
906 // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
907 const APInt *C2;
908 if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
909 return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
910
911 if (C->isSignMask()) {
912 // If wrapping is not allowed, then the addition must set the sign bit:
913 // X + (signmask) --> X | signmask
914 if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
915 return BinaryOperator::CreateOr(Op0, Op1);
916
917 // If wrapping is allowed, then the addition flips the sign bit of LHS:
918 // X + (signmask) --> X ^ signmask
919 return BinaryOperator::CreateXor(Op0, Op1);
920 }
921
922 // Is this add the last step in a convoluted sext?
923 // add(zext(xor i16 X, -32768), -32768) --> sext X
924 Type *Ty = Add.getType();
925 if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
926 C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
927 return CastInst::Create(Instruction::SExt, X, Ty);
928
929 if (C->isOneValue() && Op0->hasOneUse()) {
930 // add (sext i1 X), 1 --> zext (not X)
931 // TODO: The smallest IR representation is (select X, 0, 1), and that would
932 // not require the one-use check. But we need to remove a transform in
933 // visitSelect and make sure that IR value tracking for select is equal or
934 // better than for these ops.
935 if (match(Op0, m_SExt(m_Value(X))) &&
936 X->getType()->getScalarSizeInBits() == 1)
937 return new ZExtInst(Builder.CreateNot(X), Ty);
938
939 // Shifts and add used to flip and mask off the low bit:
940 // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
941 const APInt *C3;
942 if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
943 C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
944 Value *NotX = Builder.CreateNot(X);
945 return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
946 }
947 }
948
949 return nullptr;
950}
951
952// Matches multiplication expression Op * C where C is a constant. Returns the
953// constant value in C and the other operand in Op. Returns true if such a
954// match is found.
955static bool MatchMul(Value *E, Value *&Op, APInt &C) {
956 const APInt *AI;
957 if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
958 C = *AI;
959 return true;
960 }
961 if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
962 C = APInt(AI->getBitWidth(), 1);
963 C <<= *AI;
964 return true;
965 }
966 return false;
967}
968
969// Matches remainder expression Op % C where C is a constant. Returns the
970// constant value in C and the other operand in Op. Returns the signedness of
971// the remainder operation in IsSigned. Returns true if such a match is
972// found.
973static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
974 const APInt *AI;
975 IsSigned = false;
976 if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
977 IsSigned = true;
978 C = *AI;
979 return true;
980 }
981 if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
982 C = *AI;
983 return true;
984 }
985 if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
986 C = *AI + 1;
987 return true;
988 }
989 return false;
990}
991
992// Matches division expression Op / C with the given signedness as indicated
993// by IsSigned, where C is a constant. Returns the constant value in C and the
994// other operand in Op. Returns true if such a match is found.
995static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
996 const APInt *AI;
997 if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
998 C = *AI;
999 return true;
1000 }
1001 if (!IsSigned) {
1002 if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
1003 C = *AI;
1004 return true;
1005 }
1006 if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
1007 C = APInt(AI->getBitWidth(), 1);
1008 C <<= *AI;
1009 return true;
1010 }
1011 }
1012 return false;
1013}
1014
1015// Returns whether C0 * C1 with the given signedness overflows.
1016static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1017 bool overflow;
1018 if (IsSigned)
1019 (void)C0.smul_ov(C1, overflow);
1020 else
1021 (void)C0.umul_ov(C1, overflow);
1022 return overflow;
1023}
1024
1025// Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1026// does not overflow.
1027Value *InstCombiner::SimplifyAddWithRemainder(BinaryOperator &I) {
1028 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1029 Value *X, *MulOpV;
1030 APInt C0, MulOpC;
1031 bool IsSigned;
1032 // Match I = X % C0 + MulOpV * C0
1033 if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
1034 (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
1035 C0 == MulOpC) {
1036 Value *RemOpV;
1037 APInt C1;
1038 bool Rem2IsSigned;
1039 // Match MulOpC = RemOpV % C1
1040 if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
1041 IsSigned == Rem2IsSigned) {
1042 Value *DivOpV;
1043 APInt DivOpC;
1044 // Match RemOpV = X / C0
1045 if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1046 C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
1047 Value *NewDivisor =
1048 ConstantInt::get(X->getType()->getContext(), C0 * C1);
1049 return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
1050 : Builder.CreateURem(X, NewDivisor, "urem");
1051 }
1052 }
1053 }
1054
1055 return nullptr;
1056}
1057
1058/// Fold
1059/// (1 << NBits) - 1
1060/// Into:
1061/// ~(-(1 << NBits))
1062/// Because a 'not' is better for bit-tracking analysis and other transforms
1063/// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1064static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
1065 InstCombiner::BuilderTy &Builder) {
1066 Value *NBits;
1067 if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
1068 return nullptr;
1069
1070 Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
1071 Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
1072 // Be wary of constant folding.
1073 if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
1074 // Always NSW. But NUW propagates from `add`.
1075 BOp->setHasNoSignedWrap();
1076 BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1077 }
1078
1079 return BinaryOperator::CreateNot(NotMask, I.getName());
1080}
1081
1082static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
1083 assert(I.getOpcode() == Instruction::Add && "Expecting add instruction")((I.getOpcode() == Instruction::Add && "Expecting add instruction"
) ? static_cast<void> (0) : __assert_fail ("I.getOpcode() == Instruction::Add && \"Expecting add instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1083, __PRETTY_FUNCTION__))
;
1084 Type *Ty = I.getType();
1085 auto getUAddSat = [&]() {
1086 return Intrinsic::getDeclaration(I.getModule(), Intrinsic::uadd_sat, Ty);
1087 };
1088
1089 // add (umin X, ~Y), Y --> uaddsat X, Y
1090 Value *X, *Y;
1091 if (match(&I, m_c_Add(m_c_UMin(m_Value(X), m_Not(m_Value(Y))),
1092 m_Deferred(Y))))
1093 return CallInst::Create(getUAddSat(), { X, Y });
1094
1095 // add (umin X, ~C), C --> uaddsat X, C
1096 const APInt *C, *NotC;
1097 if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
1098 *C == ~*NotC)
1099 return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
1100
1101 return nullptr;
1102}
1103
1104Instruction *
1105InstCombiner::canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
1106 BinaryOperator &I) {
1107 assert((I.getOpcode() == Instruction::Add ||(((I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction
::Or || I.getOpcode() == Instruction::Sub) && "Expecting add/or/sub instruction"
) ? static_cast<void> (0) : __assert_fail ("(I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction::Or || I.getOpcode() == Instruction::Sub) && \"Expecting add/or/sub instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1110, __PRETTY_FUNCTION__))
1
Assuming the condition is false
2
Assuming the condition is false
3
Assuming the condition is true
4
'?' condition is true
1108 I.getOpcode() == Instruction::Or ||(((I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction
::Or || I.getOpcode() == Instruction::Sub) && "Expecting add/or/sub instruction"
) ? static_cast<void> (0) : __assert_fail ("(I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction::Or || I.getOpcode() == Instruction::Sub) && \"Expecting add/or/sub instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1110, __PRETTY_FUNCTION__))
1109 I.getOpcode() == Instruction::Sub) &&(((I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction
::Or || I.getOpcode() == Instruction::Sub) && "Expecting add/or/sub instruction"
) ? static_cast<void> (0) : __assert_fail ("(I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction::Or || I.getOpcode() == Instruction::Sub) && \"Expecting add/or/sub instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1110, __PRETTY_FUNCTION__))
1110 "Expecting add/or/sub instruction")(((I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction
::Or || I.getOpcode() == Instruction::Sub) && "Expecting add/or/sub instruction"
) ? static_cast<void> (0) : __assert_fail ("(I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction::Or || I.getOpcode() == Instruction::Sub) && \"Expecting add/or/sub instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1110, __PRETTY_FUNCTION__))
;
1111
1112 // We have a subtraction/addition between a (potentially truncated) *logical*
1113 // right-shift of X and a "select".
1114 Value *X, *Select;
1115 Instruction *LowBitsToSkip, *Extract;
1116 if (!match(&I, m_c_BinOp(m_TruncOrSelf(m_CombineAnd(
10
Calling 'm_c_BinOp<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> >, 38>, llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> > >, llvm::PatternMatch::bind_ty<llvm::Value>>'
12
Returning from 'm_c_BinOp<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> >, 38>, llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> > >, llvm::PatternMatch::bind_ty<llvm::Value>>'
13
Calling 'match<llvm::BinaryOperator, llvm::PatternMatch::AnyBinaryOp_match<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> >, 38>, llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> > >, llvm::PatternMatch::bind_ty<llvm::Value>, true>>'
36
Returning from 'match<llvm::BinaryOperator, llvm::PatternMatch::AnyBinaryOp_match<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> >, 38>, llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> > >, llvm::PatternMatch::bind_ty<llvm::Value>, true>>'
37
Taking false branch
1117 m_LShr(m_Value(X), m_Instruction(LowBitsToSkip)),
1118 m_Instruction(Extract))),
1119 m_Value(Select))))
5
Calling 'm_Value'
9
Returning from 'm_Value'
1120 return nullptr;
1121
1122 // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
1123 if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
38
Assuming pointer value is null
39
Taking false branch
1124 return nullptr;
1125
1126 Type *XTy = X->getType();
1127 bool HadTrunc = I.getType() != XTy;
40
Assuming the condition is false
1128
1129 // If there was a truncation of extracted value, then we'll need to produce
1130 // one extra instruction, so we need to ensure one instruction will go away.
1131 if (HadTrunc
40.1
'HadTrunc' is false
40.1
'HadTrunc' is false
&& !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
41
Taking false branch
1132 return nullptr;
1133
1134 // Extraction should extract high NBits bits, with shift amount calculated as:
1135 // low bits to skip = shift bitwidth - high bits to extract
1136 // The shift amount itself may be extended, and we need to look past zero-ext
1137 // when matching NBits, that will matter for matching later.
1138 Constant *C;
1139 Value *NBits;
1140 if (!match(
43
Taking false branch
1141 LowBitsToSkip,
1142 m_ZExtOrSelf(m_Sub(m_Constant(C), m_ZExtOrSelf(m_Value(NBits))))) ||
1143 !match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
42
Assuming the condition is false
1144 APInt(C->getType()->getScalarSizeInBits(),
1145 X->getType()->getScalarSizeInBits()))))
1146 return nullptr;
1147
1148 // Sign-extending value can be zero-extended if we `sub`tract it,
1149 // or sign-extended otherwise.
1150 auto SkipExtInMagic = [&I](Value *&V) {
1151 if (I.getOpcode() == Instruction::Sub)
45
Taking true branch
1152 match(V, m_ZExtOrSelf(m_Value(V)));
46
Calling 'm_Value'
48
Returning from 'm_Value'
49
Calling 'm_ZExtOrSelf<llvm::PatternMatch::bind_ty<llvm::Value>>'
57
Returning from 'm_ZExtOrSelf<llvm::PatternMatch::bind_ty<llvm::Value>>'
58
Calling 'match<llvm::Value, llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::bind_ty<llvm::Value>, 39>, llvm::PatternMatch::bind_ty<llvm::Value> >>'
60
Returning from 'match<llvm::Value, llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::bind_ty<llvm::Value>, 39>, llvm::PatternMatch::bind_ty<llvm::Value> >>'
1153 else
1154 match(V, m_SExtOrSelf(m_Value(V)));
1155 };
61
Returning without writing to 'V'
1156
1157 // Now, finally validate the sign-extending magic.
1158 // `select` itself may be appropriately extended, look past that.
1159 SkipExtInMagic(Select);
44
Calling 'operator()'
62
Returning from 'operator()'
1160
1161 ICmpInst::Predicate Pred;
1162 const APInt *Thr;
1163 Value *SignExtendingValue, *Zero;
1164 bool ShouldSignext;
1165 // It must be a select between two values we will later establish to be a
1166 // sign-extending value and a zero constant. The condition guarding the
1167 // sign-extension must be based on a sign bit of the same X we had in `lshr`.
1168 if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
63
Passing null pointer value via 1st parameter 'V'
64
Calling 'match<llvm::Value, llvm::PatternMatch::ThreeOps_match<llvm::PatternMatch::CmpClass_match<llvm::PatternMatch::specificval_ty, llvm::PatternMatch::apint_match, llvm::ICmpInst, llvm::CmpInst::Predicate, false>, llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Value>, 57>>'
1169 m_Value(SignExtendingValue), m_Value(Zero))) ||
1170 !isSignBitCheck(Pred, *Thr, ShouldSignext))
1171 return nullptr;
1172
1173 // icmp-select pair is commutative.
1174 if (!ShouldSignext)
1175 std::swap(SignExtendingValue, Zero);
1176
1177 // If we should not perform sign-extension then we must add/or/subtract zero.
1178 if (!match(Zero, m_Zero()))
1179 return nullptr;
1180 // Otherwise, it should be some constant, left-shifted by the same NBits we
1181 // had in `lshr`. Said left-shift can also be appropriately extended.
1182 // Again, we must look past zero-ext when looking for NBits.
1183 SkipExtInMagic(SignExtendingValue);
1184 Constant *SignExtendingValueBaseConstant;
1185 if (!match(SignExtendingValue,
1186 m_Shl(m_Constant(SignExtendingValueBaseConstant),
1187 m_ZExtOrSelf(m_Specific(NBits)))))
1188 return nullptr;
1189 // If we `sub`, then the constant should be one, else it should be all-ones.
1190 if (I.getOpcode() == Instruction::Sub
1191 ? !match(SignExtendingValueBaseConstant, m_One())
1192 : !match(SignExtendingValueBaseConstant, m_AllOnes()))
1193 return nullptr;
1194
1195 auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
1196 Extract->getName() + ".sext");
1197 NewAShr->copyIRFlags(Extract); // Preserve `exact`-ness.
1198 if (!HadTrunc)
1199 return NewAShr;
1200
1201 Builder.Insert(NewAShr);
1202 return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
1203}
1204
1205Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1206 if (Value *V = SimplifyAddInst(I.getOperand(0), I.getOperand(1),
1207 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1208 SQ.getWithInstruction(&I)))
1209 return replaceInstUsesWith(I, V);
1210
1211 if (SimplifyAssociativeOrCommutative(I))
1212 return &I;
1213
1214 if (Instruction *X = foldVectorBinop(I))
1215 return X;
1216
1217 // (A*B)+(A*C) -> A*(B+C) etc
1218 if (Value *V = SimplifyUsingDistributiveLaws(I))
1219 return replaceInstUsesWith(I, V);
1220
1221 if (Instruction *X = foldAddWithConstant(I))
1222 return X;
1223
1224 if (Instruction *X = foldNoWrapAdd(I, Builder))
1225 return X;
1226
1227 // FIXME: This should be moved into the above helper function to allow these
1228 // transforms for general constant or constant splat vectors.
1229 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1230 Type *Ty = I.getType();
1231 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1232 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
1233 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1234 unsigned TySizeBits = Ty->getScalarSizeInBits();
1235 const APInt &RHSVal = CI->getValue();
1236 unsigned ExtendAmt = 0;
1237 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1238 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1239 if (XorRHS->getValue() == -RHSVal) {
1240 if (RHSVal.isPowerOf2())
1241 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1242 else if (XorRHS->getValue().isPowerOf2())
1243 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
1244 }
1245
1246 if (ExtendAmt) {
1247 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
1248 if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
1249 ExtendAmt = 0;
1250 }
1251
1252 if (ExtendAmt) {
1253 Constant *ShAmt = ConstantInt::get(Ty, ExtendAmt);
1254 Value *NewShl = Builder.CreateShl(XorLHS, ShAmt, "sext");
1255 return BinaryOperator::CreateAShr(NewShl, ShAmt);
1256 }
1257
1258 // If this is a xor that was canonicalized from a sub, turn it back into
1259 // a sub and fuse this add with it.
1260 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1261 KnownBits LHSKnown = computeKnownBits(XorLHS, 0, &I);
1262 if ((XorRHS->getValue() | LHSKnown.Zero).isAllOnesValue())
1263 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1264 XorLHS);
1265 }
1266 // (X + signmask) + C could have gotten canonicalized to (X^signmask) + C,
1267 // transform them into (X + (signmask ^ C))
1268 if (XorRHS->getValue().isSignMask())
1269 return BinaryOperator::CreateAdd(XorLHS,
1270 ConstantExpr::getXor(XorRHS, CI));
1271 }
1272 }
1273
1274 if (Ty->isIntOrIntVectorTy(1))
1275 return BinaryOperator::CreateXor(LHS, RHS);
1276
1277 // X + X --> X << 1
1278 if (LHS == RHS) {
1279 auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
1280 Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1281 Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1282 return Shl;
1283 }
1284
1285 Value *A, *B;
1286 if (match(LHS, m_Neg(m_Value(A)))) {
1287 // -A + -B --> -(A + B)
1288 if (match(RHS, m_Neg(m_Value(B))))
1289 return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
1290
1291 // -A + B --> B - A
1292 return BinaryOperator::CreateSub(RHS, A);
1293 }
1294
1295 // A + -B --> A - B
1296 if (match(RHS, m_Neg(m_Value(B))))
1297 return BinaryOperator::CreateSub(LHS, B);
1298
1299 if (Value *V = checkForNegativeOperand(I, Builder))
1300 return replaceInstUsesWith(I, V);
1301
1302 // (A + 1) + ~B --> A - B
1303 // ~B + (A + 1) --> A - B
1304 // (~B + A) + 1 --> A - B
1305 // (A + ~B) + 1 --> A - B
1306 if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
1307 match(&I, m_BinOp(m_c_Add(m_Not(m_Value(B)), m_Value(A)), m_One())))
1308 return BinaryOperator::CreateSub(A, B);
1309
1310 // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1311 if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
1312
1313 // A+B --> A|B iff A and B have no bits set in common.
1314 if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
1315 return BinaryOperator::CreateOr(LHS, RHS);
1316
1317 // FIXME: We already did a check for ConstantInt RHS above this.
1318 // FIXME: Is this pattern covered by another fold? No regression tests fail on
1319 // removal.
1320 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1321 // (X & FF00) + xx00 -> (X+xx00) & FF00
1322 Value *X;
1323 ConstantInt *C2;
1324 if (LHS->hasOneUse() &&
1325 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1326 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1327 // See if all bits from the first bit set in the Add RHS up are included
1328 // in the mask. First, get the rightmost bit.
1329 const APInt &AddRHSV = CRHS->getValue();
1330
1331 // Form a mask of all bits from the lowest bit added through the top.
1332 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
1333
1334 // See if the and mask includes all of these bits.
1335 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
1336
1337 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1338 // Okay, the xform is safe. Insert the new add pronto.
1339 Value *NewAdd = Builder.CreateAdd(X, CRHS, LHS->getName());
1340 return BinaryOperator::CreateAnd(NewAdd, C2);
1341 }
1342 }
1343 }
1344
1345 // add (select X 0 (sub n A)) A --> select X A n
1346 {
1347 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1348 Value *A = RHS;
1349 if (!SI) {
1350 SI = dyn_cast<SelectInst>(RHS);
1351 A = LHS;
1352 }
1353 if (SI && SI->hasOneUse()) {
1354 Value *TV = SI->getTrueValue();
1355 Value *FV = SI->getFalseValue();
1356 Value *N;
1357
1358 // Can we fold the add into the argument of the select?
1359 // We check both true and false select arguments for a matching subtract.
1360 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1361 // Fold the add into the true select value.
1362 return SelectInst::Create(SI->getCondition(), N, A);
1363
1364 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1365 // Fold the add into the false select value.
1366 return SelectInst::Create(SI->getCondition(), A, N);
1367 }
1368 }
1369
1370 if (Instruction *Ext = narrowMathIfNoOverflow(I))
1371 return Ext;
1372
1373 // (add (xor A, B) (and A, B)) --> (or A, B)
1374 // (add (and A, B) (xor A, B)) --> (or A, B)
1375 if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
1376 m_c_And(m_Deferred(A), m_Deferred(B)))))
1377 return BinaryOperator::CreateOr(A, B);
1378
1379 // (add (or A, B) (and A, B)) --> (add A, B)
1380 // (add (and A, B) (or A, B)) --> (add A, B)
1381 if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
1382 m_c_And(m_Deferred(A), m_Deferred(B))))) {
1383 // Replacing operands in-place to preserve nuw/nsw flags.
1384 replaceOperand(I, 0, A);
1385 replaceOperand(I, 1, B);
1386 return &I;
1387 }
1388
1389 // TODO(jingyue): Consider willNotOverflowSignedAdd and
1390 // willNotOverflowUnsignedAdd to reduce the number of invocations of
1391 // computeKnownBits.
1392 bool Changed = false;
1393 if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
1394 Changed = true;
1395 I.setHasNoSignedWrap(true);
1396 }
1397 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
1398 Changed = true;
1399 I.setHasNoUnsignedWrap(true);
1400 }
1401
1402 if (Instruction *V = canonicalizeLowbitMask(I, Builder))
1403 return V;
1404
1405 if (Instruction *V =
1406 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
1407 return V;
1408
1409 if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
1410 return SatAdd;
1411
1412 return Changed ? &I : nullptr;
1413}
1414
1415/// Eliminate an op from a linear interpolation (lerp) pattern.
1416static Instruction *factorizeLerp(BinaryOperator &I,
1417 InstCombiner::BuilderTy &Builder) {
1418 Value *X, *Y, *Z;
1419 if (!match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_Value(Y),
1420 m_OneUse(m_FSub(m_FPOne(),
1421 m_Value(Z))))),
1422 m_OneUse(m_c_FMul(m_Value(X), m_Deferred(Z))))))
1423 return nullptr;
1424
1425 // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
1426 Value *XY = Builder.CreateFSubFMF(X, Y, &I);
1427 Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
1428 return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
1429}
1430
1431/// Factor a common operand out of fadd/fsub of fmul/fdiv.
1432static Instruction *factorizeFAddFSub(BinaryOperator &I,
1433 InstCombiner::BuilderTy &Builder) {
1434 assert((I.getOpcode() == Instruction::FAdd ||(((I.getOpcode() == Instruction::FAdd || I.getOpcode() == Instruction
::FSub) && "Expecting fadd/fsub") ? static_cast<void
> (0) : __assert_fail ("(I.getOpcode() == Instruction::FAdd || I.getOpcode() == Instruction::FSub) && \"Expecting fadd/fsub\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1435, __PRETTY_FUNCTION__))
1435 I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub")(((I.getOpcode() == Instruction::FAdd || I.getOpcode() == Instruction
::FSub) && "Expecting fadd/fsub") ? static_cast<void
> (0) : __assert_fail ("(I.getOpcode() == Instruction::FAdd || I.getOpcode() == Instruction::FSub) && \"Expecting fadd/fsub\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1435, __PRETTY_FUNCTION__))
;
1436 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&((I.hasAllowReassoc() && I.hasNoSignedZeros() &&
"FP factorization requires FMF") ? static_cast<void> (
0) : __assert_fail ("I.hasAllowReassoc() && I.hasNoSignedZeros() && \"FP factorization requires FMF\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1437, __PRETTY_FUNCTION__))
1437 "FP factorization requires FMF")((I.hasAllowReassoc() && I.hasNoSignedZeros() &&
"FP factorization requires FMF") ? static_cast<void> (
0) : __assert_fail ("I.hasAllowReassoc() && I.hasNoSignedZeros() && \"FP factorization requires FMF\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1437, __PRETTY_FUNCTION__))
;
1438
1439 if (Instruction *Lerp = factorizeLerp(I, Builder))
1440 return Lerp;
1441
1442 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1443 Value *X, *Y, *Z;
1444 bool IsFMul;
1445 if ((match(Op0, m_OneUse(m_FMul(m_Value(X), m_Value(Z)))) &&
1446 match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))) ||
1447 (match(Op0, m_OneUse(m_FMul(m_Value(Z), m_Value(X)))) &&
1448 match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))))
1449 IsFMul = true;
1450 else if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Z)))) &&
1451 match(Op1, m_OneUse(m_FDiv(m_Value(Y), m_Specific(Z)))))
1452 IsFMul = false;
1453 else
1454 return nullptr;
1455
1456 // (X * Z) + (Y * Z) --> (X + Y) * Z
1457 // (X * Z) - (Y * Z) --> (X - Y) * Z
1458 // (X / Z) + (Y / Z) --> (X + Y) / Z
1459 // (X / Z) - (Y / Z) --> (X - Y) / Z
1460 bool IsFAdd = I.getOpcode() == Instruction::FAdd;
1461 Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
1462 : Builder.CreateFSubFMF(X, Y, &I);
1463
1464 // Bail out if we just created a denormal constant.
1465 // TODO: This is copied from a previous implementation. Is it necessary?
1466 const APFloat *C;
1467 if (match(XY, m_APFloat(C)) && !C->isNormal())
1468 return nullptr;
1469
1470 return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
1471 : BinaryOperator::CreateFDivFMF(XY, Z, &I);
1472}
1473
1474Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1475 if (Value *V = SimplifyFAddInst(I.getOperand(0), I.getOperand(1),
1476 I.getFastMathFlags(),
1477 SQ.getWithInstruction(&I)))
1478 return replaceInstUsesWith(I, V);
1479
1480 if (SimplifyAssociativeOrCommutative(I))
1481 return &I;
1482
1483 if (Instruction *X = foldVectorBinop(I))
1484 return X;
1485
1486 if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
1487 return FoldedFAdd;
1488
1489 // (-X) + Y --> Y - X
1490 Value *X, *Y;
1491 if (match(&I, m_c_FAdd(m_FNeg(m_Value(X)), m_Value(Y))))
1492 return BinaryOperator::CreateFSubFMF(Y, X, &I);
1493
1494 // Similar to above, but look through fmul/fdiv for the negated term.
1495 // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
1496 Value *Z;
1497 if (match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))),
1498 m_Value(Z)))) {
1499 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
1500 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
1501 }
1502 // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
1503 // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
1504 if (match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y))),
1505 m_Value(Z))) ||
1506 match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))),
1507 m_Value(Z)))) {
1508 Value *XY = Builder.CreateFDivFMF(X, Y, &I);
1509 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
1510 }
1511
1512 // Check for (fadd double (sitofp x), y), see if we can merge this into an
1513 // integer add followed by a promotion.
1514 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1515 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1516 Value *LHSIntVal = LHSConv->getOperand(0);
1517 Type *FPType = LHSConv->getType();
1518
1519 // TODO: This check is overly conservative. In many cases known bits
1520 // analysis can tell us that the result of the addition has less significant
1521 // bits than the integer type can hold.
1522 auto IsValidPromotion = [](Type *FTy, Type *ITy) {
1523 Type *FScalarTy = FTy->getScalarType();
1524 Type *IScalarTy = ITy->getScalarType();
1525
1526 // Do we have enough bits in the significand to represent the result of
1527 // the integer addition?
1528 unsigned MaxRepresentableBits =
1529 APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
1530 return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
1531 };
1532
1533 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1534 // ... if the constant fits in the integer value. This is useful for things
1535 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1536 // requires a constant pool load, and generally allows the add to be better
1537 // instcombined.
1538 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1539 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1540 Constant *CI =
1541 ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
1542 if (LHSConv->hasOneUse() &&
1543 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1544 willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
1545 // Insert the new integer add.
1546 Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
1547 return new SIToFPInst(NewAdd, I.getType());
1548 }
1549 }
1550
1551 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1552 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1553 Value *RHSIntVal = RHSConv->getOperand(0);
1554 // It's enough to check LHS types only because we require int types to
1555 // be the same for this transform.
1556 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1557 // Only do this if x/y have the same type, if at least one of them has a
1558 // single use (so we don't increase the number of int->fp conversions),
1559 // and if the integer add will not overflow.
1560 if (LHSIntVal->getType() == RHSIntVal->getType() &&
1561 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1562 willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
1563 // Insert the new integer add.
1564 Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
1565 return new SIToFPInst(NewAdd, I.getType());
1566 }
1567 }
1568 }
1569 }
1570
1571 // Handle specials cases for FAdd with selects feeding the operation
1572 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
1573 return replaceInstUsesWith(I, V);
1574
1575 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
1576 if (Instruction *F = factorizeFAddFSub(I, Builder))
1577 return F;
1578 if (Value *V = FAddCombine(Builder).simplify(&I))
1579 return replaceInstUsesWith(I, V);
1580 }
1581
1582 return nullptr;
1583}
1584
1585/// Optimize pointer differences into the same array into a size. Consider:
1586/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1587/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1588Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1589 Type *Ty, bool IsNUW) {
1590 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1591 // this.
1592 bool Swapped = false;
1593 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
1594
1595 // For now we require one side to be the base pointer "A" or a constant
1596 // GEP derived from it.
1597 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1598 // (gep X, ...) - X
1599 if (LHSGEP->getOperand(0) == RHS) {
1600 GEP1 = LHSGEP;
1601 Swapped = false;
1602 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1603 // (gep X, ...) - (gep X, ...)
1604 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1605 RHSGEP->getOperand(0)->stripPointerCasts()) {
1606 GEP2 = RHSGEP;
1607 GEP1 = LHSGEP;
1608 Swapped = false;
1609 }
1610 }
1611 }
1612
1613 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1614 // X - (gep X, ...)
1615 if (RHSGEP->getOperand(0) == LHS) {
1616 GEP1 = RHSGEP;
1617 Swapped = true;
1618 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1619 // (gep X, ...) - (gep X, ...)
1620 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1621 LHSGEP->getOperand(0)->stripPointerCasts()) {
1622 GEP2 = LHSGEP;
1623 GEP1 = RHSGEP;
1624 Swapped = true;
1625 }
1626 }
1627 }
1628
1629 if (!GEP1)
1630 // No GEP found.
1631 return nullptr;
1632
1633 if (GEP2) {
1634 // (gep X, ...) - (gep X, ...)
1635 //
1636 // Avoid duplicating the arithmetic if there are more than one non-constant
1637 // indices between the two GEPs and either GEP has a non-constant index and
1638 // multiple users. If zero non-constant index, the result is a constant and
1639 // there is no duplication. If one non-constant index, the result is an add
1640 // or sub with a constant, which is no larger than the original code, and
1641 // there's no duplicated arithmetic, even if either GEP has multiple
1642 // users. If more than one non-constant indices combined, as long as the GEP
1643 // with at least one non-constant index doesn't have multiple users, there
1644 // is no duplication.
1645 unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
1646 unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
1647 if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
1648 ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
1649 (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
1650 return nullptr;
1651 }
1652 }
1653
1654 // Emit the offset of the GEP and an intptr_t.
1655 Value *Result = EmitGEPOffset(GEP1);
1656
1657 // If this is a single inbounds GEP and the original sub was nuw,
1658 // then the final multiplication is also nuw. We match an extra add zero
1659 // here, because that's what EmitGEPOffset() generates.
1660 Instruction *I;
1661 if (IsNUW && !GEP2 && !Swapped && GEP1->isInBounds() &&
1662 match(Result, m_Add(m_Instruction(I), m_Zero())) &&
1663 I->getOpcode() == Instruction::Mul)
1664 I->setHasNoUnsignedWrap();
1665
1666 // If we had a constant expression GEP on the other side offsetting the
1667 // pointer, subtract it from the offset we have.
1668 if (GEP2) {
1669 Value *Offset = EmitGEPOffset(GEP2);
1670 Result = Builder.CreateSub(Result, Offset);
1671 }
1672
1673 // If we have p - gep(p, ...) then we have to negate the result.
1674 if (Swapped)
1675 Result = Builder.CreateNeg(Result, "diff.neg");
1676
1677 return Builder.CreateIntCast(Result, Ty, true);
1678}
1679
1680Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1681 if (Value *V = SimplifySubInst(I.getOperand(0), I.getOperand(1),
1682 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1683 SQ.getWithInstruction(&I)))
1684 return replaceInstUsesWith(I, V);
1685
1686 if (Instruction *X = foldVectorBinop(I))
1687 return X;
1688
1689 // (A*B)-(A*C) -> A*(B-C) etc
1690 if (Value *V = SimplifyUsingDistributiveLaws(I))
1691 return replaceInstUsesWith(I, V);
1692
1693 // If this is a 'B = x-(-A)', change to B = x+A.
1694 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1695 if (Value *V = dyn_castNegVal(Op1)) {
1696 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1697
1698 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1699 assert(BO->getOpcode() == Instruction::Sub &&((BO->getOpcode() == Instruction::Sub && "Expected a subtraction operator!"
) ? static_cast<void> (0) : __assert_fail ("BO->getOpcode() == Instruction::Sub && \"Expected a subtraction operator!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1700, __PRETTY_FUNCTION__))
1700 "Expected a subtraction operator!")((BO->getOpcode() == Instruction::Sub && "Expected a subtraction operator!"
) ? static_cast<void> (0) : __assert_fail ("BO->getOpcode() == Instruction::Sub && \"Expected a subtraction operator!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1700, __PRETTY_FUNCTION__))
;
1701 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1702 Res->setHasNoSignedWrap(true);
1703 } else {
1704 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1705 Res->setHasNoSignedWrap(true);
1706 }
1707
1708 return Res;
1709 }
1710
1711 if (I.getType()->isIntOrIntVectorTy(1))
1712 return BinaryOperator::CreateXor(Op0, Op1);
1713
1714 // Replace (-1 - A) with (~A).
1715 if (match(Op0, m_AllOnes()))
1716 return BinaryOperator::CreateNot(Op1);
1717
1718 // (~X) - (~Y) --> Y - X
1719 Value *X, *Y;
1720 if (match(Op0, m_Not(m_Value(X))) && match(Op1, m_Not(m_Value(Y))))
1721 return BinaryOperator::CreateSub(Y, X);
1722
1723 // (X + -1) - Y --> ~Y + X
1724 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
1725 return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
1726
1727 // Y - (X + 1) --> ~X + Y
1728 if (match(Op1, m_OneUse(m_Add(m_Value(X), m_One()))))
1729 return BinaryOperator::CreateAdd(Builder.CreateNot(X), Op0);
1730
1731 // Y - ~X --> (X + 1) + Y
1732 if (match(Op1, m_OneUse(m_Not(m_Value(X))))) {
1733 return BinaryOperator::CreateAdd(
1734 Builder.CreateAdd(Op0, ConstantInt::get(I.getType(), 1)), X);
1735 }
1736
1737 if (Constant *C = dyn_cast<Constant>(Op0)) {
1738 // -f(x) -> f(-x) if possible.
1739 if (match(C, m_Zero()))
1740 if (Value *Neg = freelyNegateValue(Op1))
1741 return replaceInstUsesWith(I, Neg);
1742
1743 Value *X;
1744 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1745 // C - (zext bool) --> bool ? C - 1 : C
1746 return SelectInst::Create(X, SubOne(C), C);
1747 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1748 // C - (sext bool) --> bool ? C + 1 : C
1749 return SelectInst::Create(X, AddOne(C), C);
1750
1751 // C - ~X == X + (1+C)
1752 if (match(Op1, m_Not(m_Value(X))))
1753 return BinaryOperator::CreateAdd(X, AddOne(C));
1754
1755 // Try to fold constant sub into select arguments.
1756 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1757 if (Instruction *R = FoldOpIntoSelect(I, SI))
1758 return R;
1759
1760 // Try to fold constant sub into PHI values.
1761 if (PHINode *PN = dyn_cast<PHINode>(Op1))
1762 if (Instruction *R = foldOpIntoPhi(I, PN))
1763 return R;
1764
1765 Constant *C2;
1766
1767 // C-(C2-X) --> X+(C-C2)
1768 if (match(Op1, m_Sub(m_Constant(C2), m_Value(X))))
1769 return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
1770
1771 // C-(X+C2) --> (C-C2)-X
1772 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1773 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1774 }
1775
1776 const APInt *Op0C;
1777 if (match(Op0, m_APInt(Op0C))) {
1778 if (Op0C->isNullValue() && Op1->hasOneUse()) {
1779 Value *LHS, *RHS;
1780 SelectPatternFlavor SPF = matchSelectPattern(Op1, LHS, RHS).Flavor;
1781 if (SPF == SPF_ABS || SPF == SPF_NABS) {
1782 // This is a negate of an ABS/NABS pattern. Just swap the operands
1783 // of the select.
1784 cast<SelectInst>(Op1)->swapValues();
1785 // Don't swap prof metadata, we didn't change the branch behavior.
1786 return replaceInstUsesWith(I, Op1);
1787 }
1788 }
1789
1790 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
1791 // zero.
1792 if (Op0C->isMask()) {
1793 KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
1794 if ((*Op0C | RHSKnown.Zero).isAllOnesValue())
1795 return BinaryOperator::CreateXor(Op1, Op0);
1796 }
1797 }
1798
1799 {
1800 Value *Y;
1801 // X-(X+Y) == -Y X-(Y+X) == -Y
1802 if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
1803 return BinaryOperator::CreateNeg(Y);
1804
1805 // (X-Y)-X == -Y
1806 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1807 return BinaryOperator::CreateNeg(Y);
1808 }
1809
1810 // (sub (or A, B) (and A, B)) --> (xor A, B)
1811 {
1812 Value *A, *B;
1813 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1814 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1815 return BinaryOperator::CreateXor(A, B);
1816 }
1817
1818 // (sub (and A, B) (or A, B)) --> neg (xor A, B)
1819 {
1820 Value *A, *B;
1821 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1822 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
1823 (Op0->hasOneUse() || Op1->hasOneUse()))
1824 return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
1825 }
1826
1827 // (sub (or A, B), (xor A, B)) --> (and A, B)
1828 {
1829 Value *A, *B;
1830 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1831 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1832 return BinaryOperator::CreateAnd(A, B);
1833 }
1834
1835 // (sub (xor A, B) (or A, B)) --> neg (and A, B)
1836 {
1837 Value *A, *B;
1838 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1839 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
1840 (Op0->hasOneUse() || Op1->hasOneUse()))
1841 return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
1842 }
1843
1844 {
1845 Value *Y;
1846 // ((X | Y) - X) --> (~X & Y)
1847 if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
1848 return BinaryOperator::CreateAnd(
1849 Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
1850 }
1851
1852 {
1853 // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
1854 Value *X;
1855 if (match(Op0, m_OneUse(m_c_And(m_Specific(Op1),
1856 m_OneUse(m_Neg(m_Value(X))))))) {
1857 return BinaryOperator::CreateNeg(Builder.CreateAnd(
1858 Op1, Builder.CreateAdd(X, Constant::getAllOnesValue(I.getType()))));
1859 }
1860 }
1861
1862 {
1863 // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
1864 Constant *C;
1865 if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_Constant(C))))) {
1866 return BinaryOperator::CreateNeg(
1867 Builder.CreateAnd(Op1, Builder.CreateNot(C)));
1868 }
1869 }
1870
1871 {
1872 // If we have a subtraction between some value and a select between
1873 // said value and something else, sink subtraction into select hands, i.e.:
1874 // sub (select %Cond, %TrueVal, %FalseVal), %Op1
1875 // ->
1876 // select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
1877 // or
1878 // sub %Op0, (select %Cond, %TrueVal, %FalseVal)
1879 // ->
1880 // select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
1881 // This will result in select between new subtraction and 0.
1882 auto SinkSubIntoSelect =
1883 [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
1884 auto SubBuilder) -> Instruction * {
1885 Value *Cond, *TrueVal, *FalseVal;
1886 if (!match(Select, m_OneUse(m_Select(m_Value(Cond), m_Value(TrueVal),
1887 m_Value(FalseVal)))))
1888 return nullptr;
1889 if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
1890 return nullptr;
1891 // While it is really tempting to just create two subtractions and let
1892 // InstCombine fold one of those to 0, it isn't possible to do so
1893 // because of worklist visitation order. So ugly it is.
1894 bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
1895 Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
1896 Constant *Zero = Constant::getNullValue(Ty);
1897 SelectInst *NewSel =
1898 SelectInst::Create(Cond, OtherHandOfSubIsTrueVal ? Zero : NewSub,
1899 OtherHandOfSubIsTrueVal ? NewSub : Zero);
1900 // Preserve prof metadata if any.
1901 NewSel->copyMetadata(cast<Instruction>(*Select));
1902 return NewSel;
1903 };
1904 if (Instruction *NewSel = SinkSubIntoSelect(
1905 /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
1906 [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
1907 return Builder->CreateSub(OtherHandOfSelect,
1908 /*OtherHandOfSub=*/Op1);
1909 }))
1910 return NewSel;
1911 if (Instruction *NewSel = SinkSubIntoSelect(
1912 /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
1913 [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
1914 return Builder->CreateSub(/*OtherHandOfSub=*/Op0,
1915 OtherHandOfSelect);
1916 }))
1917 return NewSel;
1918 }
1919
1920 // (X - (X & Y)) --> (X & ~Y)
1921 if (match(Op1, m_c_And(m_Specific(Op0), m_Value(Y))) &&
1922 (Op1->hasOneUse() || isa<Constant>(Y)))
1923 return BinaryOperator::CreateAnd(
1924 Op0, Builder.CreateNot(Y, Y->getName() + ".not"));
1925
1926 if (Op1->hasOneUse()) {
1927 Value *Y = nullptr, *Z = nullptr;
1928 Constant *C = nullptr;
1929
1930 // (X - (Y - Z)) --> (X + (Z - Y)).
1931 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1932 return BinaryOperator::CreateAdd(Op0,
1933 Builder.CreateSub(Z, Y, Op1->getName()));
1934
1935 // Subtracting -1/0 is the same as adding 1/0:
1936 // sub [nsw] Op0, sext(bool Y) -> add [nsw] Op0, zext(bool Y)
1937 // 'nuw' is dropped in favor of the canonical form.
1938 if (match(Op1, m_SExt(m_Value(Y))) &&
1939 Y->getType()->getScalarSizeInBits() == 1) {
1940 Value *Zext = Builder.CreateZExt(Y, I.getType());
1941 BinaryOperator *Add = BinaryOperator::CreateAdd(Op0, Zext);
1942 Add->setHasNoSignedWrap(I.hasNoSignedWrap());
1943 return Add;
1944 }
1945 // sub [nsw] X, zext(bool Y) -> add [nsw] X, sext(bool Y)
1946 // 'nuw' is dropped in favor of the canonical form.
1947 if (match(Op1, m_ZExt(m_Value(Y))) && Y->getType()->isIntOrIntVectorTy(1)) {
1948 Value *Sext = Builder.CreateSExt(Y, I.getType());
1949 BinaryOperator *Add = BinaryOperator::CreateAdd(Op0, Sext);
1950 Add->setHasNoSignedWrap(I.hasNoSignedWrap());
1951 return Add;
1952 }
1953
1954 // X - A*-B -> X + A*B
1955 // X - -A*B -> X + A*B
1956 Value *A, *B;
1957 if (match(Op1, m_c_Mul(m_Value(A), m_Neg(m_Value(B)))))
1958 return BinaryOperator::CreateAdd(Op0, Builder.CreateMul(A, B));
1959
1960 // X - A*C -> X + A*-C
1961 // No need to handle commuted multiply because multiply handling will
1962 // ensure constant will be move to the right hand side.
1963 if (match(Op1, m_Mul(m_Value(A), m_Constant(C))) && !isa<ConstantExpr>(C)) {
1964 Value *NewMul = Builder.CreateMul(A, ConstantExpr::getNeg(C));
1965 return BinaryOperator::CreateAdd(Op0, NewMul);
1966 }
1967 }
1968
1969 {
1970 // ~A - Min/Max(~A, O) -> Max/Min(A, ~O) - A
1971 // ~A - Min/Max(O, ~A) -> Max/Min(A, ~O) - A
1972 // Min/Max(~A, O) - ~A -> A - Max/Min(A, ~O)
1973 // Min/Max(O, ~A) - ~A -> A - Max/Min(A, ~O)
1974 // So long as O here is freely invertible, this will be neutral or a win.
1975 Value *LHS, *RHS, *A;
1976 Value *NotA = Op0, *MinMax = Op1;
1977 SelectPatternFlavor SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
1978 if (!SelectPatternResult::isMinOrMax(SPF)) {
1979 NotA = Op1;
1980 MinMax = Op0;
1981 SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
1982 }
1983 if (SelectPatternResult::isMinOrMax(SPF) &&
1984 match(NotA, m_Not(m_Value(A))) && (NotA == LHS || NotA == RHS)) {
1985 if (NotA == LHS)
1986 std::swap(LHS, RHS);
1987 // LHS is now O above and expected to have at least 2 uses (the min/max)
1988 // NotA is epected to have 2 uses from the min/max and 1 from the sub.
1989 if (isFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
1990 !NotA->hasNUsesOrMore(4)) {
1991 // Note: We don't generate the inverse max/min, just create the not of
1992 // it and let other folds do the rest.
1993 Value *Not = Builder.CreateNot(MinMax);
1994 if (NotA == Op0)
1995 return BinaryOperator::CreateSub(Not, A);
1996 else
1997 return BinaryOperator::CreateSub(A, Not);
1998 }
1999 }
2000 }
2001
2002 // Optimize pointer differences into the same array into a size. Consider:
2003 // &A[10] - &A[0]: we should compile this to "10".
2004 Value *LHSOp, *RHSOp;
2005 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2006 match(Op1, m_PtrToInt(m_Value(RHSOp))))
2007 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2008 I.hasNoUnsignedWrap()))
2009 return replaceInstUsesWith(I, Res);
2010
2011 // trunc(p)-trunc(q) -> trunc(p-q)
2012 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2013 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2014 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2015 /* IsNUW */ false))
2016 return replaceInstUsesWith(I, Res);
2017
2018 // Canonicalize a shifty way to code absolute value to the common pattern.
2019 // There are 2 potential commuted variants.
2020 // We're relying on the fact that we only do this transform when the shift has
2021 // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
2022 // instructions).
2023 Value *A;
2024 const APInt *ShAmt;
2025 Type *Ty = I.getType();
2026 if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
2027 Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
2028 match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
2029 // B = ashr i32 A, 31 ; smear the sign bit
2030 // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
2031 // --> (A < 0) ? -A : A
2032 Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
2033 // Copy the nuw/nsw flags from the sub to the negate.
2034 Value *Neg = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
2035 I.hasNoSignedWrap());
2036 return SelectInst::Create(Cmp, Neg, A);
2037 }
2038
2039 if (Instruction *V =
2040 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
2041 return V;
2042
2043 if (Instruction *Ext = narrowMathIfNoOverflow(I))
2044 return Ext;
2045
2046 bool Changed = false;
2047 if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
2048 Changed = true;
2049 I.setHasNoSignedWrap(true);
2050 }
2051 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
2052 Changed = true;
2053 I.setHasNoUnsignedWrap(true);
2054 }
2055
2056 return Changed ? &I : nullptr;
2057}
2058
2059/// This eliminates floating-point negation in either 'fneg(X)' or
2060/// 'fsub(-0.0, X)' form by combining into a constant operand.
2061static Instruction *foldFNegIntoConstant(Instruction &I) {
2062 Value *X;
2063 Constant *C;
2064
2065 // Fold negation into constant operand. This is limited with one-use because
2066 // fneg is assumed better for analysis and cheaper in codegen than fmul/fdiv.
2067 // -(X * C) --> X * (-C)
2068 // FIXME: It's arguable whether these should be m_OneUse or not. The current
2069 // belief is that the FNeg allows for better reassociation opportunities.
2070 if (match(&I, m_FNeg(m_OneUse(m_FMul(m_Value(X), m_Constant(C))))))
2071 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
2072 // -(X / C) --> X / (-C)
2073 if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Value(X), m_Constant(C))))))
2074 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
2075 // -(C / X) --> (-C) / X
2076 if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Constant(C), m_Value(X))))))
2077 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
2078
2079 // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
2080 // -(X + C) --> -X + -C --> -C - X
2081 if (I.hasNoSignedZeros() &&
2082 match(&I, m_FNeg(m_OneUse(m_FAdd(m_Value(X), m_Constant(C))))))
2083 return BinaryOperator::CreateFSubFMF(ConstantExpr::getFNeg(C), X, &I);
2084
2085 return nullptr;
2086}
2087
2088static Instruction *hoistFNegAboveFMulFDiv(Instruction &I,
2089 InstCombiner::BuilderTy &Builder) {
2090 Value *FNeg;
2091 if (!match(&I, m_FNeg(m_Value(FNeg))))
2092 return nullptr;
2093
2094 Value *X, *Y;
2095 if (match(FNeg, m_OneUse(m_FMul(m_Value(X), m_Value(Y)))))
2096 return BinaryOperator::CreateFMulFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
2097
2098 if (match(FNeg, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))))
2099 return BinaryOperator::CreateFDivFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
2100
2101 return nullptr;
2102}
2103
2104Instruction *InstCombiner::visitFNeg(UnaryOperator &I) {
2105 Value *Op = I.getOperand(0);
2106
2107 if (Value *V = SimplifyFNegInst(Op, I.getFastMathFlags(),
2108 SQ.getWithInstruction(&I)))
2109 return replaceInstUsesWith(I, V);
2110
2111 if (Instruction *X = foldFNegIntoConstant(I))
2112 return X;
2113
2114 Value *X, *Y;
2115
2116 // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
2117 if (I.hasNoSignedZeros() &&
2118 match(Op, m_OneUse(m_FSub(m_Value(X), m_Value(Y)))))
2119 return BinaryOperator::CreateFSubFMF(Y, X, &I);
2120
2121 if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
2122 return R;
2123
2124 return nullptr;
2125}
2126
2127Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2128 if (Value *V = SimplifyFSubInst(I.getOperand(0), I.getOperand(1),
2129 I.getFastMathFlags(),
2130 SQ.getWithInstruction(&I)))
2131 return replaceInstUsesWith(I, V);
2132
2133 if (Instruction *X = foldVectorBinop(I))
2134 return X;
2135
2136 // Subtraction from -0.0 is the canonical form of fneg.
2137 // fsub nsz 0, X ==> fsub nsz -0.0, X
2138 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2139 if (I.hasNoSignedZeros() && match(Op0, m_PosZeroFP()))
2140 return UnaryOperator::CreateFNegFMF(Op1, &I);
2141
2142 if (Instruction *X = foldFNegIntoConstant(I))
2143 return X;
2144
2145 if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
2146 return R;
2147
2148 Value *X, *Y;
2149 Constant *C;
2150
2151 // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
2152 // Canonicalize to fadd to make analysis easier.
2153 // This can also help codegen because fadd is commutative.
2154 // Note that if this fsub was really an fneg, the fadd with -0.0 will get
2155 // killed later. We still limit that particular transform with 'hasOneUse'
2156 // because an fneg is assumed better/cheaper than a generic fsub.
2157 if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) {
2158 if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
2159 Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
2160 return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
2161 }
2162 }
2163
2164 // (-X) - Op1 --> -(X + Op1)
2165 if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Op0) &&
2166 match(Op0, m_OneUse(m_FNeg(m_Value(X))))) {
2167 Value *FAdd = Builder.CreateFAddFMF(X, Op1, &I);
2168 return UnaryOperator::CreateFNegFMF(FAdd, &I);
2169 }
2170
2171 if (isa<Constant>(Op0))
2172 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2173 if (Instruction *NV = FoldOpIntoSelect(I, SI))
2174 return NV;
2175
2176 // X - C --> X + (-C)
2177 // But don't transform constant expressions because there's an inverse fold
2178 // for X + (-Y) --> X - Y.
2179 if (match(Op1, m_Constant(C)) && !isa<ConstantExpr>(Op1))
2180 return BinaryOperator::CreateFAddFMF(Op0, ConstantExpr::getFNeg(C), &I);
2181
2182 // X - (-Y) --> X + Y
2183 if (match(Op1, m_FNeg(m_Value(Y))))
2184 return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
2185
2186 // Similar to above, but look through a cast of the negated value:
2187 // X - (fptrunc(-Y)) --> X + fptrunc(Y)
2188 Type *Ty = I.getType();
2189 if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
2190 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
2191
2192 // X - (fpext(-Y)) --> X + fpext(Y)
2193 if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
2194 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
2195
2196 // Similar to above, but look through fmul/fdiv of the negated value:
2197 // Op0 - (-X * Y) --> Op0 + (X * Y)
2198 // Op0 - (Y * -X) --> Op0 + (X * Y)
2199 if (match(Op1, m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))))) {
2200 Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
2201 return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
2202 }
2203 // Op0 - (-X / Y) --> Op0 + (X / Y)
2204 // Op0 - (X / -Y) --> Op0 + (X / Y)
2205 if (match(Op1, m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y)))) ||
2206 match(Op1, m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))))) {
2207 Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
2208 return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
2209 }
2210
2211 // Handle special cases for FSub with selects feeding the operation
2212 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
2213 return replaceInstUsesWith(I, V);
2214
2215 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
2216 // (Y - X) - Y --> -X
2217 if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
2218 return UnaryOperator::CreateFNegFMF(X, &I);
2219
2220 // Y - (X + Y) --> -X
2221 // Y - (Y + X) --> -X
2222 if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
2223 return UnaryOperator::CreateFNegFMF(X, &I);
2224
2225 // (X * C) - X --> X * (C - 1.0)
2226 if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
2227 Constant *CSubOne = ConstantExpr::getFSub(C, ConstantFP::get(Ty, 1.0));
2228 return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
2229 }
2230 // X - (X * C) --> X * (1.0 - C)
2231 if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
2232 Constant *OneSubC = ConstantExpr::getFSub(ConstantFP::get(Ty, 1.0), C);
2233 return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
2234 }
2235
2236 if (Instruction *F = factorizeFAddFSub(I, Builder))
2237 return F;
2238
2239 // TODO: This performs reassociative folds for FP ops. Some fraction of the
2240 // functionality has been subsumed by simple pattern matching here and in
2241 // InstSimplify. We should let a dedicated reassociation pass handle more
2242 // complex pattern matching and remove this from InstCombine.
2243 if (Value *V = FAddCombine(Builder).simplify(&I))
2244 return replaceInstUsesWith(I, V);
2245
2246 // (X - Y) - Op1 --> X - (Y + Op1)
2247 if (match(Op0, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
2248 Value *FAdd = Builder.CreateFAddFMF(Y, Op1, &I);
2249 return BinaryOperator::CreateFSubFMF(X, FAdd, &I);
2250 }
2251 }
2252
2253 return nullptr;
2254}

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/PatternMatch.h

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