blob: 908038b35e4ae50e640d26e6257df8aef879e42e [file] [log] [blame]
Chris Lattner53a19b72010-01-05 07:18:46 +00001//===- InstCombineAddSub.cpp ----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for add, fadd, sub, and fsub.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
15#include "llvm/Analysis/InstructionSimplify.h"
16#include "llvm/Target/TargetData.h"
17#include "llvm/Support/GetElementPtrTypeIterator.h"
18#include "llvm/Support/PatternMatch.h"
19using namespace llvm;
20using namespace PatternMatch;
21
22/// AddOne - Add one to a ConstantInt.
23static Constant *AddOne(Constant *C) {
24 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
25}
26/// SubOne - Subtract one from a ConstantInt.
27static Constant *SubOne(ConstantInt *C) {
28 return ConstantInt::get(C->getContext(), C->getValue()-1);
29}
30
31
32// dyn_castFoldableMul - If this value is a multiply that can be folded into
33// other computations (because it has a constant operand), return the
34// non-constant operand of the multiply, and set CST to point to the multiplier.
35// Otherwise, return null.
36//
37static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000038 if (!V->hasOneUse() || !V->getType()->isIntegerTy())
Chris Lattner3168c7d2010-01-05 20:56:24 +000039 return 0;
40
41 Instruction *I = dyn_cast<Instruction>(V);
42 if (I == 0) return 0;
43
44 if (I->getOpcode() == Instruction::Mul)
45 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
46 return I->getOperand(0);
47 if (I->getOpcode() == Instruction::Shl)
48 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
49 // The multiplier is really 1 << CST.
50 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
51 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
52 CST = ConstantInt::get(V->getType()->getContext(),
53 APInt(BitWidth, 1).shl(CSTVal));
54 return I->getOperand(0);
Chris Lattner53a19b72010-01-05 07:18:46 +000055 }
56 return 0;
57}
58
59
60/// WillNotOverflowSignedAdd - Return true if we can prove that:
61/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
62/// This basically requires proving that the add in the original type would not
63/// overflow to change the sign bit or have a carry out.
64bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
65 // There are different heuristics we can use for this. Here are some simple
66 // ones.
67
68 // Add has the property that adding any two 2's complement numbers can only
69 // have one carry bit which can change a sign. As such, if LHS and RHS each
70 // have at least two sign bits, we know that the addition of the two values
71 // will sign extend fine.
72 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
73 return true;
74
75
76 // If one of the operands only has one non-zero bit, and if the other operand
77 // has a known-zero bit in a more significant place than it (not including the
78 // sign bit) the ripple may go up to and fill the zero, but won't change the
79 // sign. For example, (X & ~4) + 1.
80
81 // TODO: Implement.
82
83 return false;
84}
85
86Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +000087 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner53a19b72010-01-05 07:18:46 +000088 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
89
90 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
91 I.hasNoUnsignedWrap(), TD))
92 return ReplaceInstUsesWith(I, V);
93
Duncan Sands37bf92b2010-12-22 13:36:08 +000094 // (A*B)+(A*C) -> A*(B+C) etc
95 if (Value *V = SimplifyUsingDistributiveLaws(I))
96 return ReplaceInstUsesWith(I, V);
97
Chris Lattnerb9b90442011-02-10 05:14:58 +000098 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
99 // X + (signbit) --> X ^ signbit
100 const APInt &Val = CI->getValue();
101 if (Val.isSignBit())
102 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattner53a19b72010-01-05 07:18:46 +0000103
Chris Lattnerb9b90442011-02-10 05:14:58 +0000104 // See if SimplifyDemandedBits can simplify this. This handles stuff like
105 // (X & 254)+1 -> (X&254)|1
106 if (SimplifyDemandedInstructionBits(I))
107 return &I;
108
109 // zext(bool) + C -> bool ? C + 1 : C
110 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
111 if (ZI->getSrcTy()->isIntegerTy(1))
112 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
113
114 Value *XorLHS = 0; ConstantInt *XorRHS = 0;
115 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000116 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Chris Lattnerb9b90442011-02-10 05:14:58 +0000117 const APInt &RHSVal = CI->getValue();
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000118 unsigned ExtendAmt = 0;
119 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
120 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
121 if (XorRHS->getValue() == -RHSVal) {
122 if (RHSVal.isPowerOf2())
123 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
124 else if (XorRHS->getValue().isPowerOf2())
125 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner53a19b72010-01-05 07:18:46 +0000126 }
Chris Lattnerb9b90442011-02-10 05:14:58 +0000127
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000128 if (ExtendAmt) {
129 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
130 if (!MaskedValueIsZero(XorLHS, Mask))
131 ExtendAmt = 0;
132 }
Chris Lattnerb9b90442011-02-10 05:14:58 +0000133
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000134 if (ExtendAmt) {
135 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
136 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
137 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner53a19b72010-01-05 07:18:46 +0000138 }
Benjamin Kramer49064ff2011-12-24 17:31:53 +0000139
140 // If this is a xor that was canonicalized from a sub, turn it back into
141 // a sub and fuse this add with it.
142 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
143 IntegerType *IT = cast<IntegerType>(I.getType());
144 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
145 APInt LHSKnownOne(IT->getBitWidth(), 0);
146 APInt LHSKnownZero(IT->getBitWidth(), 0);
147 ComputeMaskedBits(XorLHS, Mask, LHSKnownZero, LHSKnownOne);
148 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
149 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
150 XorLHS);
151 }
Chris Lattner53a19b72010-01-05 07:18:46 +0000152 }
153 }
154
Chris Lattnerb9b90442011-02-10 05:14:58 +0000155 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
156 if (Instruction *NV = FoldOpIntoPhi(I))
157 return NV;
158
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000159 if (I.getType()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +0000160 return BinaryOperator::CreateXor(LHS, RHS);
161
Chris Lattnerb9b90442011-02-10 05:14:58 +0000162 // X + X --> X << 1
Chris Lattnerbd9f6bf2011-02-17 20:55:29 +0000163 if (LHS == RHS) {
Chris Lattner41429e32011-02-17 02:23:02 +0000164 BinaryOperator *New =
165 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
166 New->setHasNoSignedWrap(I.hasNoSignedWrap());
167 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
168 return New;
169 }
Chris Lattner53a19b72010-01-05 07:18:46 +0000170
171 // -A + B --> B - A
172 // -A + -B --> -(A + B)
173 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnerb9b90442011-02-10 05:14:58 +0000174 if (Value *RHSV = dyn_castNegVal(RHS)) {
175 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
176 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner53a19b72010-01-05 07:18:46 +0000177 }
178
179 return BinaryOperator::CreateSub(RHS, LHSV);
180 }
181
182 // A + -B --> A - B
183 if (!isa<Constant>(RHS))
184 if (Value *V = dyn_castNegVal(RHS))
185 return BinaryOperator::CreateSub(LHS, V);
186
187
188 ConstantInt *C2;
189 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
190 if (X == RHS) // X*C + X --> X * (C+1)
191 return BinaryOperator::CreateMul(RHS, AddOne(C2));
192
193 // X*C1 + X*C2 --> X * (C1+C2)
194 ConstantInt *C1;
195 if (X == dyn_castFoldableMul(RHS, C1))
196 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
197 }
198
199 // X + X*C --> X * (C+1)
200 if (dyn_castFoldableMul(RHS, C2) == LHS)
201 return BinaryOperator::CreateMul(LHS, AddOne(C2));
202
Chris Lattner53a19b72010-01-05 07:18:46 +0000203 // A+B --> A|B iff A and B have no bits set in common.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000204 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000205 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
206 APInt LHSKnownOne(IT->getBitWidth(), 0);
207 APInt LHSKnownZero(IT->getBitWidth(), 0);
208 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
209 if (LHSKnownZero != 0) {
210 APInt RHSKnownOne(IT->getBitWidth(), 0);
211 APInt RHSKnownZero(IT->getBitWidth(), 0);
212 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
213
214 // No bits in common -> bitwise or.
215 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
216 return BinaryOperator::CreateOr(LHS, RHS);
217 }
218 }
219
220 // W*X + Y*Z --> W * (X+Z) iff W == Y
Chris Lattnerb9b90442011-02-10 05:14:58 +0000221 {
Chris Lattner53a19b72010-01-05 07:18:46 +0000222 Value *W, *X, *Y, *Z;
223 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
224 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
225 if (W != Y) {
226 if (W == Z) {
227 std::swap(Y, Z);
228 } else if (Y == X) {
229 std::swap(W, X);
230 } else if (X == Z) {
231 std::swap(Y, Z);
232 std::swap(W, X);
233 }
234 }
235
236 if (W == Y) {
237 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
238 return BinaryOperator::CreateMul(W, NewAdd);
239 }
240 }
241 }
242
243 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
244 Value *X = 0;
245 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
246 return BinaryOperator::CreateSub(SubOne(CRHS), X);
247
248 // (X & FF00) + xx00 -> (X+xx00) & FF00
249 if (LHS->hasOneUse() &&
Chris Lattnerb9b90442011-02-10 05:14:58 +0000250 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
251 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
252 // See if all bits from the first bit set in the Add RHS up are included
253 // in the mask. First, get the rightmost bit.
254 const APInt &AddRHSV = CRHS->getValue();
255
256 // Form a mask of all bits from the lowest bit added through the top.
257 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner53a19b72010-01-05 07:18:46 +0000258
Chris Lattnerb9b90442011-02-10 05:14:58 +0000259 // See if the and mask includes all of these bits.
260 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner53a19b72010-01-05 07:18:46 +0000261
Chris Lattnerb9b90442011-02-10 05:14:58 +0000262 if (AddRHSHighBits == AddRHSHighBitsAnd) {
263 // Okay, the xform is safe. Insert the new add pronto.
264 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
265 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner53a19b72010-01-05 07:18:46 +0000266 }
267 }
268
269 // Try to fold constant add into select arguments.
270 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
271 if (Instruction *R = FoldOpIntoSelect(I, SI))
272 return R;
273 }
274
275 // add (select X 0 (sub n A)) A --> select X A n
276 {
277 SelectInst *SI = dyn_cast<SelectInst>(LHS);
278 Value *A = RHS;
279 if (!SI) {
280 SI = dyn_cast<SelectInst>(RHS);
281 A = LHS;
282 }
283 if (SI && SI->hasOneUse()) {
284 Value *TV = SI->getTrueValue();
285 Value *FV = SI->getFalseValue();
286 Value *N;
287
288 // Can we fold the add into the argument of the select?
289 // We check both true and false select arguments for a matching subtract.
Chris Lattnerb9b90442011-02-10 05:14:58 +0000290 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner53a19b72010-01-05 07:18:46 +0000291 // Fold the add into the true select value.
292 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerb9b90442011-02-10 05:14:58 +0000293
294 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner53a19b72010-01-05 07:18:46 +0000295 // Fold the add into the false select value.
296 return SelectInst::Create(SI->getCondition(), A, N);
297 }
298 }
299
300 // Check for (add (sext x), y), see if we can merge this into an
301 // integer add followed by a sext.
302 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
303 // (add (sext x), cst) --> (sext (add x, cst'))
304 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
305 Constant *CI =
306 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
307 if (LHSConv->hasOneUse() &&
308 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
309 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
310 // Insert the new, smaller add.
311 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
312 CI, "addconv");
313 return new SExtInst(NewAdd, I.getType());
314 }
315 }
316
317 // (add (sext x), (sext y)) --> (sext (add int x, y))
318 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
319 // Only do this if x/y have the same type, if at last one of them has a
320 // single use (so we don't increase the number of sexts), and if the
321 // integer add will not overflow.
322 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
323 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
324 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
325 RHSConv->getOperand(0))) {
326 // Insert the new integer add.
327 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner3168c7d2010-01-05 20:56:24 +0000328 RHSConv->getOperand(0), "addconv");
Chris Lattner53a19b72010-01-05 07:18:46 +0000329 return new SExtInst(NewAdd, I.getType());
330 }
331 }
332 }
333
334 return Changed ? &I : 0;
335}
336
337Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000338 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner53a19b72010-01-05 07:18:46 +0000339 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
340
341 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
342 // X + 0 --> X
343 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
344 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
345 (I.getType())->getValueAPF()))
346 return ReplaceInstUsesWith(I, LHS);
347 }
348
349 if (isa<PHINode>(LHS))
350 if (Instruction *NV = FoldOpIntoPhi(I))
351 return NV;
352 }
353
354 // -A + B --> B - A
355 // -A + -B --> -(A + B)
356 if (Value *LHSV = dyn_castFNegVal(LHS))
357 return BinaryOperator::CreateFSub(RHS, LHSV);
358
359 // A + -B --> A - B
360 if (!isa<Constant>(RHS))
361 if (Value *V = dyn_castFNegVal(RHS))
362 return BinaryOperator::CreateFSub(LHS, V);
363
364 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
365 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
366 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
367 return ReplaceInstUsesWith(I, LHS);
368
Dan Gohmana9445e12010-03-02 01:11:08 +0000369 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner53a19b72010-01-05 07:18:46 +0000370 // integer add followed by a promotion.
371 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Dan Gohmana9445e12010-03-02 01:11:08 +0000372 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner53a19b72010-01-05 07:18:46 +0000373 // ... if the constant fits in the integer value. This is useful for things
374 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
375 // requires a constant pool load, and generally allows the add to be better
376 // instcombined.
377 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
378 Constant *CI =
379 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
380 if (LHSConv->hasOneUse() &&
381 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
382 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
383 // Insert the new integer add.
384 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
385 CI, "addconv");
386 return new SIToFPInst(NewAdd, I.getType());
387 }
388 }
389
Dan Gohmana9445e12010-03-02 01:11:08 +0000390 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner53a19b72010-01-05 07:18:46 +0000391 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
392 // Only do this if x/y have the same type, if at last one of them has a
393 // single use (so we don't increase the number of int->fp conversions),
394 // and if the integer add will not overflow.
395 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
396 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
397 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
398 RHSConv->getOperand(0))) {
399 // Insert the new integer add.
400 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
401 RHSConv->getOperand(0),"addconv");
402 return new SIToFPInst(NewAdd, I.getType());
403 }
404 }
405 }
406
407 return Changed ? &I : 0;
408}
409
410
411/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
412/// code necessary to compute the offset from the base pointer (without adding
413/// in the base pointer). Return the result as a signed integer of intptr size.
414Value *InstCombiner::EmitGEPOffset(User *GEP) {
415 TargetData &TD = *getTargetData();
416 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000417 Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
Chris Lattner53a19b72010-01-05 07:18:46 +0000418 Value *Result = Constant::getNullValue(IntPtrTy);
419
Chris Lattner6cdf2ea2011-02-10 07:11:16 +0000420 // If the GEP is inbounds, we know that none of the addressing operations will
421 // overflow in an unsigned sense.
422 bool isInBounds = cast<GEPOperator>(GEP)->isInBounds();
423
Chris Lattner53a19b72010-01-05 07:18:46 +0000424 // Build a mask for high order bits.
425 unsigned IntPtrWidth = TD.getPointerSizeInBits();
426 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
427
428 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
429 ++i, ++GTI) {
430 Value *Op = *i;
431 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
432 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
433 if (OpC->isZero()) continue;
434
435 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000436 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000437 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
438
Chris Lattner6cdf2ea2011-02-10 07:11:16 +0000439 if (Size)
440 Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
Chris Lattner6aa68a72011-02-11 21:37:43 +0000441 GEP->getName()+".offs");
Chris Lattner53a19b72010-01-05 07:18:46 +0000442 continue;
443 }
444
445 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
446 Constant *OC =
447 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner6cdf2ea2011-02-10 07:11:16 +0000448 Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
Chris Lattner53a19b72010-01-05 07:18:46 +0000449 // Emit an add instruction.
Chris Lattner6aa68a72011-02-11 21:37:43 +0000450 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattner53a19b72010-01-05 07:18:46 +0000451 continue;
452 }
453 // Convert to correct type.
454 if (Op->getType() != IntPtrTy)
455 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
456 if (Size != 1) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000457 // We'll let instcombine(mul) convert this to a shl if possible.
Chris Lattner6cdf2ea2011-02-10 07:11:16 +0000458 Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
459 GEP->getName()+".idx", isInBounds /*NUW*/);
Chris Lattner53a19b72010-01-05 07:18:46 +0000460 }
461
462 // Emit an add instruction.
Chris Lattner6aa68a72011-02-11 21:37:43 +0000463 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner53a19b72010-01-05 07:18:46 +0000464 }
465 return Result;
466}
467
468
469
470
471/// Optimize pointer differences into the same array into a size. Consider:
472/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
473/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
474///
475Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000476 Type *Ty) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000477 assert(TD && "Must have target data info for this");
478
479 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
480 // this.
481 bool Swapped = false;
Benjamin Kramerd2348632012-02-20 14:34:57 +0000482 GEPOperator *GEP1 = 0, *GEP2 = 0;
483
Chris Lattner53a19b72010-01-05 07:18:46 +0000484 // For now we require one side to be the base pointer "A" or a constant
Benjamin Kramerd2348632012-02-20 14:34:57 +0000485 // GEP derived from it.
486 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000487 // (gep X, ...) - X
488 if (LHSGEP->getOperand(0) == RHS) {
Benjamin Kramerd2348632012-02-20 14:34:57 +0000489 GEP1 = LHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +0000490 Swapped = false;
Benjamin Kramerd2348632012-02-20 14:34:57 +0000491 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
492 // (gep X, ...) - (gep X, ...)
493 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
494 RHSGEP->getOperand(0)->stripPointerCasts()) {
495 GEP2 = RHSGEP;
496 GEP1 = LHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +0000497 Swapped = false;
498 }
499 }
500 }
501
Benjamin Kramerd2348632012-02-20 14:34:57 +0000502 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000503 // X - (gep X, ...)
504 if (RHSGEP->getOperand(0) == LHS) {
Benjamin Kramerd2348632012-02-20 14:34:57 +0000505 GEP1 = RHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +0000506 Swapped = true;
Benjamin Kramerd2348632012-02-20 14:34:57 +0000507 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
508 // (gep X, ...) - (gep X, ...)
509 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
510 LHSGEP->getOperand(0)->stripPointerCasts()) {
511 GEP2 = LHSGEP;
512 GEP1 = RHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +0000513 Swapped = true;
514 }
515 }
516 }
517
Benjamin Kramerd2348632012-02-20 14:34:57 +0000518 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
519 // multiple users.
520 if (GEP1 == 0 ||
521 (GEP2 != 0 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
Chris Lattner53a19b72010-01-05 07:18:46 +0000522 return 0;
523
524 // Emit the offset of the GEP and an intptr_t.
Benjamin Kramerd2348632012-02-20 14:34:57 +0000525 Value *Result = EmitGEPOffset(GEP1);
Chris Lattner53a19b72010-01-05 07:18:46 +0000526
527 // If we had a constant expression GEP on the other side offsetting the
528 // pointer, subtract it from the offset we have.
Benjamin Kramerd2348632012-02-20 14:34:57 +0000529 if (GEP2) {
530 Value *Offset = EmitGEPOffset(GEP2);
531 Result = Builder->CreateSub(Result, Offset);
Chris Lattner53a19b72010-01-05 07:18:46 +0000532 }
Chris Lattner53a19b72010-01-05 07:18:46 +0000533
534 // If we have p - gep(p, ...) then we have to negate the result.
535 if (Swapped)
536 Result = Builder->CreateNeg(Result, "diff.neg");
537
538 return Builder->CreateIntCast(Result, Ty, true);
539}
540
541
542Instruction *InstCombiner::visitSub(BinaryOperator &I) {
543 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
544
Duncan Sandsfea3b212010-12-15 14:07:39 +0000545 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
546 I.hasNoUnsignedWrap(), TD))
547 return ReplaceInstUsesWith(I, V);
Chris Lattner53a19b72010-01-05 07:18:46 +0000548
Duncan Sands37bf92b2010-12-22 13:36:08 +0000549 // (A*B)-(A*C) -> A*(B-C) etc
550 if (Value *V = SimplifyUsingDistributiveLaws(I))
551 return ReplaceInstUsesWith(I, V);
552
Chris Lattner53a19b72010-01-05 07:18:46 +0000553 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
554 if (Value *V = dyn_castNegVal(Op1)) {
555 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
556 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
557 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
558 return Res;
559 }
560
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000561 if (I.getType()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +0000562 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattnerb9b90442011-02-10 05:14:58 +0000563
564 // Replace (-1 - A) with (~A).
565 if (match(Op0, m_AllOnes()))
566 return BinaryOperator::CreateNot(Op1);
Chris Lattner53a19b72010-01-05 07:18:46 +0000567
568 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000569 // C - ~X == X + (1+C)
570 Value *X = 0;
571 if (match(Op1, m_Not(m_Value(X))))
572 return BinaryOperator::CreateAdd(X, AddOne(C));
573
574 // -(X >>u 31) -> (X >>s 31)
575 // -(X >>s 31) -> (X >>u 31)
576 if (C->isZero()) {
Chris Lattnerb9b90442011-02-10 05:14:58 +0000577 Value *X; ConstantInt *CI;
578 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
579 // Verify we are shifting out everything but the sign bit.
580 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
581 return BinaryOperator::CreateAShr(X, CI);
582
583 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
584 // Verify we are shifting out everything but the sign bit.
585 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
586 return BinaryOperator::CreateLShr(X, CI);
Chris Lattner53a19b72010-01-05 07:18:46 +0000587 }
588
589 // Try to fold constant sub into select arguments.
590 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
591 if (Instruction *R = FoldOpIntoSelect(I, SI))
592 return R;
593
594 // C - zext(bool) -> bool ? C - 1 : C
595 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattnerb9b90442011-02-10 05:14:58 +0000596 if (ZI->getSrcTy()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +0000597 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerb9b90442011-02-10 05:14:58 +0000598
599 // C-(X+C2) --> (C-C2)-X
600 ConstantInt *C2;
601 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(C2))))
602 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
Benjamin Kramer1fdfae02011-12-24 17:31:38 +0000603
604 if (SimplifyDemandedInstructionBits(I))
605 return &I;
Chris Lattner53a19b72010-01-05 07:18:46 +0000606 }
607
Chris Lattnerb9b90442011-02-10 05:14:58 +0000608
609 { Value *Y;
610 // X-(X+Y) == -Y X-(Y+X) == -Y
611 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
612 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
613 return BinaryOperator::CreateNeg(Y);
614
615 // (X-Y)-X == -Y
616 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
617 return BinaryOperator::CreateNeg(Y);
618 }
619
620 if (Op1->hasOneUse()) {
621 Value *X = 0, *Y = 0, *Z = 0;
622 Constant *C = 0;
623 ConstantInt *CI = 0;
624
625 // (X - (Y - Z)) --> (X + (Z - Y)).
626 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
627 return BinaryOperator::CreateAdd(Op0,
628 Builder->CreateSub(Z, Y, Op1->getName()));
629
630 // (X - (X & Y)) --> (X & ~Y)
631 //
632 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
633 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
634 return BinaryOperator::CreateAnd(Op0,
635 Builder->CreateNot(Y, Y->getName() + ".not"));
636
637 // 0 - (X sdiv C) -> (X sdiv -C)
638 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
639 match(Op0, m_Zero()))
640 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
641
642 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
643 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
644 if (Value *XNeg = dyn_castNegVal(X))
645 return BinaryOperator::CreateShl(XNeg, Y);
646
647 // X - X*C --> X * (1-C)
648 if (match(Op1, m_Mul(m_Specific(Op0), m_ConstantInt(CI)))) {
649 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
650 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattner53a19b72010-01-05 07:18:46 +0000651 }
652
Chris Lattnerb9b90442011-02-10 05:14:58 +0000653 // X - X<<C --> X * (1-(1<<C))
654 if (match(Op1, m_Shl(m_Specific(Op0), m_ConstantInt(CI)))) {
655 Constant *One = ConstantInt::get(I.getType(), 1);
656 C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
657 return BinaryOperator::CreateMul(Op0, C);
658 }
659
660 // X - A*-B -> X + A*B
661 // X - -A*B -> X + A*B
662 Value *A, *B;
663 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
664 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
665 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
Chris Lattner67920322011-01-15 05:50:18 +0000666
Chris Lattnerb9b90442011-02-10 05:14:58 +0000667 // X - A*CI -> X + A*-CI
668 // X - CI*A -> X + A*-CI
669 if (match(Op1, m_Mul(m_Value(A), m_ConstantInt(CI))) ||
670 match(Op1, m_Mul(m_ConstantInt(CI), m_Value(A)))) {
671 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
672 return BinaryOperator::CreateAdd(Op0, NewMul);
Chris Lattner53a19b72010-01-05 07:18:46 +0000673 }
674 }
675
676 ConstantInt *C1;
677 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
678 if (X == Op1) // X*C - X --> X * (C-1)
679 return BinaryOperator::CreateMul(Op1, SubOne(C1));
680
681 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
682 if (X == dyn_castFoldableMul(Op1, C2))
683 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
684 }
685
686 // Optimize pointer differences into the same array into a size. Consider:
687 // &A[10] - &A[0]: we should compile this to "10".
688 if (TD) {
689 Value *LHSOp, *RHSOp;
690 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
691 match(Op1, m_PtrToInt(m_Value(RHSOp))))
692 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
693 return ReplaceInstUsesWith(I, Res);
694
695 // trunc(p)-trunc(q) -> trunc(p-q)
696 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
697 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
698 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
699 return ReplaceInstUsesWith(I, Res);
700 }
701
702 return 0;
703}
704
705Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
706 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
707
708 // If this is a 'B = x-(-A)', change to B = x+A...
709 if (Value *V = dyn_castFNegVal(Op1))
710 return BinaryOperator::CreateFAdd(Op0, V);
711
Chris Lattner53a19b72010-01-05 07:18:46 +0000712 return 0;
713}