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