LLVM 24.0.0git
InstCombineAddSub.cpp
Go to the documentation of this file.
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"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Instruction.h"
25#include "llvm/IR/Operator.h"
28#include "llvm/IR/Type.h"
29#include "llvm/IR/Value.h"
34#include <cassert>
35#include <utility>
36
37using namespace llvm;
38using namespace PatternMatch;
39
40#define DEBUG_TYPE "instcombine"
41
42namespace llvm {
44}
45
46namespace {
47
48 /// Class representing coefficient of floating-point addend.
49 /// This class needs to be highly efficient, which is especially true for
50 /// the constructor. As of I write this comment, the cost of the default
51 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
52 /// perform write-merging).
53 ///
54 class FAddendCoef {
55 public:
56 // The constructor has to initialize a APFloat, which is unnecessary for
57 // most addends which have coefficient either 1 or -1. So, the constructor
58 // is expensive. In order to avoid the cost of the constructor, we should
59 // reuse some instances whenever possible. The pre-created instances
60 // FAddCombine::Add[0-5] embodies this idea.
61 FAddendCoef() = default;
62 ~FAddendCoef();
63
64 // If possible, don't define operator+/operator- etc because these
65 // operators inevitably call FAddendCoef's constructor which is not cheap.
66 void operator=(const FAddendCoef &A);
67 void operator+=(const FAddendCoef &A);
68 void operator*=(const FAddendCoef &S);
69
70 void set(short C) {
71 assert(!insaneIntVal(C) && "Insane coefficient");
72 IsFp = false; IntVal = C;
73 }
74
75 void set(const APFloat& C);
76
77 void negate();
78
79 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
80 Value *getValue(Type *) const;
81
82 bool isOne() const { return isInt() && IntVal == 1; }
83 bool isTwo() const { return isInt() && IntVal == 2; }
84 bool isMinusOne() const { return isInt() && IntVal == -1; }
85 bool isMinusTwo() const { return isInt() && IntVal == -2; }
86
87 private:
88 bool insaneIntVal(int V) { return V > 4 || V < -4; }
89
90 APFloat *getFpValPtr() { return reinterpret_cast<APFloat *>(&FpValBuf); }
91
92 const APFloat *getFpValPtr() const {
93 return reinterpret_cast<const APFloat *>(&FpValBuf);
94 }
95
96 const APFloat &getFpVal() const {
97 assert(IsFp && BufHasFpVal && "Incorrect state");
98 return *getFpValPtr();
99 }
100
101 APFloat &getFpVal() {
102 assert(IsFp && BufHasFpVal && "Incorrect state");
103 return *getFpValPtr();
104 }
105
106 bool isInt() const { return !IsFp; }
107
108 // If the coefficient is represented by an integer, promote it to a
109 // floating point.
110 void convertToFpType(const fltSemantics &Sem);
111
112 // Construct an APFloat from a signed integer.
113 // TODO: We should get rid of this function when APFloat can be constructed
114 // from an *SIGNED* integer.
115 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
116
117 bool IsFp = false;
118
119 // True iff FpValBuf contains an instance of APFloat.
120 bool BufHasFpVal = false;
121
122 // The integer coefficient of an individual addend is either 1 or -1,
123 // and we try to simplify at most 4 addends from neighboring at most
124 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
125 // is overkill of this end.
126 short IntVal = 0;
127
128 AlignedCharArrayUnion<APFloat> FpValBuf;
129 };
130
131 /// FAddend is used to represent floating-point addend. An addend is
132 /// represented as <C, V>, where the V is a symbolic value, and C is a
133 /// constant coefficient. A constant addend is represented as <C, 0>.
134 class FAddend {
135 public:
136 FAddend() = default;
137
138 void operator+=(const FAddend &T) {
139 assert((Val == T.Val) && "Symbolic-values disagree");
140 Coeff += T.Coeff;
141 }
142
143 Value *getSymVal() const { return Val; }
144 const FAddendCoef &getCoef() const { return Coeff; }
145
146 bool isConstant() const { return Val == nullptr; }
147 bool isZero() const { return Coeff.isZero(); }
148
149 void set(short Coefficient, Value *V) {
150 Coeff.set(Coefficient);
151 Val = V;
152 }
153 void set(const APFloat &Coefficient, Value *V) {
154 Coeff.set(Coefficient);
155 Val = V;
156 }
157 void set(const ConstantFP *Coefficient, Value *V) {
158 Coeff.set(Coefficient->getValueAPF());
159 Val = V;
160 }
161
162 void negate() { Coeff.negate(); }
163
164 /// Drill down the U-D chain one step to find the definition of V, and
165 /// try to break the definition into one or two addends.
166 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
167
168 /// Similar to FAddend::drillDownOneStep() except that the value being
169 /// splitted is the addend itself.
170 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
171
172 private:
173 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
174
175 // This addend has the value of "Coeff * Val".
176 Value *Val = nullptr;
177 FAddendCoef Coeff;
178 };
179
180 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
181 /// with its neighboring at most two instructions.
182 ///
183 class FAddCombine {
184 public:
185 FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
186
187 Value *simplify(Instruction *FAdd);
188
189 private:
190 using AddendVect = SmallVector<const FAddend *, 4>;
191
192 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
193
194 /// Convert given addend to a Value
195 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
196
197 /// Return the number of instructions needed to emit the N-ary addition.
198 unsigned calcInstrNumber(const AddendVect& Vect);
199
200 Value *createFSub(Value *Opnd0, Value *Opnd1);
201 Value *createFAdd(Value *Opnd0, Value *Opnd1);
202 Value *createFMul(Value *Opnd0, Value *Opnd1);
203 Value *createFNeg(Value *V);
204 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
205 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
206
207 // Debugging stuff are clustered here.
208 #ifndef NDEBUG
209 unsigned CreateInstrNum;
210 void initCreateInstNum() { CreateInstrNum = 0; }
211 void incCreateInstNum() { CreateInstrNum++; }
212 #else
213 void initCreateInstNum() {}
214 void incCreateInstNum() {}
215 #endif
216
217 InstCombiner::BuilderTy &Builder;
218 Instruction *Instr = nullptr;
219 };
220
221} // end anonymous namespace
222
223//===----------------------------------------------------------------------===//
224//
225// Implementation of
226// {FAddendCoef, FAddend, FAddition, FAddCombine}.
227//
228//===----------------------------------------------------------------------===//
229FAddendCoef::~FAddendCoef() {
230 if (BufHasFpVal)
231 getFpValPtr()->~APFloat();
232}
233
234void FAddendCoef::set(const APFloat& C) {
235 APFloat *P = getFpValPtr();
236
237 if (isInt()) {
238 // As the buffer is meanless byte stream, we cannot call
239 // APFloat::operator=().
240 new(P) APFloat(C);
241 } else
242 *P = C;
243
244 IsFp = BufHasFpVal = true;
245}
246
247void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
248 if (!isInt())
249 return;
250
251 APFloat *P = getFpValPtr();
252 if (IntVal > 0)
253 new(P) APFloat(Sem, IntVal);
254 else {
255 new(P) APFloat(Sem, 0 - IntVal);
256 P->changeSign();
257 }
258 IsFp = BufHasFpVal = true;
259}
260
261APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
262 if (Val >= 0)
263 return APFloat(Sem, Val);
264
265 APFloat T(Sem, 0 - Val);
266 T.changeSign();
267
268 return T;
269}
270
271void FAddendCoef::operator=(const FAddendCoef &That) {
272 if (That.isInt())
273 set(That.IntVal);
274 else
275 set(That.getFpVal());
276}
277
278void FAddendCoef::operator+=(const FAddendCoef &That) {
279 RoundingMode RndMode = RoundingMode::NearestTiesToEven;
280 if (isInt() == That.isInt()) {
281 if (isInt())
282 IntVal += That.IntVal;
283 else
284 getFpVal().add(That.getFpVal(), RndMode);
285 return;
286 }
287
288 if (isInt()) {
289 const APFloat &T = That.getFpVal();
290 convertToFpType(T.getSemantics());
291 getFpVal().add(T, RndMode);
292 return;
293 }
294
295 APFloat &T = getFpVal();
296 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
297}
298
299void FAddendCoef::operator*=(const FAddendCoef &That) {
300 if (That.isOne())
301 return;
302
303 if (That.isMinusOne()) {
304 negate();
305 return;
306 }
307
308 if (isInt() && That.isInt()) {
309 int Res = IntVal * (int)That.IntVal;
310 assert(!insaneIntVal(Res) && "Insane int value");
311 IntVal = Res;
312 return;
313 }
314
315 const fltSemantics &Semantic =
316 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
317
318 if (isInt())
319 convertToFpType(Semantic);
320 APFloat &F0 = getFpVal();
321
322 if (That.isInt())
323 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
324 APFloat::rmNearestTiesToEven);
325 else
326 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
327}
328
329void FAddendCoef::negate() {
330 if (isInt())
331 IntVal = 0 - IntVal;
332 else
333 getFpVal().changeSign();
334}
335
336Value *FAddendCoef::getValue(Type *Ty) const {
337 return isInt() ?
338 ConstantFP::get(Ty, float(IntVal)) :
339 ConstantFP::get(Ty->getContext(), getFpVal());
340}
341
342// The definition of <Val> Addends
343// =========================================
344// A + B <1, A>, <1,B>
345// A - B <1, A>, <1,B>
346// 0 - B <-1, B>
347// C * A, <C, A>
348// A + C <1, A> <C, NULL>
349// 0 +/- 0 <0, NULL> (corner case)
350//
351// Legend: A and B are not constant, C is constant
352unsigned FAddend::drillValueDownOneStep
353 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
354 Instruction *I = nullptr;
355 if (!Val || !(I = dyn_cast<Instruction>(Val)))
356 return 0;
357
358 unsigned Opcode = I->getOpcode();
359
360 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
361 ConstantFP *C0, *C1;
362 Value *Opnd0 = I->getOperand(0);
363 Value *Opnd1 = I->getOperand(1);
364 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
365 Opnd0 = nullptr;
366
367 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
368 Opnd1 = nullptr;
369
370 if (Opnd0) {
371 if (!C0)
372 Addend0.set(1, Opnd0);
373 else
374 Addend0.set(C0, nullptr);
375 }
376
377 if (Opnd1) {
378 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
379 if (!C1)
380 Addend.set(1, Opnd1);
381 else
382 Addend.set(C1, nullptr);
383 if (Opcode == Instruction::FSub)
384 Addend.negate();
385 }
386
387 if (Opnd0 || Opnd1)
388 return Opnd0 && Opnd1 ? 2 : 1;
389
390 // Both operands are zero. Weird!
391 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
392 return 1;
393 }
394
395 if (I->getOpcode() == Instruction::FMul) {
396 Value *V0 = I->getOperand(0);
397 Value *V1 = I->getOperand(1);
398 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
399 Addend0.set(C, V1);
400 return 1;
401 }
402
403 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
404 Addend0.set(C, V0);
405 return 1;
406 }
407 }
408
409 return 0;
410}
411
412// Try to break *this* addend into two addends. e.g. Suppose this addend is
413// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
414// i.e. <2.3, X> and <2.3, Y>.
415unsigned FAddend::drillAddendDownOneStep
416 (FAddend &Addend0, FAddend &Addend1) const {
417 if (isConstant())
418 return 0;
419
420 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
421 if (!BreakNum || Coeff.isOne())
422 return BreakNum;
423
424 Addend0.Scale(Coeff);
425
426 if (BreakNum == 2)
427 Addend1.Scale(Coeff);
428
429 return BreakNum;
430}
431
432Value *FAddCombine::simplify(Instruction *I) {
433 assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
434 "Expected 'reassoc'+'nsz' instruction");
435
436 // Currently we are not able to handle vector type.
437 if (I->getType()->isVectorTy())
438 return nullptr;
439
440 assert((I->getOpcode() == Instruction::FAdd ||
441 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
442
443 // Save the instruction before calling other member-functions.
444 Instr = I;
445
446 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
447
448 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
449
450 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
451 unsigned Opnd0_ExpNum = 0;
452 unsigned Opnd1_ExpNum = 0;
453
454 if (!Opnd0.isConstant())
455 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
456
457 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
458 if (OpndNum == 2 && !Opnd1.isConstant())
459 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
460
461 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
462 if (Opnd0_ExpNum && Opnd1_ExpNum) {
463 AddendVect AllOpnds;
464 AllOpnds.push_back(&Opnd0_0);
465 AllOpnds.push_back(&Opnd1_0);
466 if (Opnd0_ExpNum == 2)
467 AllOpnds.push_back(&Opnd0_1);
468 if (Opnd1_ExpNum == 2)
469 AllOpnds.push_back(&Opnd1_1);
470
471 // Compute instruction quota. We should save at least one instruction.
472 unsigned InstQuota = 0;
473
474 Value *V0 = I->getOperand(0);
475 Value *V1 = I->getOperand(1);
476 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
477 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
478
479 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
480 return R;
481 }
482
483 if (OpndNum != 2) {
484 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
485 // splitted into two addends, say "V = X - Y", the instruction would have
486 // been optimized into "I = Y - X" in the previous steps.
487 //
488 const FAddendCoef &CE = Opnd0.getCoef();
489 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
490 }
491
492 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
493 if (Opnd1_ExpNum) {
494 AddendVect AllOpnds;
495 AllOpnds.push_back(&Opnd0);
496 AllOpnds.push_back(&Opnd1_0);
497 if (Opnd1_ExpNum == 2)
498 AllOpnds.push_back(&Opnd1_1);
499
500 if (Value *R = simplifyFAdd(AllOpnds, 1))
501 return R;
502 }
503
504 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
505 if (Opnd0_ExpNum) {
506 AddendVect AllOpnds;
507 AllOpnds.push_back(&Opnd1);
508 AllOpnds.push_back(&Opnd0_0);
509 if (Opnd0_ExpNum == 2)
510 AllOpnds.push_back(&Opnd0_1);
511
512 if (Value *R = simplifyFAdd(AllOpnds, 1))
513 return R;
514 }
515
516 return nullptr;
517}
518
519Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
520 unsigned AddendNum = Addends.size();
521 assert(AddendNum <= 4 && "Too many addends");
522
523 // For saving intermediate results;
524 unsigned NextTmpIdx = 0;
525 FAddend TmpResult[3];
526
527 // Simplified addends are placed <SimpVect>.
528 AddendVect SimpVect;
529
530 // The outer loop works on one symbolic-value at a time. Suppose the input
531 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
532 // The symbolic-values will be processed in this order: x, y, z.
533 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
534
535 const FAddend *ThisAddend = Addends[SymIdx];
536 if (!ThisAddend) {
537 // This addend was processed before.
538 continue;
539 }
540
541 Value *Val = ThisAddend->getSymVal();
542
543 // If the resulting expr has constant-addend, this constant-addend is
544 // desirable to reside at the top of the resulting expression tree. Placing
545 // constant close to super-expr(s) will potentially reveal some
546 // optimization opportunities in super-expr(s). Here we do not implement
547 // this logic intentionally and rely on SimplifyAssociativeOrCommutative
548 // call later.
549
550 unsigned StartIdx = SimpVect.size();
551 SimpVect.push_back(ThisAddend);
552
553 // The inner loop collects addends sharing same symbolic-value, and these
554 // addends will be later on folded into a single addend. Following above
555 // example, if the symbolic value "y" is being processed, the inner loop
556 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
557 // be later on folded into "<b1+b2, y>".
558 for (unsigned SameSymIdx = SymIdx + 1;
559 SameSymIdx < AddendNum; SameSymIdx++) {
560 const FAddend *T = Addends[SameSymIdx];
561 if (T && T->getSymVal() == Val) {
562 // Set null such that next iteration of the outer loop will not process
563 // this addend again.
564 Addends[SameSymIdx] = nullptr;
565 SimpVect.push_back(T);
566 }
567 }
568
569 // If multiple addends share same symbolic value, fold them together.
570 if (StartIdx + 1 != SimpVect.size()) {
571 FAddend &R = TmpResult[NextTmpIdx ++];
572 R = *SimpVect[StartIdx];
573 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
574 R += *SimpVect[Idx];
575
576 // Pop all addends being folded and push the resulting folded addend.
577 SimpVect.resize(StartIdx);
578 if (!R.isZero()) {
579 SimpVect.push_back(&R);
580 }
581 }
582 }
583
584 assert((NextTmpIdx <= std::size(TmpResult) + 1) && "out-of-bound access");
585
586 Value *Result;
587 if (!SimpVect.empty())
588 Result = createNaryFAdd(SimpVect, InstrQuota);
589 else {
590 // The addition is folded to 0.0.
591 Result = ConstantFP::get(Instr->getType(), 0.0);
592 }
593
594 return Result;
595}
596
597Value *FAddCombine::createNaryFAdd
598 (const AddendVect &Opnds, unsigned InstrQuota) {
599 assert(!Opnds.empty() && "Expect at least one addend");
600
601 // Step 1: Check if the # of instructions needed exceeds the quota.
602
603 unsigned InstrNeeded = calcInstrNumber(Opnds);
604 if (InstrNeeded > InstrQuota)
605 return nullptr;
606
607 initCreateInstNum();
608
609 // step 2: Emit the N-ary addition.
610 // Note that at most three instructions are involved in Fadd-InstCombine: the
611 // addition in question, and at most two neighboring instructions.
612 // The resulting optimized addition should have at least one less instruction
613 // than the original addition expression tree. This implies that the resulting
614 // N-ary addition has at most two instructions, and we don't need to worry
615 // about tree-height when constructing the N-ary addition.
616
617 Value *LastVal = nullptr;
618 bool LastValNeedNeg = false;
619
620 // Iterate the addends, creating fadd/fsub using adjacent two addends.
621 for (const FAddend *Opnd : Opnds) {
622 bool NeedNeg;
623 Value *V = createAddendVal(*Opnd, NeedNeg);
624 if (!LastVal) {
625 LastVal = V;
626 LastValNeedNeg = NeedNeg;
627 continue;
628 }
629
630 if (LastValNeedNeg == NeedNeg) {
631 LastVal = createFAdd(LastVal, V);
632 continue;
633 }
634
635 if (LastValNeedNeg)
636 LastVal = createFSub(V, LastVal);
637 else
638 LastVal = createFSub(LastVal, V);
639
640 LastValNeedNeg = false;
641 }
642
643 if (LastValNeedNeg) {
644 LastVal = createFNeg(LastVal);
645 }
646
647#ifndef NDEBUG
648 assert(CreateInstrNum == InstrNeeded &&
649 "Inconsistent in instruction numbers");
650#endif
651
652 return LastVal;
653}
654
655Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
656 Value *V = Builder.CreateFSub(Opnd0, Opnd1);
657 if (Instruction *I = dyn_cast<Instruction>(V))
658 createInstPostProc(I);
659 return V;
660}
661
662Value *FAddCombine::createFNeg(Value *V) {
663 Value *NewV = Builder.CreateFNeg(V);
664 if (Instruction *I = dyn_cast<Instruction>(NewV))
665 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
666 return NewV;
667}
668
669Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
670 Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
671 if (Instruction *I = dyn_cast<Instruction>(V))
672 createInstPostProc(I);
673 return V;
674}
675
676Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
677 Value *V = Builder.CreateFMul(Opnd0, Opnd1);
678 if (Instruction *I = dyn_cast<Instruction>(V))
679 createInstPostProc(I);
680 return V;
681}
682
683void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
684 NewInstr->setDebugLoc(Instr->getDebugLoc());
685
686 // Keep track of the number of instruction created.
687 if (!NoNumber)
688 incCreateInstNum();
689
690 // Propagate fast-math flags
691 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
692}
693
694// Return the number of instruction needed to emit the N-ary addition.
695// NOTE: Keep this function in sync with createAddendVal().
696unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
697 unsigned OpndNum = Opnds.size();
698 unsigned InstrNeeded = OpndNum - 1;
699
700 // Adjust the number of instructions needed to emit the N-ary add.
701 for (const FAddend *Opnd : Opnds) {
702 if (Opnd->isConstant())
703 continue;
704
705 // The constant check above is really for a few special constant
706 // coefficients.
707 if (isa<UndefValue>(Opnd->getSymVal()))
708 continue;
709
710 const FAddendCoef &CE = Opnd->getCoef();
711 // Let the addend be "c * x". If "c == +/-1", the value of the addend
712 // is immediately available; otherwise, it needs exactly one instruction
713 // to evaluate the value.
714 if (!CE.isMinusOne() && !CE.isOne())
715 InstrNeeded++;
716 }
717 return InstrNeeded;
718}
719
720// Input Addend Value NeedNeg(output)
721// ================================================================
722// Constant C C false
723// <+/-1, V> V coefficient is -1
724// <2/-2, V> "fadd V, V" coefficient is -2
725// <C, V> "fmul V, C" false
726//
727// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
728Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
729 const FAddendCoef &Coeff = Opnd.getCoef();
730
731 if (Opnd.isConstant()) {
732 NeedNeg = false;
733 return Coeff.getValue(Instr->getType());
734 }
735
736 Value *OpndVal = Opnd.getSymVal();
737
738 if (Coeff.isMinusOne() || Coeff.isOne()) {
739 NeedNeg = Coeff.isMinusOne();
740 return OpndVal;
741 }
742
743 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
744 NeedNeg = Coeff.isMinusTwo();
745 return createFAdd(OpndVal, OpndVal);
746 }
747
748 NeedNeg = false;
749 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
750}
751
752// Checks if any operand is negative and we can convert add to sub.
753// This function checks for following negative patterns
754// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
755// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
756// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
758 InstCombiner::BuilderTy &Builder) {
759 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
760
761 // This function creates 2 instructions to replace ADD, we need at least one
762 // of LHS or RHS to have one use to ensure benefit in transform.
763 if (!LHS->hasOneUse() && !RHS->hasOneUse())
764 return nullptr;
765
766 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
767 const APInt *C1 = nullptr, *C2 = nullptr;
768
769 // if ONE is on other side, swap
770 if (match(RHS, m_Add(m_Value(X), m_One())))
771 std::swap(LHS, RHS);
772
773 if (match(LHS, m_Add(m_Value(X), m_One()))) {
774 // if XOR on other side, swap
775 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
776 std::swap(X, RHS);
777
778 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
779 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
780 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
781 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
782 Value *NewAnd = Builder.CreateAnd(Z, *C1);
783 return Builder.CreateSub(RHS, NewAnd, "sub");
784 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
785 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
786 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
787 Value *NewOr = Builder.CreateOr(Z, ~(*C1));
788 return Builder.CreateSub(RHS, NewOr, "sub");
789 }
790 }
791 }
792
793 // Restore LHS and RHS
794 LHS = I.getOperand(0);
795 RHS = I.getOperand(1);
796
797 // if XOR is on other side, swap
798 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
799 std::swap(LHS, RHS);
800
801 // C2 is ODD
802 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
803 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
804 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
805 if (C1->countr_zero() == 0)
806 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
807 Value *NewOr = Builder.CreateOr(Z, ~(*C2));
808 return Builder.CreateSub(RHS, NewOr, "sub");
809 }
810 return nullptr;
811}
812
813/// Wrapping flags may allow combining constants separated by an extend.
815 InstCombiner::BuilderTy &Builder) {
816 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
817 Type *Ty = Add.getType();
818 Constant *Op1C;
819 if (!match(Op1, m_Constant(Op1C)))
820 return nullptr;
821
822 // Try this match first because it results in an add in the narrow type.
823 // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
824 Value *X;
825 const APInt *C1, *C2;
826 if (match(Op1, m_APInt(C1)) &&
827 match(Op0, m_ZExt(m_NUWAddLike(m_Value(X), m_APInt(C2)))) &&
828 C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
829 APInt NewC = *C2 + C1->trunc(C2->getBitWidth());
830 // If the smaller add will fold to zero, we don't need to check one use.
831 if (NewC.isZero())
832 return new ZExtInst(X, Ty);
833 // Otherwise only do this if the existing zero extend will be removed.
834 if (Op0->hasOneUse())
835 return new ZExtInst(
836 Builder.CreateNUWAdd(X, ConstantInt::get(X->getType(), NewC)), Ty);
837 }
838
839 // More general combining of constants in the wide type.
840 // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
841 // or (zext nneg (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
842 Constant *NarrowC;
843 if (match(Op0, m_OneUse(m_SExtLike(
844 m_NSWAddLike(m_Value(X), m_Constant(NarrowC)))))) {
845 Value *WideC = Builder.CreateSExt(NarrowC, Ty);
846 Value *NewC = Builder.CreateAdd(WideC, Op1C);
847 Value *WideX = Builder.CreateSExt(X, Ty);
848 return BinaryOperator::CreateAdd(WideX, NewC);
849 }
850 // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
851 if (match(Op0,
853 Value *WideC = Builder.CreateZExt(NarrowC, Ty);
854 Value *NewC = Builder.CreateAdd(WideC, Op1C);
855 Value *WideX = Builder.CreateZExt(X, Ty);
856 return BinaryOperator::CreateAdd(WideX, NewC);
857 }
858 return nullptr;
859}
860
862 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
863 Type *Ty = Add.getType();
864 Constant *Op1C;
865 if (!match(Op1, m_ImmConstant(Op1C)))
866 return nullptr;
867
869 return NV;
870
871 if (Instruction *FoldedLogic = foldBinOpSelectBinOp(Add))
872 return FoldedLogic;
873
874 Value *X;
875 Constant *Op00C;
876
877 // add (sub C1, X), C2 --> sub (add C1, C2), X
878 if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
879 return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
880
881 Value *Y;
882
883 // add (sub X, Y), -1 --> add (not Y), X
884 if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
885 match(Op1, m_AllOnes()))
886 return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
887
888 // zext(bool) + C -> bool ? C + 1 : C
889 if (match(Op0, m_ZExt(m_Value(X))) &&
890 X->getType()->getScalarSizeInBits() == 1)
891 return createSelectInstWithUnknownProfile(X, InstCombiner::AddOne(Op1C),
892 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 createSelectInstWithUnknownProfile(X, InstCombiner::SubOne(Op1C),
897 Op1);
898
899 // ~X + C --> (C-1) - X
900 if (match(Op0, m_Not(m_Value(X)))) {
901 // ~X + C has NSW and (C-1) won't oveflow => (C-1)-X can have NSW
902 auto *COne = ConstantInt::get(Op1C->getType(), 1);
903 bool WillNotSOV = willNotOverflowSignedSub(Op1C, COne, Add);
904 BinaryOperator *Res =
905 BinaryOperator::CreateSub(ConstantExpr::getSub(Op1C, COne), X);
906 Res->setHasNoSignedWrap(Add.hasNoSignedWrap() && WillNotSOV);
907 return Res;
908 }
909
910 // (iN X s>> (N - 1)) + 1 --> zext (X > -1)
911 const APInt *C;
912 unsigned BitWidth = Ty->getScalarSizeInBits();
913 if (match(Op0, m_OneUse(m_AShr(m_Value(X),
915 match(Op1, m_One()))
916 return new ZExtInst(Builder.CreateIsNotNeg(X, "isnotneg"), Ty);
917
918 if (!match(Op1, m_APInt(C)))
919 return nullptr;
920
921 // (X | Op01C) + Op1C --> X + (Op01C + Op1C) iff the `or` is actually an `add`
922 Constant *Op01C;
923 if (match(Op0, m_DisjointOr(m_Value(X), m_ImmConstant(Op01C)))) {
924 BinaryOperator *NewAdd =
925 BinaryOperator::CreateAdd(X, ConstantExpr::getAdd(Op01C, Op1C));
926 NewAdd->setHasNoSignedWrap(Add.hasNoSignedWrap() &&
927 willNotOverflowSignedAdd(Op01C, Op1C, Add));
928 NewAdd->setHasNoUnsignedWrap(Add.hasNoUnsignedWrap());
929 return NewAdd;
930 }
931
932 // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
933 const APInt *C2;
934 if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
935 return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
936
937 if (C->isSignMask()) {
938 // If wrapping is not allowed, then the addition must set the sign bit:
939 // X + (signmask) --> X | signmask
940 if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
941 return BinaryOperator::CreateDisjointOr(Op0, Op1);
942
943 // If wrapping is allowed, then the addition flips the sign bit of LHS:
944 // X + (signmask) --> X ^ signmask
945 return BinaryOperator::CreateXor(Op0, Op1);
946 }
947
948 // Is this add the last step in a convoluted sext?
949 // add(zext(xor i16 X, -32768), -32768) --> sext X
950 if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
951 C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
952 return CastInst::Create(Instruction::SExt, X, Ty);
953
954 if (match(Op0, m_Xor(m_Value(X), m_APInt(C2)))) {
955 // (X ^ signmask) + C --> (X + (signmask ^ C))
956 if (C2->isSignMask())
957 return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C2 ^ *C));
958
959 // If X has no bits set other than an xor mask,
960 // xor is equivalent to sub with no borrow between bits:
961 // add (xor X, C2), C --> sub (C2 + C), X
962 KnownBits LHSKnown = computeKnownBits(X, &Add);
963 if ((*C2 | LHSKnown.Zero).isAllOnes())
964 return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C2 + *C), X);
965
966 // Look for a math+logic pattern that corresponds to sext-in-register of a
967 // value with cleared high bits. Convert that into a pair of shifts:
968 // add (xor X, 0x80), 0xF..F80 --> (X << ShAmtC) >>s ShAmtC
969 // add (xor X, 0xF..F80), 0x80 --> (X << ShAmtC) >>s ShAmtC
970 if (Op0->hasOneUse() && *C2 == -(*C)) {
971 unsigned BitWidth = Ty->getScalarSizeInBits();
972 unsigned ShAmt = 0;
973 if (C->isPowerOf2())
974 ShAmt = BitWidth - C->logBase2() - 1;
975 else if (C2->isPowerOf2())
976 ShAmt = BitWidth - C2->logBase2() - 1;
977 if (ShAmt &&
979 Constant *ShAmtC = ConstantInt::get(Ty, ShAmt);
980 Value *NewShl = Builder.CreateShl(X, ShAmtC, "sext");
981 return BinaryOperator::CreateAShr(NewShl, ShAmtC);
982 }
983 }
984 }
985
986 if (C->isOne() && Op0->hasOneUse()) {
987 // add (sext i1 X), 1 --> zext (not X)
988 // TODO: The smallest IR representation is (select X, 0, 1), and that would
989 // not require the one-use check. But we need to remove a transform in
990 // visitSelect and make sure that IR value tracking for select is equal or
991 // better than for these ops.
992 if (match(Op0, m_SExt(m_Value(X))) &&
993 X->getType()->getScalarSizeInBits() == 1)
994 return new ZExtInst(Builder.CreateNot(X), Ty);
995
996 // Shifts and add used to flip and mask off the low bit:
997 // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
998 const APInt *C3;
999 if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
1000 C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
1001 Value *NotX = Builder.CreateNot(X);
1002 return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
1003 }
1004 }
1005
1006 // umax(X, C) + -C --> usub.sat(X, C)
1007 if (match(Op0, m_OneUse(m_UMax(m_Value(X), m_SpecificInt(-*C)))))
1008 return replaceInstUsesWith(
1009 Add, Builder.CreateBinaryIntrinsic(
1010 Intrinsic::usub_sat, X, ConstantInt::get(Add.getType(), -*C)));
1011 // uadd.sat(X, C) + -C --> umin(X, ~C)
1012 // The saturating add gives X + C or UMAX, so subtracting C leaves X or
1013 // UMAX - C. Note UMAX - C == ~C.
1014 {
1015 APInt SatC = -*C;
1017 m_Value(X), m_SpecificInt(SatC)))))
1018 return replaceInstUsesWith(
1019 Add, Builder.CreateBinaryIntrinsic(Intrinsic::umin, X,
1020 ConstantInt::get(Ty, ~SatC)));
1021 }
1022 // Fold (add (zext (add X, -C)), C) -> (zext X) if X u>= C.
1023 // Truncate C to the narrow type to avoid mismatched width comparisons.
1024 {
1025 const APInt *InnerC;
1026 if (match(Op0, m_ZExt(m_Add(m_Value(X), m_APIntAllowPoison(InnerC))))) {
1027 unsigned NarrowBW = InnerC->getBitWidth();
1028 if (C->isIntN(NarrowBW)) {
1029 APInt NarrowC = C->trunc(NarrowBW);
1030 const SimplifyQuery Q = SQ.getWithInstruction(&Add);
1031 if (*InnerC == -NarrowC &&
1032 (NarrowC.isOne()
1034 : computeKnownBits(X, &Add).getMinValue().uge(NarrowC)))
1035 return new ZExtInst(X, Ty);
1036 }
1037 }
1038 }
1039
1040 return nullptr;
1041}
1042
1043// match variations of a^2 + 2*a*b + b^2
1044//
1045// to reuse the code between the FP and Int versions, the instruction OpCodes
1046// and constant types have been turned into template parameters.
1047//
1048// Mul2Rhs: The constant to perform the multiplicative equivalent of X*2 with;
1049// should be `m_SpecificFP(2.0)` for FP and `m_SpecificInt(1)` for Int
1050// (we're matching `X<<1` instead of `X*2` for Int)
1051template <bool FP, typename Mul2Rhs>
1052static bool matchesSquareSum(BinaryOperator &I, Mul2Rhs M2Rhs, Value *&A,
1053 Value *&B) {
1054 constexpr unsigned MulOp = FP ? Instruction::FMul : Instruction::Mul;
1055 constexpr unsigned AddOp = FP ? Instruction::FAdd : Instruction::Add;
1056 constexpr unsigned Mul2Op = FP ? Instruction::FMul : Instruction::Shl;
1057
1058 // (a * a) + (((a * 2) + b) * b)
1059 if (match(&I, m_c_BinOp(
1060 AddOp, m_BinOp(MulOp, m_Value(A), m_Deferred(A)),
1062 MulOp,
1063 m_c_BinOp(AddOp, m_BinOp(Mul2Op, m_Deferred(A), M2Rhs),
1064 m_Value(B)),
1065 m_Deferred(B))))))
1066 return true;
1067
1068 // ((a * b) * 2) or ((a * 2) * b)
1069 // +
1070 // (a * a + b * b) or (b * b + a * a)
1071 return match(
1072 &I, m_c_BinOp(
1073 AddOp,
1076 Mul2Op, m_BinOp(MulOp, m_Value(A), m_Value(B)), M2Rhs)),
1077 m_OneUse(m_c_BinOp(MulOp, m_BinOp(Mul2Op, m_Value(A), M2Rhs),
1078 m_Value(B)))),
1079 m_OneUse(
1080 m_c_BinOp(AddOp, m_BinOp(MulOp, m_Deferred(A), m_Deferred(A)),
1081 m_BinOp(MulOp, m_Deferred(B), m_Deferred(B))))));
1082}
1083
1084// Fold integer variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1086 Value *A, *B;
1088 Value *AB = Builder.CreateAdd(A, B);
1089 return BinaryOperator::CreateMul(AB, AB);
1090 }
1091 return nullptr;
1092}
1093
1094// Fold floating point variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1095// Requires `nsz` and `reassoc`.
1097 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() && "Assumption mismatch");
1098 Value *A, *B;
1100 Value *AB = Builder.CreateFAddFMF(A, B, &I);
1101 return BinaryOperator::CreateFMulFMF(AB, AB, &I);
1102 }
1103 return nullptr;
1104}
1105
1106// Matches multiplication expression Op * C where C is a constant. Returns the
1107// constant value in C and the other operand in Op. Returns true if such a
1108// match is found.
1109static bool MatchMul(Value *E, Value *&Op, APInt &C) {
1110 const APInt *AI;
1111 if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
1112 C = *AI;
1113 return true;
1114 }
1115 if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
1116 C = APInt(AI->getBitWidth(), 1);
1117 C <<= *AI;
1118 return true;
1119 }
1120 return false;
1121}
1122
1123// Matches remainder expression Op % C where C is a constant. Returns the
1124// constant value in C and the other operand in Op. Returns the signedness of
1125// the remainder operation in IsSigned. Returns true if such a match is
1126// found.
1127static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
1128 const APInt *AI;
1129 IsSigned = false;
1130 if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
1131 IsSigned = true;
1132 C = *AI;
1133 return true;
1134 }
1135 if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
1136 C = *AI;
1137 return true;
1138 }
1139 if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
1140 C = *AI + 1;
1141 return true;
1142 }
1143 return false;
1144}
1145
1146// Matches division expression Op / C with the given signedness as indicated
1147// by IsSigned, where C is a constant. Returns the constant value in C and the
1148// other operand in Op. Returns true if such a match is found.
1149static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
1150 const APInt *AI;
1151 if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
1152 C = *AI;
1153 return true;
1154 }
1155 if (!IsSigned) {
1156 if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
1157 C = *AI;
1158 return true;
1159 }
1160 if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
1161 C = APInt(AI->getBitWidth(), 1);
1162 C <<= *AI;
1163 return true;
1164 }
1165 }
1166 return false;
1167}
1168
1169// Returns whether C0 * C1 with the given signedness overflows.
1170static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1171 bool overflow;
1172 if (IsSigned)
1173 (void)C0.smul_ov(C1, overflow);
1174 else
1175 (void)C0.umul_ov(C1, overflow);
1176 return overflow;
1177}
1178
1179// Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1180// does not overflow.
1181// Simplifies (X / C0) * C1 + (X % C0) * C2 to
1182// (X / C0) * (C1 - C2 * C0) + X * C2
1184 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1185 Value *X, *MulOpV;
1186 APInt C0, MulOpC;
1187 bool IsSigned;
1188 // Match I = X % C0 + MulOpV * C0
1189 if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
1190 (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
1191 C0 == MulOpC) {
1192 Value *RemOpV;
1193 APInt C1;
1194 bool Rem2IsSigned;
1195 // Match MulOpC = RemOpV % C1
1196 if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
1197 IsSigned == Rem2IsSigned) {
1198 Value *DivOpV;
1199 APInt DivOpC;
1200 // Match RemOpV = X / C0
1201 if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1202 C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
1203 Value *NewDivisor = ConstantInt::get(X->getType(), C0 * C1);
1204 return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
1205 : Builder.CreateURem(X, NewDivisor, "urem");
1206 }
1207 }
1208 }
1209
1210 // Match I = (X / C0) * C1 + (X % C0) * C2.
1211 auto FoldDivRem = [&](Value *DivSide, Value *RemSide) -> Value * {
1212 Value *Div, *Rem;
1213 APInt C1, C2;
1214 if (!DivSide->hasOneUse() || !MatchMul(DivSide, Div, C1))
1215 Div = DivSide, C1 = APInt(I.getType()->getScalarSizeInBits(), 1);
1216 if (!RemSide->hasOneUse() || !MatchMul(RemSide, Rem, C2))
1217 Rem = RemSide, C2 = APInt(I.getType()->getScalarSizeInBits(), 1);
1218 Value *DivOpV;
1219 APInt DivOpC;
1220 if (MatchRem(Rem, X, C0, IsSigned) &&
1221 MatchDiv(Div, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1222 C0 == DivOpC &&
1223 // Avoid unprofitable replacement of and with mul.
1224 !(C1.isOne() && !IsSigned && DivOpC.isPowerOf2() && DivOpC != 2)) {
1225 APInt NewC = C1 - C2 * C0;
1226 if (!NewC.isZero() && !Rem->hasOneUse())
1227 return nullptr;
1228 if (!isGuaranteedNotToBeUndef(X, &AC, &I, &DT))
1229 return nullptr;
1230 Value *MulXC2 = Builder.CreateMul(X, ConstantInt::get(X->getType(), C2));
1231 if (NewC.isZero())
1232 return MulXC2;
1233 return Builder.CreateAdd(
1234 Builder.CreateMul(Div, ConstantInt::get(X->getType(), NewC)), MulXC2);
1235 }
1236 return nullptr;
1237 };
1238 if (Value *V = FoldDivRem(LHS, RHS))
1239 return V;
1240 if (Value *V = FoldDivRem(RHS, LHS))
1241 return V;
1242
1243 return nullptr;
1244}
1245
1246/// Fold
1247/// (1 << NBits) - 1
1248/// Into:
1249/// ~(-(1 << NBits))
1250/// Because a 'not' is better for bit-tracking analysis and other transforms
1251/// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1253 InstCombiner::BuilderTy &Builder) {
1254 Value *NBits;
1255 if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
1256 return nullptr;
1257
1258 Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
1259 Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
1260 // Be wary of constant folding.
1261 if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
1262 // Always NSW. But NUW propagates from `add`.
1263 BOp->setHasNoSignedWrap();
1264 BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1265 }
1266
1267 return BinaryOperator::CreateNot(NotMask, I.getName());
1268}
1269
1271 assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
1272 Type *Ty = I.getType();
1273 auto getUAddSat = [&]() {
1274 return Intrinsic::getOrInsertDeclaration(I.getModule(), Intrinsic::uadd_sat,
1275 Ty);
1276 };
1277
1278 // add (umin X, ~Y), Y --> uaddsat X, Y
1279 Value *X, *Y;
1281 m_Deferred(Y))))
1282 return CallInst::Create(getUAddSat(), { X, Y });
1283
1284 // add (umin X, ~C), C --> uaddsat X, C
1285 const APInt *C, *NotC;
1286 if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
1287 *C == ~*NotC)
1288 return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
1289
1290 return nullptr;
1291}
1292
1293// Transform:
1294// (add A, (shl (neg B), Y))
1295// -> (sub A, (shl B, Y))
1297 const BinaryOperator &I) {
1298 Value *A, *B, *Cnt;
1299 if (match(&I,
1301 m_Value(A)))) {
1302 Value *NewShl = Builder.CreateShl(B, Cnt);
1303 return BinaryOperator::CreateSub(A, NewShl);
1304 }
1305 return nullptr;
1306}
1307
1308/// Try to reduce signed division by power-of-2 to an arithmetic shift right.
1310 // Division must be by power-of-2, but not the minimum signed value.
1311 Value *X;
1312 const APInt *DivC;
1313 if (!match(Add.getOperand(0), m_SDiv(m_Value(X), m_Power2(DivC))) ||
1314 DivC->isNegative())
1315 return nullptr;
1316
1317 // Rounding is done by adding -1 if the dividend (X) is negative and has any
1318 // low bits set. It recognizes two canonical patterns:
1319 // 1. For an 'ugt' cmp with the signed minimum value (SMIN), the
1320 // pattern is: sext (icmp ugt (X & (DivC - 1)), SMIN).
1321 // 2. For an 'eq' cmp, the pattern's: sext (icmp eq X & (SMIN + 1), SMIN + 1).
1322 // Note that, by the time we end up here, if possible, ugt has been
1323 // canonicalized into eq.
1324 const APInt *MaskC, *MaskCCmp;
1325 CmpPredicate Pred;
1326 if (!match(Add.getOperand(1),
1327 m_SExt(m_ICmp(Pred, m_And(m_Specific(X), m_APInt(MaskC)),
1328 m_APInt(MaskCCmp)))))
1329 return nullptr;
1330
1331 if ((Pred != ICmpInst::ICMP_UGT || !MaskCCmp->isSignMask()) &&
1332 (Pred != ICmpInst::ICMP_EQ || *MaskCCmp != *MaskC))
1333 return nullptr;
1334
1335 APInt SMin = APInt::getSignedMinValue(Add.getType()->getScalarSizeInBits());
1336 bool IsMaskValid = Pred == ICmpInst::ICMP_UGT
1337 ? (*MaskC == (SMin | (*DivC - 1)))
1338 : (*DivC == 2 && *MaskC == SMin + 1);
1339 if (!IsMaskValid)
1340 return nullptr;
1341
1342 // (X / DivC) + sext ((X & (SMin | (DivC - 1)) >u SMin) --> X >>s log2(DivC)
1343 return BinaryOperator::CreateAShr(
1344 X, ConstantInt::get(Add.getType(), DivC->exactLogBase2()));
1345}
1346
1348 bool NSW, bool NUW) {
1349 Value *A, *B, *C;
1350 if (match(LHS, m_Sub(m_Value(A), m_Value(B))) &&
1351 match(RHS, m_Sub(m_Value(C), m_Specific(A)))) {
1352 Instruction *R = BinaryOperator::CreateSub(C, B);
1353 bool NSWOut = NSW && match(LHS, m_NSWSub(m_Value(), m_Value())) &&
1354 match(RHS, m_NSWSub(m_Value(), m_Value()));
1355
1356 bool NUWOut = match(LHS, m_NUWSub(m_Value(), m_Value())) &&
1357 match(RHS, m_NUWSub(m_Value(), m_Value()));
1358 R->setHasNoSignedWrap(NSWOut);
1359 R->setHasNoUnsignedWrap(NUWOut);
1360 return R;
1361 }
1362
1363 // ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
1364 const APInt *C1, *C2;
1365 if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
1366 APInt One(C2->getBitWidth(), 1);
1367 APInt MinusC1 = -(*C1);
1368 if (MinusC1 == (One << *C2)) {
1369 Constant *NewRHS = ConstantInt::get(RHS->getType(), MinusC1);
1370 return BinaryOperator::CreateSRem(RHS, NewRHS);
1371 }
1372 }
1373
1374 // (A + C) + (B & ~C) == A + (B | C)
1375 if (match(LHS, m_c_Add(m_Value(A), m_APInt(C1))) &&
1376 match(RHS, m_c_And(m_Value(B), m_SpecificInt(~*C1)))) {
1377 // Replacing one add with {or, add}. Avoid growth if both sides are shared.
1378 if (!LHS->hasOneUse() && !RHS->hasOneUse())
1379 return nullptr;
1380
1381 bool NSWOut = NSW && match(LHS, m_NSWAdd(m_Value(), m_Value()));
1382 bool NUWOut = NUW && match(LHS, m_NUWAdd(m_Value(), m_Value()));
1383 Value *NewOr =
1384 Builder.CreateOr(B, Constant::getIntegerValue(LHS->getType(), *C1));
1385 Instruction *NewAdd = BinaryOperator::CreateAdd(A, NewOr);
1386 NewAdd->setHasNoSignedWrap(NSWOut);
1387 NewAdd->setHasNoUnsignedWrap(NUWOut);
1388 return NewAdd;
1389 }
1390
1391 return nullptr;
1392}
1393
1396 BinaryOperator &I) {
1397 assert((I.getOpcode() == Instruction::Add ||
1398 I.getOpcode() == Instruction::Or ||
1399 I.getOpcode() == Instruction::Sub) &&
1400 "Expecting add/or/sub instruction");
1401
1402 // We have a subtraction/addition between a (potentially truncated) *logical*
1403 // right-shift of X and a "select".
1404 Value *X, *Select;
1405 Instruction *LowBitsToSkip, *Extract;
1407 Extract, m_LShr(m_Value(X),
1408 m_Instruction(LowBitsToSkip)))),
1409 m_Value(Select))))
1410 return nullptr;
1411
1412 // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
1413 if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
1414 return nullptr;
1415
1416 Type *XTy = X->getType();
1417 bool HadTrunc = I.getType() != XTy;
1418
1419 // If there was a truncation of extracted value, then we'll need to produce
1420 // one extra instruction, so we need to ensure one instruction will go away.
1421 if (HadTrunc && !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1422 return nullptr;
1423
1424 // Extraction should extract high NBits bits, with shift amount calculated as:
1425 // low bits to skip = shift bitwidth - high bits to extract
1426 // The shift amount itself may be extended, and we need to look past zero-ext
1427 // when matching NBits, that will matter for matching later.
1428 Value *NBits;
1429 if (!match(LowBitsToSkip,
1431 m_ZExtOrSelf(m_Value(NBits))))))
1432 return nullptr;
1433
1434 // Sign-extending value can be zero-extended if we `sub`tract it,
1435 // or sign-extended otherwise.
1436 auto SkipExtInMagic = [&I](Value *&V) {
1437 if (I.getOpcode() == Instruction::Sub)
1438 match(V, m_ZExtOrSelf(m_Value(V)));
1439 else
1440 match(V, m_SExtOrSelf(m_Value(V)));
1441 };
1442
1443 // Now, finally validate the sign-extending magic.
1444 // `select` itself may be appropriately extended, look past that.
1445 SkipExtInMagic(Select);
1446
1447 CmpPredicate Pred;
1448 const APInt *Thr;
1449 Value *SignExtendingValue, *Zero;
1450 bool ShouldSignext;
1451 // It must be a select between two values we will later establish to be a
1452 // sign-extending value and a zero constant. The condition guarding the
1453 // sign-extension must be based on a sign bit of the same X we had in `lshr`.
1454 if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
1455 m_Value(SignExtendingValue), m_Value(Zero))) ||
1456 !isSignBitCheck(Pred, *Thr, ShouldSignext))
1457 return nullptr;
1458
1459 // icmp-select pair is commutative.
1460 if (!ShouldSignext)
1461 std::swap(SignExtendingValue, Zero);
1462
1463 // If we should not perform sign-extension then we must add/or/subtract zero.
1464 if (!match(Zero, m_Zero()))
1465 return nullptr;
1466 // Otherwise, it should be some constant, left-shifted by the same NBits we
1467 // had in `lshr`. Said left-shift can also be appropriately extended.
1468 // Again, we must look past zero-ext when looking for NBits.
1469 SkipExtInMagic(SignExtendingValue);
1470 Constant *SignExtendingValueBaseConstant;
1471 if (!match(SignExtendingValue,
1472 m_Shl(m_Constant(SignExtendingValueBaseConstant),
1473 m_ZExtOrSelf(m_Specific(NBits)))))
1474 return nullptr;
1475 // If we `sub`, then the constant should be one, else it should be all-ones.
1476 if (I.getOpcode() == Instruction::Sub
1477 ? !match(SignExtendingValueBaseConstant, m_One())
1478 : !match(SignExtendingValueBaseConstant, m_AllOnes()))
1479 return nullptr;
1480
1481 auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
1482 Extract->getName() + ".sext");
1483 NewAShr->copyIRFlags(Extract); // Preserve `exact`-ness.
1484 if (!HadTrunc)
1485 return NewAShr;
1486
1487 Builder.Insert(NewAShr);
1488 return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
1489}
1490
1491/// This is a specialization of a more general transform from
1492/// foldUsingDistributiveLaws. If that code can be made to work optimally
1493/// for multi-use cases or propagating nsw/nuw, then we would not need this.
1495 InstCombiner::BuilderTy &Builder) {
1496 // TODO: Also handle mul by doubling the shift amount?
1497 assert((I.getOpcode() == Instruction::Add ||
1498 I.getOpcode() == Instruction::Sub) &&
1499 "Expected add/sub");
1500 auto *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
1501 auto *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
1502 if (!Op0 || !Op1 || !(Op0->hasOneUse() || Op1->hasOneUse()))
1503 return nullptr;
1504
1505 Value *X, *Y, *ShAmt;
1506 if (!match(Op0, m_Shl(m_Value(X), m_Value(ShAmt))) ||
1507 !match(Op1, m_Shl(m_Value(Y), m_Specific(ShAmt))))
1508 return nullptr;
1509
1510 // No-wrap propagates only when all ops have no-wrap.
1511 bool HasNSW = I.hasNoSignedWrap() && Op0->hasNoSignedWrap() &&
1512 Op1->hasNoSignedWrap();
1513 bool HasNUW = I.hasNoUnsignedWrap() && Op0->hasNoUnsignedWrap() &&
1514 Op1->hasNoUnsignedWrap();
1515
1516 // add/sub (X << ShAmt), (Y << ShAmt) --> (add/sub X, Y) << ShAmt
1517 Value *NewMath = Builder.CreateBinOp(I.getOpcode(), X, Y);
1518 if (auto *NewI = dyn_cast<BinaryOperator>(NewMath)) {
1519 NewI->setHasNoSignedWrap(HasNSW);
1520 NewI->setHasNoUnsignedWrap(HasNUW);
1521 }
1522 auto *NewShl = BinaryOperator::CreateShl(NewMath, ShAmt);
1523 NewShl->setHasNoSignedWrap(HasNSW);
1524 NewShl->setHasNoUnsignedWrap(HasNUW);
1525 return NewShl;
1526}
1527
1528/// Reduce a sequence of masked half-width multiplies to a single multiply.
1529/// ((XLow * YHigh) + (YLow * XHigh)) << HalfBits) + (XLow * YLow) --> X * Y
1531 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1532 // Skip the odd bitwidth types.
1533 if ((BitWidth & 0x1))
1534 return nullptr;
1535
1536 unsigned HalfBits = BitWidth >> 1;
1537 APInt HalfMask = APInt::getMaxValue(HalfBits);
1538
1539 // ResLo = (CrossSum << HalfBits) + (YLo * XLo)
1540 Value *XLo, *YLo;
1541 Value *CrossSum;
1542 // Require one-use on the multiply to avoid increasing the number of
1543 // multiplications.
1544 if (!match(&I, m_c_Add(m_Shl(m_Value(CrossSum), m_SpecificInt(HalfBits)),
1545 m_OneUse(m_Mul(m_Value(YLo), m_Value(XLo))))))
1546 return nullptr;
1547
1548 // XLo = X & HalfMask
1549 // YLo = Y & HalfMask
1550 // TODO: Refactor with SimplifyDemandedBits or KnownBits known leading zeros
1551 // to enhance robustness
1552 Value *X, *Y;
1553 if (!match(XLo, m_And(m_Value(X), m_SpecificInt(HalfMask))) ||
1554 !match(YLo, m_And(m_Value(Y), m_SpecificInt(HalfMask))))
1555 return nullptr;
1556
1557 // CrossSum = (X' * (Y >> Halfbits)) + (Y' * (X >> HalfBits))
1558 // X' can be either X or XLo in the pattern (and the same for Y')
1559 if (match(CrossSum,
1564 return BinaryOperator::CreateMul(X, Y);
1565
1566 return nullptr;
1567}
1568
1569/// Return true if X + (Y-1) is provably non-wrapping in X's type
1570static bool checkDivCeilNUW(Value *X, Value *Y, const SimplifyQuery &SQ) {
1571 ConstantRange CRX = computeConstantRange(X, /*ForSigned=*/false, SQ);
1572 ConstantRange CRY = computeConstantRange(Y, /*ForSigned=*/false, SQ);
1573 APInt MinY = CRY.getUnsignedMin();
1574 APInt MaxX = CRX.getUnsignedMax();
1575 APInt MaxY = CRY.getUnsignedMax();
1576
1577 return !MinY.isZero() && !MaxX.ugt(-MaxY);
1578}
1579
1580/// Fold the div_ceil idiom in both forms:
1581/// add(udiv(X, Y), zext(icmp ne(urem(X, Y), 0)))
1582/// -> udiv(add nuw(X, Y - 1), Y)
1583/// add(zext(udiv(X, Y)), zext(icmp ne(urem(X, Y), 0)))
1584/// -> zext(udiv(add nuw(X, Y - 1), Y))
1585/// The zext form applies when udiv/urem operate in a narrower type than the
1586/// add.
1588 Value *X, *Y;
1589
1590 auto UDivPat = m_OneUse(m_UDiv(m_Value(X), m_Value(Y)));
1591 auto URemPat = m_OneUse(m_URem(m_Deferred(X), m_Deferred(Y)));
1592 auto ICmpPat = m_OneUse(m_SpecificICmp(ICmpInst::ICMP_NE, URemPat, m_Zero()));
1593 auto DivPat = m_OneUse(m_ZExtOrSelf(UDivPat));
1594 auto ZExtCmpPat = m_OneUse(m_ZExt(ICmpPat));
1595
1596 if (!match(&I, m_c_Add(DivPat, ZExtCmpPat)) ||
1597 !checkDivCeilNUW(X, Y, SQ.getWithInstruction(&I)))
1598 return nullptr;
1599
1600 Value *YMinusOne =
1601 Builder.CreateAdd(Y, ConstantInt::getAllOnesValue(Y->getType()));
1602 Value *NUWAdd = Builder.CreateNUWAdd(X, YMinusOne);
1603 if (X->getType() != I.getType()) {
1604 Value *Div = Builder.CreateUDiv(NUWAdd, Y);
1605 return new ZExtInst(Div, I.getType());
1606 }
1607 return BinaryOperator::CreateUDiv(NUWAdd, Y);
1608}
1609
1611 if (Value *V = simplifyAddInst(I.getOperand(0), I.getOperand(1),
1612 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1613 SQ.getWithInstruction(&I)))
1614 return replaceInstUsesWith(I, V);
1615
1617 return &I;
1618
1620 return X;
1621
1623 return Phi;
1624
1625 // (A*B)+(A*C) -> A*(B+C) etc
1627 return replaceInstUsesWith(I, V);
1628
1629 if (Instruction *R = foldBoxMultiply(I))
1630 return R;
1631
1633 return R;
1634
1636 return X;
1637
1639 return X;
1640
1642 return R;
1643
1645 return R;
1646
1647 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1648 if (Instruction *R = foldAddLikeCommutative(LHS, RHS, I.hasNoSignedWrap(),
1649 I.hasNoUnsignedWrap()))
1650 return R;
1651 if (Instruction *R = foldAddLikeCommutative(RHS, LHS, I.hasNoSignedWrap(),
1652 I.hasNoUnsignedWrap()))
1653 return R;
1654 Type *Ty = I.getType();
1655 if (Ty->isIntOrIntVectorTy(1))
1656 return BinaryOperator::CreateXor(LHS, RHS);
1657
1658 // X + X --> X << 1
1659 if (LHS == RHS) {
1660 auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
1661 Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1662 Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1663 return Shl;
1664 }
1665
1666 Value *A, *B;
1667 if (match(LHS, m_Neg(m_Value(A)))) {
1668 // -A + -B --> -(A + B)
1669 if (match(RHS, m_Neg(m_Value(B))))
1670 return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
1671
1672 // -A + B --> B - A
1673 auto *Sub = BinaryOperator::CreateSub(RHS, A);
1674 auto *OB0 = cast<OverflowingBinaryOperator>(LHS);
1675 Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OB0->hasNoSignedWrap());
1676
1677 return Sub;
1678 }
1679
1680 // A + -B --> A - B
1681 if (match(RHS, m_Neg(m_Value(B)))) {
1682 auto *Sub = BinaryOperator::CreateSub(LHS, B);
1683 auto *OBO = cast<OverflowingBinaryOperator>(RHS);
1684 Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OBO->hasNoSignedWrap());
1685 return Sub;
1686 }
1687
1689 return replaceInstUsesWith(I, V);
1690
1691 // (A + 1) + ~B --> A - B
1692 // ~B + (A + 1) --> A - B
1693 // (~B + A) + 1 --> A - B
1694 // (A + ~B) + 1 --> A - B
1695 // This relies on the ~B == -1-B identity.
1696 if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
1698 return BinaryOperator::CreateSub(A, B);
1699
1700 {
1701 // (A + C) + ~B --> A - B + (C-1)
1702 // ~B + (A + C) --> A - B + (C-1)
1703 // (~B + A) + C --> A - B + (C-1)
1704 // (A + ~B) + C --> A - B + (C-1)
1705 // With constant C, subtraction of one is free, so we replace three ops
1706 // (two adds and a bitwise-not) with two (sub and add).
1707 const APInt *C;
1709 m_Not(m_Value(B)))) ||
1711 m_APIntAllowPoison(C)))) {
1712 Value *Sub = Builder.CreateSub(A, B);
1713 return BinaryOperator::CreateAdd(Sub, ConstantInt::get(Ty, *C - 1));
1714 }
1715 }
1716
1717 // (A + RHS) + RHS --> A + (RHS << 1)
1718 if (match(LHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(RHS)))))
1719 return BinaryOperator::CreateAdd(A, Builder.CreateShl(RHS, 1, "reass.add"));
1720
1721 // LHS + (A + LHS) --> A + (LHS << 1)
1722 if (match(RHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(LHS)))))
1723 return BinaryOperator::CreateAdd(A, Builder.CreateShl(LHS, 1, "reass.add"));
1724
1725 {
1726 // (A + C1) + (C2 - B) --> (A - B) + (C1 + C2)
1727 Constant *C1, *C2;
1728 if (match(&I, m_c_Add(m_Add(m_Value(A), m_ImmConstant(C1)),
1729 m_Sub(m_ImmConstant(C2), m_Value(B)))) &&
1730 (LHS->hasOneUse() || RHS->hasOneUse())) {
1731 Value *Sub = Builder.CreateSub(A, B);
1732 return BinaryOperator::CreateAdd(Sub, ConstantExpr::getAdd(C1, C2));
1733 }
1734
1735 // Canonicalize a constant sub operand as an add operand for better folding:
1736 // (C1 - A) + B --> (B - A) + C1
1738 m_Value(B)))) {
1739 Value *Sub = Builder.CreateSub(B, A, "reass.sub");
1740 return BinaryOperator::CreateAdd(Sub, C1);
1741 }
1742 }
1743
1744 // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1746
1747 const APInt *C1;
1748 // (A & 2^C1) + A => A & (2^C1 - 1) iff bit C1 in A is a sign bit
1749 if (match(&I, m_c_Add(m_And(m_Value(A), m_APInt(C1)), m_Deferred(A))) &&
1750 C1->isPowerOf2() && (ComputeNumSignBits(A) > C1->countl_zero())) {
1751 Constant *NewMask = ConstantInt::get(RHS->getType(), *C1 - 1);
1752 return BinaryOperator::CreateAnd(A, NewMask);
1753 }
1754
1755 // ZExt (B - A) + ZExt(A) --> ZExt(B)
1756 if ((match(RHS, m_ZExt(m_Value(A))) &&
1757 match(LHS, m_ZExt(m_NUWSub(m_Value(B), m_Specific(A))))) ||
1758 (match(LHS, m_ZExt(m_Value(A))) &&
1760 return new ZExtInst(B, LHS->getType());
1761
1762 // zext(A) + sext(A) --> 0 if A is i1
1764 A->getType()->isIntOrIntVectorTy(1))
1765 return replaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1766
1767 // sext(A < B) + zext(A > B) => ucmp/scmp(A, B)
1768 CmpPredicate LTPred, GTPred;
1769 if (match(&I,
1770 m_c_Add(m_SExt(m_c_ICmp(LTPred, m_Value(A), m_Value(B))),
1771 m_ZExt(m_c_ICmp(GTPred, m_Deferred(A), m_Deferred(B))))) &&
1772 A->getType()->isIntOrIntVectorTy()) {
1773 if (ICmpInst::isGT(LTPred)) {
1774 std::swap(LTPred, GTPred);
1775 std::swap(A, B);
1776 }
1777
1778 if (ICmpInst::isLT(LTPred) && ICmpInst::isGT(GTPred) &&
1779 ICmpInst::isSigned(LTPred) == ICmpInst::isSigned(GTPred))
1780 return replaceInstUsesWith(
1781 I, Builder.CreateIntrinsic(
1782 Ty,
1783 ICmpInst::isSigned(LTPred) ? Intrinsic::scmp : Intrinsic::ucmp,
1784 {A, B}));
1785 }
1786
1787 // A+B --> A|B iff A and B have no bits set in common.
1788 WithCache<const Value *> LHSCache(LHS), RHSCache(RHS);
1789 switch (
1790 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ.getWithInstruction(&I))) {
1792 return BinaryOperator::CreateDisjointOr(LHS, RHS);
1794 return BinaryOperator::CreateOr(LHS, RHS);
1796 break;
1797 }
1798
1799 if (Instruction *Ext = narrowMathIfNoOverflow(I))
1800 return Ext;
1801
1802 // (add (xor A, B) (and A, B)) --> (or A, B)
1803 // (add (and A, B) (xor A, B)) --> (or A, B)
1804 if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
1806 return BinaryOperator::CreateOr(A, B);
1807
1808 // (add (or A, B) (and A, B)) --> (add A, B)
1809 // (add (and A, B) (or A, B)) --> (add A, B)
1810 if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
1812 // Replacing operands in-place to preserve nuw/nsw flags.
1813 replaceOperand(I, 0, A);
1814 replaceOperand(I, 1, B);
1815 return &I;
1816 }
1817
1818 // (add A (or A, -A)) --> (and (add A, -1) A)
1819 // (add A (or -A, A)) --> (and (add A, -1) A)
1820 // (add (or A, -A) A) --> (and (add A, -1) A)
1821 // (add (or -A, A) A) --> (and (add A, -1) A)
1823 m_Deferred(A)))))) {
1824 Value *Add =
1825 Builder.CreateAdd(A, Constant::getAllOnesValue(A->getType()), "",
1826 I.hasNoUnsignedWrap(), I.hasNoSignedWrap());
1827 return BinaryOperator::CreateAnd(Add, A);
1828 }
1829
1830 // Align-up idiom:
1831 // X + ((-X) & (C - 1)) --> (X + C - 1) & -C
1832 // ((X - 1) | (C - 1)) + 1 -> (X + C - 1) & -C
1833 // For a power-of-two C. Note -C == ~(C - 1), so the mask is simply the
1834 // inverted low-bit mask.
1835 {
1836 const APInt *LowMask;
1837 if (match(&I,
1839 m_Deferred(A))) ||
1841 m_LowBitMask(LowMask))),
1842 m_One()))
1843
1844 ) {
1845 Value *NewAdd = Builder.CreateAdd(A, ConstantInt::get(Ty, *LowMask));
1846 return BinaryOperator::CreateAnd(NewAdd, ConstantInt::get(Ty, ~*LowMask));
1847 }
1848 }
1849
1850 // Canonicalize ((A & -A) - 1) --> ((A - 1) & ~A)
1851 // Forms all commutable operations, and simplifies ctpop -> cttz folds.
1852 if (match(&I,
1854 m_AllOnes()))) {
1856 Value *Dec = Builder.CreateAdd(A, AllOnes);
1857 Value *Not = Builder.CreateXor(A, AllOnes);
1858 return BinaryOperator::CreateAnd(Dec, Not);
1859 }
1860
1861 // Disguised reassociation/factorization:
1862 // ~(A * C1) + A
1863 // ((A * -C1) - 1) + A
1864 // ((A * -C1) + A) - 1
1865 // (A * (1 - C1)) - 1
1866 if (match(&I,
1868 m_Deferred(A)))) {
1869 Type *Ty = I.getType();
1870 Constant *NewMulC = ConstantInt::get(Ty, 1 - *C1);
1871 Value *NewMul = Builder.CreateMul(A, NewMulC);
1872 return BinaryOperator::CreateAdd(NewMul, ConstantInt::getAllOnesValue(Ty));
1873 }
1874
1875 // (A * -2**C) + B --> B - (A << C)
1876 const APInt *NegPow2C;
1877 if (match(&I, m_c_Add(m_OneUse(m_Mul(m_Value(A), m_NegatedPower2(NegPow2C))),
1878 m_Value(B)))) {
1879 Constant *ShiftAmtC = ConstantInt::get(Ty, NegPow2C->countr_zero());
1880 Value *Shl = Builder.CreateShl(A, ShiftAmtC);
1881 return BinaryOperator::CreateSub(B, Shl);
1882 }
1883
1884 // Canonicalize signum variant that ends in add:
1885 // (A s>> (BW - 1)) + (zext (A s> 0)) --> (A s>> (BW - 1)) | (zext (A != 0))
1886 uint64_t BitWidth = Ty->getScalarSizeInBits();
1890 Value *NotZero = Builder.CreateIsNotNull(A, "isnotnull");
1891 Value *Zext = Builder.CreateZExt(NotZero, Ty, "isnotnull.zext");
1892 return BinaryOperator::CreateOr(LHS, Zext);
1893 }
1894
1895 {
1896 Value *Cond, *Ext;
1897 Constant *C;
1898 // (add X, (sext/zext (icmp eq X, C)))
1899 // -> (select (icmp eq X, C), (add C, (sext/zext 1)), X)
1900 auto CondMatcher =
1902 m_ImmConstant(C)));
1903
1904 if (match(&I,
1905 m_c_Add(m_Value(A), m_Value(Ext, m_ZExtOrSExt(CondMatcher)))) &&
1906 Ext->hasOneUse()) {
1909 return replaceInstUsesWith(I, Builder.CreateSelect(Cond, Add, A));
1910 }
1911 }
1912
1913 // (add (add A, 1), (sext (icmp ne A, 0))) => call umax(A, 1)
1914 if (match(LHS, m_Add(m_Value(A), m_One())) &&
1917 Value *OneConst = ConstantInt::get(A->getType(), 1);
1918 Value *UMax = Builder.CreateBinaryIntrinsic(Intrinsic::umax, A, OneConst);
1919 return replaceInstUsesWith(I, UMax);
1920 }
1921
1922 if (Instruction *Ashr = foldAddToAshr(I))
1923 return Ashr;
1924
1925 // Ceiling division by power-of-2:
1926 // (X >> log2(N)) + zext(X & (N-1) != 0) --> (X + (N-1)) >> log2(N)
1927 // This is valid when adding (N-1) to X doesn't overflow.
1928 {
1929 Value *X;
1930 const APInt *ShiftAmt, *Mask;
1931 CmpPredicate Pred;
1932
1933 // Match: (X >> C) + zext((X & Mask) != 0)
1934 // or: zext((X & Mask) != 0) + (X >> C)
1935 if (match(&I,
1938 m_And(m_Value(X), m_LowBitMask(Mask)), m_ZeroInt())),
1940 m_LShr(m_Deferred(X), m_APInt(ShiftAmt))))))) &&
1941 Mask->popcount() == *ShiftAmt) {
1942
1943 // Check if X + Mask doesn't overflow
1944 unsigned Xbits = X->getType()->getScalarSizeInBits();
1945 unsigned Ibits = Ty->getScalarSizeInBits();
1946 bool NeedZext = Ibits > Xbits;
1947 Constant *MaskC = ConstantInt::get(Ty, Mask->zext(Ibits));
1948 if (NeedZext || willNotOverflowUnsignedAdd(X, MaskC, I)) {
1949 if (NeedZext)
1950 X = Builder.CreateZExt(X, Ty);
1951 // (X + Mask) >> ShiftAmt
1952 Value *Add = Builder.CreateNUWAdd(X, MaskC);
1953 return BinaryOperator::CreateLShr(
1954 Add, ConstantInt::get(Ty, ShiftAmt->zext(Ibits)));
1955 }
1956 }
1957 }
1958
1959 // (~X) + (~Y) --> -2 - (X + Y)
1960 {
1961 // To ensure we can save instructions we need to ensure that we consume both
1962 // LHS/RHS (i.e they have a `not`).
1963 bool ConsumesLHS, ConsumesRHS;
1964 if (isFreeToInvert(LHS, LHS->hasOneUse(), ConsumesLHS) && ConsumesLHS &&
1965 isFreeToInvert(RHS, RHS->hasOneUse(), ConsumesRHS) && ConsumesRHS) {
1966 Value *NotLHS = getFreelyInverted(LHS, LHS->hasOneUse(), &Builder);
1967 Value *NotRHS = getFreelyInverted(RHS, RHS->hasOneUse(), &Builder);
1968 assert(NotLHS != nullptr && NotRHS != nullptr &&
1969 "isFreeToInvert desynced with getFreelyInverted");
1970 Value *LHSPlusRHS = Builder.CreateAdd(NotLHS, NotRHS);
1971 return BinaryOperator::CreateSub(
1972 ConstantInt::getSigned(RHS->getType(), -2), LHSPlusRHS);
1973 }
1974 }
1975
1977 return R;
1978
1979 // TODO(jingyue): Consider willNotOverflowSignedAdd and
1980 // willNotOverflowUnsignedAdd to reduce the number of invocations of
1981 // computeKnownBits.
1982 bool Changed = false;
1983 if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHSCache, RHSCache, I)) {
1984 Changed = true;
1985 I.setHasNoSignedWrap(true);
1986 }
1987 if (!I.hasNoUnsignedWrap() &&
1988 willNotOverflowUnsignedAdd(LHSCache, RHSCache, I)) {
1989 Changed = true;
1990 I.setHasNoUnsignedWrap(true);
1991 }
1992
1994 return V;
1995
1996 if (Instruction *V =
1998 return V;
1999
2001 return SatAdd;
2002
2003 // usub.sat(A, B) + B => umax(A, B)
2004 if (match(&I, m_c_BinOp(
2006 m_Deferred(B)))) {
2007 return replaceInstUsesWith(I,
2008 Builder.CreateIntrinsic(Intrinsic::umax, {I.getType()}, {A, B}));
2009 }
2010
2011 // ctpop(A) + ctpop(B) => ctpop(A | B) if A and B have no bits set in common.
2012 if (match(LHS, m_OneUse(m_Ctpop(m_Value(A)))) &&
2013 match(RHS, m_OneUse(m_Ctpop(m_Value(B)))) &&
2014 haveNoCommonBitsSet(A, B, SQ.getWithInstruction(&I)))
2015 return replaceInstUsesWith(
2016 I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
2017 {Builder.CreateDisjointOr(A, B)}));
2018
2019 // Fold the log2_ceil idiom:
2020 // zext(ctpop(A) >u/!= 1) + (ctlz(A, true) ^ (BW - 1))
2021 // -->
2022 // BW - ctlz(A - 1, false)
2023 const APInt *XorC;
2024 CmpPredicate Pred;
2025 if (match(&I, m_c_Add(m_ZExt(m_ICmp(Pred, m_Ctpop(m_Value(A)), m_One())),
2028 m_Ctlz(m_Deferred(A), m_One())))),
2029 m_APInt(XorC))))))) &&
2030 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_NE) &&
2031 *XorC == A->getType()->getScalarSizeInBits() - 1 &&
2032 isPowerOf2_32(A->getType()->getScalarSizeInBits())) {
2033 Value *Sub = Builder.CreateAdd(A, Constant::getAllOnesValue(A->getType()));
2034 Value *Ctlz = Builder.CreateIntrinsic(Intrinsic::ctlz, {A->getType()},
2035 {Sub, Builder.getFalse()});
2036 Value *Ret = Builder.CreateSub(
2037 ConstantInt::get(A->getType(), A->getType()->getScalarSizeInBits()),
2038 Ctlz, "", /*HasNUW=*/true, /*HasNSW=*/true);
2039 return replaceInstUsesWith(I, Builder.CreateZExtOrTrunc(Ret, I.getType()));
2040 }
2041
2042 if (Instruction *Res = foldSquareSumInt(I))
2043 return Res;
2044
2045 if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
2046 return Res;
2047
2049 return Res;
2050
2051 if (Instruction *Res = foldDivCeil(I))
2052 return Res;
2053
2054 // (A | -2) + A -> (A - 1) & -2
2055 APInt NegTwo(Ty->getScalarSizeInBits(), -2, /*isSigned=*/true);
2056 if (match(&I, m_c_BinOp(m_OneUse(m_Or(m_Value(A), m_SpecificInt(NegTwo))),
2057 m_Deferred(A)))) {
2058 Value *Ret = Builder.CreateAdd(
2059 A, ConstantInt::get(
2060 Ty, APInt(Ty->getScalarSizeInBits(), -1, /*isSigned=*/true)));
2061 return BinaryOperator::CreateAnd(Ret, ConstantInt::get(Ty, NegTwo));
2062 }
2063
2064 // Re-enqueue users of the induction variable of add recurrence if we infer
2065 // new nuw/nsw flags.
2066 if (Changed) {
2067 PHINode *PHI;
2068 Value *Start, *Step;
2069 if (matchSimpleRecurrence(&I, PHI, Start, Step))
2070 Worklist.pushUsersToWorkList(*PHI);
2071 }
2072
2073 return Changed ? &I : nullptr;
2074}
2075
2076/// Eliminate an op from a linear interpolation (lerp) pattern.
2078 InstCombiner::BuilderTy &Builder) {
2079 Value *X, *Y, *Z;
2082 m_Value(Z))))),
2084 return nullptr;
2085
2086 // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
2087 Value *XY = Builder.CreateFSubFMF(X, Y, &I);
2088 Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
2089 return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
2090}
2091
2092/// Factor a common operand out of fadd/fsub of fmul/fdiv.
2094 InstCombiner::BuilderTy &Builder) {
2095 assert((I.getOpcode() == Instruction::FAdd ||
2096 I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
2097 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
2098 "FP factorization requires FMF");
2099
2100 if (Instruction *Lerp = factorizeLerp(I, Builder))
2101 return Lerp;
2102
2103 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2104 if (!Op0->hasOneUse() || !Op1->hasOneUse())
2105 return nullptr;
2106
2107 Value *X, *Y, *Z;
2108 bool IsFMul;
2109 if ((match(Op0, m_FMul(m_Value(X), m_Value(Z))) &&
2110 match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))) ||
2111 (match(Op0, m_FMul(m_Value(Z), m_Value(X))) &&
2112 match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))))
2113 IsFMul = true;
2114 else if (match(Op0, m_FDiv(m_Value(X), m_Value(Z))) &&
2115 match(Op1, m_FDiv(m_Value(Y), m_Specific(Z))))
2116 IsFMul = false;
2117 else
2118 return nullptr;
2119
2120 // (X * Z) + (Y * Z) --> (X + Y) * Z
2121 // (X * Z) - (Y * Z) --> (X - Y) * Z
2122 // (X / Z) + (Y / Z) --> (X + Y) / Z
2123 // (X / Z) - (Y / Z) --> (X - Y) / Z
2124 bool IsFAdd = I.getOpcode() == Instruction::FAdd;
2125 Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
2126 : Builder.CreateFSubFMF(X, Y, &I);
2127
2128 // Bail out if we just created a denormal constant.
2129 // TODO: This is copied from a previous implementation. Is it necessary?
2130 const APFloat *C;
2131 if (match(XY, m_APFloat(C)) && !C->isNormal())
2132 return nullptr;
2133
2134 return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
2136}
2137
2139 if (Value *V = simplifyFAddInst(I.getOperand(0), I.getOperand(1),
2140 I.getFastMathFlags(),
2141 SQ.getWithInstruction(&I)))
2142 return replaceInstUsesWith(I, V);
2143
2145 return &I;
2146
2148 return X;
2149
2151 return Phi;
2152
2153 if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
2154 return FoldedFAdd;
2155
2156 // B = fadd A, 0.0
2157 // Z = Op B
2158 // can be transformed into
2159 // Z = Op A
2160 // Where Op is such that we can ignore sign of 0 in fadd
2161 Value *A;
2162 if (match(&I, m_OneUse(m_FAdd(m_Value(A), m_AnyZeroFP()))) &&
2163 canIgnoreSignBitOfZero(*I.use_begin()))
2164 return replaceInstUsesWith(I, A);
2165
2166 // (-X) + Y --> Y - X
2167 Value *X, *Y;
2168 if (match(&I, m_c_FAdd(m_FNeg(m_Value(X)), m_Value(Y))))
2170
2171 // Similar to above, but look through fmul/fdiv for the negated term.
2172 // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
2173 Value *Z;
2175 m_Value(Z)))) {
2176 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
2177 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
2178 }
2179 // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
2180 // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
2182 m_Value(Z))) ||
2184 m_Value(Z)))) {
2185 Value *XY = Builder.CreateFDivFMF(X, Y, &I);
2186 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
2187 }
2188
2189 // Check for (fadd double (sitofp x), y), see if we can merge this into an
2190 // integer add followed by a promotion.
2191 if (Instruction *R = foldFBinOpOfIntCasts(I))
2192 return R;
2193
2194 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2195 // Handle specials cases for FAdd with selects feeding the operation
2196 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
2197 return replaceInstUsesWith(I, V);
2198
2199 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
2201 return F;
2202
2204 return F;
2205
2206 // Try to fold fadd into start value of reduction intrinsic.
2208 m_AnyZeroFP(), m_Value(X))),
2209 m_Value(Y)))) {
2210 // fadd (rdx 0.0, X), Y --> rdx Y, X
2211 return replaceInstUsesWith(
2212 I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
2213 {X->getType()}, {Y, X}, &I));
2214 }
2215 const APFloat *StartC, *C;
2217 m_APFloat(StartC), m_Value(X)))) &&
2218 match(RHS, m_APFloat(C))) {
2219 // fadd (rdx StartC, X), C --> rdx (C + StartC), X
2220 Constant *NewStartC = ConstantFP::get(I.getType(), *C + *StartC);
2221 return replaceInstUsesWith(
2222 I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
2223 {X->getType()}, {NewStartC, X}, &I));
2224 }
2225
2226 // (X * MulC) + X --> X * (MulC + 1.0)
2227 Constant *MulC;
2228 if (match(&I, m_c_FAdd(m_FMul(m_Value(X), m_ImmConstant(MulC)),
2229 m_Deferred(X)))) {
2231 Instruction::FAdd, MulC, ConstantFP::get(I.getType(), 1.0), DL))
2232 return BinaryOperator::CreateFMulFMF(X, NewMulC, &I);
2233 }
2234
2235 // (-X - Y) + (X + Z) --> Z - Y
2237 m_c_FAdd(m_Deferred(X), m_Value(Z)))))
2238 return BinaryOperator::CreateFSubFMF(Z, Y, &I);
2239
2240 if (Value *V = FAddCombine(Builder).simplify(&I))
2241 return replaceInstUsesWith(I, V);
2242 }
2243
2244 // minumum(X, Y) + maximum(X, Y) => X + Y.
2245 if (match(&I,
2248 m_Deferred(Y))))) {
2250 // We cannot preserve ninf if nnan flag is not set.
2251 // If X is NaN and Y is Inf then in original program we had NaN + NaN,
2252 // while in optimized version NaN + Inf and this is a poison with ninf flag.
2253 if (!Result->hasNoNaNs())
2254 Result->setHasNoInfs(false);
2255 return Result;
2256 }
2257
2258 return nullptr;
2259}
2260
2263
2264 if (LHS->getType() != RHS->getType())
2265 return Base;
2266
2267 // Collect all base pointers of LHS.
2269 Value *Ptr = LHS;
2270 while (true) {
2271 Ptrs.insert(Ptr);
2272 if (auto *GEP = dyn_cast<GEPOperator>(Ptr))
2273 Ptr = GEP->getPointerOperand();
2274 else
2275 break;
2276 }
2277
2278 // Find common base and collect RHS GEPs.
2279 bool First = true;
2280 while (true) {
2281 if (Ptrs.contains(RHS)) {
2282 Base.Ptr = RHS;
2283 break;
2284 }
2285
2286 if (auto *GEP = dyn_cast<GEPOperator>(RHS)) {
2287 Base.RHSGEPs.push_back(GEP);
2288 if (First) {
2289 First = false;
2290 Base.RHSNW = GEP->getNoWrapFlags();
2291 } else {
2292 Base.RHSNW = Base.RHSNW.intersectForOffsetAdd(GEP->getNoWrapFlags());
2293 }
2294 RHS = GEP->getPointerOperand();
2295 } else {
2296 // No common base.
2297 return Base;
2298 }
2299 }
2300
2301 // Collect LHS GEPs.
2302 First = true;
2303 while (true) {
2304 if (LHS == Base.Ptr)
2305 break;
2306
2307 auto *GEP = cast<GEPOperator>(LHS);
2308 Base.LHSGEPs.push_back(GEP);
2309 if (First) {
2310 First = false;
2311 Base.LHSNW = GEP->getNoWrapFlags();
2312 } else {
2313 Base.LHSNW = Base.LHSNW.intersectForOffsetAdd(GEP->getNoWrapFlags());
2314 }
2315 LHS = GEP->getPointerOperand();
2316 }
2317
2318 return Base;
2319}
2320
2322 unsigned NumGEPs = 0;
2323 auto ProcessGEPs = [&NumGEPs](ArrayRef<GEPOperator *> GEPs) {
2324 bool SeenMultiUse = false;
2325 for (GEPOperator *GEP : GEPs) {
2326 // Only count multi-use GEPs, excluding the first one. For the first one,
2327 // we will directly reuse the offset. For one-use GEPs, their offset will
2328 // be folded into a multi-use GEP.
2329 if (!GEP->hasOneUse()) {
2330 if (SeenMultiUse)
2331 ++NumGEPs;
2332 SeenMultiUse = true;
2333 }
2334 }
2335 };
2336 ProcessGEPs(LHSGEPs);
2337 ProcessGEPs(RHSGEPs);
2338 return NumGEPs > 2;
2339}
2340
2341/// Optimize pointer differences into the same array into a size. Consider:
2342/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2343/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2345 Type *Ty, bool IsNUW) {
2347 if (!Base.Ptr || Base.isExpensive())
2348 return nullptr;
2349
2350 // To avoid duplicating the offset arithmetic, rewrite the GEP to use the
2351 // computed offset.
2352 // TODO: We should probably do this even if there is only one GEP.
2353 bool RewriteGEPs = !Base.LHSGEPs.empty() && !Base.RHSGEPs.empty();
2354
2355 Type *IdxTy = DL.getIndexType(LHS->getType());
2356 Value *Result = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, RewriteGEPs);
2357 Value *Offset2 = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy, RewriteGEPs);
2358
2359 // If this is a single inbounds GEP and the original sub was nuw,
2360 // then the final multiplication is also nuw.
2361 if (auto *I = dyn_cast<OverflowingBinaryOperator>(Result))
2362 if (IsNUW && match(Offset2, m_Zero()) && Base.LHSNW.isInBounds() &&
2363 (I->use_empty() || I->hasOneUse()) && I->hasNoSignedWrap() &&
2364 !I->hasNoUnsignedWrap() &&
2365 ((I->getOpcode() == Instruction::Mul &&
2366 match(I->getOperand(1), m_NonNegative())) ||
2367 I->getOpcode() == Instruction::Shl))
2368 cast<Instruction>(I)->setHasNoUnsignedWrap();
2369
2370 // If we have a 2nd GEP of the same base pointer, subtract the offsets.
2371 // If both GEPs are inbounds, then the subtract does not have signed overflow.
2372 // If both GEPs are nuw and the original sub is nuw, the new sub is also nuw.
2373 if (!match(Offset2, m_Zero())) {
2374 Result =
2375 Builder.CreateSub(Result, Offset2, "gepdiff",
2376 IsNUW && Base.LHSNW.hasNoUnsignedWrap() &&
2377 Base.RHSNW.hasNoUnsignedWrap(),
2378 Base.LHSNW.isInBounds() && Base.RHSNW.isInBounds());
2379 }
2380
2381 return Builder.CreateIntCast(Result, Ty, true);
2382}
2383
2385 InstCombiner::BuilderTy &Builder) {
2386 Value *Op0 = I.getOperand(0);
2387 Value *Op1 = I.getOperand(1);
2388 Type *Ty = I.getType();
2389 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op1);
2390 if (!MinMax)
2391 return nullptr;
2392
2393 // sub(add(X,Y), s/umin(X,Y)) --> s/umax(X,Y)
2394 // sub(add(X,Y), s/umax(X,Y)) --> s/umin(X,Y)
2395 Value *X = MinMax->getLHS();
2396 Value *Y = MinMax->getRHS();
2397 if (match(Op0, m_c_Add(m_Specific(X), m_Specific(Y))) &&
2398 (Op0->hasOneUse() || Op1->hasOneUse())) {
2399 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
2400 Function *F = Intrinsic::getOrInsertDeclaration(I.getModule(), InvID, Ty);
2401 return CallInst::Create(F, {X, Y});
2402 }
2403
2404 // sub(add(X,Y),umin(Y,Z)) --> add(X,usub.sat(Y,Z))
2405 // sub(add(X,Z),umin(Y,Z)) --> add(X,usub.sat(Z,Y))
2406 Value *Z;
2407 if (match(Op1, m_OneUse(m_UMin(m_Value(Y), m_Value(Z))))) {
2408 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Y), m_Value(X))))) {
2409 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Y, Z});
2410 return BinaryOperator::CreateAdd(X, USub);
2411 }
2412 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Z), m_Value(X))))) {
2413 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Z, Y});
2414 return BinaryOperator::CreateAdd(X, USub);
2415 }
2416 }
2417
2418 // sub Op0, smin((sub nsw Op0, Z), 0) --> smax Op0, Z
2419 // sub Op0, smax((sub nsw Op0, Z), 0) --> smin Op0, Z
2420 if (MinMax->isSigned() && match(Y, m_ZeroInt()) &&
2421 match(X, m_NSWSub(m_Specific(Op0), m_Value(Z)))) {
2422 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
2423 Function *F = Intrinsic::getOrInsertDeclaration(I.getModule(), InvID, Ty);
2424 return CallInst::Create(F, {Op0, Z});
2425 }
2426
2427 return nullptr;
2428}
2429
2431 if (Value *V = simplifySubInst(I.getOperand(0), I.getOperand(1),
2432 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
2433 SQ.getWithInstruction(&I)))
2434 return replaceInstUsesWith(I, V);
2435
2437 return X;
2438
2440 return Phi;
2441
2442 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2443
2444 // If this is a 'B = x-(-A)', change to B = x+A.
2445 // We deal with this without involving Negator to preserve NSW flag.
2446 if (Value *V = dyn_castNegVal(Op1)) {
2447 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2448
2449 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
2450 assert(BO->getOpcode() == Instruction::Sub &&
2451 "Expected a subtraction operator!");
2452 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
2453 Res->setHasNoSignedWrap(true);
2454 } else {
2455 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
2456 Res->setHasNoSignedWrap(true);
2457 }
2458
2459 return Res;
2460 }
2461
2462 // Try this before Negator to preserve NSW flag.
2464 return R;
2465
2466 Constant *C;
2467 if (match(Op0, m_ImmConstant(C))) {
2468 Value *X;
2469 Constant *C2;
2470
2471 // C-(X+C2) --> (C-C2)-X
2472 if (match(Op1, m_AddLike(m_Value(X), m_ImmConstant(C2)))) {
2473 // C-C2 never overflow, and C-(X+C2), (X+C2) has NSW/NUW
2474 // => (C-C2)-X can have NSW/NUW
2475 bool WillNotSOV = willNotOverflowSignedSub(C, C2, I);
2476 BinaryOperator *Res =
2477 BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
2478
2479 // or disjoint is equivalent to add nuw nsw.
2480 bool Op1NSW = true;
2481 bool Op1NUW = true;
2482
2483 if (auto *OBO1 = dyn_cast<OverflowingBinaryOperator>(Op1)) {
2484 Op1NSW = OBO1->hasNoSignedWrap();
2485 Op1NUW = OBO1->hasNoUnsignedWrap();
2486 }
2487
2488 Res->setHasNoSignedWrap(I.hasNoSignedWrap() && Op1NSW && WillNotSOV);
2489 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() && Op1NUW);
2490 return Res;
2491 }
2492 }
2493
2494 auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
2495 if (Instruction *Ext = narrowMathIfNoOverflow(I))
2496 return Ext;
2497
2498 bool Changed = false;
2499 if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
2500 Changed = true;
2501 I.setHasNoSignedWrap(true);
2502 }
2503 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
2504 Changed = true;
2505 I.setHasNoUnsignedWrap(true);
2506 }
2507
2508 return Changed ? &I : nullptr;
2509 };
2510
2511 // First, let's try to interpret `sub a, b` as `add a, (sub 0, b)`,
2512 // and let's try to sink `(sub 0, b)` into `b` itself. But only if this isn't
2513 // a pure negation used by a select that looks like abs/nabs.
2514 bool IsNegation = match(Op0, m_ZeroInt());
2515 if (!IsNegation || none_of(I.users(), match_fn(m_c_Select(m_Specific(Op1),
2516 m_Specific(&I))))) {
2517 if (Value *NegOp1 = Negator::Negate(IsNegation, /* IsNSW */ IsNegation &&
2518 I.hasNoSignedWrap(),
2519 Op1, *this))
2520 return BinaryOperator::CreateAdd(NegOp1, Op0);
2521 }
2522 if (IsNegation)
2523 return TryToNarrowDeduceFlags(); // Should have been handled in Negator!
2524
2525 // (A*B)-(A*C) -> A*(B-C) etc
2527 return replaceInstUsesWith(I, V);
2528
2529 if (I.getType()->isIntOrIntVectorTy(1))
2530 return BinaryOperator::CreateXor(Op0, Op1);
2531
2532 // Replace (-1 - A) with (~A).
2533 if (match(Op0, m_AllOnes()))
2534 return BinaryOperator::CreateNot(Op1);
2535
2536 // (X + -1) - Y --> ~Y + X
2537 Value *X, *Y;
2538 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
2539 return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
2540
2541 // if (C1 & C2) == C2 then (X & C1) - (X & C2) -> X & (C1 ^ C2)
2542 Constant *C1, *C2;
2543 if (match(Op0, m_And(m_Value(X), m_ImmConstant(C1))) &&
2544 match(Op1, m_And(m_Specific(X), m_ImmConstant(C2)))) {
2545 Value *AndC = ConstantFoldBinaryInstruction(Instruction::And, C1, C2);
2546 if (C2->isElementWiseEqual(AndC))
2547 return BinaryOperator::CreateAnd(
2548 X, ConstantFoldBinaryInstruction(Instruction::Xor, C1, C2));
2549 }
2550
2551 // Reassociate sub/add sequences to create more add instructions and
2552 // reduce dependency chains:
2553 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
2554 Value *Z;
2556 m_Value(Z))))) {
2557 Value *XZ = Builder.CreateAdd(X, Z);
2558 Value *YW = Builder.CreateAdd(Y, Op1);
2559 return BinaryOperator::CreateSub(XZ, YW);
2560 }
2561
2562 // ((X - Y) - Op1) --> X - (Y + Op1)
2563 if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y))))) {
2565 bool HasNUW = I.hasNoUnsignedWrap() && LHSSub->hasNoUnsignedWrap();
2566 bool HasNSW = HasNUW && I.hasNoSignedWrap() && LHSSub->hasNoSignedWrap();
2567 Value *Add = Builder.CreateAdd(Y, Op1, "", /*HasNUW=*/HasNUW,
2568 /*HasNSW=*/HasNSW);
2569 BinaryOperator *Sub = BinaryOperator::CreateSub(X, Add);
2570 Sub->setHasNoUnsignedWrap(HasNUW);
2571 Sub->setHasNoSignedWrap(HasNSW);
2572 return Sub;
2573 }
2574
2575 // (X + C0) - (Y + C1) --> (X - Y) + (C0 - C1)
2576 {
2577 Constant *CX, *CY;
2578 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_ImmConstant(CX)))) &&
2579 match(Op1, m_OneUse(m_Add(m_Value(Y), m_ImmConstant(CY))))) {
2580 Value *OpsSub = Builder.CreateSub(X, Y);
2581 Constant *ConstsSub = ConstantExpr::getSub(CX, CY);
2582 return BinaryOperator::CreateAdd(OpsSub, ConstsSub);
2583 }
2584 }
2585
2586 // (X + Z) - (Y + Z) --> (X - Y)
2587 {
2588 Value *W, *Z;
2589 if (match(Op0, m_AddLike(m_Value(W), m_Value(X))) &&
2590 match(Op1, m_AddLike(m_Value(Y), m_Value(Z)))) {
2591 Instruction *R = nullptr;
2592 if (W == Y)
2593 R = BinaryOperator::CreateSub(X, Z);
2594 else if (W == Z)
2595 R = BinaryOperator::CreateSub(X, Y);
2596 else if (X == Y)
2597 R = BinaryOperator::CreateSub(W, Z);
2598 else if (X == Z)
2599 R = BinaryOperator::CreateSub(W, Y);
2600 if (R) {
2601 bool NSW = I.hasNoSignedWrap() &&
2602 match(Op0, m_NSWAddLike(m_Value(), m_Value())) &&
2603 match(Op1, m_NSWAddLike(m_Value(), m_Value()));
2604
2605 bool NUW = I.hasNoUnsignedWrap() &&
2606 match(Op1, m_NUWAddLike(m_Value(), m_Value()));
2607 R->setHasNoSignedWrap(NSW);
2608 R->setHasNoUnsignedWrap(NUW);
2609 return R;
2610 }
2611 }
2612 }
2613
2614 // (~X) - (~Y) --> Y - X
2615 {
2616 // Need to ensure we can consume at least one of the `not` instructions,
2617 // otherwise this can inf loop.
2618 bool ConsumesOp0, ConsumesOp1;
2619 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
2620 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
2621 (ConsumesOp0 || ConsumesOp1)) {
2622 Value *NotOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
2623 Value *NotOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
2624 assert(NotOp0 != nullptr && NotOp1 != nullptr &&
2625 "isFreeToInvert desynced with getFreelyInverted");
2626 return BinaryOperator::CreateSub(NotOp1, NotOp0);
2627 }
2628 }
2629
2630 auto m_AddRdx = [](Value *&Vec) {
2632 };
2633 Value *V0, *V1;
2634 if (match(Op0, m_AddRdx(V0)) && match(Op1, m_AddRdx(V1)) &&
2635 V0->getType() == V1->getType()) {
2636 // Difference of sums is sum of differences:
2637 // add_rdx(V0) - add_rdx(V1) --> add_rdx(V0 - V1)
2638 Value *Sub = Builder.CreateSub(V0, V1);
2639 Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_add,
2640 {Sub->getType()}, {Sub});
2641 return replaceInstUsesWith(I, Rdx);
2642 }
2643
2644 if (Constant *C = dyn_cast<Constant>(Op0)) {
2645 Value *X;
2646 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2647 // C - (zext bool) --> bool ? C - 1 : C
2649 // We know nothing about the distribution of the condition, so mark the
2650 // branch weights as unknown.
2652 return SI;
2653 }
2654 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2655 // C - (sext bool) --> bool ? C + 1 : C
2657 // We know nothing about the distribution of the condition, so mark the
2658 // branch weights as unknown.
2660 return SI;
2661 }
2662
2663 // C - ~X == X + (1+C)
2664 if (match(Op1, m_Not(m_Value(X))))
2665 return BinaryOperator::CreateAdd(X, InstCombiner::AddOne(C));
2666
2667 // Try to fold constant sub into select arguments.
2669 if (Instruction *R = FoldOpIntoSelect(I, SI))
2670 return R;
2671
2672 // Try to fold constant sub into PHI values.
2673 if (PHINode *PN = dyn_cast<PHINode>(Op1))
2674 if (Instruction *R = foldOpIntoPhi(I, PN))
2675 return R;
2676
2677 Constant *C2;
2678
2679 // C-(C2-X) --> X+(C-C2)
2680 if (match(Op1, m_Sub(m_ImmConstant(C2), m_Value(X))))
2681 return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
2682 }
2683
2684 const APInt *Op0C;
2685 if (match(Op0, m_APInt(Op0C))) {
2686 if (Op0C->isMask()) {
2687 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
2688 // zero. We don't use information from dominating conditions so this
2689 // transform is easier to reverse if necessary.
2691 Op1, SQ.getWithInstruction(&I).getWithoutDomCondCache());
2692 if ((*Op0C | RHSKnown.Zero).isAllOnes())
2693 return BinaryOperator::CreateXor(Op1, Op0);
2694 }
2695
2696 // C - ((C3 -nuw X) & C2) --> (C - (C2 & C3)) + (X & C2) when:
2697 // (C3 - ((C2 & C3) - 1)) is pow2
2698 // ((C2 + C3) & ((C2 & C3) - 1)) == ((C2 & C3) - 1)
2699 // C2 is negative pow2 || sub nuw
2700 const APInt *C2, *C3;
2701 BinaryOperator *InnerSub;
2702 if (match(Op1, m_OneUse(m_And(m_BinOp(InnerSub), m_APInt(C2)))) &&
2703 match(InnerSub, m_Sub(m_APInt(C3), m_Value(X))) &&
2704 (InnerSub->hasNoUnsignedWrap() || C2->isNegatedPowerOf2())) {
2705 APInt C2AndC3 = *C2 & *C3;
2706 APInt C2AndC3Minus1 = C2AndC3 - 1;
2707 APInt C2AddC3 = *C2 + *C3;
2708 if ((*C3 - C2AndC3Minus1).isPowerOf2() &&
2709 C2AndC3Minus1.isSubsetOf(C2AddC3)) {
2710 Value *And = Builder.CreateAnd(X, ConstantInt::get(I.getType(), *C2));
2711 return BinaryOperator::CreateAdd(
2712 And, ConstantInt::get(I.getType(), *Op0C - C2AndC3));
2713 }
2714 }
2715 }
2716
2717 {
2718 Value *Y;
2719 // X-(X+Y) == -Y X-(Y+X) == -Y
2720 if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
2722
2723 // (X-Y)-X == -Y
2724 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
2726 }
2727
2728 // (sub (or A, B) (and A, B)) --> (xor A, B)
2729 {
2730 Value *A, *B;
2731 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
2732 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2733 return BinaryOperator::CreateXor(A, B);
2734 }
2735
2736 // (sub (add A, B) (or A, B)) --> (and A, B)
2737 {
2738 Value *A, *B;
2739 if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2740 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
2741 return BinaryOperator::CreateAnd(A, B);
2742 }
2743
2744 // (sub (add A, B) (and A, B)) --> (or A, B)
2745 {
2746 Value *A, *B;
2747 if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2749 return BinaryOperator::CreateOr(A, B);
2750 }
2751
2752 // (sub (and A, B) (or A, B)) --> neg (xor A, B)
2753 {
2754 Value *A, *B;
2755 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2756 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
2757 (Op0->hasOneUse() || Op1->hasOneUse()))
2758 return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
2759 }
2760
2761 // (sub (or A, B), (xor A, B)) --> (and A, B)
2762 {
2763 Value *A, *B;
2764 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2765 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2766 return BinaryOperator::CreateAnd(A, B);
2767 }
2768
2769 // (sub (xor A, B) (or A, B)) --> neg (and A, B)
2770 {
2771 Value *A, *B;
2772 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2773 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
2774 (Op0->hasOneUse() || Op1->hasOneUse()))
2775 return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
2776 }
2777
2778 {
2779 Value *Y;
2780 // ((X | Y) - X) --> (~X & Y)
2781 if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
2782 return BinaryOperator::CreateAnd(
2783 Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
2784 }
2785
2786 {
2787 // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
2788 Value *X;
2789 if (match(Op0, m_OneUse(m_c_And(m_Specific(Op1),
2790 m_OneUse(m_Neg(m_Value(X))))))) {
2791 return BinaryOperator::CreateNeg(Builder.CreateAnd(
2792 Op1, Builder.CreateAdd(X, Constant::getAllOnesValue(I.getType()))));
2793 }
2794 }
2795
2796 {
2797 // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
2798 Constant *C;
2799 if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_Constant(C))))) {
2801 Builder.CreateAnd(Op1, Builder.CreateNot(C)));
2802 }
2803 }
2804
2805 {
2806 // (sub (xor X, (sext C)), (sext C)) => (select C, (neg X), X)
2807 // (sub (sext C), (xor X, (sext C))) => (select C, X, (neg X))
2808 Value *C, *X;
2809 auto m_SubXorCmp = [&C, &X](Value *LHS, Value *RHS) {
2810 return match(LHS, m_OneUse(m_c_Xor(m_Value(X), m_Specific(RHS)))) &&
2811 match(RHS, m_SExt(m_Value(C))) &&
2812 (C->getType()->getScalarSizeInBits() == 1);
2813 };
2814 if (m_SubXorCmp(Op0, Op1))
2815 return createSelectInstWithUnknownProfile(C, Builder.CreateNeg(X), X);
2816 if (m_SubXorCmp(Op1, Op0))
2817 return createSelectInstWithUnknownProfile(C, X, Builder.CreateNeg(X));
2818 }
2819
2821 return R;
2822
2824 return R;
2825
2826 {
2827 // If we have a subtraction between some value and a select between
2828 // said value and something else, sink subtraction into select hands, i.e.:
2829 // sub (select %Cond, %TrueVal, %FalseVal), %Op1
2830 // ->
2831 // select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
2832 // or
2833 // sub %Op0, (select %Cond, %TrueVal, %FalseVal)
2834 // ->
2835 // select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
2836 // This will result in select between new subtraction and 0.
2837 auto SinkSubIntoSelect =
2838 [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
2839 auto SubBuilder) -> Instruction * {
2840 Value *Cond, *TrueVal, *FalseVal;
2841 if (!match(Select, m_OneUse(m_Select(m_Value(Cond), m_Value(TrueVal),
2842 m_Value(FalseVal)))))
2843 return nullptr;
2844 if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
2845 return nullptr;
2846 // While it is really tempting to just create two subtractions and let
2847 // InstCombine fold one of those to 0, it isn't possible to do so
2848 // because of worklist visitation order. So ugly it is.
2849 bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
2850 Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
2851 Constant *Zero = Constant::getNullValue(Ty);
2852 SelectInst *NewSel =
2853 SelectInst::Create(Cond, OtherHandOfSubIsTrueVal ? Zero : NewSub,
2854 OtherHandOfSubIsTrueVal ? NewSub : Zero);
2855 // Preserve prof metadata if any.
2857 return NewSel;
2858 };
2859 if (Instruction *NewSel = SinkSubIntoSelect(
2860 /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
2861 [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
2862 return Builder->CreateSub(OtherHandOfSelect,
2863 /*OtherHandOfSub=*/Op1);
2864 }))
2865 return NewSel;
2866 if (Instruction *NewSel = SinkSubIntoSelect(
2867 /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
2868 [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
2869 return Builder->CreateSub(/*OtherHandOfSub=*/Op0,
2870 OtherHandOfSelect);
2871 }))
2872 return NewSel;
2873 }
2874
2875 // (X - (X & Y)) --> (X & ~Y)
2876 if (match(Op1, m_c_And(m_Specific(Op0), m_Value(Y))) &&
2877 (Op1->hasOneUse() || isa<Constant>(Y)))
2878 return BinaryOperator::CreateAnd(
2879 Op0, Builder.CreateNot(Y, Y->getName() + ".not"));
2880
2881 // ~X - Min/Max(~X, Y) -> ~Min/Max(X, ~Y) - X
2882 // ~X - Min/Max(Y, ~X) -> ~Min/Max(X, ~Y) - X
2883 // Min/Max(~X, Y) - ~X -> X - ~Min/Max(X, ~Y)
2884 // Min/Max(Y, ~X) - ~X -> X - ~Min/Max(X, ~Y)
2885 // As long as Y is freely invertible, this will be neutral or a win.
2886 // Note: We don't generate the inverse max/min, just create the 'not' of
2887 // it and let other folds do the rest.
2888 if (match(Op0, m_Not(m_Value(X))) &&
2889 match(Op1, m_c_MaxOrMin(m_Specific(Op0), m_Value(Y))) &&
2890 !Op0->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
2891 Value *Not = Builder.CreateNot(Op1);
2892 return BinaryOperator::CreateSub(Not, X);
2893 }
2894 if (match(Op1, m_Not(m_Value(X))) &&
2895 match(Op0, m_c_MaxOrMin(m_Specific(Op1), m_Value(Y))) &&
2896 !Op1->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
2897 Value *Not = Builder.CreateNot(Op0);
2898 return BinaryOperator::CreateSub(X, Not);
2899 }
2900
2901 // min(X+1, Y) - min(X, Y) --> zext X < Y
2902 // Replacing a sub and at least one min with an icmp
2903 // and a zext is a potential improvement.
2904 if (match(Op0, m_c_SMin(m_NSWAddLike(m_Value(X), m_One()), m_Value(Y))) &&
2905 match(Op1, m_c_SMin(m_Specific(X), m_Specific(Y))) &&
2906 I.getType()->getScalarSizeInBits() != 1 &&
2907 (Op0->hasOneUse() || Op1->hasOneUse())) {
2908 Value *Cond = Builder.CreateICmpSLT(X, Y);
2909 return new ZExtInst(Cond, I.getType());
2910 }
2911 if (match(Op0, m_c_UMin(m_NUWAddLike(m_Value(X), m_One()), m_Value(Y))) &&
2912 match(Op1, m_c_UMin(m_Specific(X), m_Specific(Y))) &&
2913 I.getType()->getScalarSizeInBits() != 1 &&
2914 (Op0->hasOneUse() || Op1->hasOneUse())) {
2915 Value *Cond = Builder.CreateICmpULT(X, Y);
2916 return new ZExtInst(Cond, I.getType());
2917 }
2918
2919 // Optimize pointer differences into the same array into a size. Consider:
2920 // &A[10] - &A[0]: we should compile this to "10".
2921 Value *LHSOp, *RHSOp;
2922 if (match(Op0, m_PtrToIntOrAddr(m_Value(LHSOp))) &&
2923 match(Op1, m_PtrToIntOrAddr(m_Value(RHSOp))))
2924 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2925 I.hasNoUnsignedWrap()))
2926 return replaceInstUsesWith(I, Res);
2927
2928 // trunc(p)-trunc(q) -> trunc(p-q)
2929 if (match(Op0, m_Trunc(m_PtrToIntOrAddr(m_Value(LHSOp)))) &&
2930 match(Op1, m_Trunc(m_PtrToIntOrAddr(m_Value(RHSOp)))))
2931 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2932 /* IsNUW */ false))
2933 return replaceInstUsesWith(I, Res);
2934
2935 auto MatchSubOfZExtOfPtrToIntOrAddr = [&]() {
2936 if (match(Op0, m_ZExt(m_PtrToIntSameSize(DL, m_Value(LHSOp)))) &&
2937 match(Op1, m_ZExt(m_PtrToIntSameSize(DL, m_Value(RHSOp)))))
2938 return true;
2939 if (match(Op0, m_ZExt(m_PtrToAddr(m_Value(LHSOp)))) &&
2940 match(Op1, m_ZExt(m_PtrToAddr(m_Value(RHSOp)))))
2941 return true;
2942 // Special case for non-canonical ptrtoint in constant expression,
2943 // where the zext has been folded into the ptrtoint.
2944 if (match(Op0, m_ZExt(m_PtrToIntSameSize(DL, m_Value(LHSOp)))) &&
2945 match(Op1, m_PtrToInt(m_Value(RHSOp))))
2946 return true;
2947 return false;
2948 };
2949 if (MatchSubOfZExtOfPtrToIntOrAddr()) {
2950 if (auto *GEP = dyn_cast<GEPOperator>(LHSOp)) {
2951 if (GEP->getPointerOperand() == RHSOp) {
2952 if (GEP->hasNoUnsignedWrap() || GEP->hasNoUnsignedSignedWrap()) {
2953 Value *Offset = EmitGEPOffset(GEP);
2954 Value *Res = GEP->hasNoUnsignedWrap()
2955 ? Builder.CreateZExt(
2956 Offset, I.getType(), "",
2957 /*IsNonNeg=*/GEP->hasNoUnsignedSignedWrap())
2958 : Builder.CreateSExt(Offset, I.getType());
2959 return replaceInstUsesWith(I, Res);
2960 }
2961 }
2962 }
2963 }
2964
2965 // Canonicalize a shifty way to code absolute value to the common pattern.
2966 // There are 2 potential commuted variants.
2967 // We're relying on the fact that we only do this transform when the shift has
2968 // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
2969 // instructions).
2970 Value *A;
2971 const APInt *ShAmt;
2972 Type *Ty = I.getType();
2973 unsigned BitWidth = Ty->getScalarSizeInBits();
2974 if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
2975 Op1->hasNUses(2) && *ShAmt == BitWidth - 1 &&
2976 match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
2977 // B = ashr i32 A, 31 ; smear the sign bit
2978 // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
2979 // --> (A < 0) ? -A : A
2980 Value *IsNeg = Builder.CreateIsNeg(A);
2981 // Copy the nsw flags from the sub to the negate.
2982 Value *NegA = I.hasNoUnsignedWrap()
2983 ? Constant::getNullValue(A->getType())
2984 : Builder.CreateNeg(A, "", I.hasNoSignedWrap());
2985 return SelectInst::Create(IsNeg, NegA, A);
2986 }
2987
2988 // If we are subtracting a low-bit masked subset of some value from an add
2989 // of that same value with no low bits changed, that is clearing some low bits
2990 // of the sum:
2991 // sub (X + AddC), (X & AndC) --> and (X + AddC), ~AndC
2992 const APInt *AddC, *AndC;
2993 if (match(Op0, m_Add(m_Value(X), m_APInt(AddC))) &&
2994 match(Op1, m_And(m_Specific(X), m_APInt(AndC)))) {
2995 unsigned Cttz = AddC->countr_zero();
2996 APInt HighMask(APInt::getHighBitsSet(BitWidth, BitWidth - Cttz));
2997 if ((HighMask & *AndC).isZero())
2998 return BinaryOperator::CreateAnd(Op0, ConstantInt::get(Ty, ~(*AndC)));
2999 }
3000
3001 if (Instruction *V =
3003 return V;
3004
3005 // X - usub.sat(X, Y) => umin(X, Y)
3007 m_Value(Y)))))
3008 return replaceInstUsesWith(
3009 I, Builder.CreateIntrinsic(Intrinsic::umin, {I.getType()}, {Op0, Y}));
3010
3011 // umax(X, Op1) - Op1 --> usub.sat(X, Op1)
3012 // TODO: The one-use restriction is not strictly necessary, but it may
3013 // require improving other pattern matching and/or codegen.
3014 if (match(Op0, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op1)))))
3015 return replaceInstUsesWith(
3016 I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op1}));
3017
3018 // Op0 - umin(X, Op0) --> usub.sat(Op0, X)
3019 if (match(Op1, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op0)))))
3020 return replaceInstUsesWith(
3021 I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op0, X}));
3022
3023 // Op0 - umax(X, Op0) --> 0 - usub.sat(X, Op0)
3024 if (match(Op1, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op0))))) {
3025 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op0});
3026 return BinaryOperator::CreateNeg(USub);
3027 }
3028
3029 // umin(X, Op1) - Op1 --> 0 - usub.sat(Op1, X)
3030 if (match(Op0, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op1))))) {
3031 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op1, X});
3032 return BinaryOperator::CreateNeg(USub);
3033 }
3034
3035 // C - ctpop(X) => ctpop(~X) if C is bitwidth
3036 if (match(Op0, m_SpecificInt(BitWidth)) &&
3037 match(Op1, m_OneUse(m_Ctpop(m_Value(X)))))
3038 return replaceInstUsesWith(
3039 I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
3040 {Builder.CreateNot(X)}));
3041
3042 // Reduce multiplies for difference-of-squares by factoring:
3043 // (X * X) - (Y * Y) --> (X + Y) * (X - Y)
3044 if (match(Op0, m_OneUse(m_Mul(m_Value(X), m_Deferred(X)))) &&
3045 match(Op1, m_OneUse(m_Mul(m_Value(Y), m_Deferred(Y))))) {
3046 auto *OBO0 = cast<OverflowingBinaryOperator>(Op0);
3047 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3048 bool PropagateNSW = I.hasNoSignedWrap() && OBO0->hasNoSignedWrap() &&
3049 OBO1->hasNoSignedWrap() && BitWidth > 2;
3050 bool PropagateNUW = I.hasNoUnsignedWrap() && OBO0->hasNoUnsignedWrap() &&
3051 OBO1->hasNoUnsignedWrap() && BitWidth > 1;
3052 Value *Add = Builder.CreateAdd(X, Y, "add", PropagateNUW, PropagateNSW);
3053 Value *Sub = Builder.CreateSub(X, Y, "sub", PropagateNUW, PropagateNSW);
3054 Value *Mul = Builder.CreateMul(Add, Sub, "", PropagateNUW, PropagateNSW);
3055 return replaceInstUsesWith(I, Mul);
3056 }
3057
3058 // max(X,Y) nsw/nuw - min(X,Y) --> abs(X nsw - Y)
3059 if (match(Op0, m_OneUse(m_c_SMax(m_Value(X), m_Value(Y)))) &&
3061 if (I.hasNoUnsignedWrap() || I.hasNoSignedWrap()) {
3062 Value *Sub =
3063 Builder.CreateSub(X, Y, "sub", /*HasNUW=*/false, /*HasNSW=*/true);
3064 Value *Call =
3065 Builder.CreateBinaryIntrinsic(Intrinsic::abs, Sub, Builder.getTrue());
3066 return replaceInstUsesWith(I, Call);
3067 }
3068 }
3069
3071 return Res;
3072
3073 // (sub (sext (add nsw (X, Y)), sext (X))) --> (sext (Y))
3074 if (match(Op1, m_SExtLike(m_Value(X))) &&
3076 Value *SExtY = Builder.CreateSExt(Y, I.getType());
3077 return replaceInstUsesWith(I, SExtY);
3078 }
3079
3080 // (sub[ nsw] (sext (add nsw (X, Y)), sext (add nsw (X, Z)))) -->
3081 // --> (sub[ nsw] (sext (Y), sext (Z)))
3082 {
3083 Value *Z, *Add0, *Add1;
3084 if (match(Op0, m_SExtLike(m_Value(Add0))) &&
3085 match(Op1, m_SExtLike(m_Value(Add1))) &&
3086 ((match(Add0, m_NSWAdd(m_Value(X), m_Value(Y))) &&
3087 match(Add1, m_c_NSWAdd(m_Specific(X), m_Value(Z)))) ||
3088 (match(Add0, m_NSWAdd(m_Value(Y), m_Value(X))) &&
3089 match(Add1, m_c_NSWAdd(m_Specific(X), m_Value(Z)))))) {
3090 unsigned NumOfNewInstrs = 0;
3091 // Non-constant Y, Z require new SExt.
3092 NumOfNewInstrs += !isa<Constant>(Y) ? 1 : 0;
3093 NumOfNewInstrs += !isa<Constant>(Z) ? 1 : 0;
3094 // Check if we can trade some of the old instructions for the new ones.
3095 unsigned NumOfDeadInstrs = 0;
3096 if (Op0->hasOneUse()) {
3097 // If Op0 (sext) has multiple uses, then we keep it
3098 // and the add that it uses, otherwise, we can remove
3099 // the sext and probably the add (depending on the number of its uses).
3100 ++NumOfDeadInstrs;
3101 NumOfDeadInstrs += Add0->hasOneUse() ? 1 : 0;
3102 }
3103 if (Op1->hasOneUse()) {
3104 ++NumOfDeadInstrs;
3105 NumOfDeadInstrs += Add1->hasOneUse() ? 1 : 0;
3106 }
3107 if (NumOfDeadInstrs >= NumOfNewInstrs) {
3108 Value *SExtY = Builder.CreateSExt(Y, I.getType());
3109 Value *SExtZ = Builder.CreateSExt(Z, I.getType());
3110 Value *Sub = Builder.CreateSub(SExtY, SExtZ, "",
3111 /*HasNUW=*/false,
3112 /*HasNSW=*/I.hasNoSignedWrap());
3113 return replaceInstUsesWith(I, Sub);
3114 }
3115 }
3116 }
3117
3118 // ((X + C) & ~C) - X -> X & C where C is a power of 2.
3119 if (match(Op0,
3120 m_And(m_Add(m_Specific(Op1), m_Power2(AddC)), m_APInt(AndC))) &&
3121 *AddC == ~*AndC) {
3122 return BinaryOperator::CreateAnd(Op1, ConstantInt::get(Ty, *AddC));
3123 }
3124
3125 return TryToNarrowDeduceFlags();
3126}
3127
3128/// This eliminates floating-point negation in either 'fneg(X)' or
3129/// 'fsub(-0.0, X)' form by combining into a constant operand.
3131 // This is limited with one-use because fneg is assumed better for
3132 // reassociation and cheaper in codegen than fmul/fdiv.
3133 // TODO: Should the m_OneUse restriction be removed?
3134 Instruction *FNegOp;
3135 if (!match(&I, m_FNeg(m_OneUse(m_Instruction(FNegOp)))))
3136 return nullptr;
3137
3138 Value *X;
3139 Constant *C;
3140
3141 // Fold negation into constant operand.
3142 // -(X * C) --> X * (-C)
3143 if (match(FNegOp, m_FMul(m_Value(X), m_Constant(C))))
3144 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
3145 FastMathFlags FNegF = I.getFastMathFlags();
3146 FastMathFlags OpF = FNegOp->getFastMathFlags();
3147 FastMathFlags FMF = FastMathFlags::unionValue(FNegF, OpF) |
3149 FMF.setNoInfs(FNegF.noInfs() && OpF.noInfs());
3150 return BinaryOperator::CreateFMulFMF(X, NegC, FMF);
3151 }
3152 // -(X / C) --> X / (-C)
3153 if (match(FNegOp, m_FDiv(m_Value(X), m_Constant(C)))) {
3154 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
3156
3157 // Intersect 'nsz' and 'ninf' because those special value exceptions may
3158 // not apply to the fdiv. Everything else propagates from the fneg.
3159 FastMathFlags FMF = I.getFastMathFlags();
3160 FastMathFlags OpFMF = FNegOp->getFastMathFlags();
3161 FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
3162 FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
3163 FDiv->copyMetadata(*FNegOp);
3164 return FDiv;
3165 }
3166 }
3167 // -(C / X) --> (-C) / X
3168 if (match(FNegOp, m_FDiv(m_Constant(C), m_Value(X))))
3169 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
3171
3172 // Intersect 'nsz' and 'ninf' because those special value exceptions may
3173 // not apply to the fdiv. Everything else propagates from the fneg.
3174 // TODO: We could propagate nsz/ninf from fdiv alone?
3175 FastMathFlags FMF = I.getFastMathFlags();
3176 FastMathFlags OpFMF = FNegOp->getFastMathFlags();
3177 FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
3178 FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
3179 FDiv->copyMetadata(*FNegOp);
3180 return FDiv;
3181 }
3182 // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
3183 // -(X + C) --> -X + -C --> -C - X
3184 if (I.hasNoSignedZeros() && match(FNegOp, m_FAdd(m_Value(X), m_Constant(C))))
3185 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
3186 return BinaryOperator::CreateFSubFMF(NegC, X, &I);
3187
3188 return nullptr;
3189}
3190
3191Instruction *InstCombinerImpl::hoistFNegAboveFMulFDiv(Value *FNegOp,
3192 Instruction &FMFSource) {
3193 Value *X, *Y;
3194 if (match(FNegOp, m_FMul(m_Value(X), m_Value(Y)))) {
3195 // Push into RHS which is more likely to simplify (const or another fneg).
3196 // FIXME: It would be better to invert the transform.
3197 return cast<Instruction>(Builder.CreateFMulFMF(
3198 X, Builder.CreateFNegFMF(Y, &FMFSource), &FMFSource));
3199 }
3200
3201 if (match(FNegOp, m_FDiv(m_Value(X), m_Value(Y)))) {
3202 auto *FDiv = cast<Instruction>(Builder.CreateFDivFMF(
3203 Builder.CreateFNegFMF(X, &FMFSource), Y, &FMFSource));
3204 FDiv->copyMetadata(*cast<Instruction>(FNegOp));
3205 return FDiv;
3206 }
3207
3208 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(FNegOp)) {
3209 // Make sure to preserve flags and metadata on the call.
3210 if (II->getIntrinsicID() == Intrinsic::ldexp) {
3211 FastMathFlags FMF = FMFSource.getFastMathFlags() | II->getFastMathFlags();
3212 CallInst *New =
3213 Builder.CreateCall(II->getCalledFunction(),
3214 {Builder.CreateFNegFMF(II->getArgOperand(0), FMF),
3215 II->getArgOperand(1)});
3216 New->setFastMathFlags(FMF);
3217 New->copyMetadata(*II);
3218 return New;
3219 }
3220 }
3221
3222 return nullptr;
3223}
3224
3226 Value *Op = I.getOperand(0);
3227
3228 if (Value *V = simplifyFNegInst(Op, I.getFastMathFlags(),
3229 getSimplifyQuery().getWithInstruction(&I)))
3230 return replaceInstUsesWith(I, V);
3231
3233 return X;
3234
3235 Value *X, *Y;
3236
3237 // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
3238 if (I.hasNoSignedZeros() &&
3241
3242 Value *OneUse;
3243 if (!match(Op, m_OneUse(m_Value(OneUse))))
3244 return nullptr;
3245
3246 if (Instruction *R = hoistFNegAboveFMulFDiv(OneUse, I))
3247 return replaceInstUsesWith(I, R);
3248
3249 // Try to eliminate fneg if at least 1 arm of the select is negated.
3250 Value *Cond;
3251 if (match(OneUse, m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))) {
3252 // Unlike most transforms, this one is not safe to propagate nsz unless
3253 // it is present on the original select. We union the flags from the select
3254 // and fneg and then remove nsz if needed.
3255 auto propagateSelectFMF = [&](SelectInst *S, bool CommonOperand) {
3256 S->copyFastMathFlags(&I);
3257 if (auto *OldSel = dyn_cast<SelectInst>(Op)) {
3258 FastMathFlags FMF = I.getFastMathFlags() | OldSel->getFastMathFlags();
3259 S->setFastMathFlags(FMF);
3260 if (!OldSel->hasNoSignedZeros() && !CommonOperand &&
3261 !isGuaranteedNotToBeUndefOrPoison(OldSel->getCondition()))
3262 S->setHasNoSignedZeros(false);
3263 }
3264 };
3265 // -(Cond ? -P : Y) --> Cond ? P : -Y
3266 Value *P;
3267 if (match(X, m_FNeg(m_Value(P)))) {
3268 Value *NegY = Builder.CreateFNegFMF(Y, &I, Y->getName() + ".neg");
3270 Cond, P, NegY, "", nullptr,
3272 propagateSelectFMF(NewSel, P == Y);
3273 return NewSel;
3274 }
3275 // -(Cond ? X : -P) --> Cond ? -X : P
3276 if (match(Y, m_FNeg(m_Value(P)))) {
3277 Value *NegX = Builder.CreateFNegFMF(X, &I, X->getName() + ".neg");
3279 Cond, NegX, P, "", nullptr,
3281 propagateSelectFMF(NewSel, P == X);
3282 return NewSel;
3283 }
3284
3285 // -(Cond ? X : C) --> Cond ? -X : -C
3286 // -(Cond ? C : Y) --> Cond ? -C : -Y
3287 if (match(X, m_ImmConstant()) || match(Y, m_ImmConstant())) {
3288 Value *NegX = Builder.CreateFNegFMF(X, &I, X->getName() + ".neg");
3289 Value *NegY = Builder.CreateFNegFMF(Y, &I, Y->getName() + ".neg");
3291 Cond, NegX, NegY, "", nullptr,
3293 propagateSelectFMF(NewSel, /*CommonOperand=*/true);
3294 return NewSel;
3295 }
3296 }
3297
3298 // fneg (copysign x, y) -> copysign x, (fneg y)
3299 if (match(OneUse, m_CopySign(m_Value(X), m_Value(Y)))) {
3300 // The source copysign has an additional value input, so we can't propagate
3301 // flags the copysign doesn't also have.
3302 FastMathFlags FMF = I.getFastMathFlags();
3303 FMF &= cast<FPMathOperator>(OneUse)->getFastMathFlags();
3304 Value *NegY = Builder.CreateFNegFMF(Y, FMF);
3305 Value *NewCopySign = Builder.CreateCopySign(X, NegY, FMF);
3306 return replaceInstUsesWith(I, NewCopySign);
3307 }
3308
3309 // fneg (shuffle x, Mask) --> shuffle (fneg x), Mask
3310 ArrayRef<int> Mask;
3311 if (match(OneUse, m_Shuffle(m_Value(X), m_Poison(), m_Mask(Mask))))
3312 return new ShuffleVectorInst(Builder.CreateFNegFMF(X, &I), Mask);
3313
3314 // fneg (reverse x) --> reverse (fneg x)
3315 if (match(OneUse, m_VecReverse(m_Value(X)))) {
3316 Value *Reverse = Builder.CreateVectorReverse(Builder.CreateFNegFMF(X, &I));
3317 return replaceInstUsesWith(I, Reverse);
3318 }
3319
3320 return nullptr;
3321}
3322
3324 if (Value *V = simplifyFSubInst(I.getOperand(0), I.getOperand(1),
3325 I.getFastMathFlags(),
3326 getSimplifyQuery().getWithInstruction(&I)))
3327 return replaceInstUsesWith(I, V);
3328
3330 return X;
3331
3333 return Phi;
3334
3335 // Subtraction from -0.0 is the canonical form of fneg.
3336 // fsub -0.0, X ==> fneg X
3337 // fsub nsz 0.0, X ==> fneg nsz X
3338 //
3339 // FIXME This matcher does not respect FTZ or DAZ yet:
3340 // fsub -0.0, Denorm ==> +-0
3341 // fneg Denorm ==> -Denorm
3342 Value *Op;
3343 if (match(&I, m_FNeg(m_Value(Op))))
3345
3347 return X;
3348
3349 if (Instruction *R = foldFBinOpOfIntCasts(I))
3350 return R;
3351
3352 Value *X, *Y;
3353 Constant *C;
3354
3355 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3356 // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
3357 // Canonicalize to fadd to make analysis easier.
3358 // This can also help codegen because fadd is commutative.
3359 // Note that if this fsub was really an fneg, the fadd with -0.0 will get
3360 // killed later. We still limit that particular transform with 'hasOneUse'
3361 // because an fneg is assumed better/cheaper than a generic fsub.
3362 if (I.hasNoSignedZeros() ||
3363 cannotBeNegativeZero(Op0, getSimplifyQuery().getWithInstruction(&I))) {
3364 if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
3365 Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
3366 return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
3367 }
3368 }
3369
3370 // (-X) - Op1 --> -(X + Op1)
3371 if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Op0) &&
3372 match(Op0, m_OneUse(m_FNeg(m_Value(X))))) {
3373 Value *FAdd = Builder.CreateFAddFMF(X, Op1, &I);
3375 }
3376
3377 if (isa<Constant>(Op0))
3379 if (Instruction *NV = FoldOpIntoSelect(I, SI))
3380 return NV;
3381
3382 // X - C --> X + (-C)
3383 // But don't transform constant expressions because there's an inverse fold
3384 // for X + (-Y) --> X - Y.
3385 if (match(Op1, m_ImmConstant(C)))
3386 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
3387 return BinaryOperator::CreateFAddFMF(Op0, NegC, &I);
3388
3389 // X - (-Y) --> X + Y
3390 if (match(Op1, m_FNeg(m_Value(Y))))
3391 return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
3392
3393 // Similar to above, but look through a cast of the negated value:
3394 // X - (fptrunc(-Y)) --> X + fptrunc(Y)
3395 Type *Ty = I.getType();
3396 if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
3397 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
3398
3399 // X - (fpext(-Y)) --> X + fpext(Y)
3400 if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
3401 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
3402
3403 // Similar to above, but look through fmul/fdiv of the negated value:
3404 // Op0 - (-X * Y) --> Op0 + (X * Y)
3405 // Op0 - (Y * -X) --> Op0 + (X * Y)
3406 if (match(Op1, m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))))) {
3407 Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
3408 return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
3409 }
3410 // Op0 - (-X / Y) --> Op0 + (X / Y)
3411 // Op0 - (X / -Y) --> Op0 + (X / Y)
3412 if (match(Op1, m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y)))) ||
3413 match(Op1, m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))))) {
3414 Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
3415 return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
3416 }
3417
3418 // Handle special cases for FSub with selects feeding the operation
3419 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
3420 return replaceInstUsesWith(I, V);
3421
3422 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
3423 // (Y - X) - Y --> -X
3424 if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
3426
3427 // Y - (X + Y) --> -X
3428 // Y - (Y + X) --> -X
3429 if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
3431
3432 // (X * C) - X --> X * (C - 1.0)
3433 if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
3435 Instruction::FSub, C, ConstantFP::get(Ty, 1.0), DL))
3436 return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
3437 }
3438 // X - (X * C) --> X * (1.0 - C)
3439 if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
3441 Instruction::FSub, ConstantFP::get(Ty, 1.0), C, DL))
3442 return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
3443 }
3444
3445 // Reassociate fsub/fadd sequences to create more fadd instructions and
3446 // reduce dependency chains:
3447 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
3448 Value *Z;
3450 m_Value(Z))))) {
3451 Value *XZ = Builder.CreateFAddFMF(X, Z, &I);
3452 Value *YW = Builder.CreateFAddFMF(Y, Op1, &I);
3453 return BinaryOperator::CreateFSubFMF(XZ, YW, &I);
3454 }
3455
3456 auto m_FaddRdx = [](Value *&Sum, Value *&Vec) {
3458 m_Value(Vec)));
3459 };
3460 Value *A0, *A1, *V0, *V1;
3461 if (match(Op0, m_FaddRdx(A0, V0)) && match(Op1, m_FaddRdx(A1, V1)) &&
3462 V0->getType() == V1->getType()) {
3463 // Difference of sums is sum of differences:
3464 // add_rdx(A0, V0) - add_rdx(A1, V1) --> add_rdx(A0, V0 - V1) - A1
3465 Value *Sub = Builder.CreateFSubFMF(V0, V1, &I);
3466 Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
3467 {Sub->getType()}, {A0, Sub}, &I);
3468 return BinaryOperator::CreateFSubFMF(Rdx, A1, &I);
3469 }
3470
3472 return F;
3473
3474 // TODO: This performs reassociative folds for FP ops. Some fraction of the
3475 // functionality has been subsumed by simple pattern matching here and in
3476 // InstSimplify. We should let a dedicated reassociation pass handle more
3477 // complex pattern matching and remove this from InstCombine.
3478 if (Value *V = FAddCombine(Builder).simplify(&I))
3479 return replaceInstUsesWith(I, V);
3480
3481 // (X - Y) - Op1 --> X - (Y + Op1)
3482 if (match(Op0, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
3483 Value *FAdd = Builder.CreateFAddFMF(Y, Op1, &I);
3485 }
3486 }
3487
3488 return nullptr;
3489}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
AMDGPU Register Bank Select
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
hexagon bit simplify
Hexagon Common GEP
static Instruction * factorizeFAddFSub(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Factor a common operand out of fadd/fsub of fmul/fdiv.
static Instruction * foldAddToAshr(BinaryOperator &Add)
Try to reduce signed division by power-of-2 to an arithmetic shift right.
static bool MatchMul(Value *E, Value *&Op, APInt &C)
static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned)
static Instruction * foldFNegIntoConstant(Instruction &I, const DataLayout &DL)
This eliminates floating-point negation in either 'fneg(X)' or 'fsub(-0.0, X)' form by combining into...
static Instruction * combineAddSubWithShlAddSub(InstCombiner::BuilderTy &Builder, const BinaryOperator &I)
static Instruction * factorizeLerp(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Eliminate an op from a linear interpolation (lerp) pattern.
static Instruction * foldSubOfMinMax(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static Instruction * foldBoxMultiply(BinaryOperator &I)
Reduce a sequence of masked half-width multiplies to a single multiply.
static Value * checkForNegativeOperand(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned)
static Instruction * foldNoWrapAdd(BinaryOperator &Add, InstCombiner::BuilderTy &Builder)
Wrapping flags may allow combining constants separated by an extend.
static bool matchesSquareSum(BinaryOperator &I, Mul2Rhs M2Rhs, Value *&A, Value *&B)
static Instruction * factorizeMathWithShlOps(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
This is a specialization of a more general transform from foldUsingDistributiveLaws.
static Instruction * canonicalizeLowbitMask(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Fold (1 << NBits) - 1 Into: ~(-(1 << NBits)) Because a 'not' is better for bit-tracking analysis and ...
static bool checkDivCeilNUW(Value *X, Value *Y, const SimplifyQuery &SQ)
Return true if X + (Y-1) is provably non-wrapping in X's type.
static Instruction * foldToUnsignedSaturatedAdd(BinaryOperator &I)
static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
static constexpr Value * getValue(Ty &ValueOrUse)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static unsigned getScalarSizeInBits(Type *Ty)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1303
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
int32_t exactLogBase2() const
Definition APInt.h:1803
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
unsigned logBase2() const
Definition APInt.h:1781
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1998
bool isMask(unsigned numBits) const
Definition APInt.h:484
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:271
static LLVM_ABI BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:279
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:283
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:275
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * CreateTruncOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a Trunc or BitCast cast instruction.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_NE
not equal
Definition InstrTypes.h:762
bool isSigned() const
Definition InstrTypes.h:993
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
const APFloat & getValueAPF() const
Definition Constants.h:463
bool isZero() const
Return true if the value is positive or negative zero.
Definition Constants.h:467
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
This class represents a range of values.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isElementWiseEqual(Value *Y) const
Return true if this constant and a constant 'Y' are element-wise equal.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
static FastMathFlags intersectRewrite(FastMathFlags LHS, FastMathFlags RHS)
Intersect rewrite-based flags.
Definition FMF.h:116
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
static FastMathFlags unionValue(FastMathFlags LHS, FastMathFlags RHS)
Union value flags.
Definition FMF.h:124
void setNoInfs(bool B=true)
Definition FMF.h:81
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Instruction * foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I)
Tries to simplify binops of select and cast of the select condition.
Instruction * visitAdd(BinaryOperator &I)
Instruction * canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(BinaryOperator &I)
Instruction * foldBinOpIntoSelectOrPhi(BinaryOperator &I)
This is a convenience wrapper function for the above two functions.
bool SimplifyAssociativeOrCommutative(BinaryOperator &I)
Performs a few simplifications for operators which are associative or commutative.
Value * foldUsingDistributiveLaws(BinaryOperator &I)
Tries to simplify binary operations which some other binary operation distributes over.
Instruction * foldBinOpShiftWithShift(BinaryOperator &I)
Instruction * foldSquareSumInt(BinaryOperator &I)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Instruction * foldBinOpSelectBinOp(BinaryOperator &Op)
In some cases it is beneficial to fold a select into a binary operator.
Instruction * foldSquareSumFP(BinaryOperator &I)
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * visitSub(BinaryOperator &I)
Instruction * foldDivCeil(BinaryOperator &I)
Fold both forms of the div_ceil idiom: (add (udiv X, Y), (zext (icmp ne (urem X, Y),...
Value * OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty, bool isNUW)
Optimize pointer differences into the same array into a size.
Instruction * visitFAdd(BinaryOperator &I)
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
Instruction * foldAddLikeCommutative(Value *LHS, Value *RHS, bool NSW, bool NUW)
Common transforms for add / disjoint or.
Instruction * tryFoldInstWithCtpopWithNot(Instruction *I)
Value * SimplifyAddWithRemainder(BinaryOperator &I)
Tries to simplify add operations using the definition of remainder.
Instruction * foldAddWithConstant(BinaryOperator &Add)
Instruction * foldVectorBinop(BinaryOperator &Inst)
Canonicalize the position of binops relative to shufflevector.
Value * SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS, Value *RHS)
Instruction * visitFNeg(UnaryOperator &I)
Instruction * visitFSub(BinaryOperator &I)
SimplifyQuery SQ
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
const DataLayout & DL
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CtxI=nullptr, unsigned Depth=0) const
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
AssumptionCache & AC
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
const SimplifyQuery & getSimplifyQuery() const
static Constant * AddOne(Constant *C)
Add one to a Constant.
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction,...
LLVM_ABI void setHasNoSignedZeros(bool B)
Set or clear the no-signed-zeros flag on this instruction, which must be an operator which supports t...
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setHasNoInfs(bool B)
Set or clear the no-infs flag on this instruction, which must be an operator which supports this flag...
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
static Value * Negate(bool LHSIsZero, bool IsNSW, Value *Root, InstCombinerImpl &IC)
Attempt to negate Root.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
This instruction constructs a fixed permutation of two input vectors.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static UnaryOperator * CreateFNegFMF(Value *Op, Instruction *FMFSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:156
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:151
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
This class represents zero extension of integer types.
CallInst * Call
Changed
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::FMul, true > m_c_FMul(const LHS &L, const RHS &R)
Matches FMul with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap, true > m_c_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
CommutativeBinaryIntrinsic_match< IntrID, T0, T1 > m_c_Intrinsic(const T0 &Op0, const T1 &Op1)
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
CastOperator_match< OpTy, Instruction::PtrToAddr > m_PtrToAddr(const OpTy &Op)
Matches PtrToAddr.
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< CastInst_match< OpTy, SExtInst >, OpTy > m_SExtOrSelf(const OpTy &Op)
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
auto m_CopySign(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
specific_fpval m_FPOne()
Match a float 1.0 or vector with all elements equal to 1.0.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
match_combine_or< CastInst_match< OpTy, SExtInst >, NNegZExt_match< OpTy > > m_SExtLike(const OpTy &Op)
Match either "sext" or "zext nneg".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinaryOp_match< LHS, RHS, Instruction::FAdd, true > m_c_FAdd(const LHS &L, const RHS &R)
Matches FAdd with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FDiv > m_FDiv(const LHS &L, const RHS &R)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
CastInst_match< OpTy, FPTruncInst > m_FPTrunc(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_VecReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ Offset
Definition DWP.cpp:577
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator+=(DynamicAPInt &A, int64_t B)
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI Value * simplifySubInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Sub, fold the result or return null.
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator*=(DynamicAPInt &A, int64_t B)
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI Value * simplifyFNegInst(Value *Op, FastMathFlags FMF, const SimplifyQuery &Q)
Given operand for an FNeg, fold the result or return null.
LLVM_ABI Value * simplifyFSubInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FSub, fold the result or return null.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI Value * simplifyFAddInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FAdd, fold the result or return null.
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ Mul
Product of integers.
@ FMul
Product of floats.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
DWARFExpression::Operation Op
RoundingMode
Rounding mode.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
Value * Ptr
Common base pointer.
SmallVector< GEPOperator * > RHSGEPs
RHS GEPs until common base.
SmallVector< GEPOperator * > LHSGEPs
LHS GEPs until common base.
bool isExpensive() const
Whether expanding the GEP chains is expensive.
static CommonPointerBase compute(Value *LHS, Value *RHS)
Matching combinators.