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