blob: 98d655020178954dc333e97dabe855d9bb1c90cc [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 Sands50f26252010-11-23 20:42:39 +000094 if (Instruction *NV = SimplifyByFactorizing(I)) // (A*B)+(A*C) -> A*(B+C)
Duncan Sands5057f382010-11-23 14:23:47 +000095 return NV;
Chris Lattner53a19b72010-01-05 07:18:46 +000096
97 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
98 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
99 // X + (signbit) --> X ^ signbit
100 const APInt& Val = CI->getValue();
101 uint32_t BitWidth = Val.getBitWidth();
102 if (Val == APInt::getSignBit(BitWidth))
103 return BinaryOperator::CreateXor(LHS, RHS);
104
105 // See if SimplifyDemandedBits can simplify this. This handles stuff like
106 // (X & 254)+1 -> (X&254)|1
107 if (SimplifyDemandedInstructionBits(I))
108 return &I;
109
110 // zext(bool) + C -> bool ? C + 1 : C
111 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
112 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
113 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
114 }
115
116 if (isa<PHINode>(LHS))
117 if (Instruction *NV = FoldOpIntoPhi(I))
118 return NV;
119
120 ConstantInt *XorRHS = 0;
121 Value *XorLHS = 0;
122 if (isa<ConstantInt>(RHSC) &&
123 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
124 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
125 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000126 unsigned ExtendAmt = 0;
127 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
128 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
129 if (XorRHS->getValue() == -RHSVal) {
130 if (RHSVal.isPowerOf2())
131 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
132 else if (XorRHS->getValue().isPowerOf2())
133 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner53a19b72010-01-05 07:18:46 +0000134 }
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000135
136 if (ExtendAmt) {
137 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
138 if (!MaskedValueIsZero(XorLHS, Mask))
139 ExtendAmt = 0;
140 }
141
142 if (ExtendAmt) {
143 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
144 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
145 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner53a19b72010-01-05 07:18:46 +0000146 }
147 }
148 }
149
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000150 if (I.getType()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +0000151 return BinaryOperator::CreateXor(LHS, RHS);
152
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000153 if (I.getType()->isIntegerTy()) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000154 // X + X --> X << 1
155 if (LHS == RHS)
156 return BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
Chris Lattner53a19b72010-01-05 07:18:46 +0000157 }
158
159 // -A + B --> B - A
160 // -A + -B --> -(A + B)
161 if (Value *LHSV = dyn_castNegVal(LHS)) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000162 if (LHS->getType()->isIntOrIntVectorTy()) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000163 if (Value *RHSV = dyn_castNegVal(RHS)) {
164 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
165 return BinaryOperator::CreateNeg(NewAdd);
166 }
167 }
168
169 return BinaryOperator::CreateSub(RHS, LHSV);
170 }
171
172 // A + -B --> A - B
173 if (!isa<Constant>(RHS))
174 if (Value *V = dyn_castNegVal(RHS))
175 return BinaryOperator::CreateSub(LHS, V);
176
177
178 ConstantInt *C2;
179 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
180 if (X == RHS) // X*C + X --> X * (C+1)
181 return BinaryOperator::CreateMul(RHS, AddOne(C2));
182
183 // X*C1 + X*C2 --> X * (C1+C2)
184 ConstantInt *C1;
185 if (X == dyn_castFoldableMul(RHS, C1))
186 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
187 }
188
189 // X + X*C --> X * (C+1)
190 if (dyn_castFoldableMul(RHS, C2) == LHS)
191 return BinaryOperator::CreateMul(LHS, AddOne(C2));
192
Chris Lattner53a19b72010-01-05 07:18:46 +0000193 // A+B --> A|B iff A and B have no bits set in common.
194 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
195 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
196 APInt LHSKnownOne(IT->getBitWidth(), 0);
197 APInt LHSKnownZero(IT->getBitWidth(), 0);
198 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
199 if (LHSKnownZero != 0) {
200 APInt RHSKnownOne(IT->getBitWidth(), 0);
201 APInt RHSKnownZero(IT->getBitWidth(), 0);
202 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
203
204 // No bits in common -> bitwise or.
205 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
206 return BinaryOperator::CreateOr(LHS, RHS);
207 }
208 }
209
210 // W*X + Y*Z --> W * (X+Z) iff W == Y
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000211 if (I.getType()->isIntOrIntVectorTy()) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000212 Value *W, *X, *Y, *Z;
213 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
214 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
215 if (W != Y) {
216 if (W == Z) {
217 std::swap(Y, Z);
218 } else if (Y == X) {
219 std::swap(W, X);
220 } else if (X == Z) {
221 std::swap(Y, Z);
222 std::swap(W, X);
223 }
224 }
225
226 if (W == Y) {
227 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
228 return BinaryOperator::CreateMul(W, NewAdd);
229 }
230 }
231 }
232
233 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
234 Value *X = 0;
235 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
236 return BinaryOperator::CreateSub(SubOne(CRHS), X);
237
238 // (X & FF00) + xx00 -> (X+xx00) & FF00
239 if (LHS->hasOneUse() &&
240 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
241 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
242 if (Anded == CRHS) {
243 // See if all bits from the first bit set in the Add RHS up are included
244 // in the mask. First, get the rightmost bit.
245 const APInt &AddRHSV = CRHS->getValue();
246
247 // Form a mask of all bits from the lowest bit added through the top.
248 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
249
250 // See if the and mask includes all of these bits.
251 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
252
253 if (AddRHSHighBits == AddRHSHighBitsAnd) {
254 // Okay, the xform is safe. Insert the new add pronto.
255 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
256 return BinaryOperator::CreateAnd(NewAdd, C2);
257 }
258 }
259 }
260
261 // Try to fold constant add into select arguments.
262 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
263 if (Instruction *R = FoldOpIntoSelect(I, SI))
264 return R;
265 }
266
267 // add (select X 0 (sub n A)) A --> select X A n
268 {
269 SelectInst *SI = dyn_cast<SelectInst>(LHS);
270 Value *A = RHS;
271 if (!SI) {
272 SI = dyn_cast<SelectInst>(RHS);
273 A = LHS;
274 }
275 if (SI && SI->hasOneUse()) {
276 Value *TV = SI->getTrueValue();
277 Value *FV = SI->getFalseValue();
278 Value *N;
279
280 // Can we fold the add into the argument of the select?
281 // We check both true and false select arguments for a matching subtract.
282 if (match(FV, m_Zero()) &&
283 match(TV, m_Sub(m_Value(N), m_Specific(A))))
284 // Fold the add into the true select value.
285 return SelectInst::Create(SI->getCondition(), N, A);
286 if (match(TV, m_Zero()) &&
287 match(FV, m_Sub(m_Value(N), m_Specific(A))))
288 // Fold the add into the false select value.
289 return SelectInst::Create(SI->getCondition(), A, N);
290 }
291 }
292
293 // Check for (add (sext x), y), see if we can merge this into an
294 // integer add followed by a sext.
295 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
296 // (add (sext x), cst) --> (sext (add x, cst'))
297 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
298 Constant *CI =
299 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
300 if (LHSConv->hasOneUse() &&
301 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
302 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
303 // Insert the new, smaller add.
304 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
305 CI, "addconv");
306 return new SExtInst(NewAdd, I.getType());
307 }
308 }
309
310 // (add (sext x), (sext y)) --> (sext (add int x, y))
311 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
312 // Only do this if x/y have the same type, if at last one of them has a
313 // single use (so we don't increase the number of sexts), and if the
314 // integer add will not overflow.
315 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
316 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
317 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
318 RHSConv->getOperand(0))) {
319 // Insert the new integer add.
320 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner3168c7d2010-01-05 20:56:24 +0000321 RHSConv->getOperand(0), "addconv");
Chris Lattner53a19b72010-01-05 07:18:46 +0000322 return new SExtInst(NewAdd, I.getType());
323 }
324 }
325 }
326
327 return Changed ? &I : 0;
328}
329
330Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000331 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner53a19b72010-01-05 07:18:46 +0000332 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
333
334 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
335 // X + 0 --> X
336 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
337 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
338 (I.getType())->getValueAPF()))
339 return ReplaceInstUsesWith(I, LHS);
340 }
341
342 if (isa<PHINode>(LHS))
343 if (Instruction *NV = FoldOpIntoPhi(I))
344 return NV;
345 }
346
347 // -A + B --> B - A
348 // -A + -B --> -(A + B)
349 if (Value *LHSV = dyn_castFNegVal(LHS))
350 return BinaryOperator::CreateFSub(RHS, LHSV);
351
352 // A + -B --> A - B
353 if (!isa<Constant>(RHS))
354 if (Value *V = dyn_castFNegVal(RHS))
355 return BinaryOperator::CreateFSub(LHS, V);
356
357 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
358 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
359 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
360 return ReplaceInstUsesWith(I, LHS);
361
Dan Gohmana9445e12010-03-02 01:11:08 +0000362 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner53a19b72010-01-05 07:18:46 +0000363 // integer add followed by a promotion.
364 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Dan Gohmana9445e12010-03-02 01:11:08 +0000365 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner53a19b72010-01-05 07:18:46 +0000366 // ... if the constant fits in the integer value. This is useful for things
367 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
368 // requires a constant pool load, and generally allows the add to be better
369 // instcombined.
370 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
371 Constant *CI =
372 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
373 if (LHSConv->hasOneUse() &&
374 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
375 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
376 // Insert the new integer add.
377 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
378 CI, "addconv");
379 return new SIToFPInst(NewAdd, I.getType());
380 }
381 }
382
Dan Gohmana9445e12010-03-02 01:11:08 +0000383 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner53a19b72010-01-05 07:18:46 +0000384 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
385 // Only do this if x/y have the same type, if at last one of them has a
386 // single use (so we don't increase the number of int->fp conversions),
387 // and if the integer add will not overflow.
388 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
389 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
390 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
391 RHSConv->getOperand(0))) {
392 // Insert the new integer add.
393 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
394 RHSConv->getOperand(0),"addconv");
395 return new SIToFPInst(NewAdd, I.getType());
396 }
397 }
398 }
399
400 return Changed ? &I : 0;
401}
402
403
404/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
405/// code necessary to compute the offset from the base pointer (without adding
406/// in the base pointer). Return the result as a signed integer of intptr size.
407Value *InstCombiner::EmitGEPOffset(User *GEP) {
408 TargetData &TD = *getTargetData();
409 gep_type_iterator GTI = gep_type_begin(GEP);
410 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
411 Value *Result = Constant::getNullValue(IntPtrTy);
412
413 // Build a mask for high order bits.
414 unsigned IntPtrWidth = TD.getPointerSizeInBits();
415 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
416
417 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
418 ++i, ++GTI) {
419 Value *Op = *i;
420 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
421 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
422 if (OpC->isZero()) continue;
423
424 // Handle a struct index, which adds its field offset to the pointer.
425 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
426 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
427
428 Result = Builder->CreateAdd(Result,
429 ConstantInt::get(IntPtrTy, Size),
430 GEP->getName()+".offs");
431 continue;
432 }
433
434 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
435 Constant *OC =
436 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
437 Scale = ConstantExpr::getMul(OC, Scale);
438 // Emit an add instruction.
439 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
440 continue;
441 }
442 // Convert to correct type.
443 if (Op->getType() != IntPtrTy)
444 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
445 if (Size != 1) {
446 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
447 // We'll let instcombine(mul) convert this to a shl if possible.
448 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
449 }
450
451 // Emit an add instruction.
452 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
453 }
454 return Result;
455}
456
457
458
459
460/// Optimize pointer differences into the same array into a size. Consider:
461/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
462/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
463///
464Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
465 const Type *Ty) {
466 assert(TD && "Must have target data info for this");
467
468 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
469 // this.
470 bool Swapped = false;
471 GetElementPtrInst *GEP = 0;
472 ConstantExpr *CstGEP = 0;
473
474 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
475 // For now we require one side to be the base pointer "A" or a constant
476 // expression derived from it.
477 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
478 // (gep X, ...) - X
479 if (LHSGEP->getOperand(0) == RHS) {
480 GEP = LHSGEP;
481 Swapped = false;
482 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
483 // (gep X, ...) - (ce_gep X, ...)
484 if (CE->getOpcode() == Instruction::GetElementPtr &&
485 LHSGEP->getOperand(0) == CE->getOperand(0)) {
486 CstGEP = CE;
487 GEP = LHSGEP;
488 Swapped = false;
489 }
490 }
491 }
492
493 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
494 // X - (gep X, ...)
495 if (RHSGEP->getOperand(0) == LHS) {
496 GEP = RHSGEP;
497 Swapped = true;
498 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
499 // (ce_gep X, ...) - (gep X, ...)
500 if (CE->getOpcode() == Instruction::GetElementPtr &&
501 RHSGEP->getOperand(0) == CE->getOperand(0)) {
502 CstGEP = CE;
503 GEP = RHSGEP;
504 Swapped = true;
505 }
506 }
507 }
508
509 if (GEP == 0)
510 return 0;
511
512 // Emit the offset of the GEP and an intptr_t.
513 Value *Result = EmitGEPOffset(GEP);
514
515 // If we had a constant expression GEP on the other side offsetting the
516 // pointer, subtract it from the offset we have.
517 if (CstGEP) {
518 Value *CstOffset = EmitGEPOffset(CstGEP);
519 Result = Builder->CreateSub(Result, CstOffset);
520 }
521
522
523 // If we have p - gep(p, ...) then we have to negate the result.
524 if (Swapped)
525 Result = Builder->CreateNeg(Result, "diff.neg");
526
527 return Builder->CreateIntCast(Result, Ty, true);
528}
529
530
531Instruction *InstCombiner::visitSub(BinaryOperator &I) {
532 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
533
Duncan Sandsfea3b212010-12-15 14:07:39 +0000534 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
535 I.hasNoUnsignedWrap(), TD))
536 return ReplaceInstUsesWith(I, V);
Chris Lattner53a19b72010-01-05 07:18:46 +0000537
Duncan Sands50f26252010-11-23 20:42:39 +0000538 if (Instruction *NV = SimplifyByFactorizing(I)) // (A*B)-(A*C) -> A*(B-C)
Duncan Sands5057f382010-11-23 14:23:47 +0000539 return NV;
540
Chris Lattner53a19b72010-01-05 07:18:46 +0000541 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
542 if (Value *V = dyn_castNegVal(Op1)) {
543 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
544 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
545 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
546 return Res;
547 }
548
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000549 if (I.getType()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +0000550 return BinaryOperator::CreateXor(Op0, Op1);
551
552 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
553 // Replace (-1 - A) with (~A).
554 if (C->isAllOnesValue())
555 return BinaryOperator::CreateNot(Op1);
556
557 // C - ~X == X + (1+C)
558 Value *X = 0;
559 if (match(Op1, m_Not(m_Value(X))))
560 return BinaryOperator::CreateAdd(X, AddOne(C));
561
562 // -(X >>u 31) -> (X >>s 31)
563 // -(X >>s 31) -> (X >>u 31)
564 if (C->isZero()) {
565 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
566 if (SI->getOpcode() == Instruction::LShr) {
567 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
568 // Check to see if we are shifting out everything but the sign bit.
569 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
570 SI->getType()->getPrimitiveSizeInBits()-1) {
571 // Ok, the transformation is safe. Insert AShr.
572 return BinaryOperator::Create(Instruction::AShr,
573 SI->getOperand(0), CU, SI->getName());
574 }
575 }
576 } else if (SI->getOpcode() == Instruction::AShr) {
577 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
578 // Check to see if we are shifting out everything but the sign bit.
579 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
580 SI->getType()->getPrimitiveSizeInBits()-1) {
581 // Ok, the transformation is safe. Insert LShr.
582 return BinaryOperator::CreateLShr(
583 SI->getOperand(0), CU, SI->getName());
584 }
585 }
586 }
587 }
588 }
589
590 // Try to fold constant sub into select arguments.
591 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
592 if (Instruction *R = FoldOpIntoSelect(I, SI))
593 return R;
594
595 // C - zext(bool) -> bool ? C - 1 : C
596 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
597 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
598 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
599 }
600
601 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
602 if (Op1I->getOpcode() == Instruction::Add) {
603 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
604 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
605 I.getName());
606 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
607 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
608 I.getName());
609 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
610 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
611 // C1-(X+C2) --> (C1-C2)-X
612 return BinaryOperator::CreateSub(
613 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
614 }
615 }
616
617 if (Op1I->hasOneUse()) {
618 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
619 // is not used by anyone else...
620 //
621 if (Op1I->getOpcode() == Instruction::Sub) {
622 // Swap the two operands of the subexpr...
623 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
624 Op1I->setOperand(0, IIOp1);
625 Op1I->setOperand(1, IIOp0);
626
627 // Create the new top level add instruction...
628 return BinaryOperator::CreateAdd(Op0, Op1);
629 }
630
631 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
632 //
633 if (Op1I->getOpcode() == Instruction::And &&
634 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
635 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
636
637 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
638 return BinaryOperator::CreateAnd(Op0, NewNot);
639 }
640
641 // 0 - (X sdiv C) -> (X sdiv -C)
642 if (Op1I->getOpcode() == Instruction::SDiv)
643 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
644 if (CSI->isZero())
645 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
646 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
647 ConstantExpr::getNeg(DivRHS));
648
Eli Friedman694488f2010-01-31 02:30:23 +0000649 // 0 - (C << X) -> (-C << X)
650 if (Op1I->getOpcode() == Instruction::Shl)
651 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
652 if (CSI->isZero())
653 if (Value *ShlLHSNeg = dyn_castNegVal(Op1I->getOperand(0)))
654 return BinaryOperator::CreateShl(ShlLHSNeg, Op1I->getOperand(1));
655
Chris Lattner53a19b72010-01-05 07:18:46 +0000656 // X - X*C --> X * (1-C)
657 ConstantInt *C2 = 0;
658 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
659 Constant *CP1 =
660 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
661 C2);
662 return BinaryOperator::CreateMul(Op0, CP1);
663 }
Benjamin Kramer93f84552010-11-22 20:31:27 +0000664
665 // X - A*-B -> X + A*B
666 // X - -A*B -> X + A*B
667 Value *A, *B;
668 if (match(Op1I, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
669 match(Op1I, m_Mul(m_Neg(m_Value(A)), m_Value(B)))) {
670 Value *NewMul = Builder->CreateMul(A, B);
671 return BinaryOperator::CreateAdd(Op0, NewMul);
672 }
Chris Lattner53a19b72010-01-05 07:18:46 +0000673 }
674 }
675
676 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000677 if (Op0I->getOpcode() == Instruction::Sub) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000678 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
679 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
680 I.getName());
681 }
682 }
683
684 ConstantInt *C1;
685 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
686 if (X == Op1) // X*C - X --> X * (C-1)
687 return BinaryOperator::CreateMul(Op1, SubOne(C1));
688
689 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
690 if (X == dyn_castFoldableMul(Op1, C2))
691 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
692 }
693
694 // Optimize pointer differences into the same array into a size. Consider:
695 // &A[10] - &A[0]: we should compile this to "10".
696 if (TD) {
697 Value *LHSOp, *RHSOp;
698 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
699 match(Op1, m_PtrToInt(m_Value(RHSOp))))
700 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
701 return ReplaceInstUsesWith(I, Res);
702
703 // trunc(p)-trunc(q) -> trunc(p-q)
704 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
705 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
706 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
707 return ReplaceInstUsesWith(I, Res);
708 }
709
710 return 0;
711}
712
713Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
715
716 // If this is a 'B = x-(-A)', change to B = x+A...
717 if (Value *V = dyn_castFNegVal(Op1))
718 return BinaryOperator::CreateFAdd(Op0, V);
719
Chris Lattner53a19b72010-01-05 07:18:46 +0000720 return 0;
721}