1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All SetCC instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/ADT/DepthFirstIterator.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
57 using namespace llvm::PatternMatch;
60 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
64 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
66 class InstCombiner : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(Value &I) {
77 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
79 WorkList.push_back(cast<Instruction>(*UI));
82 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
91 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
94 virtual bool runOnFunction(Function &F);
96 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97 AU.addRequired<TargetData>();
101 TargetData &getTargetData() const { return *TD; }
103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
106 // null - No change was made
107 // I - Change was made, I is still valid, I may be dead though
108 // otherwise - Change was made, replace I with returned instruction
110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
123 Instruction *visitShiftInst(ShiftInst &I);
124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
126 Instruction *visitCastInst(CastInst &CI);
127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
129 Instruction *visitSelectInst(SelectInst &CI);
130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
134 Instruction *visitAllocationInst(AllocationInst &AI);
135 Instruction *visitFreeInst(FreeInst &FI);
136 Instruction *visitLoadInst(LoadInst &LI);
137 Instruction *visitStoreInst(StoreInst &SI);
138 Instruction *visitBranchInst(BranchInst &BI);
139 Instruction *visitSwitchInst(SwitchInst &SI);
140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
142 // visitInstruction - Specify what to return for unhandled instructions...
143 Instruction *visitInstruction(Instruction &I) { return 0; }
146 Instruction *visitCallSite(CallSite CS);
147 bool transformConstExprCastCall(CallSite CS);
150 // InsertNewInstBefore - insert an instruction New before instruction Old
151 // in the program. Add the new instruction to the worklist.
153 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
154 assert(New && New->getParent() == 0 &&
155 "New instruction already inserted into a basic block!");
156 BasicBlock *BB = Old.getParent();
157 BB->getInstList().insert(&Old, New); // Insert inst
158 WorkList.push_back(New); // Add to worklist
162 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
163 /// This also adds the cast to the worklist. Finally, this returns the
165 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
166 if (V->getType() == Ty) return V;
168 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
169 WorkList.push_back(C);
173 // ReplaceInstUsesWith - This method is to be used when an instruction is
174 // found to be dead, replacable with another preexisting expression. Here
175 // we add all uses of I to the worklist, replace all uses of I with the new
176 // value, then return I, so that the inst combiner will know that I was
179 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
180 AddUsersToWorkList(I); // Add all modified instrs to worklist
182 I.replaceAllUsesWith(V);
185 // If we are replacing the instruction with itself, this must be in a
186 // segment of unreachable code, so just clobber the instruction.
187 I.replaceAllUsesWith(UndefValue::get(I.getType()));
192 // UpdateValueUsesWith - This method is to be used when an value is
193 // found to be replacable with another preexisting expression or was
194 // updated. Here we add all uses of I to the worklist, replace all uses of
195 // I with the new value (unless the instruction was just updated), then
196 // return true, so that the inst combiner will know that I was modified.
198 bool UpdateValueUsesWith(Value *Old, Value *New) {
199 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
201 Old->replaceAllUsesWith(New);
202 if (Instruction *I = dyn_cast<Instruction>(Old))
203 WorkList.push_back(I);
204 if (Instruction *I = dyn_cast<Instruction>(New))
205 WorkList.push_back(I);
209 // EraseInstFromFunction - When dealing with an instruction that has side
210 // effects or produces a void value, we can't rely on DCE to delete the
211 // instruction. Instead, visit methods should return the value returned by
213 Instruction *EraseInstFromFunction(Instruction &I) {
214 assert(I.use_empty() && "Cannot erase instruction that is used!");
215 AddUsesToWorkList(I);
216 removeFromWorkList(&I);
218 return 0; // Don't do anything with FI
222 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
223 /// InsertBefore instruction. This is specialized a bit to avoid inserting
224 /// casts that are known to not do anything...
226 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
227 Instruction *InsertBefore);
229 // SimplifyCommutative - This performs a few simplifications for commutative
231 bool SimplifyCommutative(BinaryOperator &I);
233 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
234 uint64_t &KnownZero, uint64_t &KnownOne,
237 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
238 // PHI node as operand #0, see if we can fold the instruction into the PHI
239 // (which is only possible if all operands to the PHI are constants).
240 Instruction *FoldOpIntoPhi(Instruction &I);
242 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
243 // operator and they all are only used by the PHI, PHI together their
244 // inputs, and do the operation once, to the result of the PHI.
245 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
247 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
248 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
250 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
251 bool isSub, Instruction &I);
252 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
253 bool Inside, Instruction &IB);
254 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
257 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
260 // getComplexity: Assign a complexity or rank value to LLVM Values...
261 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
262 static unsigned getComplexity(Value *V) {
263 if (isa<Instruction>(V)) {
264 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
268 if (isa<Argument>(V)) return 3;
269 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
272 // isOnlyUse - Return true if this instruction will be deleted if we stop using
274 static bool isOnlyUse(Value *V) {
275 return V->hasOneUse() || isa<Constant>(V);
278 // getPromotedType - Return the specified type promoted as it would be to pass
279 // though a va_arg area...
280 static const Type *getPromotedType(const Type *Ty) {
281 switch (Ty->getTypeID()) {
282 case Type::SByteTyID:
283 case Type::ShortTyID: return Type::IntTy;
284 case Type::UByteTyID:
285 case Type::UShortTyID: return Type::UIntTy;
286 case Type::FloatTyID: return Type::DoubleTy;
291 /// isCast - If the specified operand is a CastInst or a constant expr cast,
292 /// return the operand value, otherwise return null.
293 static Value *isCast(Value *V) {
294 if (CastInst *I = dyn_cast<CastInst>(V))
295 return I->getOperand(0);
296 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
297 if (CE->getOpcode() == Instruction::Cast)
298 return CE->getOperand(0);
302 // SimplifyCommutative - This performs a few simplifications for commutative
305 // 1. Order operands such that they are listed from right (least complex) to
306 // left (most complex). This puts constants before unary operators before
309 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
310 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
312 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
313 bool Changed = false;
314 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
315 Changed = !I.swapOperands();
317 if (!I.isAssociative()) return Changed;
318 Instruction::BinaryOps Opcode = I.getOpcode();
319 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
320 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
321 if (isa<Constant>(I.getOperand(1))) {
322 Constant *Folded = ConstantExpr::get(I.getOpcode(),
323 cast<Constant>(I.getOperand(1)),
324 cast<Constant>(Op->getOperand(1)));
325 I.setOperand(0, Op->getOperand(0));
326 I.setOperand(1, Folded);
328 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
329 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
330 isOnlyUse(Op) && isOnlyUse(Op1)) {
331 Constant *C1 = cast<Constant>(Op->getOperand(1));
332 Constant *C2 = cast<Constant>(Op1->getOperand(1));
334 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
335 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
336 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
339 WorkList.push_back(New);
340 I.setOperand(0, New);
341 I.setOperand(1, Folded);
348 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
349 // if the LHS is a constant zero (which is the 'negate' form).
351 static inline Value *dyn_castNegVal(Value *V) {
352 if (BinaryOperator::isNeg(V))
353 return BinaryOperator::getNegArgument(V);
355 // Constants can be considered to be negated values if they can be folded.
356 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
357 return ConstantExpr::getNeg(C);
361 static inline Value *dyn_castNotVal(Value *V) {
362 if (BinaryOperator::isNot(V))
363 return BinaryOperator::getNotArgument(V);
365 // Constants can be considered to be not'ed values...
366 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
367 return ConstantExpr::getNot(C);
371 // dyn_castFoldableMul - If this value is a multiply that can be folded into
372 // other computations (because it has a constant operand), return the
373 // non-constant operand of the multiply, and set CST to point to the multiplier.
374 // Otherwise, return null.
376 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
377 if (V->hasOneUse() && V->getType()->isInteger())
378 if (Instruction *I = dyn_cast<Instruction>(V)) {
379 if (I->getOpcode() == Instruction::Mul)
380 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
381 return I->getOperand(0);
382 if (I->getOpcode() == Instruction::Shl)
383 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
384 // The multiplier is really 1 << CST.
385 Constant *One = ConstantInt::get(V->getType(), 1);
386 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
387 return I->getOperand(0);
393 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
394 /// expression, return it.
395 static User *dyn_castGetElementPtr(Value *V) {
396 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
398 if (CE->getOpcode() == Instruction::GetElementPtr)
399 return cast<User>(V);
403 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
404 static ConstantInt *AddOne(ConstantInt *C) {
405 return cast<ConstantInt>(ConstantExpr::getAdd(C,
406 ConstantInt::get(C->getType(), 1)));
408 static ConstantInt *SubOne(ConstantInt *C) {
409 return cast<ConstantInt>(ConstantExpr::getSub(C,
410 ConstantInt::get(C->getType(), 1)));
413 /// GetConstantInType - Return a ConstantInt with the specified type and value.
415 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
416 if (Ty->isUnsigned())
417 return ConstantUInt::get(Ty, Val);
418 else if (Ty->getTypeID() == Type::BoolTyID)
419 return ConstantBool::get(Val);
421 SVal <<= 64-Ty->getPrimitiveSizeInBits();
422 SVal >>= 64-Ty->getPrimitiveSizeInBits();
423 return ConstantSInt::get(Ty, SVal);
427 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
428 /// known to be either zero or one and return them in the KnownZero/KnownOne
429 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
431 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
432 uint64_t &KnownOne, unsigned Depth = 0) {
433 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
434 // we cannot optimize based on the assumption that it is zero without changing
435 // it to be an explicit zero. If we don't change it to zero, other code could
436 // optimized based on the contradictory assumption that it is non-zero.
437 // Because instcombine aggressively folds operations with undef args anyway,
438 // this won't lose us code quality.
439 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
440 // We know all of the bits for a constant!
441 KnownOne = CI->getZExtValue() & Mask;
442 KnownZero = ~KnownOne & Mask;
446 KnownZero = KnownOne = 0; // Don't know anything.
447 if (Depth == 6 || Mask == 0)
448 return; // Limit search depth.
450 uint64_t KnownZero2, KnownOne2;
451 Instruction *I = dyn_cast<Instruction>(V);
454 switch (I->getOpcode()) {
455 case Instruction::And:
456 // If either the LHS or the RHS are Zero, the result is zero.
457 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
459 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
460 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
461 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
463 // Output known-1 bits are only known if set in both the LHS & RHS.
464 KnownOne &= KnownOne2;
465 // Output known-0 are known to be clear if zero in either the LHS | RHS.
466 KnownZero |= KnownZero2;
468 case Instruction::Or:
469 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
471 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
472 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
473 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
475 // Output known-0 bits are only known if clear in both the LHS & RHS.
476 KnownZero &= KnownZero2;
477 // Output known-1 are known to be set if set in either the LHS | RHS.
478 KnownOne |= KnownOne2;
480 case Instruction::Xor: {
481 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
482 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
483 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
484 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
486 // Output known-0 bits are known if clear or set in both the LHS & RHS.
487 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
488 // Output known-1 are known to be set if set in only one of the LHS, RHS.
489 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
490 KnownZero = KnownZeroOut;
493 case Instruction::Select:
494 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
495 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
496 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
497 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
499 // Only known if known in both the LHS and RHS.
500 KnownOne &= KnownOne2;
501 KnownZero &= KnownZero2;
503 case Instruction::Cast: {
504 const Type *SrcTy = I->getOperand(0)->getType();
505 if (!SrcTy->isIntegral()) return;
507 // If this is an integer truncate or noop, just look in the input.
508 if (SrcTy->getPrimitiveSizeInBits() >=
509 I->getType()->getPrimitiveSizeInBits()) {
510 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
514 // Sign or Zero extension. Compute the bits in the result that are not
515 // present in the input.
516 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
517 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
519 // Handle zero extension.
520 if (!SrcTy->isSigned()) {
521 Mask &= SrcTy->getIntegralTypeMask();
522 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
523 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
524 // The top bits are known to be zero.
525 KnownZero |= NewBits;
528 Mask &= SrcTy->getIntegralTypeMask();
529 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
530 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
532 // If the sign bit of the input is known set or clear, then we know the
533 // top bits of the result.
534 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
535 if (KnownZero & InSignBit) { // Input sign bit known zero
536 KnownZero |= NewBits;
537 KnownOne &= ~NewBits;
538 } else if (KnownOne & InSignBit) { // Input sign bit known set
540 KnownZero &= ~NewBits;
541 } else { // Input sign bit unknown
542 KnownZero &= ~NewBits;
543 KnownOne &= ~NewBits;
548 case Instruction::Shl:
549 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
550 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
551 Mask >>= SA->getValue();
552 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
553 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
554 KnownZero <<= SA->getValue();
555 KnownOne <<= SA->getValue();
556 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
560 case Instruction::Shr:
561 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
562 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
563 // Compute the new bits that are at the top now.
564 uint64_t HighBits = (1ULL << SA->getValue())-1;
565 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
567 if (I->getType()->isUnsigned()) { // Unsigned shift right.
568 Mask <<= SA->getValue();
569 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
570 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
571 KnownZero >>= SA->getValue();
572 KnownOne >>= SA->getValue();
573 KnownZero |= HighBits; // high bits known zero.
575 Mask <<= SA->getValue();
576 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
577 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
578 KnownZero >>= SA->getValue();
579 KnownOne >>= SA->getValue();
581 // Handle the sign bits.
582 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
583 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
585 if (KnownZero & SignBit) { // New bits are known zero.
586 KnownZero |= HighBits;
587 } else if (KnownOne & SignBit) { // New bits are known one.
588 KnownOne |= HighBits;
597 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
598 /// this predicate to simplify operations downstream. Mask is known to be zero
599 /// for bits that V cannot have.
600 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
601 uint64_t KnownZero, KnownOne;
602 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
603 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
604 return (KnownZero & Mask) == Mask;
607 /// ShrinkDemandedConstant - Check to see if the specified operand of the
608 /// specified instruction is a constant integer. If so, check to see if there
609 /// are any bits set in the constant that are not demanded. If so, shrink the
610 /// constant and return true.
611 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
613 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
614 if (!OpC) return false;
616 // If there are no bits set that aren't demanded, nothing to do.
617 if ((~Demanded & OpC->getZExtValue()) == 0)
620 // This is producing any bits that are not needed, shrink the RHS.
621 uint64_t Val = Demanded & OpC->getZExtValue();
622 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
626 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
627 // set of known zero and one bits, compute the maximum and minimum values that
628 // could have the specified known zero and known one bits, returning them in
630 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
633 int64_t &Min, int64_t &Max) {
634 uint64_t TypeBits = Ty->getIntegralTypeMask();
635 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
637 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
639 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
640 // bit if it is unknown.
642 Max = KnownOne|UnknownBits;
644 if (SignBit & UnknownBits) { // Sign bit is unknown
649 // Sign extend the min/max values.
650 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
651 Min = (Min << ShAmt) >> ShAmt;
652 Max = (Max << ShAmt) >> ShAmt;
655 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
656 // a set of known zero and one bits, compute the maximum and minimum values that
657 // could have the specified known zero and known one bits, returning them in
659 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
664 uint64_t TypeBits = Ty->getIntegralTypeMask();
665 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
667 // The minimum value is when the unknown bits are all zeros.
669 // The maximum value is when the unknown bits are all ones.
670 Max = KnownOne|UnknownBits;
674 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
675 /// DemandedMask bits of the result of V are ever used downstream. If we can
676 /// use this information to simplify V, do so and return true. Otherwise,
677 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
678 /// the expression (used to simplify the caller). The KnownZero/One bits may
679 /// only be accurate for those bits in the DemandedMask.
680 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
681 uint64_t &KnownZero, uint64_t &KnownOne,
683 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
684 // We know all of the bits for a constant!
685 KnownOne = CI->getZExtValue() & DemandedMask;
686 KnownZero = ~KnownOne & DemandedMask;
690 KnownZero = KnownOne = 0;
691 if (!V->hasOneUse()) { // Other users may use these bits.
692 if (Depth != 0) { // Not at the root.
693 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
694 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
697 // If this is the root being simplified, allow it to have multiple uses,
698 // just set the DemandedMask to all bits.
699 DemandedMask = V->getType()->getIntegralTypeMask();
700 } else if (DemandedMask == 0) { // Not demanding any bits from V.
701 if (V != UndefValue::get(V->getType()))
702 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
704 } else if (Depth == 6) { // Limit search depth.
708 Instruction *I = dyn_cast<Instruction>(V);
709 if (!I) return false; // Only analyze instructions.
711 uint64_t KnownZero2, KnownOne2;
712 switch (I->getOpcode()) {
714 case Instruction::And:
715 // If either the LHS or the RHS are Zero, the result is zero.
716 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
717 KnownZero, KnownOne, Depth+1))
719 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
721 // If something is known zero on the RHS, the bits aren't demanded on the
723 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
724 KnownZero2, KnownOne2, Depth+1))
726 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
728 // If all of the demanded bits are known one on one side, return the other.
729 // These bits cannot contribute to the result of the 'and'.
730 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
731 return UpdateValueUsesWith(I, I->getOperand(0));
732 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
733 return UpdateValueUsesWith(I, I->getOperand(1));
735 // If all of the demanded bits in the inputs are known zeros, return zero.
736 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
737 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
739 // If the RHS is a constant, see if we can simplify it.
740 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
741 return UpdateValueUsesWith(I, I);
743 // Output known-1 bits are only known if set in both the LHS & RHS.
744 KnownOne &= KnownOne2;
745 // Output known-0 are known to be clear if zero in either the LHS | RHS.
746 KnownZero |= KnownZero2;
748 case Instruction::Or:
749 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
750 KnownZero, KnownOne, Depth+1))
752 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
753 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
754 KnownZero2, KnownOne2, Depth+1))
756 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
758 // If all of the demanded bits are known zero on one side, return the other.
759 // These bits cannot contribute to the result of the 'or'.
760 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
761 return UpdateValueUsesWith(I, I->getOperand(0));
762 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
763 return UpdateValueUsesWith(I, I->getOperand(1));
765 // If all of the potentially set bits on one side are known to be set on
766 // the other side, just use the 'other' side.
767 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
768 (DemandedMask & (~KnownZero)))
769 return UpdateValueUsesWith(I, I->getOperand(0));
770 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
771 (DemandedMask & (~KnownZero2)))
772 return UpdateValueUsesWith(I, I->getOperand(1));
774 // If the RHS is a constant, see if we can simplify it.
775 if (ShrinkDemandedConstant(I, 1, DemandedMask))
776 return UpdateValueUsesWith(I, I);
778 // Output known-0 bits are only known if clear in both the LHS & RHS.
779 KnownZero &= KnownZero2;
780 // Output known-1 are known to be set if set in either the LHS | RHS.
781 KnownOne |= KnownOne2;
783 case Instruction::Xor: {
784 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
785 KnownZero, KnownOne, Depth+1))
787 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
788 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
789 KnownZero2, KnownOne2, Depth+1))
791 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
793 // If all of the demanded bits are known zero on one side, return the other.
794 // These bits cannot contribute to the result of the 'xor'.
795 if ((DemandedMask & KnownZero) == DemandedMask)
796 return UpdateValueUsesWith(I, I->getOperand(0));
797 if ((DemandedMask & KnownZero2) == DemandedMask)
798 return UpdateValueUsesWith(I, I->getOperand(1));
800 // Output known-0 bits are known if clear or set in both the LHS & RHS.
801 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
802 // Output known-1 are known to be set if set in only one of the LHS, RHS.
803 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
805 // If all of the unknown bits are known to be zero on one side or the other
806 // (but not both) turn this into an *inclusive* or.
807 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
808 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
809 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
811 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
813 InsertNewInstBefore(Or, *I);
814 return UpdateValueUsesWith(I, Or);
818 // If all of the demanded bits on one side are known, and all of the set
819 // bits on that side are also known to be set on the other side, turn this
820 // into an AND, as we know the bits will be cleared.
821 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
822 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
823 if ((KnownOne & KnownOne2) == KnownOne) {
824 Constant *AndC = GetConstantInType(I->getType(),
825 ~KnownOne & DemandedMask);
827 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
828 InsertNewInstBefore(And, *I);
829 return UpdateValueUsesWith(I, And);
833 // If the RHS is a constant, see if we can simplify it.
834 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
835 if (ShrinkDemandedConstant(I, 1, DemandedMask))
836 return UpdateValueUsesWith(I, I);
838 KnownZero = KnownZeroOut;
839 KnownOne = KnownOneOut;
842 case Instruction::Select:
843 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
844 KnownZero, KnownOne, Depth+1))
846 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
847 KnownZero2, KnownOne2, Depth+1))
849 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
850 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
852 // If the operands are constants, see if we can simplify them.
853 if (ShrinkDemandedConstant(I, 1, DemandedMask))
854 return UpdateValueUsesWith(I, I);
855 if (ShrinkDemandedConstant(I, 2, DemandedMask))
856 return UpdateValueUsesWith(I, I);
858 // Only known if known in both the LHS and RHS.
859 KnownOne &= KnownOne2;
860 KnownZero &= KnownZero2;
862 case Instruction::Cast: {
863 const Type *SrcTy = I->getOperand(0)->getType();
864 if (!SrcTy->isIntegral()) return false;
866 // If this is an integer truncate or noop, just look in the input.
867 if (SrcTy->getPrimitiveSizeInBits() >=
868 I->getType()->getPrimitiveSizeInBits()) {
869 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
870 KnownZero, KnownOne, Depth+1))
872 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
876 // Sign or Zero extension. Compute the bits in the result that are not
877 // present in the input.
878 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
879 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
881 // Handle zero extension.
882 if (!SrcTy->isSigned()) {
883 DemandedMask &= SrcTy->getIntegralTypeMask();
884 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
885 KnownZero, KnownOne, Depth+1))
887 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
888 // The top bits are known to be zero.
889 KnownZero |= NewBits;
892 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
893 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
895 // If any of the sign extended bits are demanded, we know that the sign
897 if (NewBits & DemandedMask)
898 InputDemandedBits |= InSignBit;
900 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
901 KnownZero, KnownOne, Depth+1))
903 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
905 // If the sign bit of the input is known set or clear, then we know the
906 // top bits of the result.
908 // If the input sign bit is known zero, or if the NewBits are not demanded
909 // convert this into a zero extension.
910 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
911 // Convert to unsigned first.
913 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
914 I->getOperand(0)->getName());
915 InsertNewInstBefore(NewVal, *I);
916 // Then cast that to the destination type.
917 NewVal = new CastInst(NewVal, I->getType(), I->getName());
918 InsertNewInstBefore(NewVal, *I);
919 return UpdateValueUsesWith(I, NewVal);
920 } else if (KnownOne & InSignBit) { // Input sign bit known set
922 KnownZero &= ~NewBits;
923 } else { // Input sign bit unknown
924 KnownZero &= ~NewBits;
925 KnownOne &= ~NewBits;
930 case Instruction::Shl:
931 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
932 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
933 KnownZero, KnownOne, Depth+1))
935 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
936 KnownZero <<= SA->getValue();
937 KnownOne <<= SA->getValue();
938 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
941 case Instruction::Shr:
942 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
943 unsigned ShAmt = SA->getValue();
945 // Compute the new bits that are at the top now.
946 uint64_t HighBits = (1ULL << ShAmt)-1;
947 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
948 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
949 if (I->getType()->isUnsigned()) { // Unsigned shift right.
950 if (SimplifyDemandedBits(I->getOperand(0),
951 (DemandedMask << ShAmt) & TypeMask,
952 KnownZero, KnownOne, Depth+1))
954 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
955 KnownZero &= TypeMask;
956 KnownOne &= TypeMask;
959 KnownZero |= HighBits; // high bits known zero.
960 } else { // Signed shift right.
961 if (SimplifyDemandedBits(I->getOperand(0),
962 (DemandedMask << ShAmt) & TypeMask,
963 KnownZero, KnownOne, Depth+1))
965 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
966 KnownZero &= TypeMask;
967 KnownOne &= TypeMask;
968 KnownZero >>= SA->getValue();
969 KnownOne >>= SA->getValue();
971 // Handle the sign bits.
972 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
973 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
975 // If the input sign bit is known to be zero, or if none of the top bits
976 // are demanded, turn this into an unsigned shift right.
977 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
978 // Convert the input to unsigned.
980 NewVal = new CastInst(I->getOperand(0),
981 I->getType()->getUnsignedVersion(),
982 I->getOperand(0)->getName());
983 InsertNewInstBefore(NewVal, *I);
984 // Perform the unsigned shift right.
985 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
986 InsertNewInstBefore(NewVal, *I);
987 // Then cast that to the destination type.
988 NewVal = new CastInst(NewVal, I->getType(), I->getName());
989 InsertNewInstBefore(NewVal, *I);
990 return UpdateValueUsesWith(I, NewVal);
991 } else if (KnownOne & SignBit) { // New bits are known one.
992 KnownOne |= HighBits;
999 // If the client is only demanding bits that we know, return the known
1001 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1002 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1006 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1007 // true when both operands are equal...
1009 static bool isTrueWhenEqual(Instruction &I) {
1010 return I.getOpcode() == Instruction::SetEQ ||
1011 I.getOpcode() == Instruction::SetGE ||
1012 I.getOpcode() == Instruction::SetLE;
1015 /// AssociativeOpt - Perform an optimization on an associative operator. This
1016 /// function is designed to check a chain of associative operators for a
1017 /// potential to apply a certain optimization. Since the optimization may be
1018 /// applicable if the expression was reassociated, this checks the chain, then
1019 /// reassociates the expression as necessary to expose the optimization
1020 /// opportunity. This makes use of a special Functor, which must define
1021 /// 'shouldApply' and 'apply' methods.
1023 template<typename Functor>
1024 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1025 unsigned Opcode = Root.getOpcode();
1026 Value *LHS = Root.getOperand(0);
1028 // Quick check, see if the immediate LHS matches...
1029 if (F.shouldApply(LHS))
1030 return F.apply(Root);
1032 // Otherwise, if the LHS is not of the same opcode as the root, return.
1033 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1034 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1035 // Should we apply this transform to the RHS?
1036 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1038 // If not to the RHS, check to see if we should apply to the LHS...
1039 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1040 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1044 // If the functor wants to apply the optimization to the RHS of LHSI,
1045 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1047 BasicBlock *BB = Root.getParent();
1049 // Now all of the instructions are in the current basic block, go ahead
1050 // and perform the reassociation.
1051 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1053 // First move the selected RHS to the LHS of the root...
1054 Root.setOperand(0, LHSI->getOperand(1));
1056 // Make what used to be the LHS of the root be the user of the root...
1057 Value *ExtraOperand = TmpLHSI->getOperand(1);
1058 if (&Root == TmpLHSI) {
1059 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1062 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1063 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1064 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1065 BasicBlock::iterator ARI = &Root; ++ARI;
1066 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1069 // Now propagate the ExtraOperand down the chain of instructions until we
1071 while (TmpLHSI != LHSI) {
1072 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1073 // Move the instruction to immediately before the chain we are
1074 // constructing to avoid breaking dominance properties.
1075 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1076 BB->getInstList().insert(ARI, NextLHSI);
1079 Value *NextOp = NextLHSI->getOperand(1);
1080 NextLHSI->setOperand(1, ExtraOperand);
1082 ExtraOperand = NextOp;
1085 // Now that the instructions are reassociated, have the functor perform
1086 // the transformation...
1087 return F.apply(Root);
1090 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1096 // AddRHS - Implements: X + X --> X << 1
1099 AddRHS(Value *rhs) : RHS(rhs) {}
1100 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1101 Instruction *apply(BinaryOperator &Add) const {
1102 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1103 ConstantInt::get(Type::UByteTy, 1));
1107 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1109 struct AddMaskingAnd {
1111 AddMaskingAnd(Constant *c) : C2(c) {}
1112 bool shouldApply(Value *LHS) const {
1114 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1115 ConstantExpr::getAnd(C1, C2)->isNullValue();
1117 Instruction *apply(BinaryOperator &Add) const {
1118 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1122 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1124 if (isa<CastInst>(I)) {
1125 if (Constant *SOC = dyn_cast<Constant>(SO))
1126 return ConstantExpr::getCast(SOC, I.getType());
1128 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1129 SO->getName() + ".cast"), I);
1132 // Figure out if the constant is the left or the right argument.
1133 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1134 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1136 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1138 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1139 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1142 Value *Op0 = SO, *Op1 = ConstOperand;
1144 std::swap(Op0, Op1);
1146 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1147 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1148 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1149 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1151 assert(0 && "Unknown binary instruction type!");
1154 return IC->InsertNewInstBefore(New, I);
1157 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1158 // constant as the other operand, try to fold the binary operator into the
1159 // select arguments. This also works for Cast instructions, which obviously do
1160 // not have a second operand.
1161 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1163 // Don't modify shared select instructions
1164 if (!SI->hasOneUse()) return 0;
1165 Value *TV = SI->getOperand(1);
1166 Value *FV = SI->getOperand(2);
1168 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1169 // Bool selects with constant operands can be folded to logical ops.
1170 if (SI->getType() == Type::BoolTy) return 0;
1172 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1173 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1175 return new SelectInst(SI->getCondition(), SelectTrueVal,
1182 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1183 /// node as operand #0, see if we can fold the instruction into the PHI (which
1184 /// is only possible if all operands to the PHI are constants).
1185 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1186 PHINode *PN = cast<PHINode>(I.getOperand(0));
1187 unsigned NumPHIValues = PN->getNumIncomingValues();
1188 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1189 !isa<Constant>(PN->getIncomingValue(0))) return 0;
1191 // Check to see if all of the operands of the PHI are constants. If not, we
1192 // cannot do the transformation.
1193 for (unsigned i = 1; i != NumPHIValues; ++i)
1194 if (!isa<Constant>(PN->getIncomingValue(i)))
1197 // Okay, we can do the transformation: create the new PHI node.
1198 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1200 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1201 InsertNewInstBefore(NewPN, *PN);
1203 // Next, add all of the operands to the PHI.
1204 if (I.getNumOperands() == 2) {
1205 Constant *C = cast<Constant>(I.getOperand(1));
1206 for (unsigned i = 0; i != NumPHIValues; ++i) {
1207 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1208 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1209 PN->getIncomingBlock(i));
1212 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1213 const Type *RetTy = I.getType();
1214 for (unsigned i = 0; i != NumPHIValues; ++i) {
1215 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1216 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1217 PN->getIncomingBlock(i));
1220 return ReplaceInstUsesWith(I, NewPN);
1223 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1224 bool Changed = SimplifyCommutative(I);
1225 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1227 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1228 // X + undef -> undef
1229 if (isa<UndefValue>(RHS))
1230 return ReplaceInstUsesWith(I, RHS);
1233 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1234 if (RHSC->isNullValue())
1235 return ReplaceInstUsesWith(I, LHS);
1236 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1237 if (CFP->isExactlyValue(-0.0))
1238 return ReplaceInstUsesWith(I, LHS);
1241 // X + (signbit) --> X ^ signbit
1242 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1243 uint64_t Val = CI->getZExtValue();
1244 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1245 return BinaryOperator::createXor(LHS, RHS);
1248 if (isa<PHINode>(LHS))
1249 if (Instruction *NV = FoldOpIntoPhi(I))
1252 ConstantInt *XorRHS = 0;
1254 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1255 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1256 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1257 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1259 uint64_t C0080Val = 1ULL << 31;
1260 int64_t CFF80Val = -C0080Val;
1263 if (TySizeBits > Size) {
1265 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1266 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1267 if (RHSSExt == CFF80Val) {
1268 if (XorRHS->getZExtValue() == C0080Val)
1270 } else if (RHSZExt == C0080Val) {
1271 if (XorRHS->getSExtValue() == CFF80Val)
1275 // This is a sign extend if the top bits are known zero.
1276 uint64_t Mask = ~0ULL;
1277 Mask <<= 64-(TySizeBits-Size);
1278 Mask &= XorLHS->getType()->getIntegralTypeMask();
1279 if (!MaskedValueIsZero(XorLHS, Mask))
1280 Size = 0; // Not a sign ext, but can't be any others either.
1287 } while (Size >= 8);
1290 const Type *MiddleType = 0;
1293 case 32: MiddleType = Type::IntTy; break;
1294 case 16: MiddleType = Type::ShortTy; break;
1295 case 8: MiddleType = Type::SByteTy; break;
1298 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1299 InsertNewInstBefore(NewTrunc, I);
1300 return new CastInst(NewTrunc, I.getType());
1306 if (I.getType()->isInteger()) {
1307 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1309 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1310 if (RHSI->getOpcode() == Instruction::Sub)
1311 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1312 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1314 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1315 if (LHSI->getOpcode() == Instruction::Sub)
1316 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1317 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1322 if (Value *V = dyn_castNegVal(LHS))
1323 return BinaryOperator::createSub(RHS, V);
1326 if (!isa<Constant>(RHS))
1327 if (Value *V = dyn_castNegVal(RHS))
1328 return BinaryOperator::createSub(LHS, V);
1332 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1333 if (X == RHS) // X*C + X --> X * (C+1)
1334 return BinaryOperator::createMul(RHS, AddOne(C2));
1336 // X*C1 + X*C2 --> X * (C1+C2)
1338 if (X == dyn_castFoldableMul(RHS, C1))
1339 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1342 // X + X*C --> X * (C+1)
1343 if (dyn_castFoldableMul(RHS, C2) == LHS)
1344 return BinaryOperator::createMul(LHS, AddOne(C2));
1347 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1348 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1349 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1351 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1353 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1354 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1355 return BinaryOperator::createSub(C, X);
1358 // (X & FF00) + xx00 -> (X+xx00) & FF00
1359 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1360 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1361 if (Anded == CRHS) {
1362 // See if all bits from the first bit set in the Add RHS up are included
1363 // in the mask. First, get the rightmost bit.
1364 uint64_t AddRHSV = CRHS->getRawValue();
1366 // Form a mask of all bits from the lowest bit added through the top.
1367 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1368 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1370 // See if the and mask includes all of these bits.
1371 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
1373 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1374 // Okay, the xform is safe. Insert the new add pronto.
1375 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1376 LHS->getName()), I);
1377 return BinaryOperator::createAnd(NewAdd, C2);
1382 // Try to fold constant add into select arguments.
1383 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1384 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1388 return Changed ? &I : 0;
1391 // isSignBit - Return true if the value represented by the constant only has the
1392 // highest order bit set.
1393 static bool isSignBit(ConstantInt *CI) {
1394 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1395 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1398 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1400 static Value *RemoveNoopCast(Value *V) {
1401 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1402 const Type *CTy = CI->getType();
1403 const Type *OpTy = CI->getOperand(0)->getType();
1404 if (CTy->isInteger() && OpTy->isInteger()) {
1405 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1406 return RemoveNoopCast(CI->getOperand(0));
1407 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1408 return RemoveNoopCast(CI->getOperand(0));
1413 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1414 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1416 if (Op0 == Op1) // sub X, X -> 0
1417 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1419 // If this is a 'B = x-(-A)', change to B = x+A...
1420 if (Value *V = dyn_castNegVal(Op1))
1421 return BinaryOperator::createAdd(Op0, V);
1423 if (isa<UndefValue>(Op0))
1424 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1425 if (isa<UndefValue>(Op1))
1426 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1428 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1429 // Replace (-1 - A) with (~A)...
1430 if (C->isAllOnesValue())
1431 return BinaryOperator::createNot(Op1);
1433 // C - ~X == X + (1+C)
1435 if (match(Op1, m_Not(m_Value(X))))
1436 return BinaryOperator::createAdd(X,
1437 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1438 // -((uint)X >> 31) -> ((int)X >> 31)
1439 // -((int)X >> 31) -> ((uint)X >> 31)
1440 if (C->isNullValue()) {
1441 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1442 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1443 if (SI->getOpcode() == Instruction::Shr)
1444 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1446 if (SI->getType()->isSigned())
1447 NewTy = SI->getType()->getUnsignedVersion();
1449 NewTy = SI->getType()->getSignedVersion();
1450 // Check to see if we are shifting out everything but the sign bit.
1451 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
1452 // Ok, the transformation is safe. Insert a cast of the incoming
1453 // value, then the new shift, then the new cast.
1454 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1455 SI->getOperand(0)->getName());
1456 Value *InV = InsertNewInstBefore(FirstCast, I);
1457 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1459 if (NewShift->getType() == I.getType())
1462 InV = InsertNewInstBefore(NewShift, I);
1463 return new CastInst(NewShift, I.getType());
1469 // Try to fold constant sub into select arguments.
1470 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1471 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1474 if (isa<PHINode>(Op0))
1475 if (Instruction *NV = FoldOpIntoPhi(I))
1479 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1480 if (Op1I->getOpcode() == Instruction::Add &&
1481 !Op0->getType()->isFloatingPoint()) {
1482 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1483 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1484 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1485 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1486 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1487 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1488 // C1-(X+C2) --> (C1-C2)-X
1489 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1490 Op1I->getOperand(0));
1494 if (Op1I->hasOneUse()) {
1495 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1496 // is not used by anyone else...
1498 if (Op1I->getOpcode() == Instruction::Sub &&
1499 !Op1I->getType()->isFloatingPoint()) {
1500 // Swap the two operands of the subexpr...
1501 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1502 Op1I->setOperand(0, IIOp1);
1503 Op1I->setOperand(1, IIOp0);
1505 // Create the new top level add instruction...
1506 return BinaryOperator::createAdd(Op0, Op1);
1509 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1511 if (Op1I->getOpcode() == Instruction::And &&
1512 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1513 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1516 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1517 return BinaryOperator::createAnd(Op0, NewNot);
1520 // -(X sdiv C) -> (X sdiv -C)
1521 if (Op1I->getOpcode() == Instruction::Div)
1522 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1523 if (CSI->isNullValue())
1524 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1525 return BinaryOperator::createDiv(Op1I->getOperand(0),
1526 ConstantExpr::getNeg(DivRHS));
1528 // X - X*C --> X * (1-C)
1529 ConstantInt *C2 = 0;
1530 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1532 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1533 return BinaryOperator::createMul(Op0, CP1);
1538 if (!Op0->getType()->isFloatingPoint())
1539 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1540 if (Op0I->getOpcode() == Instruction::Add) {
1541 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1542 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1543 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1544 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1545 } else if (Op0I->getOpcode() == Instruction::Sub) {
1546 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1547 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1551 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1552 if (X == Op1) { // X*C - X --> X * (C-1)
1553 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1554 return BinaryOperator::createMul(Op1, CP1);
1557 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1558 if (X == dyn_castFoldableMul(Op1, C2))
1559 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1564 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1565 /// really just returns true if the most significant (sign) bit is set.
1566 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1567 if (RHS->getType()->isSigned()) {
1568 // True if source is LHS < 0 or LHS <= -1
1569 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1570 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1572 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1573 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1574 // the size of the integer type.
1575 if (Opcode == Instruction::SetGE)
1576 return RHSC->getValue() ==
1577 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1578 if (Opcode == Instruction::SetGT)
1579 return RHSC->getValue() ==
1580 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1585 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1586 bool Changed = SimplifyCommutative(I);
1587 Value *Op0 = I.getOperand(0);
1589 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1590 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1592 // Simplify mul instructions with a constant RHS...
1593 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1594 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1596 // ((X << C1)*C2) == (X * (C2 << C1))
1597 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1598 if (SI->getOpcode() == Instruction::Shl)
1599 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1600 return BinaryOperator::createMul(SI->getOperand(0),
1601 ConstantExpr::getShl(CI, ShOp));
1603 if (CI->isNullValue())
1604 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1605 if (CI->equalsInt(1)) // X * 1 == X
1606 return ReplaceInstUsesWith(I, Op0);
1607 if (CI->isAllOnesValue()) // X * -1 == 0 - X
1608 return BinaryOperator::createNeg(Op0, I.getName());
1610 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1611 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1612 uint64_t C = Log2_64(Val);
1613 return new ShiftInst(Instruction::Shl, Op0,
1614 ConstantUInt::get(Type::UByteTy, C));
1616 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1617 if (Op1F->isNullValue())
1618 return ReplaceInstUsesWith(I, Op1);
1620 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1621 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1622 if (Op1F->getValue() == 1.0)
1623 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1626 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1627 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1628 isa<ConstantInt>(Op0I->getOperand(1))) {
1629 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1630 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1632 InsertNewInstBefore(Add, I);
1633 Value *C1C2 = ConstantExpr::getMul(Op1,
1634 cast<Constant>(Op0I->getOperand(1)));
1635 return BinaryOperator::createAdd(Add, C1C2);
1639 // Try to fold constant mul into select arguments.
1640 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1641 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1644 if (isa<PHINode>(Op0))
1645 if (Instruction *NV = FoldOpIntoPhi(I))
1649 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1650 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1651 return BinaryOperator::createMul(Op0v, Op1v);
1653 // If one of the operands of the multiply is a cast from a boolean value, then
1654 // we know the bool is either zero or one, so this is a 'masking' multiply.
1655 // See if we can simplify things based on how the boolean was originally
1657 CastInst *BoolCast = 0;
1658 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1659 if (CI->getOperand(0)->getType() == Type::BoolTy)
1662 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1663 if (CI->getOperand(0)->getType() == Type::BoolTy)
1666 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1667 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1668 const Type *SCOpTy = SCIOp0->getType();
1670 // If the setcc is true iff the sign bit of X is set, then convert this
1671 // multiply into a shift/and combination.
1672 if (isa<ConstantInt>(SCIOp1) &&
1673 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1674 // Shift the X value right to turn it into "all signbits".
1675 Constant *Amt = ConstantUInt::get(Type::UByteTy,
1676 SCOpTy->getPrimitiveSizeInBits()-1);
1677 if (SCIOp0->getType()->isUnsigned()) {
1678 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1679 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1680 SCIOp0->getName()), I);
1684 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1685 BoolCast->getOperand(0)->getName()+
1688 // If the multiply type is not the same as the source type, sign extend
1689 // or truncate to the multiply type.
1690 if (I.getType() != V->getType())
1691 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1693 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1694 return BinaryOperator::createAnd(V, OtherOp);
1699 return Changed ? &I : 0;
1702 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1703 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1705 if (isa<UndefValue>(Op0)) // undef / X -> 0
1706 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1707 if (isa<UndefValue>(Op1))
1708 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1710 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1712 if (RHS->equalsInt(1))
1713 return ReplaceInstUsesWith(I, Op0);
1716 if (RHS->isAllOnesValue())
1717 return BinaryOperator::createNeg(Op0);
1719 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1720 if (LHS->getOpcode() == Instruction::Div)
1721 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1722 // (X / C1) / C2 -> X / (C1*C2)
1723 return BinaryOperator::createDiv(LHS->getOperand(0),
1724 ConstantExpr::getMul(RHS, LHSRHS));
1727 // Check to see if this is an unsigned division with an exact power of 2,
1728 // if so, convert to a right shift.
1729 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1730 if (uint64_t Val = C->getValue()) // Don't break X / 0
1731 if (isPowerOf2_64(Val)) {
1732 uint64_t C = Log2_64(Val);
1733 return new ShiftInst(Instruction::Shr, Op0,
1734 ConstantUInt::get(Type::UByteTy, C));
1738 if (RHS->getType()->isSigned())
1739 if (Value *LHSNeg = dyn_castNegVal(Op0))
1740 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1742 if (!RHS->isNullValue()) {
1743 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1744 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1746 if (isa<PHINode>(Op0))
1747 if (Instruction *NV = FoldOpIntoPhi(I))
1752 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1753 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1754 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1755 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1756 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1757 if (STO->getValue() == 0) { // Couldn't be this argument.
1758 I.setOperand(1, SFO);
1760 } else if (SFO->getValue() == 0) {
1761 I.setOperand(1, STO);
1765 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1766 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1767 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1768 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1769 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1770 TC, SI->getName()+".t");
1771 TSI = InsertNewInstBefore(TSI, I);
1773 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1774 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1775 FC, SI->getName()+".f");
1776 FSI = InsertNewInstBefore(FSI, I);
1777 return new SelectInst(SI->getOperand(0), TSI, FSI);
1781 // 0 / X == 0, we don't need to preserve faults!
1782 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1783 if (LHS->equalsInt(0))
1784 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1786 if (I.getType()->isSigned()) {
1787 // If the sign bits of both operands are zero (i.e. we can prove they are
1788 // unsigned inputs), turn this into a udiv.
1789 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1790 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1791 const Type *NTy = Op0->getType()->getUnsignedVersion();
1792 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1793 InsertNewInstBefore(LHS, I);
1795 if (Constant *R = dyn_cast<Constant>(Op1))
1796 RHS = ConstantExpr::getCast(R, NTy);
1798 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1799 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1800 InsertNewInstBefore(Div, I);
1801 return new CastInst(Div, I.getType());
1804 // Known to be an unsigned division.
1805 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1806 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1807 if (RHSI->getOpcode() == Instruction::Shl &&
1808 isa<ConstantUInt>(RHSI->getOperand(0))) {
1809 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1810 if (isPowerOf2_64(C1)) {
1811 unsigned C2 = Log2_64(C1);
1812 Value *Add = RHSI->getOperand(1);
1814 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1815 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1818 return new ShiftInst(Instruction::Shr, Op0, Add);
1828 /// GetFactor - If we can prove that the specified value is at least a multiple
1829 /// of some factor, return that factor.
1830 static Constant *GetFactor(Value *V) {
1831 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1834 // Unless we can be tricky, we know this is a multiple of 1.
1835 Constant *Result = ConstantInt::get(V->getType(), 1);
1837 Instruction *I = dyn_cast<Instruction>(V);
1838 if (!I) return Result;
1840 if (I->getOpcode() == Instruction::Mul) {
1841 // Handle multiplies by a constant, etc.
1842 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1843 GetFactor(I->getOperand(1)));
1844 } else if (I->getOpcode() == Instruction::Shl) {
1845 // (X<<C) -> X * (1 << C)
1846 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1847 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1848 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1850 } else if (I->getOpcode() == Instruction::And) {
1851 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1852 // X & 0xFFF0 is known to be a multiple of 16.
1853 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1854 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1855 return ConstantExpr::getShl(Result,
1856 ConstantUInt::get(Type::UByteTy, Zeros));
1858 } else if (I->getOpcode() == Instruction::Cast) {
1859 Value *Op = I->getOperand(0);
1860 // Only handle int->int casts.
1861 if (!Op->getType()->isInteger()) return Result;
1862 return ConstantExpr::getCast(GetFactor(Op), V->getType());
1867 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1868 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1870 // 0 % X == 0, we don't need to preserve faults!
1871 if (Constant *LHS = dyn_cast<Constant>(Op0))
1872 if (LHS->isNullValue())
1873 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1875 if (isa<UndefValue>(Op0)) // undef % X -> 0
1876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1877 if (isa<UndefValue>(Op1))
1878 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1880 if (I.getType()->isSigned()) {
1881 if (Value *RHSNeg = dyn_castNegVal(Op1))
1882 if (!isa<ConstantSInt>(RHSNeg) ||
1883 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1885 AddUsesToWorkList(I);
1886 I.setOperand(1, RHSNeg);
1890 // If the top bits of both operands are zero (i.e. we can prove they are
1891 // unsigned inputs), turn this into a urem.
1892 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1893 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1894 const Type *NTy = Op0->getType()->getUnsignedVersion();
1895 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1896 InsertNewInstBefore(LHS, I);
1898 if (Constant *R = dyn_cast<Constant>(Op1))
1899 RHS = ConstantExpr::getCast(R, NTy);
1901 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1902 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1903 InsertNewInstBefore(Rem, I);
1904 return new CastInst(Rem, I.getType());
1908 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1909 // X % 0 == undef, we don't need to preserve faults!
1910 if (RHS->equalsInt(0))
1911 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
1913 if (RHS->equalsInt(1)) // X % 1 == 0
1914 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1916 // Check to see if this is an unsigned remainder with an exact power of 2,
1917 // if so, convert to a bitwise and.
1918 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1919 if (isPowerOf2_64(C->getValue()))
1920 return BinaryOperator::createAnd(Op0, SubOne(C));
1922 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1923 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1924 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1926 } else if (isa<PHINode>(Op0I)) {
1927 if (Instruction *NV = FoldOpIntoPhi(I))
1931 // X*C1%C2 --> 0 iff C1%C2 == 0
1932 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
1933 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1937 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1938 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1939 if (I.getType()->isUnsigned() &&
1940 RHSI->getOpcode() == Instruction::Shl &&
1941 isa<ConstantUInt>(RHSI->getOperand(0))) {
1942 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1943 if (isPowerOf2_64(C1)) {
1944 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1945 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1947 return BinaryOperator::createAnd(Op0, Add);
1951 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1952 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1953 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1954 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1955 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1956 if (STO->getValue() == 0) { // Couldn't be this argument.
1957 I.setOperand(1, SFO);
1959 } else if (SFO->getValue() == 0) {
1960 I.setOperand(1, STO);
1964 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
1965 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1966 SubOne(STO), SI->getName()+".t"), I);
1967 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1968 SubOne(SFO), SI->getName()+".f"), I);
1969 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1977 // isMaxValueMinusOne - return true if this is Max-1
1978 static bool isMaxValueMinusOne(const ConstantInt *C) {
1979 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1980 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
1982 const ConstantSInt *CS = cast<ConstantSInt>(C);
1984 // Calculate 0111111111..11111
1985 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1986 int64_t Val = INT64_MAX; // All ones
1987 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1988 return CS->getValue() == Val-1;
1991 // isMinValuePlusOne - return true if this is Min+1
1992 static bool isMinValuePlusOne(const ConstantInt *C) {
1993 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1994 return CU->getValue() == 1;
1996 const ConstantSInt *CS = cast<ConstantSInt>(C);
1998 // Calculate 1111111111000000000000
1999 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2000 int64_t Val = -1; // All ones
2001 Val <<= TypeBits-1; // Shift over to the right spot
2002 return CS->getValue() == Val+1;
2005 // isOneBitSet - Return true if there is exactly one bit set in the specified
2007 static bool isOneBitSet(const ConstantInt *CI) {
2008 uint64_t V = CI->getRawValue();
2009 return V && (V & (V-1)) == 0;
2012 #if 0 // Currently unused
2013 // isLowOnes - Return true if the constant is of the form 0+1+.
2014 static bool isLowOnes(const ConstantInt *CI) {
2015 uint64_t V = CI->getRawValue();
2017 // There won't be bits set in parts that the type doesn't contain.
2018 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2020 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2021 return U && V && (U & V) == 0;
2025 // isHighOnes - Return true if the constant is of the form 1+0+.
2026 // This is the same as lowones(~X).
2027 static bool isHighOnes(const ConstantInt *CI) {
2028 uint64_t V = ~CI->getRawValue();
2029 if (~V == 0) return false; // 0's does not match "1+"
2031 // There won't be bits set in parts that the type doesn't contain.
2032 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2034 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2035 return U && V && (U & V) == 0;
2039 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2040 /// are carefully arranged to allow folding of expressions such as:
2042 /// (A < B) | (A > B) --> (A != B)
2044 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2045 /// represents that the comparison is true if A == B, and bit value '1' is true
2048 static unsigned getSetCondCode(const SetCondInst *SCI) {
2049 switch (SCI->getOpcode()) {
2051 case Instruction::SetGT: return 1;
2052 case Instruction::SetEQ: return 2;
2053 case Instruction::SetGE: return 3;
2054 case Instruction::SetLT: return 4;
2055 case Instruction::SetNE: return 5;
2056 case Instruction::SetLE: return 6;
2059 assert(0 && "Invalid SetCC opcode!");
2064 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2065 /// opcode and two operands into either a constant true or false, or a brand new
2066 /// SetCC instruction.
2067 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2069 case 0: return ConstantBool::False;
2070 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2071 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2072 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2073 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2074 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2075 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2076 case 7: return ConstantBool::True;
2077 default: assert(0 && "Illegal SetCCCode!"); return 0;
2081 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2082 struct FoldSetCCLogical {
2085 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2086 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2087 bool shouldApply(Value *V) const {
2088 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2089 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2090 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2093 Instruction *apply(BinaryOperator &Log) const {
2094 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2095 if (SCI->getOperand(0) != LHS) {
2096 assert(SCI->getOperand(1) == LHS);
2097 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2100 unsigned LHSCode = getSetCondCode(SCI);
2101 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2103 switch (Log.getOpcode()) {
2104 case Instruction::And: Code = LHSCode & RHSCode; break;
2105 case Instruction::Or: Code = LHSCode | RHSCode; break;
2106 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2107 default: assert(0 && "Illegal logical opcode!"); return 0;
2110 Value *RV = getSetCCValue(Code, LHS, RHS);
2111 if (Instruction *I = dyn_cast<Instruction>(RV))
2113 // Otherwise, it's a constant boolean value...
2114 return IC.ReplaceInstUsesWith(Log, RV);
2118 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2119 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2120 // guaranteed to be either a shift instruction or a binary operator.
2121 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2122 ConstantIntegral *OpRHS,
2123 ConstantIntegral *AndRHS,
2124 BinaryOperator &TheAnd) {
2125 Value *X = Op->getOperand(0);
2126 Constant *Together = 0;
2127 if (!isa<ShiftInst>(Op))
2128 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2130 switch (Op->getOpcode()) {
2131 case Instruction::Xor:
2132 if (Op->hasOneUse()) {
2133 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2134 std::string OpName = Op->getName(); Op->setName("");
2135 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2136 InsertNewInstBefore(And, TheAnd);
2137 return BinaryOperator::createXor(And, Together);
2140 case Instruction::Or:
2141 if (Together == AndRHS) // (X | C) & C --> C
2142 return ReplaceInstUsesWith(TheAnd, AndRHS);
2144 if (Op->hasOneUse() && Together != OpRHS) {
2145 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2146 std::string Op0Name = Op->getName(); Op->setName("");
2147 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2148 InsertNewInstBefore(Or, TheAnd);
2149 return BinaryOperator::createAnd(Or, AndRHS);
2152 case Instruction::Add:
2153 if (Op->hasOneUse()) {
2154 // Adding a one to a single bit bit-field should be turned into an XOR
2155 // of the bit. First thing to check is to see if this AND is with a
2156 // single bit constant.
2157 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
2159 // Clear bits that are not part of the constant.
2160 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2162 // If there is only one bit set...
2163 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2164 // Ok, at this point, we know that we are masking the result of the
2165 // ADD down to exactly one bit. If the constant we are adding has
2166 // no bits set below this bit, then we can eliminate the ADD.
2167 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
2169 // Check to see if any bits below the one bit set in AndRHSV are set.
2170 if ((AddRHS & (AndRHSV-1)) == 0) {
2171 // If not, the only thing that can effect the output of the AND is
2172 // the bit specified by AndRHSV. If that bit is set, the effect of
2173 // the XOR is to toggle the bit. If it is clear, then the ADD has
2175 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2176 TheAnd.setOperand(0, X);
2179 std::string Name = Op->getName(); Op->setName("");
2180 // Pull the XOR out of the AND.
2181 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2182 InsertNewInstBefore(NewAnd, TheAnd);
2183 return BinaryOperator::createXor(NewAnd, AndRHS);
2190 case Instruction::Shl: {
2191 // We know that the AND will not produce any of the bits shifted in, so if
2192 // the anded constant includes them, clear them now!
2194 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2195 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2196 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2198 if (CI == ShlMask) { // Masking out bits that the shift already masks
2199 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2200 } else if (CI != AndRHS) { // Reducing bits set in and.
2201 TheAnd.setOperand(1, CI);
2206 case Instruction::Shr:
2207 // We know that the AND will not produce any of the bits shifted in, so if
2208 // the anded constant includes them, clear them now! This only applies to
2209 // unsigned shifts, because a signed shr may bring in set bits!
2211 if (AndRHS->getType()->isUnsigned()) {
2212 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2213 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2214 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2216 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2217 return ReplaceInstUsesWith(TheAnd, Op);
2218 } else if (CI != AndRHS) {
2219 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2222 } else { // Signed shr.
2223 // See if this is shifting in some sign extension, then masking it out
2225 if (Op->hasOneUse()) {
2226 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2227 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2228 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2229 if (CI == AndRHS) { // Masking out bits shifted in.
2230 // Make the argument unsigned.
2231 Value *ShVal = Op->getOperand(0);
2232 ShVal = InsertCastBefore(ShVal,
2233 ShVal->getType()->getUnsignedVersion(),
2235 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2236 OpRHS, Op->getName()),
2238 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2239 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2242 return new CastInst(ShVal, Op->getType());
2252 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2253 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2254 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2255 /// insert new instructions.
2256 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2257 bool Inside, Instruction &IB) {
2258 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2259 "Lo is not <= Hi in range emission code!");
2261 if (Lo == Hi) // Trivially false.
2262 return new SetCondInst(Instruction::SetNE, V, V);
2263 if (cast<ConstantIntegral>(Lo)->isMinValue())
2264 return new SetCondInst(Instruction::SetLT, V, Hi);
2266 Constant *AddCST = ConstantExpr::getNeg(Lo);
2267 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2268 InsertNewInstBefore(Add, IB);
2269 // Convert to unsigned for the comparison.
2270 const Type *UnsType = Add->getType()->getUnsignedVersion();
2271 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2272 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2273 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2274 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2277 if (Lo == Hi) // Trivially true.
2278 return new SetCondInst(Instruction::SetEQ, V, V);
2280 Hi = SubOne(cast<ConstantInt>(Hi));
2281 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2282 return new SetCondInst(Instruction::SetGT, V, Hi);
2284 // Emit X-Lo > Hi-Lo-1
2285 Constant *AddCST = ConstantExpr::getNeg(Lo);
2286 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2287 InsertNewInstBefore(Add, IB);
2288 // Convert to unsigned for the comparison.
2289 const Type *UnsType = Add->getType()->getUnsignedVersion();
2290 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2291 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2292 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2293 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2296 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2297 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2298 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2299 // not, since all 1s are not contiguous.
2300 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2301 uint64_t V = Val->getRawValue();
2302 if (!isShiftedMask_64(V)) return false;
2304 // look for the first zero bit after the run of ones
2305 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2306 // look for the first non-zero bit
2307 ME = 64-CountLeadingZeros_64(V);
2313 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2314 /// where isSub determines whether the operator is a sub. If we can fold one of
2315 /// the following xforms:
2317 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2318 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2319 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2321 /// return (A +/- B).
2323 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2324 ConstantIntegral *Mask, bool isSub,
2326 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2327 if (!LHSI || LHSI->getNumOperands() != 2 ||
2328 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2330 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2332 switch (LHSI->getOpcode()) {
2334 case Instruction::And:
2335 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2336 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2337 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2340 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2341 // part, we don't need any explicit masks to take them out of A. If that
2342 // is all N is, ignore it.
2344 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2345 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2347 if (MaskedValueIsZero(RHS, Mask))
2352 case Instruction::Or:
2353 case Instruction::Xor:
2354 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2355 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2356 ConstantExpr::getAnd(N, Mask)->isNullValue())
2363 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2365 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2366 return InsertNewInstBefore(New, I);
2369 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2370 bool Changed = SimplifyCommutative(I);
2371 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2373 if (isa<UndefValue>(Op1)) // X & undef -> 0
2374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2378 return ReplaceInstUsesWith(I, Op1);
2380 // See if we can simplify any instructions used by the instruction whose sole
2381 // purpose is to compute bits we don't care about.
2382 uint64_t KnownZero, KnownOne;
2383 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2384 KnownZero, KnownOne))
2387 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2388 uint64_t AndRHSMask = AndRHS->getZExtValue();
2389 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2390 uint64_t NotAndRHS = AndRHSMask^TypeMask;
2392 // Optimize a variety of ((val OP C1) & C2) combinations...
2393 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2394 Instruction *Op0I = cast<Instruction>(Op0);
2395 Value *Op0LHS = Op0I->getOperand(0);
2396 Value *Op0RHS = Op0I->getOperand(1);
2397 switch (Op0I->getOpcode()) {
2398 case Instruction::Xor:
2399 case Instruction::Or:
2400 // If the mask is only needed on one incoming arm, push it up.
2401 if (Op0I->hasOneUse()) {
2402 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2403 // Not masking anything out for the LHS, move to RHS.
2404 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2405 Op0RHS->getName()+".masked");
2406 InsertNewInstBefore(NewRHS, I);
2407 return BinaryOperator::create(
2408 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2410 if (!isa<Constant>(Op0RHS) &&
2411 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2412 // Not masking anything out for the RHS, move to LHS.
2413 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2414 Op0LHS->getName()+".masked");
2415 InsertNewInstBefore(NewLHS, I);
2416 return BinaryOperator::create(
2417 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2422 case Instruction::Add:
2423 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2424 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2425 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2426 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2427 return BinaryOperator::createAnd(V, AndRHS);
2428 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2429 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
2432 case Instruction::Sub:
2433 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2434 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2435 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2436 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2437 return BinaryOperator::createAnd(V, AndRHS);
2441 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2442 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2444 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2445 const Type *SrcTy = CI->getOperand(0)->getType();
2447 // If this is an integer truncation or change from signed-to-unsigned, and
2448 // if the source is an and/or with immediate, transform it. This
2449 // frequently occurs for bitfield accesses.
2450 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2451 if (SrcTy->getPrimitiveSizeInBits() >=
2452 I.getType()->getPrimitiveSizeInBits() &&
2453 CastOp->getNumOperands() == 2)
2454 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2455 if (CastOp->getOpcode() == Instruction::And) {
2456 // Change: and (cast (and X, C1) to T), C2
2457 // into : and (cast X to T), trunc(C1)&C2
2458 // This will folds the two ands together, which may allow other
2460 Instruction *NewCast =
2461 new CastInst(CastOp->getOperand(0), I.getType(),
2462 CastOp->getName()+".shrunk");
2463 NewCast = InsertNewInstBefore(NewCast, I);
2465 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2466 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2467 return BinaryOperator::createAnd(NewCast, C3);
2468 } else if (CastOp->getOpcode() == Instruction::Or) {
2469 // Change: and (cast (or X, C1) to T), C2
2470 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2471 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2472 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2473 return ReplaceInstUsesWith(I, AndRHS);
2478 // Try to fold constant and into select arguments.
2479 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2480 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2482 if (isa<PHINode>(Op0))
2483 if (Instruction *NV = FoldOpIntoPhi(I))
2487 Value *Op0NotVal = dyn_castNotVal(Op0);
2488 Value *Op1NotVal = dyn_castNotVal(Op1);
2490 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2491 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2493 // (~A & ~B) == (~(A | B)) - De Morgan's Law
2494 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2495 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2496 I.getName()+".demorgan");
2497 InsertNewInstBefore(Or, I);
2498 return BinaryOperator::createNot(Or);
2502 Value *A = 0, *B = 0;
2503 ConstantInt *C1 = 0, *C2 = 0;
2504 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2505 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2506 return ReplaceInstUsesWith(I, Op1);
2507 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2508 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2509 return ReplaceInstUsesWith(I, Op0);
2513 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2514 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2515 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2518 Value *LHSVal, *RHSVal;
2519 ConstantInt *LHSCst, *RHSCst;
2520 Instruction::BinaryOps LHSCC, RHSCC;
2521 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2522 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2523 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2524 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2525 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2526 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2527 // Ensure that the larger constant is on the RHS.
2528 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2529 SetCondInst *LHS = cast<SetCondInst>(Op0);
2530 if (cast<ConstantBool>(Cmp)->getValue()) {
2531 std::swap(LHS, RHS);
2532 std::swap(LHSCst, RHSCst);
2533 std::swap(LHSCC, RHSCC);
2536 // At this point, we know we have have two setcc instructions
2537 // comparing a value against two constants and and'ing the result
2538 // together. Because of the above check, we know that we only have
2539 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2540 // FoldSetCCLogical check above), that the two constants are not
2542 assert(LHSCst != RHSCst && "Compares not folded above?");
2545 default: assert(0 && "Unknown integer condition code!");
2546 case Instruction::SetEQ:
2548 default: assert(0 && "Unknown integer condition code!");
2549 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2550 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2551 return ReplaceInstUsesWith(I, ConstantBool::False);
2552 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2553 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2554 return ReplaceInstUsesWith(I, LHS);
2556 case Instruction::SetNE:
2558 default: assert(0 && "Unknown integer condition code!");
2559 case Instruction::SetLT:
2560 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2561 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2562 break; // (X != 13 & X < 15) -> no change
2563 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2564 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2565 return ReplaceInstUsesWith(I, RHS);
2566 case Instruction::SetNE:
2567 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2568 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2569 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2570 LHSVal->getName()+".off");
2571 InsertNewInstBefore(Add, I);
2572 const Type *UnsType = Add->getType()->getUnsignedVersion();
2573 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2574 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2575 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2576 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2578 break; // (X != 13 & X != 15) -> no change
2581 case Instruction::SetLT:
2583 default: assert(0 && "Unknown integer condition code!");
2584 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2585 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2586 return ReplaceInstUsesWith(I, ConstantBool::False);
2587 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2588 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2589 return ReplaceInstUsesWith(I, LHS);
2591 case Instruction::SetGT:
2593 default: assert(0 && "Unknown integer condition code!");
2594 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2595 return ReplaceInstUsesWith(I, LHS);
2596 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2597 return ReplaceInstUsesWith(I, RHS);
2598 case Instruction::SetNE:
2599 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2600 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2601 break; // (X > 13 & X != 15) -> no change
2602 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2603 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2609 return Changed ? &I : 0;
2612 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2613 bool Changed = SimplifyCommutative(I);
2614 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2616 if (isa<UndefValue>(Op1))
2617 return ReplaceInstUsesWith(I, // X | undef -> -1
2618 ConstantIntegral::getAllOnesValue(I.getType()));
2622 return ReplaceInstUsesWith(I, Op0);
2624 // See if we can simplify any instructions used by the instruction whose sole
2625 // purpose is to compute bits we don't care about.
2626 uint64_t KnownZero, KnownOne;
2627 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2628 KnownZero, KnownOne))
2632 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2633 ConstantInt *C1 = 0; Value *X = 0;
2634 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2635 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2636 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2638 InsertNewInstBefore(Or, I);
2639 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2642 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2643 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2644 std::string Op0Name = Op0->getName(); Op0->setName("");
2645 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2646 InsertNewInstBefore(Or, I);
2647 return BinaryOperator::createXor(Or,
2648 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2651 // Try to fold constant and into select arguments.
2652 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2653 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2655 if (isa<PHINode>(Op0))
2656 if (Instruction *NV = FoldOpIntoPhi(I))
2660 Value *A = 0, *B = 0;
2661 ConstantInt *C1 = 0, *C2 = 0;
2663 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2664 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2665 return ReplaceInstUsesWith(I, Op1);
2666 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2667 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2668 return ReplaceInstUsesWith(I, Op0);
2670 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2671 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2672 MaskedValueIsZero(Op1, C1->getZExtValue())) {
2673 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2675 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2678 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2679 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2680 MaskedValueIsZero(Op0, C1->getZExtValue())) {
2681 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2683 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2686 // (A & C1)|(B & C2)
2687 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2688 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2690 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2691 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2694 // If we have: ((V + N) & C1) | (V & C2)
2695 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2696 // replace with V+N.
2697 if (C1 == ConstantExpr::getNot(C2)) {
2698 Value *V1 = 0, *V2 = 0;
2699 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2700 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2701 // Add commutes, try both ways.
2702 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
2703 return ReplaceInstUsesWith(I, A);
2704 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
2705 return ReplaceInstUsesWith(I, A);
2707 // Or commutes, try both ways.
2708 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2709 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2710 // Add commutes, try both ways.
2711 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
2712 return ReplaceInstUsesWith(I, B);
2713 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
2714 return ReplaceInstUsesWith(I, B);
2719 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2720 if (A == Op1) // ~A | A == -1
2721 return ReplaceInstUsesWith(I,
2722 ConstantIntegral::getAllOnesValue(I.getType()));
2726 // Note, A is still live here!
2727 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2729 return ReplaceInstUsesWith(I,
2730 ConstantIntegral::getAllOnesValue(I.getType()));
2732 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2733 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2734 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2735 I.getName()+".demorgan"), I);
2736 return BinaryOperator::createNot(And);
2740 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2741 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2742 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2745 Value *LHSVal, *RHSVal;
2746 ConstantInt *LHSCst, *RHSCst;
2747 Instruction::BinaryOps LHSCC, RHSCC;
2748 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2749 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2750 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2751 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2752 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2753 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2754 // Ensure that the larger constant is on the RHS.
2755 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2756 SetCondInst *LHS = cast<SetCondInst>(Op0);
2757 if (cast<ConstantBool>(Cmp)->getValue()) {
2758 std::swap(LHS, RHS);
2759 std::swap(LHSCst, RHSCst);
2760 std::swap(LHSCC, RHSCC);
2763 // At this point, we know we have have two setcc instructions
2764 // comparing a value against two constants and or'ing the result
2765 // together. Because of the above check, we know that we only have
2766 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2767 // FoldSetCCLogical check above), that the two constants are not
2769 assert(LHSCst != RHSCst && "Compares not folded above?");
2772 default: assert(0 && "Unknown integer condition code!");
2773 case Instruction::SetEQ:
2775 default: assert(0 && "Unknown integer condition code!");
2776 case Instruction::SetEQ:
2777 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2778 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2779 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2780 LHSVal->getName()+".off");
2781 InsertNewInstBefore(Add, I);
2782 const Type *UnsType = Add->getType()->getUnsignedVersion();
2783 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2784 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2785 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2786 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2788 break; // (X == 13 | X == 15) -> no change
2790 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2792 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2793 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2794 return ReplaceInstUsesWith(I, RHS);
2797 case Instruction::SetNE:
2799 default: assert(0 && "Unknown integer condition code!");
2800 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2801 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2802 return ReplaceInstUsesWith(I, LHS);
2803 case Instruction::SetNE: // (X != 13 | X != 15) -> true
2804 case Instruction::SetLT: // (X != 13 | X < 15) -> true
2805 return ReplaceInstUsesWith(I, ConstantBool::True);
2808 case Instruction::SetLT:
2810 default: assert(0 && "Unknown integer condition code!");
2811 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2813 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2814 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2815 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2816 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2817 return ReplaceInstUsesWith(I, RHS);
2820 case Instruction::SetGT:
2822 default: assert(0 && "Unknown integer condition code!");
2823 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2824 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2825 return ReplaceInstUsesWith(I, LHS);
2826 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2827 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2828 return ReplaceInstUsesWith(I, ConstantBool::True);
2834 return Changed ? &I : 0;
2837 // XorSelf - Implements: X ^ X --> 0
2840 XorSelf(Value *rhs) : RHS(rhs) {}
2841 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2842 Instruction *apply(BinaryOperator &Xor) const {
2848 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2849 bool Changed = SimplifyCommutative(I);
2850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2852 if (isa<UndefValue>(Op1))
2853 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2855 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2856 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2857 assert(Result == &I && "AssociativeOpt didn't work?");
2858 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2861 // See if we can simplify any instructions used by the instruction whose sole
2862 // purpose is to compute bits we don't care about.
2863 uint64_t KnownZero, KnownOne;
2864 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2865 KnownZero, KnownOne))
2868 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2869 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2870 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2871 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2872 if (RHS == ConstantBool::True && SCI->hasOneUse())
2873 return new SetCondInst(SCI->getInverseCondition(),
2874 SCI->getOperand(0), SCI->getOperand(1));
2876 // ~(c-X) == X-c-1 == X+(-c-1)
2877 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2878 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2879 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2880 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2881 ConstantInt::get(I.getType(), 1));
2882 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2885 // ~(~X & Y) --> (X | ~Y)
2886 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2887 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2888 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2890 BinaryOperator::createNot(Op0I->getOperand(1),
2891 Op0I->getOperand(1)->getName()+".not");
2892 InsertNewInstBefore(NotY, I);
2893 return BinaryOperator::createOr(Op0NotVal, NotY);
2897 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2898 if (Op0I->getOpcode() == Instruction::Add) {
2899 // ~(X-c) --> (-c-1)-X
2900 if (RHS->isAllOnesValue()) {
2901 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2902 return BinaryOperator::createSub(
2903 ConstantExpr::getSub(NegOp0CI,
2904 ConstantInt::get(I.getType(), 1)),
2905 Op0I->getOperand(0));
2907 } else if (Op0I->getOpcode() == Instruction::Or) {
2908 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2909 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2910 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2911 // Anything in both C1 and C2 is known to be zero, remove it from
2913 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2914 NewRHS = ConstantExpr::getAnd(NewRHS,
2915 ConstantExpr::getNot(CommonBits));
2916 WorkList.push_back(Op0I);
2917 I.setOperand(0, Op0I->getOperand(0));
2918 I.setOperand(1, NewRHS);
2924 // Try to fold constant and into select arguments.
2925 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2926 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2928 if (isa<PHINode>(Op0))
2929 if (Instruction *NV = FoldOpIntoPhi(I))
2933 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
2935 return ReplaceInstUsesWith(I,
2936 ConstantIntegral::getAllOnesValue(I.getType()));
2938 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
2940 return ReplaceInstUsesWith(I,
2941 ConstantIntegral::getAllOnesValue(I.getType()));
2943 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
2944 if (Op1I->getOpcode() == Instruction::Or) {
2945 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2946 cast<BinaryOperator>(Op1I)->swapOperands();
2948 std::swap(Op0, Op1);
2949 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2951 std::swap(Op0, Op1);
2953 } else if (Op1I->getOpcode() == Instruction::Xor) {
2954 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2955 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2956 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2957 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2960 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
2961 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
2962 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2963 cast<BinaryOperator>(Op0I)->swapOperands();
2964 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
2965 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2966 Op1->getName()+".not"), I);
2967 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
2969 } else if (Op0I->getOpcode() == Instruction::Xor) {
2970 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2971 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2972 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2973 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2976 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2977 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2978 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2981 return Changed ? &I : 0;
2984 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2985 /// overflowed for this type.
2986 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2988 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2989 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2992 static bool isPositive(ConstantInt *C) {
2993 return cast<ConstantSInt>(C)->getValue() >= 0;
2996 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2997 /// overflowed for this type.
2998 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3000 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3002 if (In1->getType()->isUnsigned())
3003 return cast<ConstantUInt>(Result)->getValue() <
3004 cast<ConstantUInt>(In1)->getValue();
3005 if (isPositive(In1) != isPositive(In2))
3007 if (isPositive(In1))
3008 return cast<ConstantSInt>(Result)->getValue() <
3009 cast<ConstantSInt>(In1)->getValue();
3010 return cast<ConstantSInt>(Result)->getValue() >
3011 cast<ConstantSInt>(In1)->getValue();
3014 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3015 /// code necessary to compute the offset from the base pointer (without adding
3016 /// in the base pointer). Return the result as a signed integer of intptr size.
3017 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3018 TargetData &TD = IC.getTargetData();
3019 gep_type_iterator GTI = gep_type_begin(GEP);
3020 const Type *UIntPtrTy = TD.getIntPtrType();
3021 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3022 Value *Result = Constant::getNullValue(SIntPtrTy);
3024 // Build a mask for high order bits.
3025 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3027 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3028 Value *Op = GEP->getOperand(i);
3029 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3030 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3032 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3033 if (!OpC->isNullValue()) {
3034 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3035 Scale = ConstantExpr::getMul(OpC, Scale);
3036 if (Constant *RC = dyn_cast<Constant>(Result))
3037 Result = ConstantExpr::getAdd(RC, Scale);
3039 // Emit an add instruction.
3040 Result = IC.InsertNewInstBefore(
3041 BinaryOperator::createAdd(Result, Scale,
3042 GEP->getName()+".offs"), I);
3046 // Convert to correct type.
3047 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3048 Op->getName()+".c"), I);
3050 // We'll let instcombine(mul) convert this to a shl if possible.
3051 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3052 GEP->getName()+".idx"), I);
3054 // Emit an add instruction.
3055 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3056 GEP->getName()+".offs"), I);
3062 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3063 /// else. At this point we know that the GEP is on the LHS of the comparison.
3064 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3065 Instruction::BinaryOps Cond,
3067 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3069 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3070 if (isa<PointerType>(CI->getOperand(0)->getType()))
3071 RHS = CI->getOperand(0);
3073 Value *PtrBase = GEPLHS->getOperand(0);
3074 if (PtrBase == RHS) {
3075 // As an optimization, we don't actually have to compute the actual value of
3076 // OFFSET if this is a seteq or setne comparison, just return whether each
3077 // index is zero or not.
3078 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3079 Instruction *InVal = 0;
3080 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3081 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3083 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3084 if (isa<UndefValue>(C)) // undef index -> undef.
3085 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3086 if (C->isNullValue())
3088 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3089 EmitIt = false; // This is indexing into a zero sized array?
3090 } else if (isa<ConstantInt>(C))
3091 return ReplaceInstUsesWith(I, // No comparison is needed here.
3092 ConstantBool::get(Cond == Instruction::SetNE));
3097 new SetCondInst(Cond, GEPLHS->getOperand(i),
3098 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3102 InVal = InsertNewInstBefore(InVal, I);
3103 InsertNewInstBefore(Comp, I);
3104 if (Cond == Instruction::SetNE) // True if any are unequal
3105 InVal = BinaryOperator::createOr(InVal, Comp);
3106 else // True if all are equal
3107 InVal = BinaryOperator::createAnd(InVal, Comp);
3115 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3116 ConstantBool::get(Cond == Instruction::SetEQ));
3119 // Only lower this if the setcc is the only user of the GEP or if we expect
3120 // the result to fold to a constant!
3121 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3122 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3123 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3124 return new SetCondInst(Cond, Offset,
3125 Constant::getNullValue(Offset->getType()));
3127 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3128 // If the base pointers are different, but the indices are the same, just
3129 // compare the base pointer.
3130 if (PtrBase != GEPRHS->getOperand(0)) {
3131 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3132 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3133 GEPRHS->getOperand(0)->getType();
3135 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3136 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3137 IndicesTheSame = false;
3141 // If all indices are the same, just compare the base pointers.
3143 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3144 GEPRHS->getOperand(0));
3146 // Otherwise, the base pointers are different and the indices are
3147 // different, bail out.
3151 // If one of the GEPs has all zero indices, recurse.
3152 bool AllZeros = true;
3153 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3154 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3155 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3160 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3161 SetCondInst::getSwappedCondition(Cond), I);
3163 // If the other GEP has all zero indices, recurse.
3165 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3166 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3167 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3172 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3174 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3175 // If the GEPs only differ by one index, compare it.
3176 unsigned NumDifferences = 0; // Keep track of # differences.
3177 unsigned DiffOperand = 0; // The operand that differs.
3178 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3179 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3180 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3181 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3182 // Irreconcilable differences.
3186 if (NumDifferences++) break;
3191 if (NumDifferences == 0) // SAME GEP?
3192 return ReplaceInstUsesWith(I, // No comparison is needed here.
3193 ConstantBool::get(Cond == Instruction::SetEQ));
3194 else if (NumDifferences == 1) {
3195 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3196 Value *RHSV = GEPRHS->getOperand(DiffOperand);
3198 // Convert the operands to signed values to make sure to perform a
3199 // signed comparison.
3200 const Type *NewTy = LHSV->getType()->getSignedVersion();
3201 if (LHSV->getType() != NewTy)
3202 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3203 LHSV->getName()), I);
3204 if (RHSV->getType() != NewTy)
3205 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3206 RHSV->getName()), I);
3207 return new SetCondInst(Cond, LHSV, RHSV);
3211 // Only lower this if the setcc is the only user of the GEP or if we expect
3212 // the result to fold to a constant!
3213 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3214 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3215 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3216 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3217 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3218 return new SetCondInst(Cond, L, R);
3225 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3226 bool Changed = SimplifyCommutative(I);
3227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3228 const Type *Ty = Op0->getType();
3232 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3234 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3235 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3237 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3238 // addresses never equal each other! We already know that Op0 != Op1.
3239 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3240 isa<ConstantPointerNull>(Op0)) &&
3241 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3242 isa<ConstantPointerNull>(Op1)))
3243 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3245 // setcc's with boolean values can always be turned into bitwise operations
3246 if (Ty == Type::BoolTy) {
3247 switch (I.getOpcode()) {
3248 default: assert(0 && "Invalid setcc instruction!");
3249 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
3250 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3251 InsertNewInstBefore(Xor, I);
3252 return BinaryOperator::createNot(Xor);
3254 case Instruction::SetNE:
3255 return BinaryOperator::createXor(Op0, Op1);
3257 case Instruction::SetGT:
3258 std::swap(Op0, Op1); // Change setgt -> setlt
3260 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3261 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3262 InsertNewInstBefore(Not, I);
3263 return BinaryOperator::createAnd(Not, Op1);
3265 case Instruction::SetGE:
3266 std::swap(Op0, Op1); // Change setge -> setle
3268 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3269 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3270 InsertNewInstBefore(Not, I);
3271 return BinaryOperator::createOr(Not, Op1);
3276 // See if we are doing a comparison between a constant and an instruction that
3277 // can be folded into the comparison.
3278 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3279 // Check to see if we are comparing against the minimum or maximum value...
3280 if (CI->isMinValue()) {
3281 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3282 return ReplaceInstUsesWith(I, ConstantBool::False);
3283 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3284 return ReplaceInstUsesWith(I, ConstantBool::True);
3285 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3286 return BinaryOperator::createSetEQ(Op0, Op1);
3287 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3288 return BinaryOperator::createSetNE(Op0, Op1);
3290 } else if (CI->isMaxValue()) {
3291 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3292 return ReplaceInstUsesWith(I, ConstantBool::False);
3293 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3294 return ReplaceInstUsesWith(I, ConstantBool::True);
3295 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3296 return BinaryOperator::createSetEQ(Op0, Op1);
3297 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3298 return BinaryOperator::createSetNE(Op0, Op1);
3300 // Comparing against a value really close to min or max?
3301 } else if (isMinValuePlusOne(CI)) {
3302 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3303 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3304 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3305 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3307 } else if (isMaxValueMinusOne(CI)) {
3308 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3309 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3310 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3311 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3314 // If we still have a setle or setge instruction, turn it into the
3315 // appropriate setlt or setgt instruction. Since the border cases have
3316 // already been handled above, this requires little checking.
3318 if (I.getOpcode() == Instruction::SetLE)
3319 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3320 if (I.getOpcode() == Instruction::SetGE)
3321 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3324 // See if we can fold the comparison based on bits known to be zero or one
3326 uint64_t KnownZero, KnownOne;
3327 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3328 KnownZero, KnownOne, 0))
3331 // Given the known and unknown bits, compute a range that the LHS could be
3333 if (KnownOne | KnownZero) {
3334 if (Ty->isUnsigned()) { // Unsigned comparison.
3336 uint64_t RHSVal = CI->getZExtValue();
3337 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3339 switch (I.getOpcode()) { // LE/GE have been folded already.
3340 default: assert(0 && "Unknown setcc opcode!");
3341 case Instruction::SetEQ:
3342 if (Max < RHSVal || Min > RHSVal)
3343 return ReplaceInstUsesWith(I, ConstantBool::False);
3345 case Instruction::SetNE:
3346 if (Max < RHSVal || Min > RHSVal)
3347 return ReplaceInstUsesWith(I, ConstantBool::True);
3349 case Instruction::SetLT:
3350 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3351 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3353 case Instruction::SetGT:
3354 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3355 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3358 } else { // Signed comparison.
3360 int64_t RHSVal = CI->getSExtValue();
3361 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3363 switch (I.getOpcode()) { // LE/GE have been folded already.
3364 default: assert(0 && "Unknown setcc opcode!");
3365 case Instruction::SetEQ:
3366 if (Max < RHSVal || Min > RHSVal)
3367 return ReplaceInstUsesWith(I, ConstantBool::False);
3369 case Instruction::SetNE:
3370 if (Max < RHSVal || Min > RHSVal)
3371 return ReplaceInstUsesWith(I, ConstantBool::True);
3373 case Instruction::SetLT:
3374 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3375 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3377 case Instruction::SetGT:
3378 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3379 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3386 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3387 switch (LHSI->getOpcode()) {
3388 case Instruction::And:
3389 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3390 LHSI->getOperand(0)->hasOneUse()) {
3391 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3392 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3393 // happens a LOT in code produced by the C front-end, for bitfield
3395 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
3396 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3398 // Check to see if there is a noop-cast between the shift and the and.
3400 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3401 if (CI->getOperand(0)->getType()->isIntegral() &&
3402 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3403 CI->getType()->getPrimitiveSizeInBits())
3404 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3407 ConstantUInt *ShAmt;
3408 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
3409 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3410 const Type *AndTy = AndCST->getType(); // Type of the and.
3412 // We can fold this as long as we can't shift unknown bits
3413 // into the mask. This can only happen with signed shift
3414 // rights, as they sign-extend.
3416 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
3419 // To test for the bad case of the signed shr, see if any
3420 // of the bits shifted in could be tested after the mask.
3421 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3422 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3424 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
3426 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3428 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3434 if (Shift->getOpcode() == Instruction::Shl)
3435 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3437 NewCst = ConstantExpr::getShl(CI, ShAmt);
3439 // Check to see if we are shifting out any of the bits being
3441 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3442 // If we shifted bits out, the fold is not going to work out.
3443 // As a special case, check to see if this means that the
3444 // result is always true or false now.
3445 if (I.getOpcode() == Instruction::SetEQ)
3446 return ReplaceInstUsesWith(I, ConstantBool::False);
3447 if (I.getOpcode() == Instruction::SetNE)
3448 return ReplaceInstUsesWith(I, ConstantBool::True);
3450 I.setOperand(1, NewCst);
3451 Constant *NewAndCST;
3452 if (Shift->getOpcode() == Instruction::Shl)
3453 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3455 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3456 LHSI->setOperand(1, NewAndCST);
3458 LHSI->setOperand(0, Shift->getOperand(0));
3460 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3462 LHSI->setOperand(0, NewCast);
3464 WorkList.push_back(Shift); // Shift is dead.
3465 AddUsesToWorkList(I);
3473 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3474 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3475 switch (I.getOpcode()) {
3477 case Instruction::SetEQ:
3478 case Instruction::SetNE: {
3479 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3481 // Check that the shift amount is in range. If not, don't perform
3482 // undefined shifts. When the shift is visited it will be
3484 if (ShAmt->getValue() >= TypeBits)
3487 // If we are comparing against bits always shifted out, the
3488 // comparison cannot succeed.
3490 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3491 if (Comp != CI) {// Comparing against a bit that we know is zero.
3492 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3493 Constant *Cst = ConstantBool::get(IsSetNE);
3494 return ReplaceInstUsesWith(I, Cst);
3497 if (LHSI->hasOneUse()) {
3498 // Otherwise strength reduce the shift into an and.
3499 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3500 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3503 if (CI->getType()->isUnsigned()) {
3504 Mask = ConstantUInt::get(CI->getType(), Val);
3505 } else if (ShAmtVal != 0) {
3506 Mask = ConstantSInt::get(CI->getType(), Val);
3508 Mask = ConstantInt::getAllOnesValue(CI->getType());
3512 BinaryOperator::createAnd(LHSI->getOperand(0),
3513 Mask, LHSI->getName()+".mask");
3514 Value *And = InsertNewInstBefore(AndI, I);
3515 return new SetCondInst(I.getOpcode(), And,
3516 ConstantExpr::getUShr(CI, ShAmt));
3523 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
3524 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3525 switch (I.getOpcode()) {
3527 case Instruction::SetEQ:
3528 case Instruction::SetNE: {
3530 // Check that the shift amount is in range. If not, don't perform
3531 // undefined shifts. When the shift is visited it will be
3533 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3534 if (ShAmt->getValue() >= TypeBits)
3537 // If we are comparing against bits always shifted out, the
3538 // comparison cannot succeed.
3540 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
3542 if (Comp != CI) {// Comparing against a bit that we know is zero.
3543 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3544 Constant *Cst = ConstantBool::get(IsSetNE);
3545 return ReplaceInstUsesWith(I, Cst);
3548 if (LHSI->hasOneUse() || CI->isNullValue()) {
3549 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3551 // Otherwise strength reduce the shift into an and.
3552 uint64_t Val = ~0ULL; // All ones.
3553 Val <<= ShAmtVal; // Shift over to the right spot.
3556 if (CI->getType()->isUnsigned()) {
3557 Val &= ~0ULL >> (64-TypeBits);
3558 Mask = ConstantUInt::get(CI->getType(), Val);
3560 Mask = ConstantSInt::get(CI->getType(), Val);
3564 BinaryOperator::createAnd(LHSI->getOperand(0),
3565 Mask, LHSI->getName()+".mask");
3566 Value *And = InsertNewInstBefore(AndI, I);
3567 return new SetCondInst(I.getOpcode(), And,
3568 ConstantExpr::getShl(CI, ShAmt));
3576 case Instruction::Div:
3577 // Fold: (div X, C1) op C2 -> range check
3578 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3579 // Fold this div into the comparison, producing a range check.
3580 // Determine, based on the divide type, what the range is being
3581 // checked. If there is an overflow on the low or high side, remember
3582 // it, otherwise compute the range [low, hi) bounding the new value.
3583 bool LoOverflow = false, HiOverflow = 0;
3584 ConstantInt *LoBound = 0, *HiBound = 0;
3587 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3589 Instruction::BinaryOps Opcode = I.getOpcode();
3591 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3592 } else if (LHSI->getType()->isUnsigned()) { // udiv
3594 LoOverflow = ProdOV;
3595 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3596 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3597 if (CI->isNullValue()) { // (X / pos) op 0
3599 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3601 } else if (isPositive(CI)) { // (X / pos) op pos
3603 LoOverflow = ProdOV;
3604 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3605 } else { // (X / pos) op neg
3606 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3607 LoOverflow = AddWithOverflow(LoBound, Prod,
3608 cast<ConstantInt>(DivRHSH));
3610 HiOverflow = ProdOV;
3612 } else { // Divisor is < 0.
3613 if (CI->isNullValue()) { // (X / neg) op 0
3614 LoBound = AddOne(DivRHS);
3615 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
3616 if (HiBound == DivRHS)
3617 LoBound = 0; // - INTMIN = INTMIN
3618 } else if (isPositive(CI)) { // (X / neg) op pos
3619 HiOverflow = LoOverflow = ProdOV;
3621 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3622 HiBound = AddOne(Prod);
3623 } else { // (X / neg) op neg
3625 LoOverflow = HiOverflow = ProdOV;
3626 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3629 // Dividing by a negate swaps the condition.
3630 Opcode = SetCondInst::getSwappedCondition(Opcode);
3634 Value *X = LHSI->getOperand(0);
3636 default: assert(0 && "Unhandled setcc opcode!");
3637 case Instruction::SetEQ:
3638 if (LoOverflow && HiOverflow)
3639 return ReplaceInstUsesWith(I, ConstantBool::False);
3640 else if (HiOverflow)
3641 return new SetCondInst(Instruction::SetGE, X, LoBound);
3642 else if (LoOverflow)
3643 return new SetCondInst(Instruction::SetLT, X, HiBound);
3645 return InsertRangeTest(X, LoBound, HiBound, true, I);
3646 case Instruction::SetNE:
3647 if (LoOverflow && HiOverflow)
3648 return ReplaceInstUsesWith(I, ConstantBool::True);
3649 else if (HiOverflow)
3650 return new SetCondInst(Instruction::SetLT, X, LoBound);
3651 else if (LoOverflow)
3652 return new SetCondInst(Instruction::SetGE, X, HiBound);
3654 return InsertRangeTest(X, LoBound, HiBound, false, I);
3655 case Instruction::SetLT:
3657 return ReplaceInstUsesWith(I, ConstantBool::False);
3658 return new SetCondInst(Instruction::SetLT, X, LoBound);
3659 case Instruction::SetGT:
3661 return ReplaceInstUsesWith(I, ConstantBool::False);
3662 return new SetCondInst(Instruction::SetGE, X, HiBound);
3669 // Simplify seteq and setne instructions...
3670 if (I.getOpcode() == Instruction::SetEQ ||
3671 I.getOpcode() == Instruction::SetNE) {
3672 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3674 // If the first operand is (and|or|xor) with a constant, and the second
3675 // operand is a constant, simplify a bit.
3676 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3677 switch (BO->getOpcode()) {
3678 case Instruction::Rem:
3679 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3680 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3682 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3683 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3684 if (isPowerOf2_64(V)) {
3685 unsigned L2 = Log2_64(V);
3686 const Type *UTy = BO->getType()->getUnsignedVersion();
3687 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3689 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3690 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3691 RHSCst, BO->getName()), I);
3692 return BinaryOperator::create(I.getOpcode(), NewRem,
3693 Constant::getNullValue(UTy));
3698 case Instruction::Add:
3699 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3700 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3701 if (BO->hasOneUse())
3702 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3703 ConstantExpr::getSub(CI, BOp1C));
3704 } else if (CI->isNullValue()) {
3705 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3706 // efficiently invertible, or if the add has just this one use.
3707 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3709 if (Value *NegVal = dyn_castNegVal(BOp1))
3710 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3711 else if (Value *NegVal = dyn_castNegVal(BOp0))
3712 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3713 else if (BO->hasOneUse()) {
3714 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3716 InsertNewInstBefore(Neg, I);
3717 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3721 case Instruction::Xor:
3722 // For the xor case, we can xor two constants together, eliminating
3723 // the explicit xor.
3724 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3725 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3726 ConstantExpr::getXor(CI, BOC));
3729 case Instruction::Sub:
3730 // Replace (([sub|xor] A, B) != 0) with (A != B)
3731 if (CI->isNullValue())
3732 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3736 case Instruction::Or:
3737 // If bits are being or'd in that are not present in the constant we
3738 // are comparing against, then the comparison could never succeed!
3739 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3740 Constant *NotCI = ConstantExpr::getNot(CI);
3741 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3742 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3746 case Instruction::And:
3747 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3748 // If bits are being compared against that are and'd out, then the
3749 // comparison can never succeed!
3750 if (!ConstantExpr::getAnd(CI,
3751 ConstantExpr::getNot(BOC))->isNullValue())
3752 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3754 // If we have ((X & C) == C), turn it into ((X & C) != 0).
3755 if (CI == BOC && isOneBitSet(CI))
3756 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3757 Instruction::SetNE, Op0,
3758 Constant::getNullValue(CI->getType()));
3760 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3761 // to be a signed value as appropriate.
3762 if (isSignBit(BOC)) {
3763 Value *X = BO->getOperand(0);
3764 // If 'X' is not signed, insert a cast now...
3765 if (!BOC->getType()->isSigned()) {
3766 const Type *DestTy = BOC->getType()->getSignedVersion();
3767 X = InsertCastBefore(X, DestTy, I);
3769 return new SetCondInst(isSetNE ? Instruction::SetLT :
3770 Instruction::SetGE, X,
3771 Constant::getNullValue(X->getType()));
3774 // ((X & ~7) == 0) --> X < 8
3775 if (CI->isNullValue() && isHighOnes(BOC)) {
3776 Value *X = BO->getOperand(0);
3777 Constant *NegX = ConstantExpr::getNeg(BOC);
3779 // If 'X' is signed, insert a cast now.
3780 if (NegX->getType()->isSigned()) {
3781 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3782 X = InsertCastBefore(X, DestTy, I);
3783 NegX = ConstantExpr::getCast(NegX, DestTy);
3786 return new SetCondInst(isSetNE ? Instruction::SetGE :
3787 Instruction::SetLT, X, NegX);
3794 } else { // Not a SetEQ/SetNE
3795 // If the LHS is a cast from an integral value of the same size,
3796 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3797 Value *CastOp = Cast->getOperand(0);
3798 const Type *SrcTy = CastOp->getType();
3799 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3800 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3801 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3802 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3803 "Source and destination signednesses should differ!");
3804 if (Cast->getType()->isSigned()) {
3805 // If this is a signed comparison, check for comparisons in the
3806 // vicinity of zero.
3807 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3809 return BinaryOperator::createSetGT(CastOp,
3810 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3811 else if (I.getOpcode() == Instruction::SetGT &&
3812 cast<ConstantSInt>(CI)->getValue() == -1)
3813 // X > -1 => x < 128
3814 return BinaryOperator::createSetLT(CastOp,
3815 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3817 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3818 if (I.getOpcode() == Instruction::SetLT &&
3819 CUI->getValue() == 1ULL << (SrcTySize-1))
3820 // X < 128 => X > -1
3821 return BinaryOperator::createSetGT(CastOp,
3822 ConstantSInt::get(SrcTy, -1));
3823 else if (I.getOpcode() == Instruction::SetGT &&
3824 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3826 return BinaryOperator::createSetLT(CastOp,
3827 Constant::getNullValue(SrcTy));
3834 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3835 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3836 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3837 switch (LHSI->getOpcode()) {
3838 case Instruction::GetElementPtr:
3839 if (RHSC->isNullValue()) {
3840 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3841 bool isAllZeros = true;
3842 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3843 if (!isa<Constant>(LHSI->getOperand(i)) ||
3844 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3849 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3850 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3854 case Instruction::PHI:
3855 if (Instruction *NV = FoldOpIntoPhi(I))
3858 case Instruction::Select:
3859 // If either operand of the select is a constant, we can fold the
3860 // comparison into the select arms, which will cause one to be
3861 // constant folded and the select turned into a bitwise or.
3862 Value *Op1 = 0, *Op2 = 0;
3863 if (LHSI->hasOneUse()) {
3864 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3865 // Fold the known value into the constant operand.
3866 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3867 // Insert a new SetCC of the other select operand.
3868 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3869 LHSI->getOperand(2), RHSC,
3871 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3872 // Fold the known value into the constant operand.
3873 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3874 // Insert a new SetCC of the other select operand.
3875 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3876 LHSI->getOperand(1), RHSC,
3882 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3887 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3888 if (User *GEP = dyn_castGetElementPtr(Op0))
3889 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3891 if (User *GEP = dyn_castGetElementPtr(Op1))
3892 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3893 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3896 // Test to see if the operands of the setcc are casted versions of other
3897 // values. If the cast can be stripped off both arguments, we do so now.
3898 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3899 Value *CastOp0 = CI->getOperand(0);
3900 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3901 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3902 (I.getOpcode() == Instruction::SetEQ ||
3903 I.getOpcode() == Instruction::SetNE)) {
3904 // We keep moving the cast from the left operand over to the right
3905 // operand, where it can often be eliminated completely.
3908 // If operand #1 is a cast instruction, see if we can eliminate it as
3910 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3911 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3913 Op1 = CI2->getOperand(0);
3915 // If Op1 is a constant, we can fold the cast into the constant.
3916 if (Op1->getType() != Op0->getType())
3917 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3918 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3920 // Otherwise, cast the RHS right before the setcc
3921 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3922 InsertNewInstBefore(cast<Instruction>(Op1), I);
3924 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3927 // Handle the special case of: setcc (cast bool to X), <cst>
3928 // This comes up when you have code like
3931 // For generality, we handle any zero-extension of any operand comparison
3932 // with a constant or another cast from the same type.
3933 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3934 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3938 if (I.getOpcode() == Instruction::SetNE ||
3939 I.getOpcode() == Instruction::SetEQ) {
3941 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3942 (A == Op1 || B == Op1)) {
3943 // (A^B) == A -> B == 0
3944 Value *OtherVal = A == Op1 ? B : A;
3945 return BinaryOperator::create(I.getOpcode(), OtherVal,
3946 Constant::getNullValue(A->getType()));
3947 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3948 (A == Op0 || B == Op0)) {
3949 // A == (A^B) -> B == 0
3950 Value *OtherVal = A == Op0 ? B : A;
3951 return BinaryOperator::create(I.getOpcode(), OtherVal,
3952 Constant::getNullValue(A->getType()));
3953 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
3954 // (A-B) == A -> B == 0
3955 return BinaryOperator::create(I.getOpcode(), B,
3956 Constant::getNullValue(B->getType()));
3957 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
3958 // A == (A-B) -> B == 0
3959 return BinaryOperator::create(I.getOpcode(), B,
3960 Constant::getNullValue(B->getType()));
3963 return Changed ? &I : 0;
3966 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3967 // We only handle extending casts so far.
3969 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3970 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3971 const Type *SrcTy = LHSCIOp->getType();
3972 const Type *DestTy = SCI.getOperand(0)->getType();
3975 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
3978 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3979 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3980 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3982 // Is this a sign or zero extension?
3983 bool isSignSrc = SrcTy->isSigned();
3984 bool isSignDest = DestTy->isSigned();
3986 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3987 // Not an extension from the same type?
3988 RHSCIOp = CI->getOperand(0);
3989 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3990 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3991 // Compute the constant that would happen if we truncated to SrcTy then
3992 // reextended to DestTy.
3993 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3995 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3998 // If the value cannot be represented in the shorter type, we cannot emit
3999 // a simple comparison.
4000 if (SCI.getOpcode() == Instruction::SetEQ)
4001 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4002 if (SCI.getOpcode() == Instruction::SetNE)
4003 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4005 // Evaluate the comparison for LT.
4007 if (DestTy->isSigned()) {
4008 // We're performing a signed comparison.
4010 // Signed extend and signed comparison.
4011 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4012 Result = ConstantBool::False;
4014 Result = ConstantBool::True; // X < (large) --> true
4016 // Unsigned extend and signed comparison.
4017 if (cast<ConstantSInt>(CI)->getValue() < 0)
4018 Result = ConstantBool::False;
4020 Result = ConstantBool::True;
4023 // We're performing an unsigned comparison.
4025 // Unsigned extend & compare -> always true.
4026 Result = ConstantBool::True;
4028 // We're performing an unsigned comp with a sign extended value.
4029 // This is true if the input is >= 0. [aka >s -1]
4030 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4031 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4032 NegOne, SCI.getName()), SCI);
4036 // Finally, return the value computed.
4037 if (SCI.getOpcode() == Instruction::SetLT) {
4038 return ReplaceInstUsesWith(SCI, Result);
4040 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4041 if (Constant *CI = dyn_cast<Constant>(Result))
4042 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4044 return BinaryOperator::createNot(Result);
4051 // Okay, just insert a compare of the reduced operands now!
4052 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4055 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4056 assert(I.getOperand(1)->getType() == Type::UByteTy);
4057 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4058 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4060 // shl X, 0 == X and shr X, 0 == X
4061 // shl 0, X == 0 and shr 0, X == 0
4062 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4063 Op0 == Constant::getNullValue(Op0->getType()))
4064 return ReplaceInstUsesWith(I, Op0);
4066 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4067 if (!isLeftShift && I.getType()->isSigned())
4068 return ReplaceInstUsesWith(I, Op0);
4069 else // undef << X -> 0 AND undef >>u X -> 0
4070 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4072 if (isa<UndefValue>(Op1)) {
4073 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4074 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4076 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4079 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4081 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4082 if (CSI->isAllOnesValue())
4083 return ReplaceInstUsesWith(I, CSI);
4085 // Try to fold constant and into select arguments.
4086 if (isa<Constant>(Op0))
4087 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4088 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4091 // See if we can turn a signed shr into an unsigned shr.
4092 if (!isLeftShift && I.getType()->isSigned()) {
4093 if (MaskedValueIsZero(Op0,
4094 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4095 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4096 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4098 return new CastInst(V, I.getType());
4102 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4103 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4108 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4110 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4111 bool isSignedShift = Op0->getType()->isSigned();
4112 bool isUnsignedShift = !isSignedShift;
4114 // See if we can simplify any instructions used by the instruction whose sole
4115 // purpose is to compute bits we don't care about.
4116 uint64_t KnownZero, KnownOne;
4117 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4118 KnownZero, KnownOne))
4121 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4122 // of a signed value.
4124 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4125 if (Op1->getValue() >= TypeBits) {
4126 if (isUnsignedShift || isLeftShift)
4127 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4129 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4134 // ((X*C1) << C2) == (X * (C1 << C2))
4135 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4136 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4137 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4138 return BinaryOperator::createMul(BO->getOperand(0),
4139 ConstantExpr::getShl(BOOp, Op1));
4141 // Try to fold constant and into select arguments.
4142 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4143 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4145 if (isa<PHINode>(Op0))
4146 if (Instruction *NV = FoldOpIntoPhi(I))
4149 if (Op0->hasOneUse()) {
4150 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4151 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4154 switch (Op0BO->getOpcode()) {
4156 case Instruction::Add:
4157 case Instruction::And:
4158 case Instruction::Or:
4159 case Instruction::Xor:
4160 // These operators commute.
4161 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
4162 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4163 match(Op0BO->getOperand(1),
4164 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4165 Instruction *YS = new ShiftInst(Instruction::Shl,
4166 Op0BO->getOperand(0), Op1,
4168 InsertNewInstBefore(YS, I); // (Y << C)
4170 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4171 Op0BO->getOperand(1)->getName());
4172 InsertNewInstBefore(X, I); // (X + (Y << C))
4173 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4174 C2 = ConstantExpr::getShl(C2, Op1);
4175 return BinaryOperator::createAnd(X, C2);
4178 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4179 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4180 match(Op0BO->getOperand(1),
4181 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4182 m_ConstantInt(CC))) && V2 == Op1 &&
4183 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
4184 Instruction *YS = new ShiftInst(Instruction::Shl,
4185 Op0BO->getOperand(0), Op1,
4187 InsertNewInstBefore(YS, I); // (Y << C)
4189 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4190 V1->getName()+".mask");
4191 InsertNewInstBefore(XM, I); // X & (CC << C)
4193 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4197 case Instruction::Sub:
4198 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4199 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4200 match(Op0BO->getOperand(0),
4201 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4202 Instruction *YS = new ShiftInst(Instruction::Shl,
4203 Op0BO->getOperand(1), Op1,
4205 InsertNewInstBefore(YS, I); // (Y << C)
4207 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4208 Op0BO->getOperand(0)->getName());
4209 InsertNewInstBefore(X, I); // (X + (Y << C))
4210 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4211 C2 = ConstantExpr::getShl(C2, Op1);
4212 return BinaryOperator::createAnd(X, C2);
4215 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4216 match(Op0BO->getOperand(0),
4217 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4218 m_ConstantInt(CC))) && V2 == Op1 &&
4219 cast<BinaryOperator>(Op0BO->getOperand(0))
4220 ->getOperand(0)->hasOneUse()) {
4221 Instruction *YS = new ShiftInst(Instruction::Shl,
4222 Op0BO->getOperand(1), Op1,
4224 InsertNewInstBefore(YS, I); // (Y << C)
4226 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4227 V1->getName()+".mask");
4228 InsertNewInstBefore(XM, I); // X & (CC << C)
4230 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4237 // If the operand is an bitwise operator with a constant RHS, and the
4238 // shift is the only use, we can pull it out of the shift.
4239 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4240 bool isValid = true; // Valid only for And, Or, Xor
4241 bool highBitSet = false; // Transform if high bit of constant set?
4243 switch (Op0BO->getOpcode()) {
4244 default: isValid = false; break; // Do not perform transform!
4245 case Instruction::Add:
4246 isValid = isLeftShift;
4248 case Instruction::Or:
4249 case Instruction::Xor:
4252 case Instruction::And:
4257 // If this is a signed shift right, and the high bit is modified
4258 // by the logical operation, do not perform the transformation.
4259 // The highBitSet boolean indicates the value of the high bit of
4260 // the constant which would cause it to be modified for this
4263 if (isValid && !isLeftShift && isSignedShift) {
4264 uint64_t Val = Op0C->getRawValue();
4265 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4269 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4271 Instruction *NewShift =
4272 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4275 InsertNewInstBefore(NewShift, I);
4277 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4284 // Find out if this is a shift of a shift by a constant.
4285 ShiftInst *ShiftOp = 0;
4286 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
4288 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4289 // If this is a noop-integer case of a shift instruction, use the shift.
4290 if (CI->getOperand(0)->getType()->isInteger() &&
4291 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4292 CI->getType()->getPrimitiveSizeInBits() &&
4293 isa<ShiftInst>(CI->getOperand(0))) {
4294 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4298 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4299 // Find the operands and properties of the input shift. Note that the
4300 // signedness of the input shift may differ from the current shift if there
4301 // is a noop cast between the two.
4302 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4303 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
4304 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
4306 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4308 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4309 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4311 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4312 if (isLeftShift == isShiftOfLeftShift) {
4313 // Do not fold these shifts if the first one is signed and the second one
4314 // is unsigned and this is a right shift. Further, don't do any folding
4316 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4319 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4320 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4321 Amt = Op0->getType()->getPrimitiveSizeInBits();
4323 Value *Op = ShiftOp->getOperand(0);
4324 if (isShiftOfSignedShift != isSignedShift)
4325 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4326 return new ShiftInst(I.getOpcode(), Op,
4327 ConstantUInt::get(Type::UByteTy, Amt));
4330 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4331 // signed types, we can only support the (A >> c1) << c2 configuration,
4332 // because it can not turn an arbitrary bit of A into a sign bit.
4333 if (isUnsignedShift || isLeftShift) {
4334 // Calculate bitmask for what gets shifted off the edge.
4335 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4337 C = ConstantExpr::getShl(C, ShiftAmt1C);
4339 C = ConstantExpr::getUShr(C, ShiftAmt1C);
4341 Value *Op = ShiftOp->getOperand(0);
4342 if (isShiftOfSignedShift != isSignedShift)
4343 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4346 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4347 InsertNewInstBefore(Mask, I);
4349 // Figure out what flavor of shift we should use...
4350 if (ShiftAmt1 == ShiftAmt2) {
4351 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
4352 } else if (ShiftAmt1 < ShiftAmt2) {
4353 return new ShiftInst(I.getOpcode(), Mask,
4354 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
4355 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4356 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4357 // Make sure to emit an unsigned shift right, not a signed one.
4358 Mask = InsertNewInstBefore(new CastInst(Mask,
4359 Mask->getType()->getUnsignedVersion(),
4361 Mask = new ShiftInst(Instruction::Shr, Mask,
4362 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4363 InsertNewInstBefore(Mask, I);
4364 return new CastInst(Mask, I.getType());
4366 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4367 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4370 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4371 Op = InsertNewInstBefore(new CastInst(Mask,
4372 I.getType()->getSignedVersion(),
4373 Mask->getName()), I);
4374 Instruction *Shift =
4375 new ShiftInst(ShiftOp->getOpcode(), Op,
4376 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4377 InsertNewInstBefore(Shift, I);
4379 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4380 C = ConstantExpr::getShl(C, Op1);
4381 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4382 InsertNewInstBefore(Mask, I);
4383 return new CastInst(Mask, I.getType());
4386 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
4387 // this case, C1 == C2 and C1 is 8, 16, or 32.
4388 if (ShiftAmt1 == ShiftAmt2) {
4389 const Type *SExtType = 0;
4390 switch (ShiftAmt1) {
4391 case 8 : SExtType = Type::SByteTy; break;
4392 case 16: SExtType = Type::ShortTy; break;
4393 case 32: SExtType = Type::IntTy; break;
4397 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4399 InsertNewInstBefore(NewTrunc, I);
4400 return new CastInst(NewTrunc, I.getType());
4415 /// getCastType - In the future, we will split the cast instruction into these
4416 /// various types. Until then, we have to do the analysis here.
4417 static CastType getCastType(const Type *Src, const Type *Dest) {
4418 assert(Src->isIntegral() && Dest->isIntegral() &&
4419 "Only works on integral types!");
4420 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4421 unsigned DestSize = Dest->getPrimitiveSizeInBits();
4423 if (SrcSize == DestSize) return Noop;
4424 if (SrcSize > DestSize) return Truncate;
4425 if (Src->isSigned()) return Signext;
4430 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4433 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4434 const Type *DstTy, TargetData *TD) {
4436 // It is legal to eliminate the instruction if casting A->B->A if the sizes
4437 // are identical and the bits don't get reinterpreted (for example
4438 // int->float->int would not be allowed).
4439 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
4442 // If we are casting between pointer and integer types, treat pointers as
4443 // integers of the appropriate size for the code below.
4444 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4445 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4446 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
4448 // Allow free casting and conversion of sizes as long as the sign doesn't
4450 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
4451 CastType FirstCast = getCastType(SrcTy, MidTy);
4452 CastType SecondCast = getCastType(MidTy, DstTy);
4454 // Capture the effect of these two casts. If the result is a legal cast,
4455 // the CastType is stored here, otherwise a special code is used.
4456 static const unsigned CastResult[] = {
4457 // First cast is noop
4459 // First cast is a truncate
4460 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4461 // First cast is a sign ext
4462 2, 5, 2, 4, // signext->zeroext never ok
4463 // First cast is a zero ext
4467 unsigned Result = CastResult[FirstCast*4+SecondCast];
4469 default: assert(0 && "Illegal table value!");
4474 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4475 // truncates, we could eliminate more casts.
4476 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4478 return false; // Not possible to eliminate this here.
4480 // Sign or zero extend followed by truncate is always ok if the result
4481 // is a truncate or noop.
4482 CastType ResultCast = getCastType(SrcTy, DstTy);
4483 if (ResultCast == Noop || ResultCast == Truncate)
4485 // Otherwise we are still growing the value, we are only safe if the
4486 // result will match the sign/zeroextendness of the result.
4487 return ResultCast == FirstCast;
4491 // If this is a cast from 'float -> double -> integer', cast from
4492 // 'float -> integer' directly, as the value isn't changed by the
4493 // float->double conversion.
4494 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4495 DstTy->isIntegral() &&
4496 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4502 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
4503 if (V->getType() == Ty || isa<Constant>(V)) return false;
4504 if (const CastInst *CI = dyn_cast<CastInst>(V))
4505 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4511 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4512 /// InsertBefore instruction. This is specialized a bit to avoid inserting
4513 /// casts that are known to not do anything...
4515 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4516 Instruction *InsertBefore) {
4517 if (V->getType() == DestTy) return V;
4518 if (Constant *C = dyn_cast<Constant>(V))
4519 return ConstantExpr::getCast(C, DestTy);
4521 CastInst *CI = new CastInst(V, DestTy, V->getName());
4522 InsertNewInstBefore(CI, *InsertBefore);
4526 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4527 /// expression. If so, decompose it, returning some value X, such that Val is
4530 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4532 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4533 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4534 Offset = CI->getValue();
4536 return ConstantUInt::get(Type::UIntTy, 0);
4537 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4538 if (I->getNumOperands() == 2) {
4539 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4540 if (I->getOpcode() == Instruction::Shl) {
4541 // This is a value scaled by '1 << the shift amt'.
4542 Scale = 1U << CUI->getValue();
4544 return I->getOperand(0);
4545 } else if (I->getOpcode() == Instruction::Mul) {
4546 // This value is scaled by 'CUI'.
4547 Scale = CUI->getValue();
4549 return I->getOperand(0);
4550 } else if (I->getOpcode() == Instruction::Add) {
4551 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4554 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4556 Offset += CUI->getValue();
4557 if (SubScale > 1 && (Offset % SubScale == 0)) {
4566 // Otherwise, we can't look past this.
4573 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4574 /// try to eliminate the cast by moving the type information into the alloc.
4575 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4576 AllocationInst &AI) {
4577 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
4578 if (!PTy) return 0; // Not casting the allocation to a pointer type.
4580 // Remove any uses of AI that are dead.
4581 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4582 std::vector<Instruction*> DeadUsers;
4583 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4584 Instruction *User = cast<Instruction>(*UI++);
4585 if (isInstructionTriviallyDead(User)) {
4586 while (UI != E && *UI == User)
4587 ++UI; // If this instruction uses AI more than once, don't break UI.
4589 // Add operands to the worklist.
4590 AddUsesToWorkList(*User);
4592 DEBUG(std::cerr << "IC: DCE: " << *User);
4594 User->eraseFromParent();
4595 removeFromWorkList(User);
4599 // Get the type really allocated and the type casted to.
4600 const Type *AllocElTy = AI.getAllocatedType();
4601 const Type *CastElTy = PTy->getElementType();
4602 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4604 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4605 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4606 if (CastElTyAlign < AllocElTyAlign) return 0;
4608 // If the allocation has multiple uses, only promote it if we are strictly
4609 // increasing the alignment of the resultant allocation. If we keep it the
4610 // same, we open the door to infinite loops of various kinds.
4611 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4613 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4614 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4615 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4617 // See if we can satisfy the modulus by pulling a scale out of the array
4619 unsigned ArraySizeScale, ArrayOffset;
4620 Value *NumElements = // See if the array size is a decomposable linear expr.
4621 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4623 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4625 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4626 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
4628 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4633 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4634 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4635 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4636 else if (Scale != 1) {
4637 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4638 Amt = InsertNewInstBefore(Tmp, AI);
4642 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4643 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4644 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4645 Amt = InsertNewInstBefore(Tmp, AI);
4648 std::string Name = AI.getName(); AI.setName("");
4649 AllocationInst *New;
4650 if (isa<MallocInst>(AI))
4651 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4653 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4654 InsertNewInstBefore(New, AI);
4656 // If the allocation has multiple uses, insert a cast and change all things
4657 // that used it to use the new cast. This will also hack on CI, but it will
4659 if (!AI.hasOneUse()) {
4660 AddUsesToWorkList(AI);
4661 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4662 InsertNewInstBefore(NewCast, AI);
4663 AI.replaceAllUsesWith(NewCast);
4665 return ReplaceInstUsesWith(CI, New);
4669 // CastInst simplification
4671 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4672 Value *Src = CI.getOperand(0);
4674 // If the user is casting a value to the same type, eliminate this cast
4676 if (CI.getType() == Src->getType())
4677 return ReplaceInstUsesWith(CI, Src);
4679 if (isa<UndefValue>(Src)) // cast undef -> undef
4680 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4682 // If casting the result of another cast instruction, try to eliminate this
4685 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4686 Value *A = CSrc->getOperand(0);
4687 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4688 CI.getType(), TD)) {
4689 // This instruction now refers directly to the cast's src operand. This
4690 // has a good chance of making CSrc dead.
4691 CI.setOperand(0, CSrc->getOperand(0));
4695 // If this is an A->B->A cast, and we are dealing with integral types, try
4696 // to convert this into a logical 'and' instruction.
4698 if (A->getType()->isInteger() &&
4699 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
4700 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
4701 CSrc->getType()->getPrimitiveSizeInBits() <
4702 CI.getType()->getPrimitiveSizeInBits()&&
4703 A->getType()->getPrimitiveSizeInBits() ==
4704 CI.getType()->getPrimitiveSizeInBits()) {
4705 assert(CSrc->getType() != Type::ULongTy &&
4706 "Cannot have type bigger than ulong!");
4707 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
4708 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4710 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4711 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4712 if (And->getType() != CI.getType()) {
4713 And->setName(CSrc->getName()+".mask");
4714 InsertNewInstBefore(And, CI);
4715 And = new CastInst(And, CI.getType());
4721 // If this is a cast to bool, turn it into the appropriate setne instruction.
4722 if (CI.getType() == Type::BoolTy)
4723 return BinaryOperator::createSetNE(CI.getOperand(0),
4724 Constant::getNullValue(CI.getOperand(0)->getType()));
4726 // See if we can simplify any instructions used by the LHS whose sole
4727 // purpose is to compute bits we don't care about.
4728 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4729 uint64_t KnownZero, KnownOne;
4730 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4731 KnownZero, KnownOne))
4735 // If casting the result of a getelementptr instruction with no offset, turn
4736 // this into a cast of the original pointer!
4738 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4739 bool AllZeroOperands = true;
4740 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4741 if (!isa<Constant>(GEP->getOperand(i)) ||
4742 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4743 AllZeroOperands = false;
4746 if (AllZeroOperands) {
4747 CI.setOperand(0, GEP->getOperand(0));
4752 // If we are casting a malloc or alloca to a pointer to a type of the same
4753 // size, rewrite the allocation instruction to allocate the "right" type.
4755 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
4756 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4759 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4760 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4762 if (isa<PHINode>(Src))
4763 if (Instruction *NV = FoldOpIntoPhi(CI))
4766 // If the source value is an instruction with only this use, we can attempt to
4767 // propagate the cast into the instruction. Also, only handle integral types
4769 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4770 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4771 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4772 const Type *DestTy = CI.getType();
4773 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4774 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
4776 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4777 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4779 switch (SrcI->getOpcode()) {
4780 case Instruction::Add:
4781 case Instruction::Mul:
4782 case Instruction::And:
4783 case Instruction::Or:
4784 case Instruction::Xor:
4785 // If we are discarding information, or just changing the sign, rewrite.
4786 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4787 // Don't insert two casts if they cannot be eliminated. We allow two
4788 // casts to be inserted if the sizes are the same. This could only be
4789 // converting signedness, which is a noop.
4790 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4791 !ValueRequiresCast(Op0, DestTy, TD)) {
4792 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4793 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4794 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4795 ->getOpcode(), Op0c, Op1c);
4799 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4800 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4801 Op1 == ConstantBool::True &&
4802 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4803 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4804 return BinaryOperator::createXor(New,
4805 ConstantInt::get(CI.getType(), 1));
4808 case Instruction::Shl:
4809 // Allow changing the sign of the source operand. Do not allow changing
4810 // the size of the shift, UNLESS the shift amount is a constant. We
4811 // mush not change variable sized shifts to a smaller size, because it
4812 // is undefined to shift more bits out than exist in the value.
4813 if (DestBitSize == SrcBitSize ||
4814 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4815 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4816 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4819 case Instruction::Shr:
4820 // If this is a signed shr, and if all bits shifted in are about to be
4821 // truncated off, turn it into an unsigned shr to allow greater
4823 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4824 isa<ConstantInt>(Op1)) {
4825 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4826 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4827 // Convert to unsigned.
4828 Value *N1 = InsertOperandCastBefore(Op0,
4829 Op0->getType()->getUnsignedVersion(), &CI);
4830 // Insert the new shift, which is now unsigned.
4831 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4832 Op1, Src->getName()), CI);
4833 return new CastInst(N1, CI.getType());
4838 case Instruction::SetEQ:
4839 case Instruction::SetNE:
4840 // We if we are just checking for a seteq of a single bit and casting it
4841 // to an integer. If so, shift the bit to the appropriate place then
4842 // cast to integer to avoid the comparison.
4843 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4844 uint64_t Op1CV = Op1C->getZExtValue();
4845 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
4846 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4847 // cast (X == 1) to int --> X iff X has only the low bit set.
4848 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
4849 // cast (X != 0) to int --> X iff X has only the low bit set.
4850 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
4851 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
4852 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4853 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4854 // If Op1C some other power of two, convert:
4855 uint64_t KnownZero, KnownOne;
4856 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4857 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4859 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4860 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4861 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4862 // (X&4) == 2 --> false
4863 // (X&4) != 2 --> true
4864 Constant *Res = ConstantBool::get(isSetNE);
4865 Res = ConstantExpr::getCast(Res, CI.getType());
4866 return ReplaceInstUsesWith(CI, Res);
4869 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4872 // Perform an unsigned shr by shiftamt. Convert input to
4873 // unsigned if it is signed.
4874 if (In->getType()->isSigned())
4875 In = InsertNewInstBefore(new CastInst(In,
4876 In->getType()->getUnsignedVersion(), In->getName()),CI);
4877 // Insert the shift to put the result in the low bit.
4878 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4879 ConstantInt::get(Type::UByteTy, ShiftAmt),
4880 In->getName()+".lobit"), CI);
4883 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
4884 Constant *One = ConstantInt::get(In->getType(), 1);
4885 In = BinaryOperator::createXor(In, One, "tmp");
4886 InsertNewInstBefore(cast<Instruction>(In), CI);
4889 if (CI.getType() == In->getType())
4890 return ReplaceInstUsesWith(CI, In);
4892 return new CastInst(In, CI.getType());
4903 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4905 /// %D = select %cond, %C, %A
4907 /// %C = select %cond, %B, 0
4910 /// Assuming that the specified instruction is an operand to the select, return
4911 /// a bitmask indicating which operands of this instruction are foldable if they
4912 /// equal the other incoming value of the select.
4914 static unsigned GetSelectFoldableOperands(Instruction *I) {
4915 switch (I->getOpcode()) {
4916 case Instruction::Add:
4917 case Instruction::Mul:
4918 case Instruction::And:
4919 case Instruction::Or:
4920 case Instruction::Xor:
4921 return 3; // Can fold through either operand.
4922 case Instruction::Sub: // Can only fold on the amount subtracted.
4923 case Instruction::Shl: // Can only fold on the shift amount.
4924 case Instruction::Shr:
4927 return 0; // Cannot fold
4931 /// GetSelectFoldableConstant - For the same transformation as the previous
4932 /// function, return the identity constant that goes into the select.
4933 static Constant *GetSelectFoldableConstant(Instruction *I) {
4934 switch (I->getOpcode()) {
4935 default: assert(0 && "This cannot happen!"); abort();
4936 case Instruction::Add:
4937 case Instruction::Sub:
4938 case Instruction::Or:
4939 case Instruction::Xor:
4940 return Constant::getNullValue(I->getType());
4941 case Instruction::Shl:
4942 case Instruction::Shr:
4943 return Constant::getNullValue(Type::UByteTy);
4944 case Instruction::And:
4945 return ConstantInt::getAllOnesValue(I->getType());
4946 case Instruction::Mul:
4947 return ConstantInt::get(I->getType(), 1);
4951 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4952 /// have the same opcode and only one use each. Try to simplify this.
4953 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4955 if (TI->getNumOperands() == 1) {
4956 // If this is a non-volatile load or a cast from the same type,
4958 if (TI->getOpcode() == Instruction::Cast) {
4959 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4962 return 0; // unknown unary op.
4965 // Fold this by inserting a select from the input values.
4966 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4967 FI->getOperand(0), SI.getName()+".v");
4968 InsertNewInstBefore(NewSI, SI);
4969 return new CastInst(NewSI, TI->getType());
4972 // Only handle binary operators here.
4973 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4976 // Figure out if the operations have any operands in common.
4977 Value *MatchOp, *OtherOpT, *OtherOpF;
4979 if (TI->getOperand(0) == FI->getOperand(0)) {
4980 MatchOp = TI->getOperand(0);
4981 OtherOpT = TI->getOperand(1);
4982 OtherOpF = FI->getOperand(1);
4983 MatchIsOpZero = true;
4984 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4985 MatchOp = TI->getOperand(1);
4986 OtherOpT = TI->getOperand(0);
4987 OtherOpF = FI->getOperand(0);
4988 MatchIsOpZero = false;
4989 } else if (!TI->isCommutative()) {
4991 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4992 MatchOp = TI->getOperand(0);
4993 OtherOpT = TI->getOperand(1);
4994 OtherOpF = FI->getOperand(0);
4995 MatchIsOpZero = true;
4996 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4997 MatchOp = TI->getOperand(1);
4998 OtherOpT = TI->getOperand(0);
4999 OtherOpF = FI->getOperand(1);
5000 MatchIsOpZero = true;
5005 // If we reach here, they do have operations in common.
5006 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5007 OtherOpF, SI.getName()+".v");
5008 InsertNewInstBefore(NewSI, SI);
5010 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5012 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5014 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5017 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5019 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5023 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
5024 Value *CondVal = SI.getCondition();
5025 Value *TrueVal = SI.getTrueValue();
5026 Value *FalseVal = SI.getFalseValue();
5028 // select true, X, Y -> X
5029 // select false, X, Y -> Y
5030 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
5031 if (C == ConstantBool::True)
5032 return ReplaceInstUsesWith(SI, TrueVal);
5034 assert(C == ConstantBool::False);
5035 return ReplaceInstUsesWith(SI, FalseVal);
5038 // select C, X, X -> X
5039 if (TrueVal == FalseVal)
5040 return ReplaceInstUsesWith(SI, TrueVal);
5042 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5043 return ReplaceInstUsesWith(SI, FalseVal);
5044 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5045 return ReplaceInstUsesWith(SI, TrueVal);
5046 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5047 if (isa<Constant>(TrueVal))
5048 return ReplaceInstUsesWith(SI, TrueVal);
5050 return ReplaceInstUsesWith(SI, FalseVal);
5053 if (SI.getType() == Type::BoolTy)
5054 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5055 if (C == ConstantBool::True) {
5056 // Change: A = select B, true, C --> A = or B, C
5057 return BinaryOperator::createOr(CondVal, FalseVal);
5059 // Change: A = select B, false, C --> A = and !B, C
5061 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5062 "not."+CondVal->getName()), SI);
5063 return BinaryOperator::createAnd(NotCond, FalseVal);
5065 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5066 if (C == ConstantBool::False) {
5067 // Change: A = select B, C, false --> A = and B, C
5068 return BinaryOperator::createAnd(CondVal, TrueVal);
5070 // Change: A = select B, C, true --> A = or !B, C
5072 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5073 "not."+CondVal->getName()), SI);
5074 return BinaryOperator::createOr(NotCond, TrueVal);
5078 // Selecting between two integer constants?
5079 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5080 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5081 // select C, 1, 0 -> cast C to int
5082 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5083 return new CastInst(CondVal, SI.getType());
5084 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5085 // select C, 0, 1 -> cast !C to int
5087 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5088 "not."+CondVal->getName()), SI);
5089 return new CastInst(NotCond, SI.getType());
5092 // If one of the constants is zero (we know they can't both be) and we
5093 // have a setcc instruction with zero, and we have an 'and' with the
5094 // non-constant value, eliminate this whole mess. This corresponds to
5095 // cases like this: ((X & 27) ? 27 : 0)
5096 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5097 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5098 if ((IC->getOpcode() == Instruction::SetEQ ||
5099 IC->getOpcode() == Instruction::SetNE) &&
5100 isa<ConstantInt>(IC->getOperand(1)) &&
5101 cast<Constant>(IC->getOperand(1))->isNullValue())
5102 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5103 if (ICA->getOpcode() == Instruction::And &&
5104 isa<ConstantInt>(ICA->getOperand(1)) &&
5105 (ICA->getOperand(1) == TrueValC ||
5106 ICA->getOperand(1) == FalseValC) &&
5107 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5108 // Okay, now we know that everything is set up, we just don't
5109 // know whether we have a setne or seteq and whether the true or
5110 // false val is the zero.
5111 bool ShouldNotVal = !TrueValC->isNullValue();
5112 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5115 V = InsertNewInstBefore(BinaryOperator::create(
5116 Instruction::Xor, V, ICA->getOperand(1)), SI);
5117 return ReplaceInstUsesWith(SI, V);
5121 // See if we are selecting two values based on a comparison of the two values.
5122 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5123 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5124 // Transform (X == Y) ? X : Y -> Y
5125 if (SCI->getOpcode() == Instruction::SetEQ)
5126 return ReplaceInstUsesWith(SI, FalseVal);
5127 // Transform (X != Y) ? X : Y -> X
5128 if (SCI->getOpcode() == Instruction::SetNE)
5129 return ReplaceInstUsesWith(SI, TrueVal);
5130 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5132 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5133 // Transform (X == Y) ? Y : X -> X
5134 if (SCI->getOpcode() == Instruction::SetEQ)
5135 return ReplaceInstUsesWith(SI, FalseVal);
5136 // Transform (X != Y) ? Y : X -> Y
5137 if (SCI->getOpcode() == Instruction::SetNE)
5138 return ReplaceInstUsesWith(SI, TrueVal);
5139 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5143 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5144 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5145 if (TI->hasOneUse() && FI->hasOneUse()) {
5146 bool isInverse = false;
5147 Instruction *AddOp = 0, *SubOp = 0;
5149 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5150 if (TI->getOpcode() == FI->getOpcode())
5151 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5154 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5155 // even legal for FP.
5156 if (TI->getOpcode() == Instruction::Sub &&
5157 FI->getOpcode() == Instruction::Add) {
5158 AddOp = FI; SubOp = TI;
5159 } else if (FI->getOpcode() == Instruction::Sub &&
5160 TI->getOpcode() == Instruction::Add) {
5161 AddOp = TI; SubOp = FI;
5165 Value *OtherAddOp = 0;
5166 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5167 OtherAddOp = AddOp->getOperand(1);
5168 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5169 OtherAddOp = AddOp->getOperand(0);
5173 // So at this point we know we have (Y -> OtherAddOp):
5174 // select C, (add X, Y), (sub X, Z)
5175 Value *NegVal; // Compute -Z
5176 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5177 NegVal = ConstantExpr::getNeg(C);
5179 NegVal = InsertNewInstBefore(
5180 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
5183 Value *NewTrueOp = OtherAddOp;
5184 Value *NewFalseOp = NegVal;
5186 std::swap(NewTrueOp, NewFalseOp);
5187 Instruction *NewSel =
5188 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5190 NewSel = InsertNewInstBefore(NewSel, SI);
5191 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
5196 // See if we can fold the select into one of our operands.
5197 if (SI.getType()->isInteger()) {
5198 // See the comment above GetSelectFoldableOperands for a description of the
5199 // transformation we are doing here.
5200 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5201 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5202 !isa<Constant>(FalseVal))
5203 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5204 unsigned OpToFold = 0;
5205 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5207 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5212 Constant *C = GetSelectFoldableConstant(TVI);
5213 std::string Name = TVI->getName(); TVI->setName("");
5214 Instruction *NewSel =
5215 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5217 InsertNewInstBefore(NewSel, SI);
5218 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5219 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5220 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5221 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5223 assert(0 && "Unknown instruction!!");
5228 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5229 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5230 !isa<Constant>(TrueVal))
5231 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5232 unsigned OpToFold = 0;
5233 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5235 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5240 Constant *C = GetSelectFoldableConstant(FVI);
5241 std::string Name = FVI->getName(); FVI->setName("");
5242 Instruction *NewSel =
5243 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5245 InsertNewInstBefore(NewSel, SI);
5246 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5247 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5248 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5249 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5251 assert(0 && "Unknown instruction!!");
5257 if (BinaryOperator::isNot(CondVal)) {
5258 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5259 SI.setOperand(1, FalseVal);
5260 SI.setOperand(2, TrueVal);
5267 /// GetKnownAlignment - If the specified pointer has an alignment that we can
5268 /// determine, return it, otherwise return 0.
5269 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5270 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5271 unsigned Align = GV->getAlignment();
5272 if (Align == 0 && TD)
5273 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5275 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5276 unsigned Align = AI->getAlignment();
5277 if (Align == 0 && TD) {
5278 if (isa<AllocaInst>(AI))
5279 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5280 else if (isa<MallocInst>(AI)) {
5281 // Malloc returns maximally aligned memory.
5282 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5283 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5284 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5288 } else if (isa<CastInst>(V) ||
5289 (isa<ConstantExpr>(V) &&
5290 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5291 User *CI = cast<User>(V);
5292 if (isa<PointerType>(CI->getOperand(0)->getType()))
5293 return GetKnownAlignment(CI->getOperand(0), TD);
5295 } else if (isa<GetElementPtrInst>(V) ||
5296 (isa<ConstantExpr>(V) &&
5297 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5298 User *GEPI = cast<User>(V);
5299 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5300 if (BaseAlignment == 0) return 0;
5302 // If all indexes are zero, it is just the alignment of the base pointer.
5303 bool AllZeroOperands = true;
5304 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5305 if (!isa<Constant>(GEPI->getOperand(i)) ||
5306 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5307 AllZeroOperands = false;
5310 if (AllZeroOperands)
5311 return BaseAlignment;
5313 // Otherwise, if the base alignment is >= the alignment we expect for the
5314 // base pointer type, then we know that the resultant pointer is aligned at
5315 // least as much as its type requires.
5318 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5319 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
5321 const Type *GEPTy = GEPI->getType();
5322 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5330 /// visitCallInst - CallInst simplification. This mostly only handles folding
5331 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5332 /// the heavy lifting.
5334 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
5335 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5336 if (!II) return visitCallSite(&CI);
5338 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5340 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
5341 bool Changed = false;
5343 // memmove/cpy/set of zero bytes is a noop.
5344 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5345 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5347 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5348 if (CI->getRawValue() == 1) {
5349 // Replace the instruction with just byte operations. We would
5350 // transform other cases to loads/stores, but we don't know if
5351 // alignment is sufficient.
5355 // If we have a memmove and the source operation is a constant global,
5356 // then the source and dest pointers can't alias, so we can change this
5357 // into a call to memcpy.
5358 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
5359 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5360 if (GVSrc->isConstant()) {
5361 Module *M = CI.getParent()->getParent()->getParent();
5363 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5365 Name = "llvm.memcpy.i32";
5367 Name = "llvm.memcpy.i64";
5368 Function *MemCpy = M->getOrInsertFunction(Name,
5369 CI.getCalledFunction()->getFunctionType());
5370 CI.setOperand(0, MemCpy);
5375 // If we can determine a pointer alignment that is bigger than currently
5376 // set, update the alignment.
5377 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5378 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5379 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5380 unsigned Align = std::min(Alignment1, Alignment2);
5381 if (MI->getAlignment()->getRawValue() < Align) {
5382 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5385 } else if (isa<MemSetInst>(MI)) {
5386 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5387 if (MI->getAlignment()->getRawValue() < Alignment) {
5388 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5393 if (Changed) return II;
5395 switch (II->getIntrinsicID()) {
5397 case Intrinsic::stackrestore: {
5398 // If the save is right next to the restore, remove the restore. This can
5399 // happen when variable allocas are DCE'd.
5400 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5401 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5402 BasicBlock::iterator BI = SS;
5404 return EraseInstFromFunction(CI);
5408 // If the stack restore is in a return/unwind block and if there are no
5409 // allocas or calls between the restore and the return, nuke the restore.
5410 TerminatorInst *TI = II->getParent()->getTerminator();
5411 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5412 BasicBlock::iterator BI = II;
5413 bool CannotRemove = false;
5414 for (++BI; &*BI != TI; ++BI) {
5415 if (isa<AllocaInst>(BI) ||
5416 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5417 CannotRemove = true;
5422 return EraseInstFromFunction(CI);
5429 return visitCallSite(II);
5432 // InvokeInst simplification
5434 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
5435 return visitCallSite(&II);
5438 // visitCallSite - Improvements for call and invoke instructions.
5440 Instruction *InstCombiner::visitCallSite(CallSite CS) {
5441 bool Changed = false;
5443 // If the callee is a constexpr cast of a function, attempt to move the cast
5444 // to the arguments of the call/invoke.
5445 if (transformConstExprCastCall(CS)) return 0;
5447 Value *Callee = CS.getCalledValue();
5449 if (Function *CalleeF = dyn_cast<Function>(Callee))
5450 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5451 Instruction *OldCall = CS.getInstruction();
5452 // If the call and callee calling conventions don't match, this call must
5453 // be unreachable, as the call is undefined.
5454 new StoreInst(ConstantBool::True,
5455 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5456 if (!OldCall->use_empty())
5457 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5458 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5459 return EraseInstFromFunction(*OldCall);
5463 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5464 // This instruction is not reachable, just remove it. We insert a store to
5465 // undef so that we know that this code is not reachable, despite the fact
5466 // that we can't modify the CFG here.
5467 new StoreInst(ConstantBool::True,
5468 UndefValue::get(PointerType::get(Type::BoolTy)),
5469 CS.getInstruction());
5471 if (!CS.getInstruction()->use_empty())
5472 CS.getInstruction()->
5473 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5475 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5476 // Don't break the CFG, insert a dummy cond branch.
5477 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5478 ConstantBool::True, II);
5480 return EraseInstFromFunction(*CS.getInstruction());
5483 const PointerType *PTy = cast<PointerType>(Callee->getType());
5484 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5485 if (FTy->isVarArg()) {
5486 // See if we can optimize any arguments passed through the varargs area of
5488 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5489 E = CS.arg_end(); I != E; ++I)
5490 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5491 // If this cast does not effect the value passed through the varargs
5492 // area, we can eliminate the use of the cast.
5493 Value *Op = CI->getOperand(0);
5494 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5501 return Changed ? CS.getInstruction() : 0;
5504 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
5505 // attempt to move the cast to the arguments of the call/invoke.
5507 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5508 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5509 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
5510 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
5512 Function *Callee = cast<Function>(CE->getOperand(0));
5513 Instruction *Caller = CS.getInstruction();
5515 // Okay, this is a cast from a function to a different type. Unless doing so
5516 // would cause a type conversion of one of our arguments, change this call to
5517 // be a direct call with arguments casted to the appropriate types.
5519 const FunctionType *FT = Callee->getFunctionType();
5520 const Type *OldRetTy = Caller->getType();
5522 // Check to see if we are changing the return type...
5523 if (OldRetTy != FT->getReturnType()) {
5524 if (Callee->isExternal() &&
5525 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5526 !Caller->use_empty())
5527 return false; // Cannot transform this return value...
5529 // If the callsite is an invoke instruction, and the return value is used by
5530 // a PHI node in a successor, we cannot change the return type of the call
5531 // because there is no place to put the cast instruction (without breaking
5532 // the critical edge). Bail out in this case.
5533 if (!Caller->use_empty())
5534 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5535 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5537 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5538 if (PN->getParent() == II->getNormalDest() ||
5539 PN->getParent() == II->getUnwindDest())
5543 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5544 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
5546 CallSite::arg_iterator AI = CS.arg_begin();
5547 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5548 const Type *ParamTy = FT->getParamType(i);
5549 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
5550 if (Callee->isExternal() && !isConvertible) return false;
5553 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5554 Callee->isExternal())
5555 return false; // Do not delete arguments unless we have a function body...
5557 // Okay, we decided that this is a safe thing to do: go ahead and start
5558 // inserting cast instructions as necessary...
5559 std::vector<Value*> Args;
5560 Args.reserve(NumActualArgs);
5562 AI = CS.arg_begin();
5563 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5564 const Type *ParamTy = FT->getParamType(i);
5565 if ((*AI)->getType() == ParamTy) {
5566 Args.push_back(*AI);
5568 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5573 // If the function takes more arguments than the call was taking, add them
5575 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5576 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5578 // If we are removing arguments to the function, emit an obnoxious warning...
5579 if (FT->getNumParams() < NumActualArgs)
5580 if (!FT->isVarArg()) {
5581 std::cerr << "WARNING: While resolving call to function '"
5582 << Callee->getName() << "' arguments were dropped!\n";
5584 // Add all of the arguments in their promoted form to the arg list...
5585 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5586 const Type *PTy = getPromotedType((*AI)->getType());
5587 if (PTy != (*AI)->getType()) {
5588 // Must promote to pass through va_arg area!
5589 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5590 InsertNewInstBefore(Cast, *Caller);
5591 Args.push_back(Cast);
5593 Args.push_back(*AI);
5598 if (FT->getReturnType() == Type::VoidTy)
5599 Caller->setName(""); // Void type should not have a name...
5602 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5603 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
5604 Args, Caller->getName(), Caller);
5605 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
5607 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
5608 if (cast<CallInst>(Caller)->isTailCall())
5609 cast<CallInst>(NC)->setTailCall();
5610 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
5613 // Insert a cast of the return type as necessary...
5615 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5616 if (NV->getType() != Type::VoidTy) {
5617 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
5619 // If this is an invoke instruction, we should insert it after the first
5620 // non-phi, instruction in the normal successor block.
5621 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5622 BasicBlock::iterator I = II->getNormalDest()->begin();
5623 while (isa<PHINode>(I)) ++I;
5624 InsertNewInstBefore(NC, *I);
5626 // Otherwise, it's a call, just insert cast right after the call instr
5627 InsertNewInstBefore(NC, *Caller);
5629 AddUsersToWorkList(*Caller);
5631 NV = UndefValue::get(Caller->getType());
5635 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5636 Caller->replaceAllUsesWith(NV);
5637 Caller->getParent()->getInstList().erase(Caller);
5638 removeFromWorkList(Caller);
5643 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5644 // operator and they all are only used by the PHI, PHI together their
5645 // inputs, and do the operation once, to the result of the PHI.
5646 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5647 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5649 // Scan the instruction, looking for input operations that can be folded away.
5650 // If all input operands to the phi are the same instruction (e.g. a cast from
5651 // the same type or "+42") we can pull the operation through the PHI, reducing
5652 // code size and simplifying code.
5653 Constant *ConstantOp = 0;
5654 const Type *CastSrcTy = 0;
5655 if (isa<CastInst>(FirstInst)) {
5656 CastSrcTy = FirstInst->getOperand(0)->getType();
5657 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5658 // Can fold binop or shift if the RHS is a constant.
5659 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5660 if (ConstantOp == 0) return 0;
5662 return 0; // Cannot fold this operation.
5665 // Check to see if all arguments are the same operation.
5666 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5667 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5668 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5669 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5672 if (I->getOperand(0)->getType() != CastSrcTy)
5673 return 0; // Cast operation must match.
5674 } else if (I->getOperand(1) != ConstantOp) {
5679 // Okay, they are all the same operation. Create a new PHI node of the
5680 // correct type, and PHI together all of the LHS's of the instructions.
5681 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5682 PN.getName()+".in");
5683 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
5685 Value *InVal = FirstInst->getOperand(0);
5686 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
5688 // Add all operands to the new PHI.
5689 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5690 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5691 if (NewInVal != InVal)
5693 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5698 // The new PHI unions all of the same values together. This is really
5699 // common, so we handle it intelligently here for compile-time speed.
5703 InsertNewInstBefore(NewPN, PN);
5707 // Insert and return the new operation.
5708 if (isa<CastInst>(FirstInst))
5709 return new CastInst(PhiVal, PN.getType());
5710 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
5711 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
5713 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
5714 PhiVal, ConstantOp);
5717 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5719 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5720 if (PN->use_empty()) return true;
5721 if (!PN->hasOneUse()) return false;
5723 // Remember this node, and if we find the cycle, return.
5724 if (!PotentiallyDeadPHIs.insert(PN).second)
5727 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5728 return DeadPHICycle(PU, PotentiallyDeadPHIs);
5733 // PHINode simplification
5735 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
5736 if (Value *V = PN.hasConstantValue())
5737 return ReplaceInstUsesWith(PN, V);
5739 // If the only user of this instruction is a cast instruction, and all of the
5740 // incoming values are constants, change this PHI to merge together the casted
5743 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5744 if (CI->getType() != PN.getType()) { // noop casts will be folded
5745 bool AllConstant = true;
5746 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5747 if (!isa<Constant>(PN.getIncomingValue(i))) {
5748 AllConstant = false;
5752 // Make a new PHI with all casted values.
5753 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5754 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5755 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5756 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5757 PN.getIncomingBlock(i));
5760 // Update the cast instruction.
5761 CI->setOperand(0, New);
5762 WorkList.push_back(CI); // revisit the cast instruction to fold.
5763 WorkList.push_back(New); // Make sure to revisit the new Phi
5764 return &PN; // PN is now dead!
5768 // If all PHI operands are the same operation, pull them through the PHI,
5769 // reducing code size.
5770 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5771 PN.getIncomingValue(0)->hasOneUse())
5772 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5775 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5776 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5777 // PHI)... break the cycle.
5779 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5780 std::set<PHINode*> PotentiallyDeadPHIs;
5781 PotentiallyDeadPHIs.insert(&PN);
5782 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5783 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5789 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5790 Instruction *InsertPoint,
5792 unsigned PS = IC->getTargetData().getPointerSize();
5793 const Type *VTy = V->getType();
5794 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5795 // We must insert a cast to ensure we sign-extend.
5796 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5797 V->getName()), *InsertPoint);
5798 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5803 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
5804 Value *PtrOp = GEP.getOperand(0);
5805 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
5806 // If so, eliminate the noop.
5807 if (GEP.getNumOperands() == 1)
5808 return ReplaceInstUsesWith(GEP, PtrOp);
5810 if (isa<UndefValue>(GEP.getOperand(0)))
5811 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5813 bool HasZeroPointerIndex = false;
5814 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5815 HasZeroPointerIndex = C->isNullValue();
5817 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
5818 return ReplaceInstUsesWith(GEP, PtrOp);
5820 // Eliminate unneeded casts for indices.
5821 bool MadeChange = false;
5822 gep_type_iterator GTI = gep_type_begin(GEP);
5823 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5824 if (isa<SequentialType>(*GTI)) {
5825 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5826 Value *Src = CI->getOperand(0);
5827 const Type *SrcTy = Src->getType();
5828 const Type *DestTy = CI->getType();
5829 if (Src->getType()->isInteger()) {
5830 if (SrcTy->getPrimitiveSizeInBits() ==
5831 DestTy->getPrimitiveSizeInBits()) {
5832 // We can always eliminate a cast from ulong or long to the other.
5833 // We can always eliminate a cast from uint to int or the other on
5834 // 32-bit pointer platforms.
5835 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
5837 GEP.setOperand(i, Src);
5839 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5840 SrcTy->getPrimitiveSize() == 4) {
5841 // We can always eliminate a cast from int to [u]long. We can
5842 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5844 if (SrcTy->isSigned() ||
5845 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
5847 GEP.setOperand(i, Src);
5852 // If we are using a wider index than needed for this platform, shrink it
5853 // to what we need. If the incoming value needs a cast instruction,
5854 // insert it. This explicit cast can make subsequent optimizations more
5856 Value *Op = GEP.getOperand(i);
5857 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
5858 if (Constant *C = dyn_cast<Constant>(Op)) {
5859 GEP.setOperand(i, ConstantExpr::getCast(C,
5860 TD->getIntPtrType()->getSignedVersion()));
5863 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5864 Op->getName()), GEP);
5865 GEP.setOperand(i, Op);
5869 // If this is a constant idx, make sure to canonicalize it to be a signed
5870 // operand, otherwise CSE and other optimizations are pessimized.
5871 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5872 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5873 CUI->getType()->getSignedVersion()));
5877 if (MadeChange) return &GEP;
5879 // Combine Indices - If the source pointer to this getelementptr instruction
5880 // is a getelementptr instruction, combine the indices of the two
5881 // getelementptr instructions into a single instruction.
5883 std::vector<Value*> SrcGEPOperands;
5884 if (User *Src = dyn_castGetElementPtr(PtrOp))
5885 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
5887 if (!SrcGEPOperands.empty()) {
5888 // Note that if our source is a gep chain itself that we wait for that
5889 // chain to be resolved before we perform this transformation. This
5890 // avoids us creating a TON of code in some cases.
5892 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5893 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5894 return 0; // Wait until our source is folded to completion.
5896 std::vector<Value *> Indices;
5898 // Find out whether the last index in the source GEP is a sequential idx.
5899 bool EndsWithSequential = false;
5900 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5901 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
5902 EndsWithSequential = !isa<StructType>(*I);
5904 // Can we combine the two pointer arithmetics offsets?
5905 if (EndsWithSequential) {
5906 // Replace: gep (gep %P, long B), long A, ...
5907 // With: T = long A+B; gep %P, T, ...
5909 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
5910 if (SO1 == Constant::getNullValue(SO1->getType())) {
5912 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5915 // If they aren't the same type, convert both to an integer of the
5916 // target's pointer size.
5917 if (SO1->getType() != GO1->getType()) {
5918 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5919 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5920 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5921 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5923 unsigned PS = TD->getPointerSize();
5924 if (SO1->getType()->getPrimitiveSize() == PS) {
5925 // Convert GO1 to SO1's type.
5926 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5928 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5929 // Convert SO1 to GO1's type.
5930 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5932 const Type *PT = TD->getIntPtrType();
5933 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5934 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5938 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5939 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5941 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5942 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
5946 // Recycle the GEP we already have if possible.
5947 if (SrcGEPOperands.size() == 2) {
5948 GEP.setOperand(0, SrcGEPOperands[0]);
5949 GEP.setOperand(1, Sum);
5952 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5953 SrcGEPOperands.end()-1);
5954 Indices.push_back(Sum);
5955 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5957 } else if (isa<Constant>(*GEP.idx_begin()) &&
5958 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
5959 SrcGEPOperands.size() != 1) {
5960 // Otherwise we can do the fold if the first index of the GEP is a zero
5961 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5962 SrcGEPOperands.end());
5963 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5966 if (!Indices.empty())
5967 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
5969 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
5970 // GEP of global variable. If all of the indices for this GEP are
5971 // constants, we can promote this to a constexpr instead of an instruction.
5973 // Scan for nonconstants...
5974 std::vector<Constant*> Indices;
5975 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5976 for (; I != E && isa<Constant>(*I); ++I)
5977 Indices.push_back(cast<Constant>(*I));
5979 if (I == E) { // If they are all constants...
5980 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
5982 // Replace all uses of the GEP with the new constexpr...
5983 return ReplaceInstUsesWith(GEP, CE);
5985 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5986 if (!isa<PointerType>(X->getType())) {
5987 // Not interesting. Source pointer must be a cast from pointer.
5988 } else if (HasZeroPointerIndex) {
5989 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5990 // into : GEP [10 x ubyte]* X, long 0, ...
5992 // This occurs when the program declares an array extern like "int X[];"
5994 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5995 const PointerType *XTy = cast<PointerType>(X->getType());
5996 if (const ArrayType *XATy =
5997 dyn_cast<ArrayType>(XTy->getElementType()))
5998 if (const ArrayType *CATy =
5999 dyn_cast<ArrayType>(CPTy->getElementType()))
6000 if (CATy->getElementType() == XATy->getElementType()) {
6001 // At this point, we know that the cast source type is a pointer
6002 // to an array of the same type as the destination pointer
6003 // array. Because the array type is never stepped over (there
6004 // is a leading zero) we can fold the cast into this GEP.
6005 GEP.setOperand(0, X);
6008 } else if (GEP.getNumOperands() == 2) {
6009 // Transform things like:
6010 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6011 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
6012 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6013 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6014 if (isa<ArrayType>(SrcElTy) &&
6015 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6016 TD->getTypeSize(ResElTy)) {
6017 Value *V = InsertNewInstBefore(
6018 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6019 GEP.getOperand(1), GEP.getName()), GEP);
6020 return new CastInst(V, GEP.getType());
6023 // Transform things like:
6024 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6025 // (where tmp = 8*tmp2) into:
6026 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6028 if (isa<ArrayType>(SrcElTy) &&
6029 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6030 uint64_t ArrayEltSize =
6031 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6033 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6034 // allow either a mul, shift, or constant here.
6036 ConstantInt *Scale = 0;
6037 if (ArrayEltSize == 1) {
6038 NewIdx = GEP.getOperand(1);
6039 Scale = ConstantInt::get(NewIdx->getType(), 1);
6040 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
6041 NewIdx = ConstantInt::get(CI->getType(), 1);
6043 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6044 if (Inst->getOpcode() == Instruction::Shl &&
6045 isa<ConstantInt>(Inst->getOperand(1))) {
6046 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6047 if (Inst->getType()->isSigned())
6048 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6050 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6051 NewIdx = Inst->getOperand(0);
6052 } else if (Inst->getOpcode() == Instruction::Mul &&
6053 isa<ConstantInt>(Inst->getOperand(1))) {
6054 Scale = cast<ConstantInt>(Inst->getOperand(1));
6055 NewIdx = Inst->getOperand(0);
6059 // If the index will be to exactly the right offset with the scale taken
6060 // out, perform the transformation.
6061 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6062 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6063 Scale = ConstantSInt::get(C->getType(),
6064 (int64_t)C->getRawValue() /
6065 (int64_t)ArrayEltSize);
6067 Scale = ConstantUInt::get(Scale->getType(),
6068 Scale->getRawValue() / ArrayEltSize);
6069 if (Scale->getRawValue() != 1) {
6070 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6071 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6072 NewIdx = InsertNewInstBefore(Sc, GEP);
6075 // Insert the new GEP instruction.
6077 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6078 NewIdx, GEP.getName());
6079 Idx = InsertNewInstBefore(Idx, GEP);
6080 return new CastInst(Idx, GEP.getType());
6089 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6090 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6091 if (AI.isArrayAllocation()) // Check C != 1
6092 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6093 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
6094 AllocationInst *New = 0;
6096 // Create and insert the replacement instruction...
6097 if (isa<MallocInst>(AI))
6098 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
6100 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
6101 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
6104 InsertNewInstBefore(New, AI);
6106 // Scan to the end of the allocation instructions, to skip over a block of
6107 // allocas if possible...
6109 BasicBlock::iterator It = New;
6110 while (isa<AllocationInst>(*It)) ++It;
6112 // Now that I is pointing to the first non-allocation-inst in the block,
6113 // insert our getelementptr instruction...
6115 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6116 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6117 New->getName()+".sub", It);
6119 // Now make everything use the getelementptr instead of the original
6121 return ReplaceInstUsesWith(AI, V);
6122 } else if (isa<UndefValue>(AI.getArraySize())) {
6123 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6126 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6127 // Note that we only do this for alloca's, because malloc should allocate and
6128 // return a unique pointer, even for a zero byte allocation.
6129 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
6130 TD->getTypeSize(AI.getAllocatedType()) == 0)
6131 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6136 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6137 Value *Op = FI.getOperand(0);
6139 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6140 if (CastInst *CI = dyn_cast<CastInst>(Op))
6141 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6142 FI.setOperand(0, CI->getOperand(0));
6146 // free undef -> unreachable.
6147 if (isa<UndefValue>(Op)) {
6148 // Insert a new store to null because we cannot modify the CFG here.
6149 new StoreInst(ConstantBool::True,
6150 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6151 return EraseInstFromFunction(FI);
6154 // If we have 'free null' delete the instruction. This can happen in stl code
6155 // when lots of inlining happens.
6156 if (isa<ConstantPointerNull>(Op))
6157 return EraseInstFromFunction(FI);
6163 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
6164 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6165 User *CI = cast<User>(LI.getOperand(0));
6166 Value *CastOp = CI->getOperand(0);
6168 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6169 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6170 const Type *SrcPTy = SrcTy->getElementType();
6172 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6173 // If the source is an array, the code below will not succeed. Check to
6174 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6176 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6177 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6178 if (ASrcTy->getNumElements() != 0) {
6179 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6180 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6181 SrcTy = cast<PointerType>(CastOp->getType());
6182 SrcPTy = SrcTy->getElementType();
6185 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
6186 // Do not allow turning this into a load of an integer, which is then
6187 // casted to a pointer, this pessimizes pointer analysis a lot.
6188 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
6189 IC.getTargetData().getTypeSize(SrcPTy) ==
6190 IC.getTargetData().getTypeSize(DestPTy)) {
6192 // Okay, we are casting from one integer or pointer type to another of
6193 // the same size. Instead of casting the pointer before the load, cast
6194 // the result of the loaded value.
6195 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6197 LI.isVolatile()),LI);
6198 // Now cast the result of the load.
6199 return new CastInst(NewLoad, LI.getType());
6206 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
6207 /// from this value cannot trap. If it is not obviously safe to load from the
6208 /// specified pointer, we do a quick local scan of the basic block containing
6209 /// ScanFrom, to determine if the address is already accessed.
6210 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6211 // If it is an alloca or global variable, it is always safe to load from.
6212 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6214 // Otherwise, be a little bit agressive by scanning the local block where we
6215 // want to check to see if the pointer is already being loaded or stored
6216 // from/to. If so, the previous load or store would have already trapped,
6217 // so there is no harm doing an extra load (also, CSE will later eliminate
6218 // the load entirely).
6219 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6224 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6225 if (LI->getOperand(0) == V) return true;
6226 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6227 if (SI->getOperand(1) == V) return true;
6233 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6234 Value *Op = LI.getOperand(0);
6236 // load (cast X) --> cast (load X) iff safe
6237 if (CastInst *CI = dyn_cast<CastInst>(Op))
6238 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6241 // None of the following transforms are legal for volatile loads.
6242 if (LI.isVolatile()) return 0;
6244 if (&LI.getParent()->front() != &LI) {
6245 BasicBlock::iterator BBI = &LI; --BBI;
6246 // If the instruction immediately before this is a store to the same
6247 // address, do a simple form of store->load forwarding.
6248 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6249 if (SI->getOperand(1) == LI.getOperand(0))
6250 return ReplaceInstUsesWith(LI, SI->getOperand(0));
6251 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6252 if (LIB->getOperand(0) == LI.getOperand(0))
6253 return ReplaceInstUsesWith(LI, LIB);
6256 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6257 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6258 isa<UndefValue>(GEPI->getOperand(0))) {
6259 // Insert a new store to null instruction before the load to indicate
6260 // that this code is not reachable. We do this instead of inserting
6261 // an unreachable instruction directly because we cannot modify the
6263 new StoreInst(UndefValue::get(LI.getType()),
6264 Constant::getNullValue(Op->getType()), &LI);
6265 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6268 if (Constant *C = dyn_cast<Constant>(Op)) {
6269 // load null/undef -> undef
6270 if ((C->isNullValue() || isa<UndefValue>(C))) {
6271 // Insert a new store to null instruction before the load to indicate that
6272 // this code is not reachable. We do this instead of inserting an
6273 // unreachable instruction directly because we cannot modify the CFG.
6274 new StoreInst(UndefValue::get(LI.getType()),
6275 Constant::getNullValue(Op->getType()), &LI);
6276 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6279 // Instcombine load (constant global) into the value loaded.
6280 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6281 if (GV->isConstant() && !GV->isExternal())
6282 return ReplaceInstUsesWith(LI, GV->getInitializer());
6284 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6285 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6286 if (CE->getOpcode() == Instruction::GetElementPtr) {
6287 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6288 if (GV->isConstant() && !GV->isExternal())
6290 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
6291 return ReplaceInstUsesWith(LI, V);
6292 if (CE->getOperand(0)->isNullValue()) {
6293 // Insert a new store to null instruction before the load to indicate
6294 // that this code is not reachable. We do this instead of inserting
6295 // an unreachable instruction directly because we cannot modify the
6297 new StoreInst(UndefValue::get(LI.getType()),
6298 Constant::getNullValue(Op->getType()), &LI);
6299 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6302 } else if (CE->getOpcode() == Instruction::Cast) {
6303 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6308 if (Op->hasOneUse()) {
6309 // Change select and PHI nodes to select values instead of addresses: this
6310 // helps alias analysis out a lot, allows many others simplifications, and
6311 // exposes redundancy in the code.
6313 // Note that we cannot do the transformation unless we know that the
6314 // introduced loads cannot trap! Something like this is valid as long as
6315 // the condition is always false: load (select bool %C, int* null, int* %G),
6316 // but it would not be valid if we transformed it to load from null
6319 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6320 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
6321 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6322 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
6323 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
6324 SI->getOperand(1)->getName()+".val"), LI);
6325 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
6326 SI->getOperand(2)->getName()+".val"), LI);
6327 return new SelectInst(SI->getCondition(), V1, V2);
6330 // load (select (cond, null, P)) -> load P
6331 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6332 if (C->isNullValue()) {
6333 LI.setOperand(0, SI->getOperand(2));
6337 // load (select (cond, P, null)) -> load P
6338 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6339 if (C->isNullValue()) {
6340 LI.setOperand(0, SI->getOperand(1));
6344 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6345 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
6346 bool Safe = PN->getParent() == LI.getParent();
6348 // Scan all of the instructions between the PHI and the load to make
6349 // sure there are no instructions that might possibly alter the value
6350 // loaded from the PHI.
6352 BasicBlock::iterator I = &LI;
6353 for (--I; !isa<PHINode>(I); --I)
6354 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6360 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
6361 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
6362 PN->getIncomingBlock(i)->getTerminator()))
6367 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6368 InsertNewInstBefore(NewPN, *PN);
6369 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6371 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6372 BasicBlock *BB = PN->getIncomingBlock(i);
6373 Value *&TheLoad = LoadMap[BB];
6375 Value *InVal = PN->getIncomingValue(i);
6376 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6377 InVal->getName()+".val"),
6378 *BB->getTerminator());
6380 NewPN->addIncoming(TheLoad, BB);
6382 return ReplaceInstUsesWith(LI, NewPN);
6389 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6391 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6392 User *CI = cast<User>(SI.getOperand(1));
6393 Value *CastOp = CI->getOperand(0);
6395 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6396 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6397 const Type *SrcPTy = SrcTy->getElementType();
6399 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6400 // If the source is an array, the code below will not succeed. Check to
6401 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6403 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6404 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6405 if (ASrcTy->getNumElements() != 0) {
6406 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6407 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6408 SrcTy = cast<PointerType>(CastOp->getType());
6409 SrcPTy = SrcTy->getElementType();
6412 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
6413 IC.getTargetData().getTypeSize(SrcPTy) ==
6414 IC.getTargetData().getTypeSize(DestPTy)) {
6416 // Okay, we are casting from one integer or pointer type to another of
6417 // the same size. Instead of casting the pointer before the store, cast
6418 // the value to be stored.
6420 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6421 NewCast = ConstantExpr::getCast(C, SrcPTy);
6423 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6425 SI.getOperand(0)->getName()+".c"), SI);
6427 return new StoreInst(NewCast, CastOp);
6434 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6435 Value *Val = SI.getOperand(0);
6436 Value *Ptr = SI.getOperand(1);
6438 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
6439 EraseInstFromFunction(SI);
6444 // Do really simple DSE, to catch cases where there are several consequtive
6445 // stores to the same location, separated by a few arithmetic operations. This
6446 // situation often occurs with bitfield accesses.
6447 BasicBlock::iterator BBI = &SI;
6448 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6452 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6453 // Prev store isn't volatile, and stores to the same location?
6454 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6457 EraseInstFromFunction(*PrevSI);
6463 // Don't skip over loads or things that can modify memory.
6464 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6469 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
6471 // store X, null -> turns into 'unreachable' in SimplifyCFG
6472 if (isa<ConstantPointerNull>(Ptr)) {
6473 if (!isa<UndefValue>(Val)) {
6474 SI.setOperand(0, UndefValue::get(Val->getType()));
6475 if (Instruction *U = dyn_cast<Instruction>(Val))
6476 WorkList.push_back(U); // Dropped a use.
6479 return 0; // Do not modify these!
6482 // store undef, Ptr -> noop
6483 if (isa<UndefValue>(Val)) {
6484 EraseInstFromFunction(SI);
6489 // If the pointer destination is a cast, see if we can fold the cast into the
6491 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6492 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6494 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6495 if (CE->getOpcode() == Instruction::Cast)
6496 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6500 // If this store is the last instruction in the basic block, and if the block
6501 // ends with an unconditional branch, try to move it to the successor block.
6503 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6504 if (BI->isUnconditional()) {
6505 // Check to see if the successor block has exactly two incoming edges. If
6506 // so, see if the other predecessor contains a store to the same location.
6507 // if so, insert a PHI node (if needed) and move the stores down.
6508 BasicBlock *Dest = BI->getSuccessor(0);
6510 pred_iterator PI = pred_begin(Dest);
6511 BasicBlock *Other = 0;
6512 if (*PI != BI->getParent())
6515 if (PI != pred_end(Dest)) {
6516 if (*PI != BI->getParent())
6521 if (++PI != pred_end(Dest))
6524 if (Other) { // If only one other pred...
6525 BBI = Other->getTerminator();
6526 // Make sure this other block ends in an unconditional branch and that
6527 // there is an instruction before the branch.
6528 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6529 BBI != Other->begin()) {
6531 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6533 // If this instruction is a store to the same location.
6534 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6535 // Okay, we know we can perform this transformation. Insert a PHI
6536 // node now if we need it.
6537 Value *MergedVal = OtherStore->getOperand(0);
6538 if (MergedVal != SI.getOperand(0)) {
6539 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6540 PN->reserveOperandSpace(2);
6541 PN->addIncoming(SI.getOperand(0), SI.getParent());
6542 PN->addIncoming(OtherStore->getOperand(0), Other);
6543 MergedVal = InsertNewInstBefore(PN, Dest->front());
6546 // Advance to a place where it is safe to insert the new store and
6548 BBI = Dest->begin();
6549 while (isa<PHINode>(BBI)) ++BBI;
6550 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6551 OtherStore->isVolatile()), *BBI);
6553 // Nuke the old stores.
6554 EraseInstFromFunction(SI);
6555 EraseInstFromFunction(*OtherStore);
6567 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6568 // Change br (not X), label True, label False to: br X, label False, True
6570 BasicBlock *TrueDest;
6571 BasicBlock *FalseDest;
6572 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6573 !isa<Constant>(X)) {
6574 // Swap Destinations and condition...
6576 BI.setSuccessor(0, FalseDest);
6577 BI.setSuccessor(1, TrueDest);
6581 // Cannonicalize setne -> seteq
6582 Instruction::BinaryOps Op; Value *Y;
6583 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6584 TrueDest, FalseDest)))
6585 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6586 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6587 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6588 std::string Name = I->getName(); I->setName("");
6589 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6590 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
6591 // Swap Destinations and condition...
6592 BI.setCondition(NewSCC);
6593 BI.setSuccessor(0, FalseDest);
6594 BI.setSuccessor(1, TrueDest);
6595 removeFromWorkList(I);
6596 I->getParent()->getInstList().erase(I);
6597 WorkList.push_back(cast<Instruction>(NewSCC));
6604 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6605 Value *Cond = SI.getCondition();
6606 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6607 if (I->getOpcode() == Instruction::Add)
6608 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6609 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6610 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
6611 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
6613 SI.setOperand(0, I->getOperand(0));
6614 WorkList.push_back(I);
6621 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6622 /// is to leave as a vector operation.
6623 static bool CheapToScalarize(Value *V, bool isConstant) {
6624 if (isa<ConstantAggregateZero>(V))
6626 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6627 if (isConstant) return true;
6628 // If all elts are the same, we can extract.
6629 Constant *Op0 = C->getOperand(0);
6630 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6631 if (C->getOperand(i) != Op0)
6635 Instruction *I = dyn_cast<Instruction>(V);
6636 if (!I) return false;
6638 // Insert element gets simplified to the inserted element or is deleted if
6639 // this is constant idx extract element and its a constant idx insertelt.
6640 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6641 isa<ConstantInt>(I->getOperand(2)))
6643 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6645 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6646 if (BO->hasOneUse() &&
6647 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6648 CheapToScalarize(BO->getOperand(1), isConstant)))
6654 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6655 if (ConstantAggregateZero *C =
6656 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6657 // If packed val is constant 0, replace extract with scalar 0
6658 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6659 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6661 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6662 // If packed val is constant with uniform operands, replace EI
6663 // with that operand
6664 Constant *op0 = C->getOperand(0);
6665 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6666 if (C->getOperand(i) != op0) {
6671 return ReplaceInstUsesWith(EI, op0);
6674 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6675 if (I->hasOneUse()) {
6676 // Push extractelement into predecessor operation if legal and
6677 // profitable to do so
6678 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6679 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
6680 if (CheapToScalarize(BO, isConstantElt)) {
6681 ExtractElementInst *newEI0 =
6682 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6683 EI.getName()+".lhs");
6684 ExtractElementInst *newEI1 =
6685 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6686 EI.getName()+".rhs");
6687 InsertNewInstBefore(newEI0, EI);
6688 InsertNewInstBefore(newEI1, EI);
6689 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6691 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6692 Value *Ptr = InsertCastBefore(I->getOperand(0),
6693 PointerType::get(EI.getType()), EI);
6694 GetElementPtrInst *GEP =
6695 new GetElementPtrInst(Ptr, EI.getOperand(1),
6696 I->getName() + ".gep");
6697 InsertNewInstBefore(GEP, EI);
6698 return new LoadInst(GEP);
6699 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
6700 // Extracting the inserted element?
6701 if (IE->getOperand(2) == EI.getOperand(1))
6702 return ReplaceInstUsesWith(EI, IE->getOperand(1));
6703 // If the inserted and extracted elements are constants, they must not
6704 // be the same value, replace with the pre-inserted value.
6705 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1)))
6706 return ReplaceInstUsesWith(EI, IE->getOperand(0));
6713 void InstCombiner::removeFromWorkList(Instruction *I) {
6714 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6719 /// TryToSinkInstruction - Try to move the specified instruction from its
6720 /// current block into the beginning of DestBlock, which can only happen if it's
6721 /// safe to move the instruction past all of the instructions between it and the
6722 /// end of its block.
6723 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6724 assert(I->hasOneUse() && "Invariants didn't hold!");
6726 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6727 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
6729 // Do not sink alloca instructions out of the entry block.
6730 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6733 // We can only sink load instructions if there is nothing between the load and
6734 // the end of block that could change the value.
6735 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6736 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6738 if (Scan->mayWriteToMemory())
6742 BasicBlock::iterator InsertPos = DestBlock->begin();
6743 while (isa<PHINode>(InsertPos)) ++InsertPos;
6745 I->moveBefore(InsertPos);
6750 bool InstCombiner::runOnFunction(Function &F) {
6751 bool Changed = false;
6752 TD = &getAnalysis<TargetData>();
6755 // Populate the worklist with the reachable instructions.
6756 std::set<BasicBlock*> Visited;
6757 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6758 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6759 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6760 WorkList.push_back(I);
6762 // Do a quick scan over the function. If we find any blocks that are
6763 // unreachable, remove any instructions inside of them. This prevents
6764 // the instcombine code from having to deal with some bad special cases.
6765 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6766 if (!Visited.count(BB)) {
6767 Instruction *Term = BB->getTerminator();
6768 while (Term != BB->begin()) { // Remove instrs bottom-up
6769 BasicBlock::iterator I = Term; --I;
6771 DEBUG(std::cerr << "IC: DCE: " << *I);
6774 if (!I->use_empty())
6775 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6776 I->eraseFromParent();
6781 while (!WorkList.empty()) {
6782 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6783 WorkList.pop_back();
6785 // Check to see if we can DCE or ConstantPropagate the instruction...
6786 // Check to see if we can DIE the instruction...
6787 if (isInstructionTriviallyDead(I)) {
6788 // Add operands to the worklist...
6789 if (I->getNumOperands() < 4)
6790 AddUsesToWorkList(*I);
6793 DEBUG(std::cerr << "IC: DCE: " << *I);
6795 I->eraseFromParent();
6796 removeFromWorkList(I);
6800 // Instruction isn't dead, see if we can constant propagate it...
6801 if (Constant *C = ConstantFoldInstruction(I)) {
6802 Value* Ptr = I->getOperand(0);
6803 if (isa<GetElementPtrInst>(I) &&
6804 cast<Constant>(Ptr)->isNullValue() &&
6805 !isa<ConstantPointerNull>(C) &&
6806 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
6807 // If this is a constant expr gep that is effectively computing an
6808 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6809 bool isFoldableGEP = true;
6810 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6811 if (!isa<ConstantInt>(I->getOperand(i)))
6812 isFoldableGEP = false;
6813 if (isFoldableGEP) {
6814 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
6815 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6816 C = ConstantUInt::get(Type::ULongTy, Offset);
6817 C = ConstantExpr::getCast(C, TD->getIntPtrType());
6818 C = ConstantExpr::getCast(C, I->getType());
6822 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6824 // Add operands to the worklist...
6825 AddUsesToWorkList(*I);
6826 ReplaceInstUsesWith(*I, C);
6829 I->getParent()->getInstList().erase(I);
6830 removeFromWorkList(I);
6834 // See if we can trivially sink this instruction to a successor basic block.
6835 if (I->hasOneUse()) {
6836 BasicBlock *BB = I->getParent();
6837 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6838 if (UserParent != BB) {
6839 bool UserIsSuccessor = false;
6840 // See if the user is one of our successors.
6841 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6842 if (*SI == UserParent) {
6843 UserIsSuccessor = true;
6847 // If the user is one of our immediate successors, and if that successor
6848 // only has us as a predecessors (we'd have to split the critical edge
6849 // otherwise), we can keep going.
6850 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6851 next(pred_begin(UserParent)) == pred_end(UserParent))
6852 // Okay, the CFG is simple enough, try to sink this instruction.
6853 Changed |= TryToSinkInstruction(I, UserParent);
6857 // Now that we have an instruction, try combining it to simplify it...
6858 if (Instruction *Result = visit(*I)) {
6860 // Should we replace the old instruction with a new one?
6862 DEBUG(std::cerr << "IC: Old = " << *I
6863 << " New = " << *Result);
6865 // Everything uses the new instruction now.
6866 I->replaceAllUsesWith(Result);
6868 // Push the new instruction and any users onto the worklist.
6869 WorkList.push_back(Result);
6870 AddUsersToWorkList(*Result);
6872 // Move the name to the new instruction first...
6873 std::string OldName = I->getName(); I->setName("");
6874 Result->setName(OldName);
6876 // Insert the new instruction into the basic block...
6877 BasicBlock *InstParent = I->getParent();
6878 BasicBlock::iterator InsertPos = I;
6880 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6881 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6884 InstParent->getInstList().insert(InsertPos, Result);
6886 // Make sure that we reprocess all operands now that we reduced their
6888 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6889 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6890 WorkList.push_back(OpI);
6892 // Instructions can end up on the worklist more than once. Make sure
6893 // we do not process an instruction that has been deleted.
6894 removeFromWorkList(I);
6896 // Erase the old instruction.
6897 InstParent->getInstList().erase(I);
6899 DEBUG(std::cerr << "IC: MOD = " << *I);
6901 // If the instruction was modified, it's possible that it is now dead.
6902 // if so, remove it.
6903 if (isInstructionTriviallyDead(I)) {
6904 // Make sure we process all operands now that we are reducing their
6906 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6907 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6908 WorkList.push_back(OpI);
6910 // Instructions may end up in the worklist more than once. Erase all
6911 // occurrences of this instruction.
6912 removeFromWorkList(I);
6913 I->eraseFromParent();
6915 WorkList.push_back(Result);
6916 AddUsersToWorkList(*Result);
6926 FunctionPass *llvm::createInstructionCombiningPass() {
6927 return new InstCombiner();