1 //===- InstCombineAddSub.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for add, fadd, sub, and fsub.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "instcombine"
15 #include "InstCombine.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/GetElementPtrTypeIterator.h"
20 #include "llvm/IR/PatternMatch.h"
22 using namespace PatternMatch;
26 /// Class representing coefficient of floating-point addend.
27 /// This class needs to be highly efficient, which is especially true for
28 /// the constructor. As of I write this comment, the cost of the default
29 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
30 /// perform write-merging).
34 // The constructor has to initialize a APFloat, which is uncessary for
35 // most addends which have coefficient either 1 or -1. So, the constructor
36 // is expensive. In order to avoid the cost of the constructor, we should
37 // reuse some instances whenever possible. The pre-created instances
38 // FAddCombine::Add[0-5] embodies this idea.
40 FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
44 assert(!insaneIntVal(C) && "Insane coefficient");
45 IsFp = false; IntVal = C;
48 void set(const APFloat& C);
52 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
53 Value *getValue(Type *) const;
55 // If possible, don't define operator+/operator- etc because these
56 // operators inevitably call FAddendCoef's constructor which is not cheap.
57 void operator=(const FAddendCoef &A);
58 void operator+=(const FAddendCoef &A);
59 void operator-=(const FAddendCoef &A);
60 void operator*=(const FAddendCoef &S);
62 bool isOne() const { return isInt() && IntVal == 1; }
63 bool isTwo() const { return isInt() && IntVal == 2; }
64 bool isMinusOne() const { return isInt() && IntVal == -1; }
65 bool isMinusTwo() const { return isInt() && IntVal == -2; }
68 bool insaneIntVal(int V) { return V > 4 || V < -4; }
69 APFloat *getFpValPtr(void)
70 { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
71 const APFloat *getFpValPtr(void) const
72 { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
74 const APFloat &getFpVal(void) const {
75 assert(IsFp && BufHasFpVal && "Incorret state");
76 return *getFpValPtr();
79 APFloat &getFpVal(void) {
80 assert(IsFp && BufHasFpVal && "Incorret state");
81 return *getFpValPtr();
84 bool isInt() const { return !IsFp; }
86 // If the coefficient is represented by an integer, promote it to a
88 void convertToFpType(const fltSemantics &Sem);
90 // Construct an APFloat from a signed integer.
91 // TODO: We should get rid of this function when APFloat can be constructed
92 // from an *SIGNED* integer.
93 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
98 // True iff FpValBuf contains an instance of APFloat.
101 // The integer coefficient of an individual addend is either 1 or -1,
102 // and we try to simplify at most 4 addends from neighboring at most
103 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
104 // is overkill of this end.
107 AlignedCharArrayUnion<APFloat> FpValBuf;
110 /// FAddend is used to represent floating-point addend. An addend is
111 /// represented as <C, V>, where the V is a symbolic value, and C is a
112 /// constant coefficient. A constant addend is represented as <C, 0>.
116 FAddend() { Val = 0; }
118 Value *getSymVal (void) const { return Val; }
119 const FAddendCoef &getCoef(void) const { return Coeff; }
121 bool isConstant() const { return Val == 0; }
122 bool isZero() const { return Coeff.isZero(); }
124 void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
125 void set(const APFloat& Coefficient, Value *V)
126 { Coeff.set(Coefficient); Val = V; }
127 void set(const ConstantFP* Coefficient, Value *V)
128 { Coeff.set(Coefficient->getValueAPF()); Val = V; }
130 void negate() { Coeff.negate(); }
132 /// Drill down the U-D chain one step to find the definition of V, and
133 /// try to break the definition into one or two addends.
134 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
136 /// Similar to FAddend::drillDownOneStep() except that the value being
137 /// splitted is the addend itself.
138 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
140 void operator+=(const FAddend &T) {
141 assert((Val == T.Val) && "Symbolic-values disagree");
146 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
148 // This addend has the value of "Coeff * Val".
153 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
154 /// with its neighboring at most two instructions.
158 FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(0) {}
159 Value *simplify(Instruction *FAdd);
162 typedef SmallVector<const FAddend*, 4> AddendVect;
164 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
166 Value *performFactorization(Instruction *I);
168 /// Convert given addend to a Value
169 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
171 /// Return the number of instructions needed to emit the N-ary addition.
172 unsigned calcInstrNumber(const AddendVect& Vect);
173 Value *createFSub(Value *Opnd0, Value *Opnd1);
174 Value *createFAdd(Value *Opnd0, Value *Opnd1);
175 Value *createFMul(Value *Opnd0, Value *Opnd1);
176 Value *createFDiv(Value *Opnd0, Value *Opnd1);
177 Value *createFNeg(Value *V);
178 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
179 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
181 InstCombiner::BuilderTy *Builder;
185 // Debugging stuff are clustered here.
187 unsigned CreateInstrNum;
188 void initCreateInstNum() { CreateInstrNum = 0; }
189 void incCreateInstNum() { CreateInstrNum++; }
191 void initCreateInstNum() {}
192 void incCreateInstNum() {}
197 //===----------------------------------------------------------------------===//
200 // {FAddendCoef, FAddend, FAddition, FAddCombine}.
202 //===----------------------------------------------------------------------===//
203 FAddendCoef::~FAddendCoef() {
205 getFpValPtr()->~APFloat();
208 void FAddendCoef::set(const APFloat& C) {
209 APFloat *P = getFpValPtr();
212 // As the buffer is meanless byte stream, we cannot call
213 // APFloat::operator=().
218 IsFp = BufHasFpVal = true;
221 void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
225 APFloat *P = getFpValPtr();
227 new(P) APFloat(Sem, IntVal);
229 new(P) APFloat(Sem, 0 - IntVal);
232 IsFp = BufHasFpVal = true;
235 APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
237 return APFloat(Sem, Val);
239 APFloat T(Sem, 0 - Val);
245 void FAddendCoef::operator=(const FAddendCoef &That) {
249 set(That.getFpVal());
252 void FAddendCoef::operator+=(const FAddendCoef &That) {
253 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
254 if (isInt() == That.isInt()) {
256 IntVal += That.IntVal;
258 getFpVal().add(That.getFpVal(), RndMode);
263 const APFloat &T = That.getFpVal();
264 convertToFpType(T.getSemantics());
265 getFpVal().add(T, RndMode);
269 APFloat &T = getFpVal();
270 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
273 void FAddendCoef::operator-=(const FAddendCoef &That) {
274 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
275 if (isInt() == That.isInt()) {
277 IntVal -= That.IntVal;
279 getFpVal().subtract(That.getFpVal(), RndMode);
284 const APFloat &T = That.getFpVal();
285 convertToFpType(T.getSemantics());
286 getFpVal().subtract(T, RndMode);
290 APFloat &T = getFpVal();
291 T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
294 void FAddendCoef::operator*=(const FAddendCoef &That) {
298 if (That.isMinusOne()) {
303 if (isInt() && That.isInt()) {
304 int Res = IntVal * (int)That.IntVal;
305 assert(!insaneIntVal(Res) && "Insane int value");
310 const fltSemantics &Semantic =
311 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
314 convertToFpType(Semantic);
315 APFloat &F0 = getFpVal();
318 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
319 APFloat::rmNearestTiesToEven);
321 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
326 void FAddendCoef::negate() {
330 getFpVal().changeSign();
333 Value *FAddendCoef::getValue(Type *Ty) const {
335 ConstantFP::get(Ty, float(IntVal)) :
336 ConstantFP::get(Ty->getContext(), getFpVal());
339 // The definition of <Val> Addends
340 // =========================================
341 // A + B <1, A>, <1,B>
342 // A - B <1, A>, <1,B>
345 // A + C <1, A> <C, NULL>
346 // 0 +/- 0 <0, NULL> (corner case)
348 // Legend: A and B are not constant, C is constant
350 unsigned FAddend::drillValueDownOneStep
351 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
353 if (Val == 0 || !(I = dyn_cast<Instruction>(Val)))
356 unsigned Opcode = I->getOpcode();
358 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
360 Value *Opnd0 = I->getOperand(0);
361 Value *Opnd1 = I->getOperand(1);
362 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
365 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
370 Addend0.set(1, Opnd0);
376 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
378 Addend.set(1, Opnd1);
381 if (Opcode == Instruction::FSub)
386 return Opnd0 && Opnd1 ? 2 : 1;
388 // Both operands are zero. Weird!
389 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), 0);
393 if (I->getOpcode() == Instruction::FMul) {
394 Value *V0 = I->getOperand(0);
395 Value *V1 = I->getOperand(1);
396 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
401 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
410 // Try to break *this* addend into two addends. e.g. Suppose this addend is
411 // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
412 // i.e. <2.3, X> and <2.3, Y>.
414 unsigned FAddend::drillAddendDownOneStep
415 (FAddend &Addend0, FAddend &Addend1) const {
419 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
420 if (!BreakNum || Coeff.isOne())
423 Addend0.Scale(Coeff);
426 Addend1.Scale(Coeff);
431 // Try to perform following optimization on the input instruction I. Return the
432 // simplified expression if was successful; otherwise, return 0.
434 // Instruction "I" is Simplified into
435 // -------------------------------------------------------
436 // (x * y) +/- (x * z) x * (y +/- z)
437 // (y / x) +/- (z / x) (y +/- z) / x
439 Value *FAddCombine::performFactorization(Instruction *I) {
440 assert((I->getOpcode() == Instruction::FAdd ||
441 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
443 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
444 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
446 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
450 if (I0->getOpcode() == Instruction::FMul)
452 else if (I0->getOpcode() != Instruction::FDiv)
455 Value *Opnd0_0 = I0->getOperand(0);
456 Value *Opnd0_1 = I0->getOperand(1);
457 Value *Opnd1_0 = I1->getOperand(0);
458 Value *Opnd1_1 = I1->getOperand(1);
460 // Input Instr I Factor AddSub0 AddSub1
461 // ----------------------------------------------
462 // (x*y) +/- (x*z) x y z
463 // (y/x) +/- (z/x) x y z
466 Value *AddSub0 = 0, *AddSub1 = 0;
469 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
471 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
475 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
476 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
478 } else if (Opnd0_1 == Opnd1_1) {
488 Flags.setUnsafeAlgebra();
489 if (I0) Flags &= I->getFastMathFlags();
490 if (I1) Flags &= I->getFastMathFlags();
492 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
493 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
494 createFAdd(AddSub0, AddSub1) :
495 createFSub(AddSub0, AddSub1);
496 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
497 const APFloat &F = CFP->getValueAPF();
500 } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
501 II->setFastMathFlags(Flags);
504 Value *RI = createFMul(Factor, NewAddSub);
505 if (Instruction *II = dyn_cast<Instruction>(RI))
506 II->setFastMathFlags(Flags);
510 Value *RI = createFDiv(NewAddSub, Factor);
511 if (Instruction *II = dyn_cast<Instruction>(RI))
512 II->setFastMathFlags(Flags);
516 Value *FAddCombine::simplify(Instruction *I) {
517 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
519 // Currently we are not able to handle vector type.
520 if (I->getType()->isVectorTy())
523 assert((I->getOpcode() == Instruction::FAdd ||
524 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
526 // Save the instruction before calling other member-functions.
529 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
531 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
533 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
534 unsigned Opnd0_ExpNum = 0;
535 unsigned Opnd1_ExpNum = 0;
537 if (!Opnd0.isConstant())
538 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
540 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
541 if (OpndNum == 2 && !Opnd1.isConstant())
542 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
544 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
545 if (Opnd0_ExpNum && Opnd1_ExpNum) {
547 AllOpnds.push_back(&Opnd0_0);
548 AllOpnds.push_back(&Opnd1_0);
549 if (Opnd0_ExpNum == 2)
550 AllOpnds.push_back(&Opnd0_1);
551 if (Opnd1_ExpNum == 2)
552 AllOpnds.push_back(&Opnd1_1);
554 // Compute instruction quota. We should save at least one instruction.
555 unsigned InstQuota = 0;
557 Value *V0 = I->getOperand(0);
558 Value *V1 = I->getOperand(1);
559 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
560 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
562 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
567 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
568 // splitted into two addends, say "V = X - Y", the instruction would have
569 // been optimized into "I = Y - X" in the previous steps.
571 const FAddendCoef &CE = Opnd0.getCoef();
572 return CE.isOne() ? Opnd0.getSymVal() : 0;
575 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
578 AllOpnds.push_back(&Opnd0);
579 AllOpnds.push_back(&Opnd1_0);
580 if (Opnd1_ExpNum == 2)
581 AllOpnds.push_back(&Opnd1_1);
583 if (Value *R = simplifyFAdd(AllOpnds, 1))
587 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
590 AllOpnds.push_back(&Opnd1);
591 AllOpnds.push_back(&Opnd0_0);
592 if (Opnd0_ExpNum == 2)
593 AllOpnds.push_back(&Opnd0_1);
595 if (Value *R = simplifyFAdd(AllOpnds, 1))
599 // step 6: Try factorization as the last resort,
600 return performFactorization(I);
603 Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
605 unsigned AddendNum = Addends.size();
606 assert(AddendNum <= 4 && "Too many addends");
608 // For saving intermediate results;
609 unsigned NextTmpIdx = 0;
610 FAddend TmpResult[3];
612 // Points to the constant addend of the resulting simplified expression.
613 // If the resulting expr has constant-addend, this constant-addend is
614 // desirable to reside at the top of the resulting expression tree. Placing
615 // constant close to supper-expr(s) will potentially reveal some optimization
616 // opportunities in super-expr(s).
618 const FAddend *ConstAdd = 0;
620 // Simplified addends are placed <SimpVect>.
623 // The outer loop works on one symbolic-value at a time. Suppose the input
624 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
625 // The symbolic-values will be processed in this order: x, y, z.
627 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
629 const FAddend *ThisAddend = Addends[SymIdx];
631 // This addend was processed before.
635 Value *Val = ThisAddend->getSymVal();
636 unsigned StartIdx = SimpVect.size();
637 SimpVect.push_back(ThisAddend);
639 // The inner loop collects addends sharing same symbolic-value, and these
640 // addends will be later on folded into a single addend. Following above
641 // example, if the symbolic value "y" is being processed, the inner loop
642 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
643 // be later on folded into "<b1+b2, y>".
645 for (unsigned SameSymIdx = SymIdx + 1;
646 SameSymIdx < AddendNum; SameSymIdx++) {
647 const FAddend *T = Addends[SameSymIdx];
648 if (T && T->getSymVal() == Val) {
649 // Set null such that next iteration of the outer loop will not process
650 // this addend again.
651 Addends[SameSymIdx] = 0;
652 SimpVect.push_back(T);
656 // If multiple addends share same symbolic value, fold them together.
657 if (StartIdx + 1 != SimpVect.size()) {
658 FAddend &R = TmpResult[NextTmpIdx ++];
659 R = *SimpVect[StartIdx];
660 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
663 // Pop all addends being folded and push the resulting folded addend.
664 SimpVect.resize(StartIdx);
667 SimpVect.push_back(&R);
670 // Don't push constant addend at this time. It will be the last element
677 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
678 "out-of-bound access");
681 SimpVect.push_back(ConstAdd);
684 if (!SimpVect.empty())
685 Result = createNaryFAdd(SimpVect, InstrQuota);
687 // The addition is folded to 0.0.
688 Result = ConstantFP::get(Instr->getType(), 0.0);
694 Value *FAddCombine::createNaryFAdd
695 (const AddendVect &Opnds, unsigned InstrQuota) {
696 assert(!Opnds.empty() && "Expect at least one addend");
698 // Step 1: Check if the # of instructions needed exceeds the quota.
700 unsigned InstrNeeded = calcInstrNumber(Opnds);
701 if (InstrNeeded > InstrQuota)
706 // step 2: Emit the N-ary addition.
707 // Note that at most three instructions are involved in Fadd-InstCombine: the
708 // addition in question, and at most two neighboring instructions.
709 // The resulting optimized addition should have at least one less instruction
710 // than the original addition expression tree. This implies that the resulting
711 // N-ary addition has at most two instructions, and we don't need to worry
712 // about tree-height when constructing the N-ary addition.
715 bool LastValNeedNeg = false;
717 // Iterate the addends, creating fadd/fsub using adjacent two addends.
718 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
721 Value *V = createAddendVal(**I, NeedNeg);
724 LastValNeedNeg = NeedNeg;
728 if (LastValNeedNeg == NeedNeg) {
729 LastVal = createFAdd(LastVal, V);
734 LastVal = createFSub(V, LastVal);
736 LastVal = createFSub(LastVal, V);
738 LastValNeedNeg = false;
741 if (LastValNeedNeg) {
742 LastVal = createFNeg(LastVal);
746 assert(CreateInstrNum == InstrNeeded &&
747 "Inconsistent in instruction numbers");
753 Value *FAddCombine::createFSub
754 (Value *Opnd0, Value *Opnd1) {
755 Value *V = Builder->CreateFSub(Opnd0, Opnd1);
756 if (Instruction *I = dyn_cast<Instruction>(V))
757 createInstPostProc(I);
761 Value *FAddCombine::createFNeg(Value *V) {
762 Value *Zero = cast<Value>(ConstantFP::get(V->getType(), 0.0));
763 Value *NewV = createFSub(Zero, V);
764 if (Instruction *I = dyn_cast<Instruction>(NewV))
765 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
769 Value *FAddCombine::createFAdd
770 (Value *Opnd0, Value *Opnd1) {
771 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
772 if (Instruction *I = dyn_cast<Instruction>(V))
773 createInstPostProc(I);
777 Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
778 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
779 if (Instruction *I = dyn_cast<Instruction>(V))
780 createInstPostProc(I);
784 Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
785 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
786 if (Instruction *I = dyn_cast<Instruction>(V))
787 createInstPostProc(I);
791 void FAddCombine::createInstPostProc(Instruction *NewInstr,
793 NewInstr->setDebugLoc(Instr->getDebugLoc());
795 // Keep track of the number of instruction created.
799 // Propagate fast-math flags
800 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
803 // Return the number of instruction needed to emit the N-ary addition.
804 // NOTE: Keep this function in sync with createAddendVal().
805 unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
806 unsigned OpndNum = Opnds.size();
807 unsigned InstrNeeded = OpndNum - 1;
809 // The number of addends in the form of "(-1)*x".
810 unsigned NegOpndNum = 0;
812 // Adjust the number of instructions needed to emit the N-ary add.
813 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
815 const FAddend *Opnd = *I;
816 if (Opnd->isConstant())
819 const FAddendCoef &CE = Opnd->getCoef();
820 if (CE.isMinusOne() || CE.isMinusTwo())
823 // Let the addend be "c * x". If "c == +/-1", the value of the addend
824 // is immediately available; otherwise, it needs exactly one instruction
825 // to evaluate the value.
826 if (!CE.isMinusOne() && !CE.isOne())
829 if (NegOpndNum == OpndNum)
834 // Input Addend Value NeedNeg(output)
835 // ================================================================
836 // Constant C C false
837 // <+/-1, V> V coefficient is -1
838 // <2/-2, V> "fadd V, V" coefficient is -2
839 // <C, V> "fmul V, C" false
841 // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
842 Value *FAddCombine::createAddendVal
843 (const FAddend &Opnd, bool &NeedNeg) {
844 const FAddendCoef &Coeff = Opnd.getCoef();
846 if (Opnd.isConstant()) {
848 return Coeff.getValue(Instr->getType());
851 Value *OpndVal = Opnd.getSymVal();
853 if (Coeff.isMinusOne() || Coeff.isOne()) {
854 NeedNeg = Coeff.isMinusOne();
858 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
859 NeedNeg = Coeff.isMinusTwo();
860 return createFAdd(OpndVal, OpndVal);
864 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
867 // dyn_castFoldableMul - If this value is a multiply that can be folded into
868 // other computations (because it has a constant operand), return the
869 // non-constant operand of the multiply, and set CST to point to the multiplier.
870 // Otherwise, return null.
872 static inline Value *dyn_castFoldableMul(Value *V, Constant *&CST) {
873 if (!V->hasOneUse() || !V->getType()->isIntOrIntVectorTy())
876 Instruction *I = dyn_cast<Instruction>(V);
877 if (I == 0) return 0;
879 if (I->getOpcode() == Instruction::Mul)
880 if ((CST = dyn_cast<Constant>(I->getOperand(1))))
881 return I->getOperand(0);
882 if (I->getOpcode() == Instruction::Shl)
883 if ((CST = dyn_cast<Constant>(I->getOperand(1)))) {
884 // The multiplier is really 1 << CST.
885 CST = ConstantExpr::getShl(ConstantInt::get(V->getType(), 1), CST);
886 return I->getOperand(0);
892 /// WillNotOverflowSignedAdd - Return true if we can prove that:
893 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
894 /// This basically requires proving that the add in the original type would not
895 /// overflow to change the sign bit or have a carry out.
896 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
897 // There are different heuristics we can use for this. Here are some simple
900 // Add has the property that adding any two 2's complement numbers can only
901 // have one carry bit which can change a sign. As such, if LHS and RHS each
902 // have at least two sign bits, we know that the addition of the two values
903 // will sign extend fine.
904 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
908 // If one of the operands only has one non-zero bit, and if the other operand
909 // has a known-zero bit in a more significant place than it (not including the
910 // sign bit) the ripple may go up to and fill the zero, but won't change the
911 // sign. For example, (X & ~4) + 1.
918 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
919 bool Changed = SimplifyAssociativeOrCommutative(I);
920 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
922 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
923 I.hasNoUnsignedWrap(), DL))
924 return ReplaceInstUsesWith(I, V);
926 // (A*B)+(A*C) -> A*(B+C) etc
927 if (Value *V = SimplifyUsingDistributiveLaws(I))
928 return ReplaceInstUsesWith(I, V);
930 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
931 // X + (signbit) --> X ^ signbit
932 const APInt &Val = CI->getValue();
934 return BinaryOperator::CreateXor(LHS, RHS);
936 // See if SimplifyDemandedBits can simplify this. This handles stuff like
937 // (X & 254)+1 -> (X&254)|1
938 if (SimplifyDemandedInstructionBits(I))
941 // zext(bool) + C -> bool ? C + 1 : C
942 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
943 if (ZI->getSrcTy()->isIntegerTy(1))
944 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
946 Value *XorLHS = 0; ConstantInt *XorRHS = 0;
947 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
948 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
949 const APInt &RHSVal = CI->getValue();
950 unsigned ExtendAmt = 0;
951 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
952 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
953 if (XorRHS->getValue() == -RHSVal) {
954 if (RHSVal.isPowerOf2())
955 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
956 else if (XorRHS->getValue().isPowerOf2())
957 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
961 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
962 if (!MaskedValueIsZero(XorLHS, Mask))
967 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
968 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
969 return BinaryOperator::CreateAShr(NewShl, ShAmt);
972 // If this is a xor that was canonicalized from a sub, turn it back into
973 // a sub and fuse this add with it.
974 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
975 IntegerType *IT = cast<IntegerType>(I.getType());
976 APInt LHSKnownOne(IT->getBitWidth(), 0);
977 APInt LHSKnownZero(IT->getBitWidth(), 0);
978 ComputeMaskedBits(XorLHS, LHSKnownZero, LHSKnownOne);
979 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
980 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
983 // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
984 // transform them into (X + (signbit ^ C))
985 if (XorRHS->getValue().isSignBit())
986 return BinaryOperator::CreateAdd(XorLHS,
987 ConstantExpr::getXor(XorRHS, CI));
991 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
992 if (Instruction *NV = FoldOpIntoPhi(I))
995 if (I.getType()->getScalarType()->isIntegerTy(1))
996 return BinaryOperator::CreateXor(LHS, RHS);
1000 BinaryOperator *New =
1001 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1002 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1003 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1008 // -A + -B --> -(A + B)
1009 if (Value *LHSV = dyn_castNegVal(LHS)) {
1010 if (!isa<Constant>(RHS))
1011 if (Value *RHSV = dyn_castNegVal(RHS)) {
1012 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1013 return BinaryOperator::CreateNeg(NewAdd);
1016 return BinaryOperator::CreateSub(RHS, LHSV);
1020 if (!isa<Constant>(RHS))
1021 if (Value *V = dyn_castNegVal(RHS))
1022 return BinaryOperator::CreateSub(LHS, V);
1027 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1028 if (X == RHS) // X*C + X --> X * (C+1)
1029 return BinaryOperator::CreateMul(RHS, AddOne(C2));
1031 // X*C1 + X*C2 --> X * (C1+C2)
1033 if (X == dyn_castFoldableMul(RHS, C1))
1034 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
1037 // X + X*C --> X * (C+1)
1038 if (dyn_castFoldableMul(RHS, C2) == LHS)
1039 return BinaryOperator::CreateMul(LHS, AddOne(C2));
1042 // A+B --> A|B iff A and B have no bits set in common.
1043 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
1044 APInt LHSKnownOne(IT->getBitWidth(), 0);
1045 APInt LHSKnownZero(IT->getBitWidth(), 0);
1046 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
1047 if (LHSKnownZero != 0) {
1048 APInt RHSKnownOne(IT->getBitWidth(), 0);
1049 APInt RHSKnownZero(IT->getBitWidth(), 0);
1050 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
1052 // No bits in common -> bitwise or.
1053 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
1054 return BinaryOperator::CreateOr(LHS, RHS);
1058 // W*X + Y*Z --> W * (X+Z) iff W == Y
1060 Value *W, *X, *Y, *Z;
1061 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
1062 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
1066 } else if (Y == X) {
1068 } else if (X == Z) {
1075 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
1076 return BinaryOperator::CreateMul(W, NewAdd);
1081 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1083 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
1084 return BinaryOperator::CreateSub(SubOne(CRHS), X);
1087 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1088 // (X & FF00) + xx00 -> (X+xx00) & FF00
1091 if (LHS->hasOneUse() &&
1092 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1093 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1094 // See if all bits from the first bit set in the Add RHS up are included
1095 // in the mask. First, get the rightmost bit.
1096 const APInt &AddRHSV = CRHS->getValue();
1098 // Form a mask of all bits from the lowest bit added through the top.
1099 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
1101 // See if the and mask includes all of these bits.
1102 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
1104 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1105 // Okay, the xform is safe. Insert the new add pronto.
1106 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1107 return BinaryOperator::CreateAnd(NewAdd, C2);
1111 // Try to fold constant add into select arguments.
1112 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1113 if (Instruction *R = FoldOpIntoSelect(I, SI))
1117 // add (select X 0 (sub n A)) A --> select X A n
1119 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1122 SI = dyn_cast<SelectInst>(RHS);
1125 if (SI && SI->hasOneUse()) {
1126 Value *TV = SI->getTrueValue();
1127 Value *FV = SI->getFalseValue();
1130 // Can we fold the add into the argument of the select?
1131 // We check both true and false select arguments for a matching subtract.
1132 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1133 // Fold the add into the true select value.
1134 return SelectInst::Create(SI->getCondition(), N, A);
1136 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1137 // Fold the add into the false select value.
1138 return SelectInst::Create(SI->getCondition(), A, N);
1142 // Check for (add (sext x), y), see if we can merge this into an
1143 // integer add followed by a sext.
1144 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1145 // (add (sext x), cst) --> (sext (add x, cst'))
1146 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1148 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1149 if (LHSConv->hasOneUse() &&
1150 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1151 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1152 // Insert the new, smaller add.
1153 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1155 return new SExtInst(NewAdd, I.getType());
1159 // (add (sext x), (sext y)) --> (sext (add int x, y))
1160 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1161 // Only do this if x/y have the same type, if at last one of them has a
1162 // single use (so we don't increase the number of sexts), and if the
1163 // integer add will not overflow.
1164 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1165 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1166 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1167 RHSConv->getOperand(0))) {
1168 // Insert the new integer add.
1169 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1170 RHSConv->getOperand(0), "addconv");
1171 return new SExtInst(NewAdd, I.getType());
1176 // Check for (x & y) + (x ^ y)
1178 Value *A = 0, *B = 0;
1179 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1180 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1181 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1182 return BinaryOperator::CreateOr(A, B);
1184 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1185 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1186 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1187 return BinaryOperator::CreateOr(A, B);
1190 return Changed ? &I : 0;
1193 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1194 bool Changed = SimplifyAssociativeOrCommutative(I);
1195 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1197 if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL))
1198 return ReplaceInstUsesWith(I, V);
1200 if (isa<Constant>(RHS)) {
1201 if (isa<PHINode>(LHS))
1202 if (Instruction *NV = FoldOpIntoPhi(I))
1205 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1206 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1211 // -A + -B --> -(A + B)
1212 if (Value *LHSV = dyn_castFNegVal(LHS)) {
1213 Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1214 RI->copyFastMathFlags(&I);
1219 if (!isa<Constant>(RHS))
1220 if (Value *V = dyn_castFNegVal(RHS)) {
1221 Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1222 RI->copyFastMathFlags(&I);
1226 // Check for (fadd double (sitofp x), y), see if we can merge this into an
1227 // integer add followed by a promotion.
1228 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1229 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1230 // ... if the constant fits in the integer value. This is useful for things
1231 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1232 // requires a constant pool load, and generally allows the add to be better
1234 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
1236 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1237 if (LHSConv->hasOneUse() &&
1238 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1239 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1240 // Insert the new integer add.
1241 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1243 return new SIToFPInst(NewAdd, I.getType());
1247 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1248 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1249 // Only do this if x/y have the same type, if at last one of them has a
1250 // single use (so we don't increase the number of int->fp conversions),
1251 // and if the integer add will not overflow.
1252 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1253 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1254 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1255 RHSConv->getOperand(0))) {
1256 // Insert the new integer add.
1257 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1258 RHSConv->getOperand(0),"addconv");
1259 return new SIToFPInst(NewAdd, I.getType());
1264 // select C, 0, B + select C, A, 0 -> select C, A, B
1266 Value *A1, *B1, *C1, *A2, *B2, *C2;
1267 if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1268 match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1270 Constant *Z1=0, *Z2=0;
1271 Value *A, *B, *C=C1;
1272 if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1273 Z1 = dyn_cast<Constant>(A1); A = A2;
1274 Z2 = dyn_cast<Constant>(B2); B = B1;
1275 } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1276 Z1 = dyn_cast<Constant>(B1); B = B2;
1277 Z2 = dyn_cast<Constant>(A2); A = A1;
1281 (I.hasNoSignedZeros() ||
1282 (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1283 return SelectInst::Create(C, A, B);
1289 if (I.hasUnsafeAlgebra()) {
1290 if (Value *V = FAddCombine(Builder).simplify(&I))
1291 return ReplaceInstUsesWith(I, V);
1294 return Changed ? &I : 0;
1298 /// Optimize pointer differences into the same array into a size. Consider:
1299 /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1300 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1302 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1304 assert(DL && "Must have target data info for this");
1306 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1308 bool Swapped = false;
1309 GEPOperator *GEP1 = 0, *GEP2 = 0;
1311 // For now we require one side to be the base pointer "A" or a constant
1312 // GEP derived from it.
1313 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1315 if (LHSGEP->getOperand(0) == RHS) {
1318 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1319 // (gep X, ...) - (gep X, ...)
1320 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1321 RHSGEP->getOperand(0)->stripPointerCasts()) {
1329 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1331 if (RHSGEP->getOperand(0) == LHS) {
1334 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1335 // (gep X, ...) - (gep X, ...)
1336 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1337 LHSGEP->getOperand(0)->stripPointerCasts()) {
1345 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1348 (GEP2 != 0 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1351 // Emit the offset of the GEP and an intptr_t.
1352 Value *Result = EmitGEPOffset(GEP1);
1354 // If we had a constant expression GEP on the other side offsetting the
1355 // pointer, subtract it from the offset we have.
1357 Value *Offset = EmitGEPOffset(GEP2);
1358 Result = Builder->CreateSub(Result, Offset);
1361 // If we have p - gep(p, ...) then we have to negate the result.
1363 Result = Builder->CreateNeg(Result, "diff.neg");
1365 return Builder->CreateIntCast(Result, Ty, true);
1369 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1370 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1372 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
1373 I.hasNoUnsignedWrap(), DL))
1374 return ReplaceInstUsesWith(I, V);
1376 // (A*B)-(A*C) -> A*(B-C) etc
1377 if (Value *V = SimplifyUsingDistributiveLaws(I))
1378 return ReplaceInstUsesWith(I, V);
1380 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1381 if (Value *V = dyn_castNegVal(Op1)) {
1382 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1383 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1384 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1388 if (I.getType()->isIntegerTy(1))
1389 return BinaryOperator::CreateXor(Op0, Op1);
1391 // Replace (-1 - A) with (~A).
1392 if (match(Op0, m_AllOnes()))
1393 return BinaryOperator::CreateNot(Op1);
1395 if (Constant *C = dyn_cast<Constant>(Op0)) {
1396 // C - ~X == X + (1+C)
1398 if (match(Op1, m_Not(m_Value(X))))
1399 return BinaryOperator::CreateAdd(X, AddOne(C));
1401 // Try to fold constant sub into select arguments.
1402 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1403 if (Instruction *R = FoldOpIntoSelect(I, SI))
1406 // C-(X+C2) --> (C-C2)-X
1408 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1409 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1411 if (SimplifyDemandedInstructionBits(I))
1414 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1415 if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1416 if (X->getType()->getScalarType()->isIntegerTy(1))
1417 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1419 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1420 if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1421 if (X->getType()->getScalarType()->isIntegerTy(1))
1422 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1425 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1426 // -(X >>u 31) -> (X >>s 31)
1427 // -(X >>s 31) -> (X >>u 31)
1429 Value *X; ConstantInt *CI;
1430 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1431 // Verify we are shifting out everything but the sign bit.
1432 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1433 return BinaryOperator::CreateAShr(X, CI);
1435 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1436 // Verify we are shifting out everything but the sign bit.
1437 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1438 return BinaryOperator::CreateLShr(X, CI);
1444 // X-(X+Y) == -Y X-(Y+X) == -Y
1445 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1446 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1447 return BinaryOperator::CreateNeg(Y);
1450 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1451 return BinaryOperator::CreateNeg(Y);
1454 if (Op1->hasOneUse()) {
1455 Value *X = 0, *Y = 0, *Z = 0;
1459 // (X - (Y - Z)) --> (X + (Z - Y)).
1460 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1461 return BinaryOperator::CreateAdd(Op0,
1462 Builder->CreateSub(Z, Y, Op1->getName()));
1464 // (X - (X & Y)) --> (X & ~Y)
1466 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1467 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1468 return BinaryOperator::CreateAnd(Op0,
1469 Builder->CreateNot(Y, Y->getName() + ".not"));
1471 // 0 - (X sdiv C) -> (X sdiv -C)
1472 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
1473 match(Op0, m_Zero()))
1474 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1476 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1477 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1478 if (Value *XNeg = dyn_castNegVal(X))
1479 return BinaryOperator::CreateShl(XNeg, Y);
1481 // X - X*C --> X * (1-C)
1482 if (match(Op1, m_Mul(m_Specific(Op0), m_Constant(CI)))) {
1483 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
1484 return BinaryOperator::CreateMul(Op0, CP1);
1487 // X - X<<C --> X * (1-(1<<C))
1488 if (match(Op1, m_Shl(m_Specific(Op0), m_Constant(CI)))) {
1489 Constant *One = ConstantInt::get(I.getType(), 1);
1490 C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
1491 return BinaryOperator::CreateMul(Op0, C);
1494 // X - A*-B -> X + A*B
1495 // X - -A*B -> X + A*B
1497 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1498 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1499 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
1501 // X - A*CI -> X + A*-CI
1502 // X - CI*A -> X + A*-CI
1503 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1504 match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
1505 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1506 return BinaryOperator::CreateAdd(Op0, NewMul);
1511 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1512 if (X == Op1) // X*C - X --> X * (C-1)
1513 return BinaryOperator::CreateMul(Op1, SubOne(C1));
1515 Constant *C2; // X*C1 - X*C2 -> X * (C1-C2)
1516 if (X == dyn_castFoldableMul(Op1, C2))
1517 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
1520 // Optimize pointer differences into the same array into a size. Consider:
1521 // &A[10] - &A[0]: we should compile this to "10".
1523 Value *LHSOp, *RHSOp;
1524 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1525 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1526 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1527 return ReplaceInstUsesWith(I, Res);
1529 // trunc(p)-trunc(q) -> trunc(p-q)
1530 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1531 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1532 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1533 return ReplaceInstUsesWith(I, Res);
1539 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1542 if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL))
1543 return ReplaceInstUsesWith(I, V);
1545 if (isa<Constant>(Op0))
1546 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1547 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1550 // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1551 // through FP extensions/truncations along the way.
1552 if (Value *V = dyn_castFNegVal(Op1)) {
1553 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1554 NewI->copyFastMathFlags(&I);
1557 if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1558 if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1559 Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
1560 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1561 NewI->copyFastMathFlags(&I);
1564 } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1565 if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
1566 Value *NewExt = Builder->CreateFPExt(V, I.getType());
1567 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1568 NewI->copyFastMathFlags(&I);
1573 if (I.hasUnsafeAlgebra()) {
1574 if (Value *V = FAddCombine(Builder).simplify(&I))
1575 return ReplaceInstUsesWith(I, V);