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"
56 using namespace llvm::PatternMatch;
59 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
64 class InstCombiner : public FunctionPass,
65 public InstVisitor<InstCombiner, Instruction*> {
66 // Worklist of all of the instructions that need to be simplified.
67 std::vector<Instruction*> WorkList;
70 /// AddUsersToWorkList - When an instruction is simplified, add all users of
71 /// the instruction to the work lists because they might get more simplified
74 void AddUsersToWorkList(Instruction &I) {
75 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
77 WorkList.push_back(cast<Instruction>(*UI));
80 /// AddUsesToWorkList - When an instruction is simplified, add operands to
81 /// the work lists because they might get more simplified now.
83 void AddUsesToWorkList(Instruction &I) {
84 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
85 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
86 WorkList.push_back(Op);
89 // removeFromWorkList - remove all instances of I from the worklist.
90 void removeFromWorkList(Instruction *I);
92 virtual bool runOnFunction(Function &F);
94 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
95 AU.addRequired<TargetData>();
99 TargetData &getTargetData() const { return *TD; }
101 // Visitation implementation - Implement instruction combining for different
102 // instruction types. The semantics are as follows:
104 // null - No change was made
105 // I - Change was made, I is still valid, I may be dead though
106 // otherwise - Change was made, replace I with returned instruction
108 Instruction *visitAdd(BinaryOperator &I);
109 Instruction *visitSub(BinaryOperator &I);
110 Instruction *visitMul(BinaryOperator &I);
111 Instruction *visitDiv(BinaryOperator &I);
112 Instruction *visitRem(BinaryOperator &I);
113 Instruction *visitAnd(BinaryOperator &I);
114 Instruction *visitOr (BinaryOperator &I);
115 Instruction *visitXor(BinaryOperator &I);
116 Instruction *visitSetCondInst(SetCondInst &I);
117 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
119 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120 Instruction::BinaryOps Cond, Instruction &I);
121 Instruction *visitShiftInst(ShiftInst &I);
122 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
124 Instruction *visitCastInst(CastInst &CI);
125 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
127 Instruction *visitSelectInst(SelectInst &CI);
128 Instruction *visitCallInst(CallInst &CI);
129 Instruction *visitInvokeInst(InvokeInst &II);
130 Instruction *visitPHINode(PHINode &PN);
131 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
132 Instruction *visitAllocationInst(AllocationInst &AI);
133 Instruction *visitFreeInst(FreeInst &FI);
134 Instruction *visitLoadInst(LoadInst &LI);
135 Instruction *visitStoreInst(StoreInst &SI);
136 Instruction *visitBranchInst(BranchInst &BI);
137 Instruction *visitSwitchInst(SwitchInst &SI);
138 Instruction *visitExtractElementInst(ExtractElementInst &EI);
140 // visitInstruction - Specify what to return for unhandled instructions...
141 Instruction *visitInstruction(Instruction &I) { return 0; }
144 Instruction *visitCallSite(CallSite CS);
145 bool transformConstExprCastCall(CallSite CS);
148 // InsertNewInstBefore - insert an instruction New before instruction Old
149 // in the program. Add the new instruction to the worklist.
151 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
152 assert(New && New->getParent() == 0 &&
153 "New instruction already inserted into a basic block!");
154 BasicBlock *BB = Old.getParent();
155 BB->getInstList().insert(&Old, New); // Insert inst
156 WorkList.push_back(New); // Add to worklist
160 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
161 /// This also adds the cast to the worklist. Finally, this returns the
163 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
164 if (V->getType() == Ty) return V;
166 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
167 WorkList.push_back(C);
171 // ReplaceInstUsesWith - This method is to be used when an instruction is
172 // found to be dead, replacable with another preexisting expression. Here
173 // we add all uses of I to the worklist, replace all uses of I with the new
174 // value, then return I, so that the inst combiner will know that I was
177 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
178 AddUsersToWorkList(I); // Add all modified instrs to worklist
180 I.replaceAllUsesWith(V);
183 // If we are replacing the instruction with itself, this must be in a
184 // segment of unreachable code, so just clobber the instruction.
185 I.replaceAllUsesWith(UndefValue::get(I.getType()));
190 // EraseInstFromFunction - When dealing with an instruction that has side
191 // effects or produces a void value, we can't rely on DCE to delete the
192 // instruction. Instead, visit methods should return the value returned by
194 Instruction *EraseInstFromFunction(Instruction &I) {
195 assert(I.use_empty() && "Cannot erase instruction that is used!");
196 AddUsesToWorkList(I);
197 removeFromWorkList(&I);
199 return 0; // Don't do anything with FI
204 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
205 /// InsertBefore instruction. This is specialized a bit to avoid inserting
206 /// casts that are known to not do anything...
208 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
209 Instruction *InsertBefore);
211 // SimplifyCommutative - This performs a few simplifications for commutative
213 bool SimplifyCommutative(BinaryOperator &I);
216 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
217 // PHI node as operand #0, see if we can fold the instruction into the PHI
218 // (which is only possible if all operands to the PHI are constants).
219 Instruction *FoldOpIntoPhi(Instruction &I);
221 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
222 // operator and they all are only used by the PHI, PHI together their
223 // inputs, and do the operation once, to the result of the PHI.
224 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
226 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
227 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
229 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
230 bool isSub, Instruction &I);
231 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
232 bool Inside, Instruction &IB);
233 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
236 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
239 // getComplexity: Assign a complexity or rank value to LLVM Values...
240 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
241 static unsigned getComplexity(Value *V) {
242 if (isa<Instruction>(V)) {
243 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
247 if (isa<Argument>(V)) return 3;
248 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
251 // isOnlyUse - Return true if this instruction will be deleted if we stop using
253 static bool isOnlyUse(Value *V) {
254 return V->hasOneUse() || isa<Constant>(V);
257 // getPromotedType - Return the specified type promoted as it would be to pass
258 // though a va_arg area...
259 static const Type *getPromotedType(const Type *Ty) {
260 switch (Ty->getTypeID()) {
261 case Type::SByteTyID:
262 case Type::ShortTyID: return Type::IntTy;
263 case Type::UByteTyID:
264 case Type::UShortTyID: return Type::UIntTy;
265 case Type::FloatTyID: return Type::DoubleTy;
270 /// isCast - If the specified operand is a CastInst or a constant expr cast,
271 /// return the operand value, otherwise return null.
272 static Value *isCast(Value *V) {
273 if (CastInst *I = dyn_cast<CastInst>(V))
274 return I->getOperand(0);
275 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
276 if (CE->getOpcode() == Instruction::Cast)
277 return CE->getOperand(0);
281 // SimplifyCommutative - This performs a few simplifications for commutative
284 // 1. Order operands such that they are listed from right (least complex) to
285 // left (most complex). This puts constants before unary operators before
288 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
289 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
291 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
292 bool Changed = false;
293 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
294 Changed = !I.swapOperands();
296 if (!I.isAssociative()) return Changed;
297 Instruction::BinaryOps Opcode = I.getOpcode();
298 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
299 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
300 if (isa<Constant>(I.getOperand(1))) {
301 Constant *Folded = ConstantExpr::get(I.getOpcode(),
302 cast<Constant>(I.getOperand(1)),
303 cast<Constant>(Op->getOperand(1)));
304 I.setOperand(0, Op->getOperand(0));
305 I.setOperand(1, Folded);
307 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
308 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
309 isOnlyUse(Op) && isOnlyUse(Op1)) {
310 Constant *C1 = cast<Constant>(Op->getOperand(1));
311 Constant *C2 = cast<Constant>(Op1->getOperand(1));
313 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
314 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
315 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
318 WorkList.push_back(New);
319 I.setOperand(0, New);
320 I.setOperand(1, Folded);
327 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
328 // if the LHS is a constant zero (which is the 'negate' form).
330 static inline Value *dyn_castNegVal(Value *V) {
331 if (BinaryOperator::isNeg(V))
332 return BinaryOperator::getNegArgument(V);
334 // Constants can be considered to be negated values if they can be folded.
335 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
336 return ConstantExpr::getNeg(C);
340 static inline Value *dyn_castNotVal(Value *V) {
341 if (BinaryOperator::isNot(V))
342 return BinaryOperator::getNotArgument(V);
344 // Constants can be considered to be not'ed values...
345 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
346 return ConstantExpr::getNot(C);
350 // dyn_castFoldableMul - If this value is a multiply that can be folded into
351 // other computations (because it has a constant operand), return the
352 // non-constant operand of the multiply, and set CST to point to the multiplier.
353 // Otherwise, return null.
355 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
356 if (V->hasOneUse() && V->getType()->isInteger())
357 if (Instruction *I = dyn_cast<Instruction>(V)) {
358 if (I->getOpcode() == Instruction::Mul)
359 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
360 return I->getOperand(0);
361 if (I->getOpcode() == Instruction::Shl)
362 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
363 // The multiplier is really 1 << CST.
364 Constant *One = ConstantInt::get(V->getType(), 1);
365 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
366 return I->getOperand(0);
372 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
373 /// expression, return it.
374 static User *dyn_castGetElementPtr(Value *V) {
375 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
377 if (CE->getOpcode() == Instruction::GetElementPtr)
378 return cast<User>(V);
382 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
383 static ConstantInt *AddOne(ConstantInt *C) {
384 return cast<ConstantInt>(ConstantExpr::getAdd(C,
385 ConstantInt::get(C->getType(), 1)));
387 static ConstantInt *SubOne(ConstantInt *C) {
388 return cast<ConstantInt>(ConstantExpr::getSub(C,
389 ConstantInt::get(C->getType(), 1)));
392 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
393 /// this predicate to simplify operations downstream. V and Mask are known to
394 /// be the same type.
395 static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask,
396 unsigned Depth = 0) {
397 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
398 // we cannot optimize based on the assumption that it is zero without changing
399 // to to an explicit zero. If we don't change it to zero, other code could
400 // optimized based on the contradictory assumption that it is non-zero.
401 // Because instcombine aggressively folds operations with undef args anyway,
402 // this won't lose us code quality.
403 if (Mask->isNullValue())
405 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
406 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
408 if (Depth == 6) return false; // Limit search depth.
410 if (Instruction *I = dyn_cast<Instruction>(V)) {
411 switch (I->getOpcode()) {
412 case Instruction::And:
413 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
414 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
415 ConstantIntegral *C1C2 =
416 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
417 if (MaskedValueIsZero(I->getOperand(0), C1C2, Depth+1))
420 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
421 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
422 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
423 case Instruction::Or:
424 case Instruction::Xor:
425 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
426 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
427 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
428 case Instruction::Select:
429 // If the T and F values are MaskedValueIsZero, the result is also zero.
430 return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
431 MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
432 case Instruction::Cast: {
433 const Type *SrcTy = I->getOperand(0)->getType();
434 if (SrcTy == Type::BoolTy)
435 return (Mask->getRawValue() & 1) == 0;
437 if (SrcTy->isInteger()) {
438 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
439 if (SrcTy->isUnsigned() && // Only handle zero ext.
440 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
443 // If this is a noop cast, recurse.
444 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
445 SrcTy->getSignedVersion() == I->getType()) {
447 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
448 return MaskedValueIsZero(I->getOperand(0),
449 cast<ConstantIntegral>(NewMask), Depth+1);
454 case Instruction::Shl:
455 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
456 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
457 return MaskedValueIsZero(I->getOperand(0),
458 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)),
461 case Instruction::Shr:
462 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
463 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
464 if (I->getType()->isUnsigned()) {
465 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
466 C1 = ConstantExpr::getShr(C1, SA);
467 C1 = ConstantExpr::getAnd(C1, Mask);
468 if (C1->isNullValue())
478 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
479 // true when both operands are equal...
481 static bool isTrueWhenEqual(Instruction &I) {
482 return I.getOpcode() == Instruction::SetEQ ||
483 I.getOpcode() == Instruction::SetGE ||
484 I.getOpcode() == Instruction::SetLE;
487 /// AssociativeOpt - Perform an optimization on an associative operator. This
488 /// function is designed to check a chain of associative operators for a
489 /// potential to apply a certain optimization. Since the optimization may be
490 /// applicable if the expression was reassociated, this checks the chain, then
491 /// reassociates the expression as necessary to expose the optimization
492 /// opportunity. This makes use of a special Functor, which must define
493 /// 'shouldApply' and 'apply' methods.
495 template<typename Functor>
496 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
497 unsigned Opcode = Root.getOpcode();
498 Value *LHS = Root.getOperand(0);
500 // Quick check, see if the immediate LHS matches...
501 if (F.shouldApply(LHS))
502 return F.apply(Root);
504 // Otherwise, if the LHS is not of the same opcode as the root, return.
505 Instruction *LHSI = dyn_cast<Instruction>(LHS);
506 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
507 // Should we apply this transform to the RHS?
508 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
510 // If not to the RHS, check to see if we should apply to the LHS...
511 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
512 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
516 // If the functor wants to apply the optimization to the RHS of LHSI,
517 // reassociate the expression from ((? op A) op B) to (? op (A op B))
519 BasicBlock *BB = Root.getParent();
521 // Now all of the instructions are in the current basic block, go ahead
522 // and perform the reassociation.
523 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
525 // First move the selected RHS to the LHS of the root...
526 Root.setOperand(0, LHSI->getOperand(1));
528 // Make what used to be the LHS of the root be the user of the root...
529 Value *ExtraOperand = TmpLHSI->getOperand(1);
530 if (&Root == TmpLHSI) {
531 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
534 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
535 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
536 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
537 BasicBlock::iterator ARI = &Root; ++ARI;
538 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
541 // Now propagate the ExtraOperand down the chain of instructions until we
543 while (TmpLHSI != LHSI) {
544 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
545 // Move the instruction to immediately before the chain we are
546 // constructing to avoid breaking dominance properties.
547 NextLHSI->getParent()->getInstList().remove(NextLHSI);
548 BB->getInstList().insert(ARI, NextLHSI);
551 Value *NextOp = NextLHSI->getOperand(1);
552 NextLHSI->setOperand(1, ExtraOperand);
554 ExtraOperand = NextOp;
557 // Now that the instructions are reassociated, have the functor perform
558 // the transformation...
559 return F.apply(Root);
562 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
568 // AddRHS - Implements: X + X --> X << 1
571 AddRHS(Value *rhs) : RHS(rhs) {}
572 bool shouldApply(Value *LHS) const { return LHS == RHS; }
573 Instruction *apply(BinaryOperator &Add) const {
574 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
575 ConstantInt::get(Type::UByteTy, 1));
579 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
581 struct AddMaskingAnd {
583 AddMaskingAnd(Constant *c) : C2(c) {}
584 bool shouldApply(Value *LHS) const {
586 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
587 ConstantExpr::getAnd(C1, C2)->isNullValue();
589 Instruction *apply(BinaryOperator &Add) const {
590 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
594 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
596 if (isa<CastInst>(I)) {
597 if (Constant *SOC = dyn_cast<Constant>(SO))
598 return ConstantExpr::getCast(SOC, I.getType());
600 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
601 SO->getName() + ".cast"), I);
604 // Figure out if the constant is the left or the right argument.
605 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
606 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
608 if (Constant *SOC = dyn_cast<Constant>(SO)) {
610 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
611 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
614 Value *Op0 = SO, *Op1 = ConstOperand;
618 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
619 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
620 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
621 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
623 assert(0 && "Unknown binary instruction type!");
626 return IC->InsertNewInstBefore(New, I);
629 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
630 // constant as the other operand, try to fold the binary operator into the
631 // select arguments. This also works for Cast instructions, which obviously do
632 // not have a second operand.
633 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
635 // Don't modify shared select instructions
636 if (!SI->hasOneUse()) return 0;
637 Value *TV = SI->getOperand(1);
638 Value *FV = SI->getOperand(2);
640 if (isa<Constant>(TV) || isa<Constant>(FV)) {
641 // Bool selects with constant operands can be folded to logical ops.
642 if (SI->getType() == Type::BoolTy) return 0;
644 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
645 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
647 return new SelectInst(SI->getCondition(), SelectTrueVal,
654 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
655 /// node as operand #0, see if we can fold the instruction into the PHI (which
656 /// is only possible if all operands to the PHI are constants).
657 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
658 PHINode *PN = cast<PHINode>(I.getOperand(0));
659 unsigned NumPHIValues = PN->getNumIncomingValues();
660 if (!PN->hasOneUse() || NumPHIValues == 0 ||
661 !isa<Constant>(PN->getIncomingValue(0))) return 0;
663 // Check to see if all of the operands of the PHI are constants. If not, we
664 // cannot do the transformation.
665 for (unsigned i = 1; i != NumPHIValues; ++i)
666 if (!isa<Constant>(PN->getIncomingValue(i)))
669 // Okay, we can do the transformation: create the new PHI node.
670 PHINode *NewPN = new PHINode(I.getType(), I.getName());
672 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
673 InsertNewInstBefore(NewPN, *PN);
675 // Next, add all of the operands to the PHI.
676 if (I.getNumOperands() == 2) {
677 Constant *C = cast<Constant>(I.getOperand(1));
678 for (unsigned i = 0; i != NumPHIValues; ++i) {
679 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
680 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
681 PN->getIncomingBlock(i));
684 assert(isa<CastInst>(I) && "Unary op should be a cast!");
685 const Type *RetTy = I.getType();
686 for (unsigned i = 0; i != NumPHIValues; ++i) {
687 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
688 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
689 PN->getIncomingBlock(i));
692 return ReplaceInstUsesWith(I, NewPN);
695 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
696 bool Changed = SimplifyCommutative(I);
697 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
699 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
700 // X + undef -> undef
701 if (isa<UndefValue>(RHS))
702 return ReplaceInstUsesWith(I, RHS);
705 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
706 if (RHSC->isNullValue())
707 return ReplaceInstUsesWith(I, LHS);
708 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
709 if (CFP->isExactlyValue(-0.0))
710 return ReplaceInstUsesWith(I, LHS);
713 // X + (signbit) --> X ^ signbit
714 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
715 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
716 uint64_t Val = CI->getRawValue() & (~0ULL >> (64- NumBits));
717 if (Val == (1ULL << (NumBits-1)))
718 return BinaryOperator::createXor(LHS, RHS);
721 if (isa<PHINode>(LHS))
722 if (Instruction *NV = FoldOpIntoPhi(I))
725 ConstantInt *XorRHS = 0;
727 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
728 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
729 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
730 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
732 uint64_t C0080Val = 1ULL << 31;
733 int64_t CFF80Val = -C0080Val;
736 if (TySizeBits > Size) {
738 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
739 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
740 if (RHSSExt == CFF80Val) {
741 if (XorRHS->getZExtValue() == C0080Val)
743 } else if (RHSZExt == C0080Val) {
744 if (XorRHS->getSExtValue() == CFF80Val)
748 // This is a sign extend if the top bits are known zero.
749 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
750 Mask = ConstantExpr::getShl(Mask,
751 ConstantInt::get(Type::UByteTy, 64-(TySizeBits-Size)));
752 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
753 Size = 0; // Not a sign ext, but can't be any others either.
763 const Type *MiddleType = 0;
766 case 32: MiddleType = Type::IntTy; break;
767 case 16: MiddleType = Type::ShortTy; break;
768 case 8: MiddleType = Type::SByteTy; break;
771 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
772 InsertNewInstBefore(NewTrunc, I);
773 return new CastInst(NewTrunc, I.getType());
779 if (I.getType()->isInteger()) {
780 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
782 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
783 if (RHSI->getOpcode() == Instruction::Sub)
784 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
785 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
787 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
788 if (LHSI->getOpcode() == Instruction::Sub)
789 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
790 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
795 if (Value *V = dyn_castNegVal(LHS))
796 return BinaryOperator::createSub(RHS, V);
799 if (!isa<Constant>(RHS))
800 if (Value *V = dyn_castNegVal(RHS))
801 return BinaryOperator::createSub(LHS, V);
805 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
806 if (X == RHS) // X*C + X --> X * (C+1)
807 return BinaryOperator::createMul(RHS, AddOne(C2));
809 // X*C1 + X*C2 --> X * (C1+C2)
811 if (X == dyn_castFoldableMul(RHS, C1))
812 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
815 // X + X*C --> X * (C+1)
816 if (dyn_castFoldableMul(RHS, C2) == LHS)
817 return BinaryOperator::createMul(LHS, AddOne(C2));
820 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
821 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
822 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
824 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
826 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
827 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
828 return BinaryOperator::createSub(C, X);
831 // (X & FF00) + xx00 -> (X+xx00) & FF00
832 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
833 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
835 // See if all bits from the first bit set in the Add RHS up are included
836 // in the mask. First, get the rightmost bit.
837 uint64_t AddRHSV = CRHS->getRawValue();
839 // Form a mask of all bits from the lowest bit added through the top.
840 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
841 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
843 // See if the and mask includes all of these bits.
844 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
846 if (AddRHSHighBits == AddRHSHighBitsAnd) {
847 // Okay, the xform is safe. Insert the new add pronto.
848 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
850 return BinaryOperator::createAnd(NewAdd, C2);
855 // Try to fold constant add into select arguments.
856 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
857 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
861 return Changed ? &I : 0;
864 // isSignBit - Return true if the value represented by the constant only has the
865 // highest order bit set.
866 static bool isSignBit(ConstantInt *CI) {
867 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
868 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
871 /// RemoveNoopCast - Strip off nonconverting casts from the value.
873 static Value *RemoveNoopCast(Value *V) {
874 if (CastInst *CI = dyn_cast<CastInst>(V)) {
875 const Type *CTy = CI->getType();
876 const Type *OpTy = CI->getOperand(0)->getType();
877 if (CTy->isInteger() && OpTy->isInteger()) {
878 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
879 return RemoveNoopCast(CI->getOperand(0));
880 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
881 return RemoveNoopCast(CI->getOperand(0));
886 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
887 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
889 if (Op0 == Op1) // sub X, X -> 0
890 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
892 // If this is a 'B = x-(-A)', change to B = x+A...
893 if (Value *V = dyn_castNegVal(Op1))
894 return BinaryOperator::createAdd(Op0, V);
896 if (isa<UndefValue>(Op0))
897 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
898 if (isa<UndefValue>(Op1))
899 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
901 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
902 // Replace (-1 - A) with (~A)...
903 if (C->isAllOnesValue())
904 return BinaryOperator::createNot(Op1);
906 // C - ~X == X + (1+C)
908 if (match(Op1, m_Not(m_Value(X))))
909 return BinaryOperator::createAdd(X,
910 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
911 // -((uint)X >> 31) -> ((int)X >> 31)
912 // -((int)X >> 31) -> ((uint)X >> 31)
913 if (C->isNullValue()) {
914 Value *NoopCastedRHS = RemoveNoopCast(Op1);
915 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
916 if (SI->getOpcode() == Instruction::Shr)
917 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
919 if (SI->getType()->isSigned())
920 NewTy = SI->getType()->getUnsignedVersion();
922 NewTy = SI->getType()->getSignedVersion();
923 // Check to see if we are shifting out everything but the sign bit.
924 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
925 // Ok, the transformation is safe. Insert a cast of the incoming
926 // value, then the new shift, then the new cast.
927 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
928 SI->getOperand(0)->getName());
929 Value *InV = InsertNewInstBefore(FirstCast, I);
930 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
932 if (NewShift->getType() == I.getType())
935 InV = InsertNewInstBefore(NewShift, I);
936 return new CastInst(NewShift, I.getType());
942 // Try to fold constant sub into select arguments.
943 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
944 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
947 if (isa<PHINode>(Op0))
948 if (Instruction *NV = FoldOpIntoPhi(I))
952 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
953 if (Op1I->getOpcode() == Instruction::Add &&
954 !Op0->getType()->isFloatingPoint()) {
955 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
956 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
957 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
958 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
959 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
960 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
961 // C1-(X+C2) --> (C1-C2)-X
962 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
963 Op1I->getOperand(0));
967 if (Op1I->hasOneUse()) {
968 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
969 // is not used by anyone else...
971 if (Op1I->getOpcode() == Instruction::Sub &&
972 !Op1I->getType()->isFloatingPoint()) {
973 // Swap the two operands of the subexpr...
974 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
975 Op1I->setOperand(0, IIOp1);
976 Op1I->setOperand(1, IIOp0);
978 // Create the new top level add instruction...
979 return BinaryOperator::createAdd(Op0, Op1);
982 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
984 if (Op1I->getOpcode() == Instruction::And &&
985 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
986 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
989 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
990 return BinaryOperator::createAnd(Op0, NewNot);
993 // -(X sdiv C) -> (X sdiv -C)
994 if (Op1I->getOpcode() == Instruction::Div)
995 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
996 if (CSI->isNullValue())
997 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
998 return BinaryOperator::createDiv(Op1I->getOperand(0),
999 ConstantExpr::getNeg(DivRHS));
1001 // X - X*C --> X * (1-C)
1002 ConstantInt *C2 = 0;
1003 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1005 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1006 return BinaryOperator::createMul(Op0, CP1);
1011 if (!Op0->getType()->isFloatingPoint())
1012 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1013 if (Op0I->getOpcode() == Instruction::Add) {
1014 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1015 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1016 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1017 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1018 } else if (Op0I->getOpcode() == Instruction::Sub) {
1019 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1020 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1024 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1025 if (X == Op1) { // X*C - X --> X * (C-1)
1026 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1027 return BinaryOperator::createMul(Op1, CP1);
1030 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1031 if (X == dyn_castFoldableMul(Op1, C2))
1032 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1037 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1038 /// really just returns true if the most significant (sign) bit is set.
1039 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1040 if (RHS->getType()->isSigned()) {
1041 // True if source is LHS < 0 or LHS <= -1
1042 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1043 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1045 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1046 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1047 // the size of the integer type.
1048 if (Opcode == Instruction::SetGE)
1049 return RHSC->getValue() ==
1050 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1051 if (Opcode == Instruction::SetGT)
1052 return RHSC->getValue() ==
1053 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1058 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1059 bool Changed = SimplifyCommutative(I);
1060 Value *Op0 = I.getOperand(0);
1062 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1063 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1065 // Simplify mul instructions with a constant RHS...
1066 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1067 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1069 // ((X << C1)*C2) == (X * (C2 << C1))
1070 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1071 if (SI->getOpcode() == Instruction::Shl)
1072 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1073 return BinaryOperator::createMul(SI->getOperand(0),
1074 ConstantExpr::getShl(CI, ShOp));
1076 if (CI->isNullValue())
1077 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1078 if (CI->equalsInt(1)) // X * 1 == X
1079 return ReplaceInstUsesWith(I, Op0);
1080 if (CI->isAllOnesValue()) // X * -1 == 0 - X
1081 return BinaryOperator::createNeg(Op0, I.getName());
1083 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1084 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1085 uint64_t C = Log2_64(Val);
1086 return new ShiftInst(Instruction::Shl, Op0,
1087 ConstantUInt::get(Type::UByteTy, C));
1089 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1090 if (Op1F->isNullValue())
1091 return ReplaceInstUsesWith(I, Op1);
1093 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1094 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1095 if (Op1F->getValue() == 1.0)
1096 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1099 // Try to fold constant mul into select arguments.
1100 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1101 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1104 if (isa<PHINode>(Op0))
1105 if (Instruction *NV = FoldOpIntoPhi(I))
1109 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1110 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1111 return BinaryOperator::createMul(Op0v, Op1v);
1113 // If one of the operands of the multiply is a cast from a boolean value, then
1114 // we know the bool is either zero or one, so this is a 'masking' multiply.
1115 // See if we can simplify things based on how the boolean was originally
1117 CastInst *BoolCast = 0;
1118 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1119 if (CI->getOperand(0)->getType() == Type::BoolTy)
1122 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1123 if (CI->getOperand(0)->getType() == Type::BoolTy)
1126 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1127 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1128 const Type *SCOpTy = SCIOp0->getType();
1130 // If the setcc is true iff the sign bit of X is set, then convert this
1131 // multiply into a shift/and combination.
1132 if (isa<ConstantInt>(SCIOp1) &&
1133 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1134 // Shift the X value right to turn it into "all signbits".
1135 Constant *Amt = ConstantUInt::get(Type::UByteTy,
1136 SCOpTy->getPrimitiveSizeInBits()-1);
1137 if (SCIOp0->getType()->isUnsigned()) {
1138 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1139 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1140 SCIOp0->getName()), I);
1144 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1145 BoolCast->getOperand(0)->getName()+
1148 // If the multiply type is not the same as the source type, sign extend
1149 // or truncate to the multiply type.
1150 if (I.getType() != V->getType())
1151 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1153 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1154 return BinaryOperator::createAnd(V, OtherOp);
1159 return Changed ? &I : 0;
1162 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1163 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1165 if (isa<UndefValue>(Op0)) // undef / X -> 0
1166 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1167 if (isa<UndefValue>(Op1))
1168 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1170 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1172 if (RHS->equalsInt(1))
1173 return ReplaceInstUsesWith(I, Op0);
1176 if (RHS->isAllOnesValue())
1177 return BinaryOperator::createNeg(Op0);
1179 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1180 if (LHS->getOpcode() == Instruction::Div)
1181 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1182 // (X / C1) / C2 -> X / (C1*C2)
1183 return BinaryOperator::createDiv(LHS->getOperand(0),
1184 ConstantExpr::getMul(RHS, LHSRHS));
1187 // Check to see if this is an unsigned division with an exact power of 2,
1188 // if so, convert to a right shift.
1189 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1190 if (uint64_t Val = C->getValue()) // Don't break X / 0
1191 if (isPowerOf2_64(Val)) {
1192 uint64_t C = Log2_64(Val);
1193 return new ShiftInst(Instruction::Shr, Op0,
1194 ConstantUInt::get(Type::UByteTy, C));
1198 if (RHS->getType()->isSigned())
1199 if (Value *LHSNeg = dyn_castNegVal(Op0))
1200 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1202 if (!RHS->isNullValue()) {
1203 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1204 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1206 if (isa<PHINode>(Op0))
1207 if (Instruction *NV = FoldOpIntoPhi(I))
1212 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1213 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1214 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1215 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1216 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1217 if (STO->getValue() == 0) { // Couldn't be this argument.
1218 I.setOperand(1, SFO);
1220 } else if (SFO->getValue() == 0) {
1221 I.setOperand(1, STO);
1225 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1226 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1227 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1228 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1229 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1230 TC, SI->getName()+".t");
1231 TSI = InsertNewInstBefore(TSI, I);
1233 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1234 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1235 FC, SI->getName()+".f");
1236 FSI = InsertNewInstBefore(FSI, I);
1237 return new SelectInst(SI->getOperand(0), TSI, FSI);
1241 // 0 / X == 0, we don't need to preserve faults!
1242 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1243 if (LHS->equalsInt(0))
1244 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1246 if (I.getType()->isSigned()) {
1247 // If the top bits of both operands are zero (i.e. we can prove they are
1248 // unsigned inputs), turn this into a udiv.
1249 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1250 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1251 const Type *NTy = Op0->getType()->getUnsignedVersion();
1252 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1253 InsertNewInstBefore(LHS, I);
1255 if (Constant *R = dyn_cast<Constant>(Op1))
1256 RHS = ConstantExpr::getCast(R, NTy);
1258 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1259 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1260 InsertNewInstBefore(Div, I);
1261 return new CastInst(Div, I.getType());
1269 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1271 if (I.getType()->isSigned()) {
1272 if (Value *RHSNeg = dyn_castNegVal(Op1))
1273 if (!isa<ConstantSInt>(RHSNeg) ||
1274 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1276 AddUsesToWorkList(I);
1277 I.setOperand(1, RHSNeg);
1281 // If the top bits of both operands are zero (i.e. we can prove they are
1282 // unsigned inputs), turn this into a urem.
1283 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1284 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1285 const Type *NTy = Op0->getType()->getUnsignedVersion();
1286 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1287 InsertNewInstBefore(LHS, I);
1289 if (Constant *R = dyn_cast<Constant>(Op1))
1290 RHS = ConstantExpr::getCast(R, NTy);
1292 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1293 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1294 InsertNewInstBefore(Rem, I);
1295 return new CastInst(Rem, I.getType());
1299 if (isa<UndefValue>(Op0)) // undef % X -> 0
1300 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1301 if (isa<UndefValue>(Op1))
1302 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1304 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1305 if (RHS->equalsInt(1)) // X % 1 == 0
1306 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1308 // Check to see if this is an unsigned remainder with an exact power of 2,
1309 // if so, convert to a bitwise and.
1310 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1311 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
1312 if (!(Val & (Val-1))) // Power of 2
1313 return BinaryOperator::createAnd(Op0,
1314 ConstantUInt::get(I.getType(), Val-1));
1316 if (!RHS->isNullValue()) {
1317 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1318 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1320 if (isa<PHINode>(Op0))
1321 if (Instruction *NV = FoldOpIntoPhi(I))
1326 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1327 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1328 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1329 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1330 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1331 if (STO->getValue() == 0) { // Couldn't be this argument.
1332 I.setOperand(1, SFO);
1334 } else if (SFO->getValue() == 0) {
1335 I.setOperand(1, STO);
1339 if (!(STO->getValue() & (STO->getValue()-1)) &&
1340 !(SFO->getValue() & (SFO->getValue()-1))) {
1341 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1342 SubOne(STO), SI->getName()+".t"), I);
1343 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1344 SubOne(SFO), SI->getName()+".f"), I);
1345 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1349 // 0 % X == 0, we don't need to preserve faults!
1350 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1351 if (LHS->equalsInt(0))
1352 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1357 // isMaxValueMinusOne - return true if this is Max-1
1358 static bool isMaxValueMinusOne(const ConstantInt *C) {
1359 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1360 // Calculate -1 casted to the right type...
1361 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1362 uint64_t Val = ~0ULL; // All ones
1363 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1364 return CU->getValue() == Val-1;
1367 const ConstantSInt *CS = cast<ConstantSInt>(C);
1369 // Calculate 0111111111..11111
1370 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1371 int64_t Val = INT64_MAX; // All ones
1372 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1373 return CS->getValue() == Val-1;
1376 // isMinValuePlusOne - return true if this is Min+1
1377 static bool isMinValuePlusOne(const ConstantInt *C) {
1378 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1379 return CU->getValue() == 1;
1381 const ConstantSInt *CS = cast<ConstantSInt>(C);
1383 // Calculate 1111111111000000000000
1384 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1385 int64_t Val = -1; // All ones
1386 Val <<= TypeBits-1; // Shift over to the right spot
1387 return CS->getValue() == Val+1;
1390 // isOneBitSet - Return true if there is exactly one bit set in the specified
1392 static bool isOneBitSet(const ConstantInt *CI) {
1393 uint64_t V = CI->getRawValue();
1394 return V && (V & (V-1)) == 0;
1397 #if 0 // Currently unused
1398 // isLowOnes - Return true if the constant is of the form 0+1+.
1399 static bool isLowOnes(const ConstantInt *CI) {
1400 uint64_t V = CI->getRawValue();
1402 // There won't be bits set in parts that the type doesn't contain.
1403 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1405 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1406 return U && V && (U & V) == 0;
1410 // isHighOnes - Return true if the constant is of the form 1+0+.
1411 // This is the same as lowones(~X).
1412 static bool isHighOnes(const ConstantInt *CI) {
1413 uint64_t V = ~CI->getRawValue();
1414 if (~V == 0) return false; // 0's does not match "1+"
1416 // There won't be bits set in parts that the type doesn't contain.
1417 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1419 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1420 return U && V && (U & V) == 0;
1424 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1425 /// are carefully arranged to allow folding of expressions such as:
1427 /// (A < B) | (A > B) --> (A != B)
1429 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1430 /// represents that the comparison is true if A == B, and bit value '1' is true
1433 static unsigned getSetCondCode(const SetCondInst *SCI) {
1434 switch (SCI->getOpcode()) {
1436 case Instruction::SetGT: return 1;
1437 case Instruction::SetEQ: return 2;
1438 case Instruction::SetGE: return 3;
1439 case Instruction::SetLT: return 4;
1440 case Instruction::SetNE: return 5;
1441 case Instruction::SetLE: return 6;
1444 assert(0 && "Invalid SetCC opcode!");
1449 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1450 /// opcode and two operands into either a constant true or false, or a brand new
1451 /// SetCC instruction.
1452 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1454 case 0: return ConstantBool::False;
1455 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1456 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1457 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1458 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1459 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1460 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1461 case 7: return ConstantBool::True;
1462 default: assert(0 && "Illegal SetCCCode!"); return 0;
1466 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1467 struct FoldSetCCLogical {
1470 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1471 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1472 bool shouldApply(Value *V) const {
1473 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1474 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1475 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1478 Instruction *apply(BinaryOperator &Log) const {
1479 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1480 if (SCI->getOperand(0) != LHS) {
1481 assert(SCI->getOperand(1) == LHS);
1482 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1485 unsigned LHSCode = getSetCondCode(SCI);
1486 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1488 switch (Log.getOpcode()) {
1489 case Instruction::And: Code = LHSCode & RHSCode; break;
1490 case Instruction::Or: Code = LHSCode | RHSCode; break;
1491 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1492 default: assert(0 && "Illegal logical opcode!"); return 0;
1495 Value *RV = getSetCCValue(Code, LHS, RHS);
1496 if (Instruction *I = dyn_cast<Instruction>(RV))
1498 // Otherwise, it's a constant boolean value...
1499 return IC.ReplaceInstUsesWith(Log, RV);
1503 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1504 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1505 // guaranteed to be either a shift instruction or a binary operator.
1506 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1507 ConstantIntegral *OpRHS,
1508 ConstantIntegral *AndRHS,
1509 BinaryOperator &TheAnd) {
1510 Value *X = Op->getOperand(0);
1511 Constant *Together = 0;
1512 if (!isa<ShiftInst>(Op))
1513 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1515 switch (Op->getOpcode()) {
1516 case Instruction::Xor:
1517 if (Op->hasOneUse()) {
1518 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1519 std::string OpName = Op->getName(); Op->setName("");
1520 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1521 InsertNewInstBefore(And, TheAnd);
1522 return BinaryOperator::createXor(And, Together);
1525 case Instruction::Or:
1526 if (Together == AndRHS) // (X | C) & C --> C
1527 return ReplaceInstUsesWith(TheAnd, AndRHS);
1529 if (Op->hasOneUse() && Together != OpRHS) {
1530 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1531 std::string Op0Name = Op->getName(); Op->setName("");
1532 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1533 InsertNewInstBefore(Or, TheAnd);
1534 return BinaryOperator::createAnd(Or, AndRHS);
1537 case Instruction::Add:
1538 if (Op->hasOneUse()) {
1539 // Adding a one to a single bit bit-field should be turned into an XOR
1540 // of the bit. First thing to check is to see if this AND is with a
1541 // single bit constant.
1542 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1544 // Clear bits that are not part of the constant.
1545 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
1547 // If there is only one bit set...
1548 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1549 // Ok, at this point, we know that we are masking the result of the
1550 // ADD down to exactly one bit. If the constant we are adding has
1551 // no bits set below this bit, then we can eliminate the ADD.
1552 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1554 // Check to see if any bits below the one bit set in AndRHSV are set.
1555 if ((AddRHS & (AndRHSV-1)) == 0) {
1556 // If not, the only thing that can effect the output of the AND is
1557 // the bit specified by AndRHSV. If that bit is set, the effect of
1558 // the XOR is to toggle the bit. If it is clear, then the ADD has
1560 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1561 TheAnd.setOperand(0, X);
1564 std::string Name = Op->getName(); Op->setName("");
1565 // Pull the XOR out of the AND.
1566 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1567 InsertNewInstBefore(NewAnd, TheAnd);
1568 return BinaryOperator::createXor(NewAnd, AndRHS);
1575 case Instruction::Shl: {
1576 // We know that the AND will not produce any of the bits shifted in, so if
1577 // the anded constant includes them, clear them now!
1579 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1580 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1581 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1583 if (CI == ShlMask) { // Masking out bits that the shift already masks
1584 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1585 } else if (CI != AndRHS) { // Reducing bits set in and.
1586 TheAnd.setOperand(1, CI);
1591 case Instruction::Shr:
1592 // We know that the AND will not produce any of the bits shifted in, so if
1593 // the anded constant includes them, clear them now! This only applies to
1594 // unsigned shifts, because a signed shr may bring in set bits!
1596 if (AndRHS->getType()->isUnsigned()) {
1597 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1598 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1599 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1601 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1602 return ReplaceInstUsesWith(TheAnd, Op);
1603 } else if (CI != AndRHS) {
1604 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1607 } else { // Signed shr.
1608 // See if this is shifting in some sign extension, then masking it out
1610 if (Op->hasOneUse()) {
1611 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1612 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1613 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1614 if (CI == AndRHS) { // Masking out bits shifted in.
1615 // Make the argument unsigned.
1616 Value *ShVal = Op->getOperand(0);
1617 ShVal = InsertCastBefore(ShVal,
1618 ShVal->getType()->getUnsignedVersion(),
1620 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1621 OpRHS, Op->getName()),
1623 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1624 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1627 return new CastInst(ShVal, Op->getType());
1637 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1638 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1639 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1640 /// insert new instructions.
1641 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1642 bool Inside, Instruction &IB) {
1643 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1644 "Lo is not <= Hi in range emission code!");
1646 if (Lo == Hi) // Trivially false.
1647 return new SetCondInst(Instruction::SetNE, V, V);
1648 if (cast<ConstantIntegral>(Lo)->isMinValue())
1649 return new SetCondInst(Instruction::SetLT, V, Hi);
1651 Constant *AddCST = ConstantExpr::getNeg(Lo);
1652 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1653 InsertNewInstBefore(Add, IB);
1654 // Convert to unsigned for the comparison.
1655 const Type *UnsType = Add->getType()->getUnsignedVersion();
1656 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1657 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1658 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1659 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1662 if (Lo == Hi) // Trivially true.
1663 return new SetCondInst(Instruction::SetEQ, V, V);
1665 Hi = SubOne(cast<ConstantInt>(Hi));
1666 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1667 return new SetCondInst(Instruction::SetGT, V, Hi);
1669 // Emit X-Lo > Hi-Lo-1
1670 Constant *AddCST = ConstantExpr::getNeg(Lo);
1671 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1672 InsertNewInstBefore(Add, IB);
1673 // Convert to unsigned for the comparison.
1674 const Type *UnsType = Add->getType()->getUnsignedVersion();
1675 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1676 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1677 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1678 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1681 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1682 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
1683 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1684 // not, since all 1s are not contiguous.
1685 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1686 uint64_t V = Val->getRawValue();
1687 if (!isShiftedMask_64(V)) return false;
1689 // look for the first zero bit after the run of ones
1690 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1691 // look for the first non-zero bit
1692 ME = 64-CountLeadingZeros_64(V);
1698 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1699 /// where isSub determines whether the operator is a sub. If we can fold one of
1700 /// the following xforms:
1702 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1703 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1704 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1706 /// return (A +/- B).
1708 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1709 ConstantIntegral *Mask, bool isSub,
1711 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1712 if (!LHSI || LHSI->getNumOperands() != 2 ||
1713 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1715 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1717 switch (LHSI->getOpcode()) {
1719 case Instruction::And:
1720 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1721 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1722 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1725 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1726 // part, we don't need any explicit masks to take them out of A. If that
1727 // is all N is, ignore it.
1729 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1730 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1731 Mask = ConstantExpr::getUShr(Mask,
1732 ConstantInt::get(Type::UByteTy,
1734 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1739 case Instruction::Or:
1740 case Instruction::Xor:
1741 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1742 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1743 ConstantExpr::getAnd(N, Mask)->isNullValue())
1750 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1752 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1753 return InsertNewInstBefore(New, I);
1756 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1757 bool Changed = SimplifyCommutative(I);
1758 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1760 if (isa<UndefValue>(Op1)) // X & undef -> 0
1761 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1765 return ReplaceInstUsesWith(I, Op1);
1767 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
1769 if (AndRHS->isAllOnesValue())
1770 return ReplaceInstUsesWith(I, Op0);
1772 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1773 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1774 // through many levels of ands.
1776 Value *X = 0; ConstantInt *C1 = 0;
1777 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1778 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1781 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1782 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1784 // If the mask is not masking out any bits, there is no reason to do the
1785 // and in the first place.
1786 ConstantIntegral *NotAndRHS =
1787 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
1788 if (MaskedValueIsZero(Op0, NotAndRHS))
1789 return ReplaceInstUsesWith(I, Op0);
1791 // Optimize a variety of ((val OP C1) & C2) combinations...
1792 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1793 Instruction *Op0I = cast<Instruction>(Op0);
1794 Value *Op0LHS = Op0I->getOperand(0);
1795 Value *Op0RHS = Op0I->getOperand(1);
1796 switch (Op0I->getOpcode()) {
1797 case Instruction::Xor:
1798 case Instruction::Or:
1799 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1800 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1801 if (MaskedValueIsZero(Op0LHS, AndRHS))
1802 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1803 if (MaskedValueIsZero(Op0RHS, AndRHS))
1804 return BinaryOperator::createAnd(Op0LHS, AndRHS);
1806 // If the mask is only needed on one incoming arm, push it up.
1807 if (Op0I->hasOneUse()) {
1808 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1809 // Not masking anything out for the LHS, move to RHS.
1810 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1811 Op0RHS->getName()+".masked");
1812 InsertNewInstBefore(NewRHS, I);
1813 return BinaryOperator::create(
1814 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
1816 if (!isa<Constant>(NotAndRHS) &&
1817 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1818 // Not masking anything out for the RHS, move to LHS.
1819 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1820 Op0LHS->getName()+".masked");
1821 InsertNewInstBefore(NewLHS, I);
1822 return BinaryOperator::create(
1823 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1828 case Instruction::And:
1829 // (X & V) & C2 --> 0 iff (V & C2) == 0
1830 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1831 MaskedValueIsZero(Op0RHS, AndRHS))
1832 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1834 case Instruction::Add:
1835 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1836 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1837 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1838 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1839 return BinaryOperator::createAnd(V, AndRHS);
1840 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1841 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
1844 case Instruction::Sub:
1845 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1846 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1847 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1848 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1849 return BinaryOperator::createAnd(V, AndRHS);
1853 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1854 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1856 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1857 const Type *SrcTy = CI->getOperand(0)->getType();
1859 // If this is an integer truncation or change from signed-to-unsigned, and
1860 // if the source is an and/or with immediate, transform it. This
1861 // frequently occurs for bitfield accesses.
1862 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1863 if (SrcTy->getPrimitiveSizeInBits() >=
1864 I.getType()->getPrimitiveSizeInBits() &&
1865 CastOp->getNumOperands() == 2)
1866 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1867 if (CastOp->getOpcode() == Instruction::And) {
1868 // Change: and (cast (and X, C1) to T), C2
1869 // into : and (cast X to T), trunc(C1)&C2
1870 // This will folds the two ands together, which may allow other
1872 Instruction *NewCast =
1873 new CastInst(CastOp->getOperand(0), I.getType(),
1874 CastOp->getName()+".shrunk");
1875 NewCast = InsertNewInstBefore(NewCast, I);
1877 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1878 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1879 return BinaryOperator::createAnd(NewCast, C3);
1880 } else if (CastOp->getOpcode() == Instruction::Or) {
1881 // Change: and (cast (or X, C1) to T), C2
1882 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1883 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1884 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1885 return ReplaceInstUsesWith(I, AndRHS);
1890 // If this is an integer sign or zero extension instruction.
1891 if (SrcTy->isIntegral() &&
1892 SrcTy->getPrimitiveSizeInBits() <
1893 CI->getType()->getPrimitiveSizeInBits()) {
1895 if (SrcTy->isUnsigned()) {
1896 // See if this and is clearing out bits that are known to be zero
1897 // anyway (due to the zero extension).
1898 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1899 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1900 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1901 if (Result == Mask) // The "and" isn't doing anything, remove it.
1902 return ReplaceInstUsesWith(I, CI);
1903 if (Result != AndRHS) { // Reduce the and RHS constant.
1904 I.setOperand(1, Result);
1909 if (CI->hasOneUse() && SrcTy->isInteger()) {
1910 // We can only do this if all of the sign bits brought in are masked
1911 // out. Compute this by first getting 0000011111, then inverting
1913 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1914 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1915 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1916 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1917 // If the and is clearing all of the sign bits, change this to a
1918 // zero extension cast. To do this, cast the cast input to
1919 // unsigned, then to the requested size.
1920 Value *CastOp = CI->getOperand(0);
1922 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1923 CI->getName()+".uns");
1924 NC = InsertNewInstBefore(NC, I);
1925 // Finally, insert a replacement for CI.
1926 NC = new CastInst(NC, CI->getType(), CI->getName());
1928 NC = InsertNewInstBefore(NC, I);
1929 WorkList.push_back(CI); // Delete CI later.
1930 I.setOperand(0, NC);
1931 return &I; // The AND operand was modified.
1938 // Try to fold constant and into select arguments.
1939 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1940 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1942 if (isa<PHINode>(Op0))
1943 if (Instruction *NV = FoldOpIntoPhi(I))
1947 Value *Op0NotVal = dyn_castNotVal(Op0);
1948 Value *Op1NotVal = dyn_castNotVal(Op1);
1950 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1951 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1953 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1954 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1955 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1956 I.getName()+".demorgan");
1957 InsertNewInstBefore(Or, I);
1958 return BinaryOperator::createNot(Or);
1961 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1962 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1963 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1966 Value *LHSVal, *RHSVal;
1967 ConstantInt *LHSCst, *RHSCst;
1968 Instruction::BinaryOps LHSCC, RHSCC;
1969 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1970 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1971 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1972 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1973 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1974 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1975 // Ensure that the larger constant is on the RHS.
1976 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1977 SetCondInst *LHS = cast<SetCondInst>(Op0);
1978 if (cast<ConstantBool>(Cmp)->getValue()) {
1979 std::swap(LHS, RHS);
1980 std::swap(LHSCst, RHSCst);
1981 std::swap(LHSCC, RHSCC);
1984 // At this point, we know we have have two setcc instructions
1985 // comparing a value against two constants and and'ing the result
1986 // together. Because of the above check, we know that we only have
1987 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1988 // FoldSetCCLogical check above), that the two constants are not
1990 assert(LHSCst != RHSCst && "Compares not folded above?");
1993 default: assert(0 && "Unknown integer condition code!");
1994 case Instruction::SetEQ:
1996 default: assert(0 && "Unknown integer condition code!");
1997 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1998 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1999 return ReplaceInstUsesWith(I, ConstantBool::False);
2000 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2001 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2002 return ReplaceInstUsesWith(I, LHS);
2004 case Instruction::SetNE:
2006 default: assert(0 && "Unknown integer condition code!");
2007 case Instruction::SetLT:
2008 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2009 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2010 break; // (X != 13 & X < 15) -> no change
2011 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2012 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2013 return ReplaceInstUsesWith(I, RHS);
2014 case Instruction::SetNE:
2015 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2016 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2017 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2018 LHSVal->getName()+".off");
2019 InsertNewInstBefore(Add, I);
2020 const Type *UnsType = Add->getType()->getUnsignedVersion();
2021 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2022 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2023 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2024 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2026 break; // (X != 13 & X != 15) -> no change
2029 case Instruction::SetLT:
2031 default: assert(0 && "Unknown integer condition code!");
2032 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2033 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2034 return ReplaceInstUsesWith(I, ConstantBool::False);
2035 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2036 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2037 return ReplaceInstUsesWith(I, LHS);
2039 case Instruction::SetGT:
2041 default: assert(0 && "Unknown integer condition code!");
2042 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2043 return ReplaceInstUsesWith(I, LHS);
2044 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2045 return ReplaceInstUsesWith(I, RHS);
2046 case Instruction::SetNE:
2047 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2048 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2049 break; // (X > 13 & X != 15) -> no change
2050 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2051 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2057 return Changed ? &I : 0;
2060 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2061 bool Changed = SimplifyCommutative(I);
2062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2064 if (isa<UndefValue>(Op1))
2065 return ReplaceInstUsesWith(I, // X | undef -> -1
2066 ConstantIntegral::getAllOnesValue(I.getType()));
2068 // or X, X = X or X, 0 == X
2069 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2070 return ReplaceInstUsesWith(I, Op0);
2073 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2074 // If X is known to only contain bits that already exist in RHS, just
2075 // replace this instruction with RHS directly.
2076 if (MaskedValueIsZero(Op0,
2077 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2078 return ReplaceInstUsesWith(I, RHS);
2080 ConstantInt *C1 = 0; Value *X = 0;
2081 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2082 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2083 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2085 InsertNewInstBefore(Or, I);
2086 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2089 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2090 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2091 std::string Op0Name = Op0->getName(); Op0->setName("");
2092 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2093 InsertNewInstBefore(Or, I);
2094 return BinaryOperator::createXor(Or,
2095 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2098 // Try to fold constant and into select arguments.
2099 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2100 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2102 if (isa<PHINode>(Op0))
2103 if (Instruction *NV = FoldOpIntoPhi(I))
2107 Value *A = 0, *B = 0;
2108 ConstantInt *C1 = 0, *C2 = 0;
2110 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2111 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2112 return ReplaceInstUsesWith(I, Op1);
2113 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2114 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2115 return ReplaceInstUsesWith(I, Op0);
2117 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2118 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2119 MaskedValueIsZero(Op1, C1)) {
2120 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2122 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2125 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2126 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2127 MaskedValueIsZero(Op0, C1)) {
2128 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2130 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2133 // (A & C1)|(B & C2)
2134 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2135 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2137 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2138 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2141 // If we have: ((V + N) & C1) | (V & C2)
2142 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2143 // replace with V+N.
2144 if (C1 == ConstantExpr::getNot(C2)) {
2145 Value *V1 = 0, *V2 = 0;
2146 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2147 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2148 // Add commutes, try both ways.
2149 if (V1 == B && MaskedValueIsZero(V2, C2))
2150 return ReplaceInstUsesWith(I, A);
2151 if (V2 == B && MaskedValueIsZero(V1, C2))
2152 return ReplaceInstUsesWith(I, A);
2154 // Or commutes, try both ways.
2155 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2156 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2157 // Add commutes, try both ways.
2158 if (V1 == A && MaskedValueIsZero(V2, C1))
2159 return ReplaceInstUsesWith(I, B);
2160 if (V2 == A && MaskedValueIsZero(V1, C1))
2161 return ReplaceInstUsesWith(I, B);
2166 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2167 if (A == Op1) // ~A | A == -1
2168 return ReplaceInstUsesWith(I,
2169 ConstantIntegral::getAllOnesValue(I.getType()));
2173 // Note, A is still live here!
2174 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2176 return ReplaceInstUsesWith(I,
2177 ConstantIntegral::getAllOnesValue(I.getType()));
2179 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2180 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2181 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2182 I.getName()+".demorgan"), I);
2183 return BinaryOperator::createNot(And);
2187 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2188 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2189 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2192 Value *LHSVal, *RHSVal;
2193 ConstantInt *LHSCst, *RHSCst;
2194 Instruction::BinaryOps LHSCC, RHSCC;
2195 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2196 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2197 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2198 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2199 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2200 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2201 // Ensure that the larger constant is on the RHS.
2202 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2203 SetCondInst *LHS = cast<SetCondInst>(Op0);
2204 if (cast<ConstantBool>(Cmp)->getValue()) {
2205 std::swap(LHS, RHS);
2206 std::swap(LHSCst, RHSCst);
2207 std::swap(LHSCC, RHSCC);
2210 // At this point, we know we have have two setcc instructions
2211 // comparing a value against two constants and or'ing the result
2212 // together. Because of the above check, we know that we only have
2213 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2214 // FoldSetCCLogical check above), that the two constants are not
2216 assert(LHSCst != RHSCst && "Compares not folded above?");
2219 default: assert(0 && "Unknown integer condition code!");
2220 case Instruction::SetEQ:
2222 default: assert(0 && "Unknown integer condition code!");
2223 case Instruction::SetEQ:
2224 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2225 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2226 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2227 LHSVal->getName()+".off");
2228 InsertNewInstBefore(Add, I);
2229 const Type *UnsType = Add->getType()->getUnsignedVersion();
2230 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2231 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2232 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2233 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2235 break; // (X == 13 | X == 15) -> no change
2237 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2239 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2240 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2241 return ReplaceInstUsesWith(I, RHS);
2244 case Instruction::SetNE:
2246 default: assert(0 && "Unknown integer condition code!");
2247 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2248 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2249 return ReplaceInstUsesWith(I, LHS);
2250 case Instruction::SetNE: // (X != 13 | X != 15) -> true
2251 case Instruction::SetLT: // (X != 13 | X < 15) -> true
2252 return ReplaceInstUsesWith(I, ConstantBool::True);
2255 case Instruction::SetLT:
2257 default: assert(0 && "Unknown integer condition code!");
2258 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2260 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2261 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2262 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2263 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2264 return ReplaceInstUsesWith(I, RHS);
2267 case Instruction::SetGT:
2269 default: assert(0 && "Unknown integer condition code!");
2270 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2271 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2272 return ReplaceInstUsesWith(I, LHS);
2273 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2274 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2275 return ReplaceInstUsesWith(I, ConstantBool::True);
2281 return Changed ? &I : 0;
2284 // XorSelf - Implements: X ^ X --> 0
2287 XorSelf(Value *rhs) : RHS(rhs) {}
2288 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2289 Instruction *apply(BinaryOperator &Xor) const {
2295 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2296 bool Changed = SimplifyCommutative(I);
2297 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2299 if (isa<UndefValue>(Op1))
2300 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2302 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2303 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2304 assert(Result == &I && "AssociativeOpt didn't work?");
2305 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2308 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2310 if (RHS->isNullValue())
2311 return ReplaceInstUsesWith(I, Op0);
2313 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2314 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2315 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2316 if (RHS == ConstantBool::True && SCI->hasOneUse())
2317 return new SetCondInst(SCI->getInverseCondition(),
2318 SCI->getOperand(0), SCI->getOperand(1));
2320 // ~(c-X) == X-c-1 == X+(-c-1)
2321 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2322 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2323 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2324 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2325 ConstantInt::get(I.getType(), 1));
2326 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2329 // ~(~X & Y) --> (X | ~Y)
2330 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2331 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2332 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2334 BinaryOperator::createNot(Op0I->getOperand(1),
2335 Op0I->getOperand(1)->getName()+".not");
2336 InsertNewInstBefore(NotY, I);
2337 return BinaryOperator::createOr(Op0NotVal, NotY);
2341 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2342 switch (Op0I->getOpcode()) {
2343 case Instruction::Add:
2344 // ~(X-c) --> (-c-1)-X
2345 if (RHS->isAllOnesValue()) {
2346 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2347 return BinaryOperator::createSub(
2348 ConstantExpr::getSub(NegOp0CI,
2349 ConstantInt::get(I.getType(), 1)),
2350 Op0I->getOperand(0));
2353 case Instruction::And:
2354 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
2355 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2356 return BinaryOperator::createOr(Op0, RHS);
2358 case Instruction::Or:
2359 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
2360 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
2361 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
2367 // Try to fold constant and into select arguments.
2368 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2369 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2371 if (isa<PHINode>(Op0))
2372 if (Instruction *NV = FoldOpIntoPhi(I))
2376 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
2378 return ReplaceInstUsesWith(I,
2379 ConstantIntegral::getAllOnesValue(I.getType()));
2381 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
2383 return ReplaceInstUsesWith(I,
2384 ConstantIntegral::getAllOnesValue(I.getType()));
2386 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
2387 if (Op1I->getOpcode() == Instruction::Or) {
2388 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2389 cast<BinaryOperator>(Op1I)->swapOperands();
2391 std::swap(Op0, Op1);
2392 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2394 std::swap(Op0, Op1);
2396 } else if (Op1I->getOpcode() == Instruction::Xor) {
2397 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2398 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2399 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2400 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2403 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
2404 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
2405 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2406 cast<BinaryOperator>(Op0I)->swapOperands();
2407 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
2408 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2409 Op1->getName()+".not"), I);
2410 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
2412 } else if (Op0I->getOpcode() == Instruction::Xor) {
2413 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2414 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2415 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2416 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2419 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
2420 ConstantInt *C1 = 0, *C2 = 0;
2421 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2422 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
2423 ConstantExpr::getAnd(C1, C2)->isNullValue())
2424 return BinaryOperator::createOr(Op0, Op1);
2426 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2427 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2428 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2431 return Changed ? &I : 0;
2434 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2435 /// overflowed for this type.
2436 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2438 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2439 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2442 static bool isPositive(ConstantInt *C) {
2443 return cast<ConstantSInt>(C)->getValue() >= 0;
2446 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2447 /// overflowed for this type.
2448 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2450 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2452 if (In1->getType()->isUnsigned())
2453 return cast<ConstantUInt>(Result)->getValue() <
2454 cast<ConstantUInt>(In1)->getValue();
2455 if (isPositive(In1) != isPositive(In2))
2457 if (isPositive(In1))
2458 return cast<ConstantSInt>(Result)->getValue() <
2459 cast<ConstantSInt>(In1)->getValue();
2460 return cast<ConstantSInt>(Result)->getValue() >
2461 cast<ConstantSInt>(In1)->getValue();
2464 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2465 /// code necessary to compute the offset from the base pointer (without adding
2466 /// in the base pointer). Return the result as a signed integer of intptr size.
2467 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2468 TargetData &TD = IC.getTargetData();
2469 gep_type_iterator GTI = gep_type_begin(GEP);
2470 const Type *UIntPtrTy = TD.getIntPtrType();
2471 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2472 Value *Result = Constant::getNullValue(SIntPtrTy);
2474 // Build a mask for high order bits.
2475 uint64_t PtrSizeMask = ~0ULL;
2476 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2478 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2479 Value *Op = GEP->getOperand(i);
2480 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
2481 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2483 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2484 if (!OpC->isNullValue()) {
2485 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
2486 Scale = ConstantExpr::getMul(OpC, Scale);
2487 if (Constant *RC = dyn_cast<Constant>(Result))
2488 Result = ConstantExpr::getAdd(RC, Scale);
2490 // Emit an add instruction.
2491 Result = IC.InsertNewInstBefore(
2492 BinaryOperator::createAdd(Result, Scale,
2493 GEP->getName()+".offs"), I);
2497 // Convert to correct type.
2498 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2499 Op->getName()+".c"), I);
2501 // We'll let instcombine(mul) convert this to a shl if possible.
2502 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2503 GEP->getName()+".idx"), I);
2505 // Emit an add instruction.
2506 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
2507 GEP->getName()+".offs"), I);
2513 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2514 /// else. At this point we know that the GEP is on the LHS of the comparison.
2515 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2516 Instruction::BinaryOps Cond,
2518 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
2520 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2521 if (isa<PointerType>(CI->getOperand(0)->getType()))
2522 RHS = CI->getOperand(0);
2524 Value *PtrBase = GEPLHS->getOperand(0);
2525 if (PtrBase == RHS) {
2526 // As an optimization, we don't actually have to compute the actual value of
2527 // OFFSET if this is a seteq or setne comparison, just return whether each
2528 // index is zero or not.
2529 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2530 Instruction *InVal = 0;
2531 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2532 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
2534 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2535 if (isa<UndefValue>(C)) // undef index -> undef.
2536 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2537 if (C->isNullValue())
2539 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2540 EmitIt = false; // This is indexing into a zero sized array?
2541 } else if (isa<ConstantInt>(C))
2542 return ReplaceInstUsesWith(I, // No comparison is needed here.
2543 ConstantBool::get(Cond == Instruction::SetNE));
2548 new SetCondInst(Cond, GEPLHS->getOperand(i),
2549 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2553 InVal = InsertNewInstBefore(InVal, I);
2554 InsertNewInstBefore(Comp, I);
2555 if (Cond == Instruction::SetNE) // True if any are unequal
2556 InVal = BinaryOperator::createOr(InVal, Comp);
2557 else // True if all are equal
2558 InVal = BinaryOperator::createAnd(InVal, Comp);
2566 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2567 ConstantBool::get(Cond == Instruction::SetEQ));
2570 // Only lower this if the setcc is the only user of the GEP or if we expect
2571 // the result to fold to a constant!
2572 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2573 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2574 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2575 return new SetCondInst(Cond, Offset,
2576 Constant::getNullValue(Offset->getType()));
2578 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2579 // If the base pointers are different, but the indices are the same, just
2580 // compare the base pointer.
2581 if (PtrBase != GEPRHS->getOperand(0)) {
2582 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
2583 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
2584 GEPRHS->getOperand(0)->getType();
2586 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2587 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2588 IndicesTheSame = false;
2592 // If all indices are the same, just compare the base pointers.
2594 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2595 GEPRHS->getOperand(0));
2597 // Otherwise, the base pointers are different and the indices are
2598 // different, bail out.
2602 // If one of the GEPs has all zero indices, recurse.
2603 bool AllZeros = true;
2604 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2605 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2606 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2611 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2612 SetCondInst::getSwappedCondition(Cond), I);
2614 // If the other GEP has all zero indices, recurse.
2616 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2617 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2618 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2623 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2625 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2626 // If the GEPs only differ by one index, compare it.
2627 unsigned NumDifferences = 0; // Keep track of # differences.
2628 unsigned DiffOperand = 0; // The operand that differs.
2629 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2630 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2631 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2632 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
2633 // Irreconcilable differences.
2637 if (NumDifferences++) break;
2642 if (NumDifferences == 0) // SAME GEP?
2643 return ReplaceInstUsesWith(I, // No comparison is needed here.
2644 ConstantBool::get(Cond == Instruction::SetEQ));
2645 else if (NumDifferences == 1) {
2646 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2647 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2649 // Convert the operands to signed values to make sure to perform a
2650 // signed comparison.
2651 const Type *NewTy = LHSV->getType()->getSignedVersion();
2652 if (LHSV->getType() != NewTy)
2653 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2654 LHSV->getName()), I);
2655 if (RHSV->getType() != NewTy)
2656 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2657 RHSV->getName()), I);
2658 return new SetCondInst(Cond, LHSV, RHSV);
2662 // Only lower this if the setcc is the only user of the GEP or if we expect
2663 // the result to fold to a constant!
2664 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2665 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2666 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2667 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2668 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2669 return new SetCondInst(Cond, L, R);
2676 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
2677 bool Changed = SimplifyCommutative(I);
2678 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2679 const Type *Ty = Op0->getType();
2683 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
2685 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2686 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2688 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2689 // addresses never equal each other! We already know that Op0 != Op1.
2690 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2691 isa<ConstantPointerNull>(Op0)) &&
2692 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2693 isa<ConstantPointerNull>(Op1)))
2694 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2696 // setcc's with boolean values can always be turned into bitwise operations
2697 if (Ty == Type::BoolTy) {
2698 switch (I.getOpcode()) {
2699 default: assert(0 && "Invalid setcc instruction!");
2700 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
2701 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
2702 InsertNewInstBefore(Xor, I);
2703 return BinaryOperator::createNot(Xor);
2705 case Instruction::SetNE:
2706 return BinaryOperator::createXor(Op0, Op1);
2708 case Instruction::SetGT:
2709 std::swap(Op0, Op1); // Change setgt -> setlt
2711 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2712 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2713 InsertNewInstBefore(Not, I);
2714 return BinaryOperator::createAnd(Not, Op1);
2716 case Instruction::SetGE:
2717 std::swap(Op0, Op1); // Change setge -> setle
2719 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2720 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2721 InsertNewInstBefore(Not, I);
2722 return BinaryOperator::createOr(Not, Op1);
2727 // See if we are doing a comparison between a constant and an instruction that
2728 // can be folded into the comparison.
2729 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2730 // Check to see if we are comparing against the minimum or maximum value...
2731 if (CI->isMinValue()) {
2732 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2733 return ReplaceInstUsesWith(I, ConstantBool::False);
2734 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2735 return ReplaceInstUsesWith(I, ConstantBool::True);
2736 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2737 return BinaryOperator::createSetEQ(Op0, Op1);
2738 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2739 return BinaryOperator::createSetNE(Op0, Op1);
2741 } else if (CI->isMaxValue()) {
2742 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2743 return ReplaceInstUsesWith(I, ConstantBool::False);
2744 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2745 return ReplaceInstUsesWith(I, ConstantBool::True);
2746 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2747 return BinaryOperator::createSetEQ(Op0, Op1);
2748 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2749 return BinaryOperator::createSetNE(Op0, Op1);
2751 // Comparing against a value really close to min or max?
2752 } else if (isMinValuePlusOne(CI)) {
2753 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2754 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2755 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2756 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2758 } else if (isMaxValueMinusOne(CI)) {
2759 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2760 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2761 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2762 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2765 // If we still have a setle or setge instruction, turn it into the
2766 // appropriate setlt or setgt instruction. Since the border cases have
2767 // already been handled above, this requires little checking.
2769 if (I.getOpcode() == Instruction::SetLE)
2770 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2771 if (I.getOpcode() == Instruction::SetGE)
2772 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2774 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2775 switch (LHSI->getOpcode()) {
2776 case Instruction::And:
2777 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2778 LHSI->getOperand(0)->hasOneUse()) {
2779 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2780 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2781 // happens a LOT in code produced by the C front-end, for bitfield
2783 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2784 ConstantUInt *ShAmt;
2785 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2786 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2787 const Type *Ty = LHSI->getType();
2789 // We can fold this as long as we can't shift unknown bits
2790 // into the mask. This can only happen with signed shift
2791 // rights, as they sign-extend.
2793 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
2794 Shift->getType()->isUnsigned();
2796 // To test for the bad case of the signed shr, see if any
2797 // of the bits shifted in could be tested after the mask.
2798 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2799 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2801 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
2803 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2804 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2810 if (Shift->getOpcode() == Instruction::Shl)
2811 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2813 NewCst = ConstantExpr::getShl(CI, ShAmt);
2815 // Check to see if we are shifting out any of the bits being
2817 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2818 // If we shifted bits out, the fold is not going to work out.
2819 // As a special case, check to see if this means that the
2820 // result is always true or false now.
2821 if (I.getOpcode() == Instruction::SetEQ)
2822 return ReplaceInstUsesWith(I, ConstantBool::False);
2823 if (I.getOpcode() == Instruction::SetNE)
2824 return ReplaceInstUsesWith(I, ConstantBool::True);
2826 I.setOperand(1, NewCst);
2827 Constant *NewAndCST;
2828 if (Shift->getOpcode() == Instruction::Shl)
2829 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2831 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2832 LHSI->setOperand(1, NewAndCST);
2833 LHSI->setOperand(0, Shift->getOperand(0));
2834 WorkList.push_back(Shift); // Shift is dead.
2835 AddUsesToWorkList(I);
2843 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2844 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2845 switch (I.getOpcode()) {
2847 case Instruction::SetEQ:
2848 case Instruction::SetNE: {
2849 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2851 // Check that the shift amount is in range. If not, don't perform
2852 // undefined shifts. When the shift is visited it will be
2854 if (ShAmt->getValue() >= TypeBits)
2857 // If we are comparing against bits always shifted out, the
2858 // comparison cannot succeed.
2860 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2861 if (Comp != CI) {// Comparing against a bit that we know is zero.
2862 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2863 Constant *Cst = ConstantBool::get(IsSetNE);
2864 return ReplaceInstUsesWith(I, Cst);
2867 if (LHSI->hasOneUse()) {
2868 // Otherwise strength reduce the shift into an and.
2869 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
2870 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2873 if (CI->getType()->isUnsigned()) {
2874 Mask = ConstantUInt::get(CI->getType(), Val);
2875 } else if (ShAmtVal != 0) {
2876 Mask = ConstantSInt::get(CI->getType(), Val);
2878 Mask = ConstantInt::getAllOnesValue(CI->getType());
2882 BinaryOperator::createAnd(LHSI->getOperand(0),
2883 Mask, LHSI->getName()+".mask");
2884 Value *And = InsertNewInstBefore(AndI, I);
2885 return new SetCondInst(I.getOpcode(), And,
2886 ConstantExpr::getUShr(CI, ShAmt));
2893 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
2894 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2895 switch (I.getOpcode()) {
2897 case Instruction::SetEQ:
2898 case Instruction::SetNE: {
2900 // Check that the shift amount is in range. If not, don't perform
2901 // undefined shifts. When the shift is visited it will be
2903 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2904 if (ShAmt->getValue() >= TypeBits)
2907 // If we are comparing against bits always shifted out, the
2908 // comparison cannot succeed.
2910 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2912 if (Comp != CI) {// Comparing against a bit that we know is zero.
2913 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2914 Constant *Cst = ConstantBool::get(IsSetNE);
2915 return ReplaceInstUsesWith(I, Cst);
2918 if (LHSI->hasOneUse() || CI->isNullValue()) {
2919 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
2921 // Otherwise strength reduce the shift into an and.
2922 uint64_t Val = ~0ULL; // All ones.
2923 Val <<= ShAmtVal; // Shift over to the right spot.
2926 if (CI->getType()->isUnsigned()) {
2927 Val &= ~0ULL >> (64-TypeBits);
2928 Mask = ConstantUInt::get(CI->getType(), Val);
2930 Mask = ConstantSInt::get(CI->getType(), Val);
2934 BinaryOperator::createAnd(LHSI->getOperand(0),
2935 Mask, LHSI->getName()+".mask");
2936 Value *And = InsertNewInstBefore(AndI, I);
2937 return new SetCondInst(I.getOpcode(), And,
2938 ConstantExpr::getShl(CI, ShAmt));
2946 case Instruction::Div:
2947 // Fold: (div X, C1) op C2 -> range check
2948 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2949 // Fold this div into the comparison, producing a range check.
2950 // Determine, based on the divide type, what the range is being
2951 // checked. If there is an overflow on the low or high side, remember
2952 // it, otherwise compute the range [low, hi) bounding the new value.
2953 bool LoOverflow = false, HiOverflow = 0;
2954 ConstantInt *LoBound = 0, *HiBound = 0;
2957 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2959 Instruction::BinaryOps Opcode = I.getOpcode();
2961 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2962 } else if (LHSI->getType()->isUnsigned()) { // udiv
2964 LoOverflow = ProdOV;
2965 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2966 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2967 if (CI->isNullValue()) { // (X / pos) op 0
2969 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2971 } else if (isPositive(CI)) { // (X / pos) op pos
2973 LoOverflow = ProdOV;
2974 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2975 } else { // (X / pos) op neg
2976 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2977 LoOverflow = AddWithOverflow(LoBound, Prod,
2978 cast<ConstantInt>(DivRHSH));
2980 HiOverflow = ProdOV;
2982 } else { // Divisor is < 0.
2983 if (CI->isNullValue()) { // (X / neg) op 0
2984 LoBound = AddOne(DivRHS);
2985 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2986 if (HiBound == DivRHS)
2987 LoBound = 0; // - INTMIN = INTMIN
2988 } else if (isPositive(CI)) { // (X / neg) op pos
2989 HiOverflow = LoOverflow = ProdOV;
2991 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2992 HiBound = AddOne(Prod);
2993 } else { // (X / neg) op neg
2995 LoOverflow = HiOverflow = ProdOV;
2996 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2999 // Dividing by a negate swaps the condition.
3000 Opcode = SetCondInst::getSwappedCondition(Opcode);
3004 Value *X = LHSI->getOperand(0);
3006 default: assert(0 && "Unhandled setcc opcode!");
3007 case Instruction::SetEQ:
3008 if (LoOverflow && HiOverflow)
3009 return ReplaceInstUsesWith(I, ConstantBool::False);
3010 else if (HiOverflow)
3011 return new SetCondInst(Instruction::SetGE, X, LoBound);
3012 else if (LoOverflow)
3013 return new SetCondInst(Instruction::SetLT, X, HiBound);
3015 return InsertRangeTest(X, LoBound, HiBound, true, I);
3016 case Instruction::SetNE:
3017 if (LoOverflow && HiOverflow)
3018 return ReplaceInstUsesWith(I, ConstantBool::True);
3019 else if (HiOverflow)
3020 return new SetCondInst(Instruction::SetLT, X, LoBound);
3021 else if (LoOverflow)
3022 return new SetCondInst(Instruction::SetGE, X, HiBound);
3024 return InsertRangeTest(X, LoBound, HiBound, false, I);
3025 case Instruction::SetLT:
3027 return ReplaceInstUsesWith(I, ConstantBool::False);
3028 return new SetCondInst(Instruction::SetLT, X, LoBound);
3029 case Instruction::SetGT:
3031 return ReplaceInstUsesWith(I, ConstantBool::False);
3032 return new SetCondInst(Instruction::SetGE, X, HiBound);
3039 // Simplify seteq and setne instructions...
3040 if (I.getOpcode() == Instruction::SetEQ ||
3041 I.getOpcode() == Instruction::SetNE) {
3042 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3044 // If the first operand is (and|or|xor) with a constant, and the second
3045 // operand is a constant, simplify a bit.
3046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3047 switch (BO->getOpcode()) {
3048 case Instruction::Rem:
3049 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3050 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3052 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3053 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3054 if (isPowerOf2_64(V)) {
3055 unsigned L2 = Log2_64(V);
3056 const Type *UTy = BO->getType()->getUnsignedVersion();
3057 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3059 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3060 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3061 RHSCst, BO->getName()), I);
3062 return BinaryOperator::create(I.getOpcode(), NewRem,
3063 Constant::getNullValue(UTy));
3068 case Instruction::Add:
3069 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3070 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3071 if (BO->hasOneUse())
3072 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3073 ConstantExpr::getSub(CI, BOp1C));
3074 } else if (CI->isNullValue()) {
3075 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3076 // efficiently invertible, or if the add has just this one use.
3077 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3079 if (Value *NegVal = dyn_castNegVal(BOp1))
3080 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3081 else if (Value *NegVal = dyn_castNegVal(BOp0))
3082 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3083 else if (BO->hasOneUse()) {
3084 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3086 InsertNewInstBefore(Neg, I);
3087 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3091 case Instruction::Xor:
3092 // For the xor case, we can xor two constants together, eliminating
3093 // the explicit xor.
3094 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3095 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3096 ConstantExpr::getXor(CI, BOC));
3099 case Instruction::Sub:
3100 // Replace (([sub|xor] A, B) != 0) with (A != B)
3101 if (CI->isNullValue())
3102 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3106 case Instruction::Or:
3107 // If bits are being or'd in that are not present in the constant we
3108 // are comparing against, then the comparison could never succeed!
3109 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3110 Constant *NotCI = ConstantExpr::getNot(CI);
3111 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3112 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3116 case Instruction::And:
3117 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3118 // If bits are being compared against that are and'd out, then the
3119 // comparison can never succeed!
3120 if (!ConstantExpr::getAnd(CI,
3121 ConstantExpr::getNot(BOC))->isNullValue())
3122 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3124 // If we have ((X & C) == C), turn it into ((X & C) != 0).
3125 if (CI == BOC && isOneBitSet(CI))
3126 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3127 Instruction::SetNE, Op0,
3128 Constant::getNullValue(CI->getType()));
3130 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3131 // to be a signed value as appropriate.
3132 if (isSignBit(BOC)) {
3133 Value *X = BO->getOperand(0);
3134 // If 'X' is not signed, insert a cast now...
3135 if (!BOC->getType()->isSigned()) {
3136 const Type *DestTy = BOC->getType()->getSignedVersion();
3137 X = InsertCastBefore(X, DestTy, I);
3139 return new SetCondInst(isSetNE ? Instruction::SetLT :
3140 Instruction::SetGE, X,
3141 Constant::getNullValue(X->getType()));
3144 // ((X & ~7) == 0) --> X < 8
3145 if (CI->isNullValue() && isHighOnes(BOC)) {
3146 Value *X = BO->getOperand(0);
3147 Constant *NegX = ConstantExpr::getNeg(BOC);
3149 // If 'X' is signed, insert a cast now.
3150 if (NegX->getType()->isSigned()) {
3151 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3152 X = InsertCastBefore(X, DestTy, I);
3153 NegX = ConstantExpr::getCast(NegX, DestTy);
3156 return new SetCondInst(isSetNE ? Instruction::SetGE :
3157 Instruction::SetLT, X, NegX);
3164 } else { // Not a SetEQ/SetNE
3165 // If the LHS is a cast from an integral value of the same size,
3166 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3167 Value *CastOp = Cast->getOperand(0);
3168 const Type *SrcTy = CastOp->getType();
3169 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3170 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3171 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3172 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3173 "Source and destination signednesses should differ!");
3174 if (Cast->getType()->isSigned()) {
3175 // If this is a signed comparison, check for comparisons in the
3176 // vicinity of zero.
3177 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3179 return BinaryOperator::createSetGT(CastOp,
3180 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3181 else if (I.getOpcode() == Instruction::SetGT &&
3182 cast<ConstantSInt>(CI)->getValue() == -1)
3183 // X > -1 => x < 128
3184 return BinaryOperator::createSetLT(CastOp,
3185 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3187 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3188 if (I.getOpcode() == Instruction::SetLT &&
3189 CUI->getValue() == 1ULL << (SrcTySize-1))
3190 // X < 128 => X > -1
3191 return BinaryOperator::createSetGT(CastOp,
3192 ConstantSInt::get(SrcTy, -1));
3193 else if (I.getOpcode() == Instruction::SetGT &&
3194 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3196 return BinaryOperator::createSetLT(CastOp,
3197 Constant::getNullValue(SrcTy));
3204 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3205 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3206 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3207 switch (LHSI->getOpcode()) {
3208 case Instruction::GetElementPtr:
3209 if (RHSC->isNullValue()) {
3210 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3211 bool isAllZeros = true;
3212 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3213 if (!isa<Constant>(LHSI->getOperand(i)) ||
3214 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3219 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3220 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3224 case Instruction::PHI:
3225 if (Instruction *NV = FoldOpIntoPhi(I))
3228 case Instruction::Select:
3229 // If either operand of the select is a constant, we can fold the
3230 // comparison into the select arms, which will cause one to be
3231 // constant folded and the select turned into a bitwise or.
3232 Value *Op1 = 0, *Op2 = 0;
3233 if (LHSI->hasOneUse()) {
3234 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3235 // Fold the known value into the constant operand.
3236 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3237 // Insert a new SetCC of the other select operand.
3238 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3239 LHSI->getOperand(2), RHSC,
3241 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3242 // Fold the known value into the constant operand.
3243 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3244 // Insert a new SetCC of the other select operand.
3245 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3246 LHSI->getOperand(1), RHSC,
3252 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3257 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3258 if (User *GEP = dyn_castGetElementPtr(Op0))
3259 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3261 if (User *GEP = dyn_castGetElementPtr(Op1))
3262 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3263 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3266 // Test to see if the operands of the setcc are casted versions of other
3267 // values. If the cast can be stripped off both arguments, we do so now.
3268 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3269 Value *CastOp0 = CI->getOperand(0);
3270 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3271 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3272 (I.getOpcode() == Instruction::SetEQ ||
3273 I.getOpcode() == Instruction::SetNE)) {
3274 // We keep moving the cast from the left operand over to the right
3275 // operand, where it can often be eliminated completely.
3278 // If operand #1 is a cast instruction, see if we can eliminate it as
3280 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3281 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3283 Op1 = CI2->getOperand(0);
3285 // If Op1 is a constant, we can fold the cast into the constant.
3286 if (Op1->getType() != Op0->getType())
3287 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3288 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3290 // Otherwise, cast the RHS right before the setcc
3291 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3292 InsertNewInstBefore(cast<Instruction>(Op1), I);
3294 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3297 // Handle the special case of: setcc (cast bool to X), <cst>
3298 // This comes up when you have code like
3301 // For generality, we handle any zero-extension of any operand comparison
3302 // with a constant or another cast from the same type.
3303 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3304 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3307 return Changed ? &I : 0;
3310 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3311 // We only handle extending casts so far.
3313 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3314 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3315 const Type *SrcTy = LHSCIOp->getType();
3316 const Type *DestTy = SCI.getOperand(0)->getType();
3319 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
3322 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3323 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3324 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3326 // Is this a sign or zero extension?
3327 bool isSignSrc = SrcTy->isSigned();
3328 bool isSignDest = DestTy->isSigned();
3330 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3331 // Not an extension from the same type?
3332 RHSCIOp = CI->getOperand(0);
3333 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3334 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3335 // Compute the constant that would happen if we truncated to SrcTy then
3336 // reextended to DestTy.
3337 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3339 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3342 // If the value cannot be represented in the shorter type, we cannot emit
3343 // a simple comparison.
3344 if (SCI.getOpcode() == Instruction::SetEQ)
3345 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3346 if (SCI.getOpcode() == Instruction::SetNE)
3347 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3349 // Evaluate the comparison for LT.
3351 if (DestTy->isSigned()) {
3352 // We're performing a signed comparison.
3354 // Signed extend and signed comparison.
3355 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3356 Result = ConstantBool::False;
3358 Result = ConstantBool::True; // X < (large) --> true
3360 // Unsigned extend and signed comparison.
3361 if (cast<ConstantSInt>(CI)->getValue() < 0)
3362 Result = ConstantBool::False;
3364 Result = ConstantBool::True;
3367 // We're performing an unsigned comparison.
3369 // Unsigned extend & compare -> always true.
3370 Result = ConstantBool::True;
3372 // We're performing an unsigned comp with a sign extended value.
3373 // This is true if the input is >= 0. [aka >s -1]
3374 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3375 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3376 NegOne, SCI.getName()), SCI);
3380 // Finally, return the value computed.
3381 if (SCI.getOpcode() == Instruction::SetLT) {
3382 return ReplaceInstUsesWith(SCI, Result);
3384 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3385 if (Constant *CI = dyn_cast<Constant>(Result))
3386 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3388 return BinaryOperator::createNot(Result);
3395 // Okay, just insert a compare of the reduced operands now!
3396 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3399 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
3400 assert(I.getOperand(1)->getType() == Type::UByteTy);
3401 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3402 bool isLeftShift = I.getOpcode() == Instruction::Shl;
3404 // shl X, 0 == X and shr X, 0 == X
3405 // shl 0, X == 0 and shr 0, X == 0
3406 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
3407 Op0 == Constant::getNullValue(Op0->getType()))
3408 return ReplaceInstUsesWith(I, Op0);
3410 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3411 if (!isLeftShift && I.getType()->isSigned())
3412 return ReplaceInstUsesWith(I, Op0);
3413 else // undef << X -> 0 AND undef >>u X -> 0
3414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3416 if (isa<UndefValue>(Op1)) {
3417 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
3418 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3420 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3423 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3425 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3426 if (CSI->isAllOnesValue())
3427 return ReplaceInstUsesWith(I, CSI);
3429 // Try to fold constant and into select arguments.
3430 if (isa<Constant>(Op0))
3431 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3432 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3435 // See if we can turn a signed shr into an unsigned shr.
3436 if (!isLeftShift && I.getType()->isSigned()) {
3437 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3438 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3439 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3441 return new CastInst(V, I.getType());
3445 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3446 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3451 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3453 bool isLeftShift = I.getOpcode() == Instruction::Shl;
3454 bool isSignedShift = Op0->getType()->isSigned();
3455 bool isUnsignedShift = !isSignedShift;
3457 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3458 // of a signed value.
3460 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3461 if (Op1->getValue() >= TypeBits) {
3462 if (isUnsignedShift || isLeftShift)
3463 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3465 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3470 // ((X*C1) << C2) == (X * (C1 << C2))
3471 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3472 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3473 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3474 return BinaryOperator::createMul(BO->getOperand(0),
3475 ConstantExpr::getShl(BOOp, Op1));
3477 // Try to fold constant and into select arguments.
3478 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3479 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3481 if (isa<PHINode>(Op0))
3482 if (Instruction *NV = FoldOpIntoPhi(I))
3485 if (Op0->hasOneUse()) {
3486 // If this is a SHL of a sign-extending cast, see if we can turn the input
3487 // into a zero extending cast (a simple strength reduction).
3488 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3489 const Type *SrcTy = CI->getOperand(0)->getType();
3490 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3491 SrcTy->getPrimitiveSizeInBits() <
3492 CI->getType()->getPrimitiveSizeInBits()) {
3493 // We can change it to a zero extension if we are shifting out all of
3494 // the sign extended bits. To check this, form a mask of all of the
3495 // sign extend bits, then shift them left and see if we have anything
3497 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3498 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3499 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3500 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3501 // If the shift is nuking all of the sign bits, change this to a
3502 // zero extension cast. To do this, cast the cast input to
3503 // unsigned, then to the requested size.
3504 Value *CastOp = CI->getOperand(0);
3506 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3507 CI->getName()+".uns");
3508 NC = InsertNewInstBefore(NC, I);
3509 // Finally, insert a replacement for CI.
3510 NC = new CastInst(NC, CI->getType(), CI->getName());
3512 NC = InsertNewInstBefore(NC, I);
3513 WorkList.push_back(CI); // Delete CI later.
3514 I.setOperand(0, NC);
3515 return &I; // The SHL operand was modified.
3520 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3521 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3524 switch (Op0BO->getOpcode()) {
3526 case Instruction::Add:
3527 case Instruction::And:
3528 case Instruction::Or:
3529 case Instruction::Xor:
3530 // These operators commute.
3531 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
3532 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3533 match(Op0BO->getOperand(1),
3534 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
3535 Instruction *YS = new ShiftInst(Instruction::Shl,
3536 Op0BO->getOperand(0), Op1,
3538 InsertNewInstBefore(YS, I); // (Y << C)
3539 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3541 Op0BO->getOperand(1)->getName());
3542 InsertNewInstBefore(X, I); // (X + (Y << C))
3543 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3544 C2 = ConstantExpr::getShl(C2, Op1);
3545 return BinaryOperator::createAnd(X, C2);
3548 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3549 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3550 match(Op0BO->getOperand(1),
3551 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3552 m_ConstantInt(CC))) && V2 == Op1 &&
3553 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3554 Instruction *YS = new ShiftInst(Instruction::Shl,
3555 Op0BO->getOperand(0), Op1,
3557 InsertNewInstBefore(YS, I); // (Y << C)
3559 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
3560 V1->getName()+".mask");
3561 InsertNewInstBefore(XM, I); // X & (CC << C)
3563 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3567 case Instruction::Sub:
3568 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3569 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3570 match(Op0BO->getOperand(0),
3571 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
3572 Instruction *YS = new ShiftInst(Instruction::Shl,
3573 Op0BO->getOperand(1), Op1,
3575 InsertNewInstBefore(YS, I); // (Y << C)
3576 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3578 Op0BO->getOperand(0)->getName());
3579 InsertNewInstBefore(X, I); // (X + (Y << C))
3580 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3581 C2 = ConstantExpr::getShl(C2, Op1);
3582 return BinaryOperator::createAnd(X, C2);
3585 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3586 match(Op0BO->getOperand(0),
3587 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3588 m_ConstantInt(CC))) && V2 == Op1 &&
3589 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3590 Instruction *YS = new ShiftInst(Instruction::Shl,
3591 Op0BO->getOperand(1), Op1,
3593 InsertNewInstBefore(YS, I); // (Y << C)
3595 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
3596 V1->getName()+".mask");
3597 InsertNewInstBefore(XM, I); // X & (CC << C)
3599 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3606 // If the operand is an bitwise operator with a constant RHS, and the
3607 // shift is the only use, we can pull it out of the shift.
3608 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3609 bool isValid = true; // Valid only for And, Or, Xor
3610 bool highBitSet = false; // Transform if high bit of constant set?
3612 switch (Op0BO->getOpcode()) {
3613 default: isValid = false; break; // Do not perform transform!
3614 case Instruction::Add:
3615 isValid = isLeftShift;
3617 case Instruction::Or:
3618 case Instruction::Xor:
3621 case Instruction::And:
3626 // If this is a signed shift right, and the high bit is modified
3627 // by the logical operation, do not perform the transformation.
3628 // The highBitSet boolean indicates the value of the high bit of
3629 // the constant which would cause it to be modified for this
3632 if (isValid && !isLeftShift && isSignedShift) {
3633 uint64_t Val = Op0C->getRawValue();
3634 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3638 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3640 Instruction *NewShift =
3641 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3644 InsertNewInstBefore(NewShift, I);
3646 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3653 // Find out if this is a shift of a shift by a constant.
3654 ShiftInst *ShiftOp = 0;
3655 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
3657 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3658 // If this is a noop-integer case of a shift instruction, use the shift.
3659 if (CI->getOperand(0)->getType()->isInteger() &&
3660 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3661 CI->getType()->getPrimitiveSizeInBits() &&
3662 isa<ShiftInst>(CI->getOperand(0))) {
3663 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3667 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3668 // Find the operands and properties of the input shift. Note that the
3669 // signedness of the input shift may differ from the current shift if there
3670 // is a noop cast between the two.
3671 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3672 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
3673 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
3675 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3677 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3678 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3680 // Check for (A << c1) << c2 and (A >> c1) >> c2.
3681 if (isLeftShift == isShiftOfLeftShift) {
3682 // Do not fold these shifts if the first one is signed and the second one
3683 // is unsigned and this is a right shift. Further, don't do any folding
3685 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3688 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3689 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3690 Amt = Op0->getType()->getPrimitiveSizeInBits();
3692 Value *Op = ShiftOp->getOperand(0);
3693 if (isShiftOfSignedShift != isSignedShift)
3694 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3695 return new ShiftInst(I.getOpcode(), Op,
3696 ConstantUInt::get(Type::UByteTy, Amt));
3699 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
3700 // signed types, we can only support the (A >> c1) << c2 configuration,
3701 // because it can not turn an arbitrary bit of A into a sign bit.
3702 if (isUnsignedShift || isLeftShift) {
3703 // Calculate bitmask for what gets shifted off the edge.
3704 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3706 C = ConstantExpr::getShl(C, ShiftAmt1C);
3708 C = ConstantExpr::getUShr(C, ShiftAmt1C);
3710 Value *Op = ShiftOp->getOperand(0);
3711 if (isShiftOfSignedShift != isSignedShift)
3712 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3715 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
3716 InsertNewInstBefore(Mask, I);
3718 // Figure out what flavor of shift we should use...
3719 if (ShiftAmt1 == ShiftAmt2) {
3720 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3721 } else if (ShiftAmt1 < ShiftAmt2) {
3722 return new ShiftInst(I.getOpcode(), Mask,
3723 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3724 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
3725 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
3726 // Make sure to emit an unsigned shift right, not a signed one.
3727 Mask = InsertNewInstBefore(new CastInst(Mask,
3728 Mask->getType()->getUnsignedVersion(),
3730 Mask = new ShiftInst(Instruction::Shr, Mask,
3731 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3732 InsertNewInstBefore(Mask, I);
3733 return new CastInst(Mask, I.getType());
3735 return new ShiftInst(ShiftOp->getOpcode(), Mask,
3736 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3739 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
3740 Op = InsertNewInstBefore(new CastInst(Mask,
3741 I.getType()->getSignedVersion(),
3742 Mask->getName()), I);
3743 Instruction *Shift =
3744 new ShiftInst(ShiftOp->getOpcode(), Op,
3745 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3746 InsertNewInstBefore(Shift, I);
3748 C = ConstantIntegral::getAllOnesValue(Shift->getType());
3749 C = ConstantExpr::getShl(C, Op1);
3750 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
3751 InsertNewInstBefore(Mask, I);
3752 return new CastInst(Mask, I.getType());
3755 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
3756 // this case, C1 == C2 and C1 is 8, 16, or 32.
3757 if (ShiftAmt1 == ShiftAmt2) {
3758 const Type *SExtType = 0;
3759 switch (ShiftAmt1) {
3760 case 8 : SExtType = Type::SByteTy; break;
3761 case 16: SExtType = Type::ShortTy; break;
3762 case 32: SExtType = Type::IntTy; break;
3766 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
3768 InsertNewInstBefore(NewTrunc, I);
3769 return new CastInst(NewTrunc, I.getType());
3784 /// getCastType - In the future, we will split the cast instruction into these
3785 /// various types. Until then, we have to do the analysis here.
3786 static CastType getCastType(const Type *Src, const Type *Dest) {
3787 assert(Src->isIntegral() && Dest->isIntegral() &&
3788 "Only works on integral types!");
3789 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3790 unsigned DestSize = Dest->getPrimitiveSizeInBits();
3792 if (SrcSize == DestSize) return Noop;
3793 if (SrcSize > DestSize) return Truncate;
3794 if (Src->isSigned()) return Signext;
3799 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3802 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
3803 const Type *DstTy, TargetData *TD) {
3805 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3806 // are identical and the bits don't get reinterpreted (for example
3807 // int->float->int would not be allowed).
3808 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
3811 // If we are casting between pointer and integer types, treat pointers as
3812 // integers of the appropriate size for the code below.
3813 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3814 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3815 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
3817 // Allow free casting and conversion of sizes as long as the sign doesn't
3819 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
3820 CastType FirstCast = getCastType(SrcTy, MidTy);
3821 CastType SecondCast = getCastType(MidTy, DstTy);
3823 // Capture the effect of these two casts. If the result is a legal cast,
3824 // the CastType is stored here, otherwise a special code is used.
3825 static const unsigned CastResult[] = {
3826 // First cast is noop
3828 // First cast is a truncate
3829 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3830 // First cast is a sign ext
3831 2, 5, 2, 4, // signext->zeroext never ok
3832 // First cast is a zero ext
3836 unsigned Result = CastResult[FirstCast*4+SecondCast];
3838 default: assert(0 && "Illegal table value!");
3843 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3844 // truncates, we could eliminate more casts.
3845 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3847 return false; // Not possible to eliminate this here.
3849 // Sign or zero extend followed by truncate is always ok if the result
3850 // is a truncate or noop.
3851 CastType ResultCast = getCastType(SrcTy, DstTy);
3852 if (ResultCast == Noop || ResultCast == Truncate)
3854 // Otherwise we are still growing the value, we are only safe if the
3855 // result will match the sign/zeroextendness of the result.
3856 return ResultCast == FirstCast;
3860 // If this is a cast from 'float -> double -> integer', cast from
3861 // 'float -> integer' directly, as the value isn't changed by the
3862 // float->double conversion.
3863 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
3864 DstTy->isIntegral() &&
3865 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
3871 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
3872 if (V->getType() == Ty || isa<Constant>(V)) return false;
3873 if (const CastInst *CI = dyn_cast<CastInst>(V))
3874 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3880 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3881 /// InsertBefore instruction. This is specialized a bit to avoid inserting
3882 /// casts that are known to not do anything...
3884 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3885 Instruction *InsertBefore) {
3886 if (V->getType() == DestTy) return V;
3887 if (Constant *C = dyn_cast<Constant>(V))
3888 return ConstantExpr::getCast(C, DestTy);
3890 CastInst *CI = new CastInst(V, DestTy, V->getName());
3891 InsertNewInstBefore(CI, *InsertBefore);
3895 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
3896 /// expression. If so, decompose it, returning some value X, such that Val is
3899 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
3901 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
3902 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
3903 Offset = CI->getValue();
3905 return ConstantUInt::get(Type::UIntTy, 0);
3906 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
3907 if (I->getNumOperands() == 2) {
3908 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
3909 if (I->getOpcode() == Instruction::Shl) {
3910 // This is a value scaled by '1 << the shift amt'.
3911 Scale = 1U << CUI->getValue();
3913 return I->getOperand(0);
3914 } else if (I->getOpcode() == Instruction::Mul) {
3915 // This value is scaled by 'CUI'.
3916 Scale = CUI->getValue();
3918 return I->getOperand(0);
3919 } else if (I->getOpcode() == Instruction::Add) {
3920 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
3923 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
3925 Offset += CUI->getValue();
3926 if (SubScale > 1 && (Offset % SubScale == 0)) {
3935 // Otherwise, we can't look past this.
3942 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
3943 /// try to eliminate the cast by moving the type information into the alloc.
3944 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
3945 AllocationInst &AI) {
3946 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
3947 if (!PTy) return 0; // Not casting the allocation to a pointer type.
3949 // Remove any uses of AI that are dead.
3950 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
3951 std::vector<Instruction*> DeadUsers;
3952 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
3953 Instruction *User = cast<Instruction>(*UI++);
3954 if (isInstructionTriviallyDead(User)) {
3955 while (UI != E && *UI == User)
3956 ++UI; // If this instruction uses AI more than once, don't break UI.
3958 // Add operands to the worklist.
3959 AddUsesToWorkList(*User);
3961 DEBUG(std::cerr << "IC: DCE: " << *User);
3963 User->eraseFromParent();
3964 removeFromWorkList(User);
3968 // Get the type really allocated and the type casted to.
3969 const Type *AllocElTy = AI.getAllocatedType();
3970 const Type *CastElTy = PTy->getElementType();
3971 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
3973 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
3974 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
3975 if (CastElTyAlign < AllocElTyAlign) return 0;
3977 // If the allocation has multiple uses, only promote it if we are strictly
3978 // increasing the alignment of the resultant allocation. If we keep it the
3979 // same, we open the door to infinite loops of various kinds.
3980 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
3982 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3983 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
3984 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
3986 // See if we can satisfy the modulus by pulling a scale out of the array
3988 unsigned ArraySizeScale, ArrayOffset;
3989 Value *NumElements = // See if the array size is a decomposable linear expr.
3990 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
3992 // If we can now satisfy the modulus, by using a non-1 scale, we really can
3994 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
3995 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
3997 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4002 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4003 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4004 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4005 else if (Scale != 1) {
4006 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4007 Amt = InsertNewInstBefore(Tmp, AI);
4011 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4012 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4013 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4014 Amt = InsertNewInstBefore(Tmp, AI);
4017 std::string Name = AI.getName(); AI.setName("");
4018 AllocationInst *New;
4019 if (isa<MallocInst>(AI))
4020 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4022 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4023 InsertNewInstBefore(New, AI);
4025 // If the allocation has multiple uses, insert a cast and change all things
4026 // that used it to use the new cast. This will also hack on CI, but it will
4028 if (!AI.hasOneUse()) {
4029 AddUsesToWorkList(AI);
4030 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4031 InsertNewInstBefore(NewCast, AI);
4032 AI.replaceAllUsesWith(NewCast);
4034 return ReplaceInstUsesWith(CI, New);
4038 // CastInst simplification
4040 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4041 Value *Src = CI.getOperand(0);
4043 // If the user is casting a value to the same type, eliminate this cast
4045 if (CI.getType() == Src->getType())
4046 return ReplaceInstUsesWith(CI, Src);
4048 if (isa<UndefValue>(Src)) // cast undef -> undef
4049 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4051 // If casting the result of another cast instruction, try to eliminate this
4054 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4055 Value *A = CSrc->getOperand(0);
4056 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4057 CI.getType(), TD)) {
4058 // This instruction now refers directly to the cast's src operand. This
4059 // has a good chance of making CSrc dead.
4060 CI.setOperand(0, CSrc->getOperand(0));
4064 // If this is an A->B->A cast, and we are dealing with integral types, try
4065 // to convert this into a logical 'and' instruction.
4067 if (A->getType()->isInteger() &&
4068 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
4069 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
4070 CSrc->getType()->getPrimitiveSizeInBits() <
4071 CI.getType()->getPrimitiveSizeInBits()&&
4072 A->getType()->getPrimitiveSizeInBits() ==
4073 CI.getType()->getPrimitiveSizeInBits()) {
4074 assert(CSrc->getType() != Type::ULongTy &&
4075 "Cannot have type bigger than ulong!");
4076 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
4077 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4079 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4080 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4081 if (And->getType() != CI.getType()) {
4082 And->setName(CSrc->getName()+".mask");
4083 InsertNewInstBefore(And, CI);
4084 And = new CastInst(And, CI.getType());
4090 // If this is a cast to bool, turn it into the appropriate setne instruction.
4091 if (CI.getType() == Type::BoolTy)
4092 return BinaryOperator::createSetNE(CI.getOperand(0),
4093 Constant::getNullValue(CI.getOperand(0)->getType()));
4095 // If casting the result of a getelementptr instruction with no offset, turn
4096 // this into a cast of the original pointer!
4098 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4099 bool AllZeroOperands = true;
4100 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4101 if (!isa<Constant>(GEP->getOperand(i)) ||
4102 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4103 AllZeroOperands = false;
4106 if (AllZeroOperands) {
4107 CI.setOperand(0, GEP->getOperand(0));
4112 // If we are casting a malloc or alloca to a pointer to a type of the same
4113 // size, rewrite the allocation instruction to allocate the "right" type.
4115 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
4116 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4119 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4120 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4122 if (isa<PHINode>(Src))
4123 if (Instruction *NV = FoldOpIntoPhi(CI))
4126 // If the source value is an instruction with only this use, we can attempt to
4127 // propagate the cast into the instruction. Also, only handle integral types
4129 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4130 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4131 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4132 const Type *DestTy = CI.getType();
4133 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4134 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
4136 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4137 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4139 switch (SrcI->getOpcode()) {
4140 case Instruction::Add:
4141 case Instruction::Mul:
4142 case Instruction::And:
4143 case Instruction::Or:
4144 case Instruction::Xor:
4145 // If we are discarding information, or just changing the sign, rewrite.
4146 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4147 // Don't insert two casts if they cannot be eliminated. We allow two
4148 // casts to be inserted if the sizes are the same. This could only be
4149 // converting signedness, which is a noop.
4150 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4151 !ValueRequiresCast(Op0, DestTy, TD)) {
4152 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4153 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4154 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4155 ->getOpcode(), Op0c, Op1c);
4159 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4160 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4161 Op1 == ConstantBool::True &&
4162 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4163 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4164 return BinaryOperator::createXor(New,
4165 ConstantInt::get(CI.getType(), 1));
4168 case Instruction::Shl:
4169 // Allow changing the sign of the source operand. Do not allow changing
4170 // the size of the shift, UNLESS the shift amount is a constant. We
4171 // mush not change variable sized shifts to a smaller size, because it
4172 // is undefined to shift more bits out than exist in the value.
4173 if (DestBitSize == SrcBitSize ||
4174 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4175 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4176 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4179 case Instruction::Shr:
4180 // If this is a signed shr, and if all bits shifted in are about to be
4181 // truncated off, turn it into an unsigned shr to allow greater
4183 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4184 isa<ConstantInt>(Op1)) {
4185 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4186 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4187 // Convert to unsigned.
4188 Value *N1 = InsertOperandCastBefore(Op0,
4189 Op0->getType()->getUnsignedVersion(), &CI);
4190 // Insert the new shift, which is now unsigned.
4191 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4192 Op1, Src->getName()), CI);
4193 return new CastInst(N1, CI.getType());
4198 case Instruction::SetNE:
4199 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4200 if (Op1C->getRawValue() == 0) {
4201 // If the input only has the low bit set, simplify directly.
4203 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4204 // cast (X != 0) to int --> X if X&~1 == 0
4205 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4206 if (CI.getType() == Op0->getType())
4207 return ReplaceInstUsesWith(CI, Op0);
4209 return new CastInst(Op0, CI.getType());
4212 // If the input is an and with a single bit, shift then simplify.
4213 ConstantInt *AndRHS;
4214 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4215 if (AndRHS->getRawValue() &&
4216 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
4217 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
4218 // Perform an unsigned shr by shiftamt. Convert input to
4219 // unsigned if it is signed.
4221 if (In->getType()->isSigned())
4222 In = InsertNewInstBefore(new CastInst(In,
4223 In->getType()->getUnsignedVersion(), In->getName()),CI);
4224 // Insert the shift to put the result in the low bit.
4225 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4226 ConstantInt::get(Type::UByteTy, ShiftAmt),
4227 In->getName()+".lobit"), CI);
4228 if (CI.getType() == In->getType())
4229 return ReplaceInstUsesWith(CI, In);
4231 return new CastInst(In, CI.getType());
4236 case Instruction::SetEQ:
4237 // We if we are just checking for a seteq of a single bit and casting it
4238 // to an integer. If so, shift the bit to the appropriate place then
4239 // cast to integer to avoid the comparison.
4240 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4241 // Is Op1C a power of two or zero?
4242 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4243 // cast (X == 1) to int -> X iff X has only the low bit set.
4244 if (Op1C->getRawValue() == 1) {
4246 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4247 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4248 if (CI.getType() == Op0->getType())
4249 return ReplaceInstUsesWith(CI, Op0);
4251 return new CastInst(Op0, CI.getType());
4263 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4265 /// %D = select %cond, %C, %A
4267 /// %C = select %cond, %B, 0
4270 /// Assuming that the specified instruction is an operand to the select, return
4271 /// a bitmask indicating which operands of this instruction are foldable if they
4272 /// equal the other incoming value of the select.
4274 static unsigned GetSelectFoldableOperands(Instruction *I) {
4275 switch (I->getOpcode()) {
4276 case Instruction::Add:
4277 case Instruction::Mul:
4278 case Instruction::And:
4279 case Instruction::Or:
4280 case Instruction::Xor:
4281 return 3; // Can fold through either operand.
4282 case Instruction::Sub: // Can only fold on the amount subtracted.
4283 case Instruction::Shl: // Can only fold on the shift amount.
4284 case Instruction::Shr:
4287 return 0; // Cannot fold
4291 /// GetSelectFoldableConstant - For the same transformation as the previous
4292 /// function, return the identity constant that goes into the select.
4293 static Constant *GetSelectFoldableConstant(Instruction *I) {
4294 switch (I->getOpcode()) {
4295 default: assert(0 && "This cannot happen!"); abort();
4296 case Instruction::Add:
4297 case Instruction::Sub:
4298 case Instruction::Or:
4299 case Instruction::Xor:
4300 return Constant::getNullValue(I->getType());
4301 case Instruction::Shl:
4302 case Instruction::Shr:
4303 return Constant::getNullValue(Type::UByteTy);
4304 case Instruction::And:
4305 return ConstantInt::getAllOnesValue(I->getType());
4306 case Instruction::Mul:
4307 return ConstantInt::get(I->getType(), 1);
4311 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4312 /// have the same opcode and only one use each. Try to simplify this.
4313 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4315 if (TI->getNumOperands() == 1) {
4316 // If this is a non-volatile load or a cast from the same type,
4318 if (TI->getOpcode() == Instruction::Cast) {
4319 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4322 return 0; // unknown unary op.
4325 // Fold this by inserting a select from the input values.
4326 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4327 FI->getOperand(0), SI.getName()+".v");
4328 InsertNewInstBefore(NewSI, SI);
4329 return new CastInst(NewSI, TI->getType());
4332 // Only handle binary operators here.
4333 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4336 // Figure out if the operations have any operands in common.
4337 Value *MatchOp, *OtherOpT, *OtherOpF;
4339 if (TI->getOperand(0) == FI->getOperand(0)) {
4340 MatchOp = TI->getOperand(0);
4341 OtherOpT = TI->getOperand(1);
4342 OtherOpF = FI->getOperand(1);
4343 MatchIsOpZero = true;
4344 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4345 MatchOp = TI->getOperand(1);
4346 OtherOpT = TI->getOperand(0);
4347 OtherOpF = FI->getOperand(0);
4348 MatchIsOpZero = false;
4349 } else if (!TI->isCommutative()) {
4351 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4352 MatchOp = TI->getOperand(0);
4353 OtherOpT = TI->getOperand(1);
4354 OtherOpF = FI->getOperand(0);
4355 MatchIsOpZero = true;
4356 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4357 MatchOp = TI->getOperand(1);
4358 OtherOpT = TI->getOperand(0);
4359 OtherOpF = FI->getOperand(1);
4360 MatchIsOpZero = true;
4365 // If we reach here, they do have operations in common.
4366 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4367 OtherOpF, SI.getName()+".v");
4368 InsertNewInstBefore(NewSI, SI);
4370 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4372 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4374 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4377 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4379 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4383 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
4384 Value *CondVal = SI.getCondition();
4385 Value *TrueVal = SI.getTrueValue();
4386 Value *FalseVal = SI.getFalseValue();
4388 // select true, X, Y -> X
4389 // select false, X, Y -> Y
4390 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
4391 if (C == ConstantBool::True)
4392 return ReplaceInstUsesWith(SI, TrueVal);
4394 assert(C == ConstantBool::False);
4395 return ReplaceInstUsesWith(SI, FalseVal);
4398 // select C, X, X -> X
4399 if (TrueVal == FalseVal)
4400 return ReplaceInstUsesWith(SI, TrueVal);
4402 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4403 return ReplaceInstUsesWith(SI, FalseVal);
4404 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4405 return ReplaceInstUsesWith(SI, TrueVal);
4406 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4407 if (isa<Constant>(TrueVal))
4408 return ReplaceInstUsesWith(SI, TrueVal);
4410 return ReplaceInstUsesWith(SI, FalseVal);
4413 if (SI.getType() == Type::BoolTy)
4414 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4415 if (C == ConstantBool::True) {
4416 // Change: A = select B, true, C --> A = or B, C
4417 return BinaryOperator::createOr(CondVal, FalseVal);
4419 // Change: A = select B, false, C --> A = and !B, C
4421 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4422 "not."+CondVal->getName()), SI);
4423 return BinaryOperator::createAnd(NotCond, FalseVal);
4425 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4426 if (C == ConstantBool::False) {
4427 // Change: A = select B, C, false --> A = and B, C
4428 return BinaryOperator::createAnd(CondVal, TrueVal);
4430 // Change: A = select B, C, true --> A = or !B, C
4432 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4433 "not."+CondVal->getName()), SI);
4434 return BinaryOperator::createOr(NotCond, TrueVal);
4438 // Selecting between two integer constants?
4439 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4440 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4441 // select C, 1, 0 -> cast C to int
4442 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4443 return new CastInst(CondVal, SI.getType());
4444 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4445 // select C, 0, 1 -> cast !C to int
4447 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4448 "not."+CondVal->getName()), SI);
4449 return new CastInst(NotCond, SI.getType());
4452 // If one of the constants is zero (we know they can't both be) and we
4453 // have a setcc instruction with zero, and we have an 'and' with the
4454 // non-constant value, eliminate this whole mess. This corresponds to
4455 // cases like this: ((X & 27) ? 27 : 0)
4456 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4457 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4458 if ((IC->getOpcode() == Instruction::SetEQ ||
4459 IC->getOpcode() == Instruction::SetNE) &&
4460 isa<ConstantInt>(IC->getOperand(1)) &&
4461 cast<Constant>(IC->getOperand(1))->isNullValue())
4462 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4463 if (ICA->getOpcode() == Instruction::And &&
4464 isa<ConstantInt>(ICA->getOperand(1)) &&
4465 (ICA->getOperand(1) == TrueValC ||
4466 ICA->getOperand(1) == FalseValC) &&
4467 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4468 // Okay, now we know that everything is set up, we just don't
4469 // know whether we have a setne or seteq and whether the true or
4470 // false val is the zero.
4471 bool ShouldNotVal = !TrueValC->isNullValue();
4472 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4475 V = InsertNewInstBefore(BinaryOperator::create(
4476 Instruction::Xor, V, ICA->getOperand(1)), SI);
4477 return ReplaceInstUsesWith(SI, V);
4481 // See if we are selecting two values based on a comparison of the two values.
4482 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4483 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4484 // Transform (X == Y) ? X : Y -> Y
4485 if (SCI->getOpcode() == Instruction::SetEQ)
4486 return ReplaceInstUsesWith(SI, FalseVal);
4487 // Transform (X != Y) ? X : Y -> X
4488 if (SCI->getOpcode() == Instruction::SetNE)
4489 return ReplaceInstUsesWith(SI, TrueVal);
4490 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4492 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4493 // Transform (X == Y) ? Y : X -> X
4494 if (SCI->getOpcode() == Instruction::SetEQ)
4495 return ReplaceInstUsesWith(SI, FalseVal);
4496 // Transform (X != Y) ? Y : X -> Y
4497 if (SCI->getOpcode() == Instruction::SetNE)
4498 return ReplaceInstUsesWith(SI, TrueVal);
4499 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4503 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4504 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4505 if (TI->hasOneUse() && FI->hasOneUse()) {
4506 bool isInverse = false;
4507 Instruction *AddOp = 0, *SubOp = 0;
4509 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4510 if (TI->getOpcode() == FI->getOpcode())
4511 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4514 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4515 // even legal for FP.
4516 if (TI->getOpcode() == Instruction::Sub &&
4517 FI->getOpcode() == Instruction::Add) {
4518 AddOp = FI; SubOp = TI;
4519 } else if (FI->getOpcode() == Instruction::Sub &&
4520 TI->getOpcode() == Instruction::Add) {
4521 AddOp = TI; SubOp = FI;
4525 Value *OtherAddOp = 0;
4526 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4527 OtherAddOp = AddOp->getOperand(1);
4528 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4529 OtherAddOp = AddOp->getOperand(0);
4533 // So at this point we know we have:
4534 // select C, (add X, Y), (sub X, ?)
4535 // We can do the transform profitably if either 'Y' = '?' or '?' is
4537 if (SubOp->getOperand(1) == AddOp ||
4538 isa<Constant>(SubOp->getOperand(1))) {
4540 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4541 NegVal = ConstantExpr::getNeg(C);
4543 NegVal = InsertNewInstBefore(
4544 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4547 Value *NewTrueOp = OtherAddOp;
4548 Value *NewFalseOp = NegVal;
4550 std::swap(NewTrueOp, NewFalseOp);
4551 Instruction *NewSel =
4552 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
4554 NewSel = InsertNewInstBefore(NewSel, SI);
4555 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
4561 // See if we can fold the select into one of our operands.
4562 if (SI.getType()->isInteger()) {
4563 // See the comment above GetSelectFoldableOperands for a description of the
4564 // transformation we are doing here.
4565 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4566 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4567 !isa<Constant>(FalseVal))
4568 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4569 unsigned OpToFold = 0;
4570 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4572 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4577 Constant *C = GetSelectFoldableConstant(TVI);
4578 std::string Name = TVI->getName(); TVI->setName("");
4579 Instruction *NewSel =
4580 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4582 InsertNewInstBefore(NewSel, SI);
4583 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4584 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4585 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4586 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4588 assert(0 && "Unknown instruction!!");
4593 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4594 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4595 !isa<Constant>(TrueVal))
4596 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4597 unsigned OpToFold = 0;
4598 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4600 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4605 Constant *C = GetSelectFoldableConstant(FVI);
4606 std::string Name = FVI->getName(); FVI->setName("");
4607 Instruction *NewSel =
4608 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4610 InsertNewInstBefore(NewSel, SI);
4611 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4612 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4613 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4614 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4616 assert(0 && "Unknown instruction!!");
4622 if (BinaryOperator::isNot(CondVal)) {
4623 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4624 SI.setOperand(1, FalseVal);
4625 SI.setOperand(2, TrueVal);
4633 /// visitCallInst - CallInst simplification. This mostly only handles folding
4634 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4635 /// the heavy lifting.
4637 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
4638 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4639 if (!II) return visitCallSite(&CI);
4641 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4643 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
4644 bool Changed = false;
4646 // memmove/cpy/set of zero bytes is a noop.
4647 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4648 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4650 // FIXME: Increase alignment here.
4652 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4653 if (CI->getRawValue() == 1) {
4654 // Replace the instruction with just byte operations. We would
4655 // transform other cases to loads/stores, but we don't know if
4656 // alignment is sufficient.
4660 // If we have a memmove and the source operation is a constant global,
4661 // then the source and dest pointers can't alias, so we can change this
4662 // into a call to memcpy.
4663 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
4664 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4665 if (GVSrc->isConstant()) {
4666 Module *M = CI.getParent()->getParent()->getParent();
4667 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4668 CI.getCalledFunction()->getFunctionType());
4669 CI.setOperand(0, MemCpy);
4673 if (Changed) return II;
4674 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
4675 // If this stoppoint is at the same source location as the previous
4676 // stoppoint in the chain, it is not needed.
4677 if (DbgStopPointInst *PrevSPI =
4678 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4679 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4680 SPI->getColNo() == PrevSPI->getColNo()) {
4681 SPI->replaceAllUsesWith(PrevSPI);
4682 return EraseInstFromFunction(CI);
4685 switch (II->getIntrinsicID()) {
4687 case Intrinsic::stackrestore: {
4688 // If the save is right next to the restore, remove the restore. This can
4689 // happen when variable allocas are DCE'd.
4690 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4691 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4692 BasicBlock::iterator BI = SS;
4694 return EraseInstFromFunction(CI);
4698 // If the stack restore is in a return/unwind block and if there are no
4699 // allocas or calls between the restore and the return, nuke the restore.
4700 TerminatorInst *TI = II->getParent()->getTerminator();
4701 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
4702 BasicBlock::iterator BI = II;
4703 bool CannotRemove = false;
4704 for (++BI; &*BI != TI; ++BI) {
4705 if (isa<AllocaInst>(BI) ||
4706 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
4707 CannotRemove = true;
4712 return EraseInstFromFunction(CI);
4719 return visitCallSite(II);
4722 // InvokeInst simplification
4724 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
4725 return visitCallSite(&II);
4728 // visitCallSite - Improvements for call and invoke instructions.
4730 Instruction *InstCombiner::visitCallSite(CallSite CS) {
4731 bool Changed = false;
4733 // If the callee is a constexpr cast of a function, attempt to move the cast
4734 // to the arguments of the call/invoke.
4735 if (transformConstExprCastCall(CS)) return 0;
4737 Value *Callee = CS.getCalledValue();
4739 if (Function *CalleeF = dyn_cast<Function>(Callee))
4740 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4741 Instruction *OldCall = CS.getInstruction();
4742 // If the call and callee calling conventions don't match, this call must
4743 // be unreachable, as the call is undefined.
4744 new StoreInst(ConstantBool::True,
4745 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4746 if (!OldCall->use_empty())
4747 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4748 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4749 return EraseInstFromFunction(*OldCall);
4753 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4754 // This instruction is not reachable, just remove it. We insert a store to
4755 // undef so that we know that this code is not reachable, despite the fact
4756 // that we can't modify the CFG here.
4757 new StoreInst(ConstantBool::True,
4758 UndefValue::get(PointerType::get(Type::BoolTy)),
4759 CS.getInstruction());
4761 if (!CS.getInstruction()->use_empty())
4762 CS.getInstruction()->
4763 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4765 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4766 // Don't break the CFG, insert a dummy cond branch.
4767 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4768 ConstantBool::True, II);
4770 return EraseInstFromFunction(*CS.getInstruction());
4773 const PointerType *PTy = cast<PointerType>(Callee->getType());
4774 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4775 if (FTy->isVarArg()) {
4776 // See if we can optimize any arguments passed through the varargs area of
4778 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4779 E = CS.arg_end(); I != E; ++I)
4780 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4781 // If this cast does not effect the value passed through the varargs
4782 // area, we can eliminate the use of the cast.
4783 Value *Op = CI->getOperand(0);
4784 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4791 return Changed ? CS.getInstruction() : 0;
4794 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
4795 // attempt to move the cast to the arguments of the call/invoke.
4797 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4798 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4799 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
4800 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
4802 Function *Callee = cast<Function>(CE->getOperand(0));
4803 Instruction *Caller = CS.getInstruction();
4805 // Okay, this is a cast from a function to a different type. Unless doing so
4806 // would cause a type conversion of one of our arguments, change this call to
4807 // be a direct call with arguments casted to the appropriate types.
4809 const FunctionType *FT = Callee->getFunctionType();
4810 const Type *OldRetTy = Caller->getType();
4812 // Check to see if we are changing the return type...
4813 if (OldRetTy != FT->getReturnType()) {
4814 if (Callee->isExternal() &&
4815 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4816 !Caller->use_empty())
4817 return false; // Cannot transform this return value...
4819 // If the callsite is an invoke instruction, and the return value is used by
4820 // a PHI node in a successor, we cannot change the return type of the call
4821 // because there is no place to put the cast instruction (without breaking
4822 // the critical edge). Bail out in this case.
4823 if (!Caller->use_empty())
4824 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4825 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4827 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4828 if (PN->getParent() == II->getNormalDest() ||
4829 PN->getParent() == II->getUnwindDest())
4833 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4834 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4836 CallSite::arg_iterator AI = CS.arg_begin();
4837 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4838 const Type *ParamTy = FT->getParamType(i);
4839 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
4840 if (Callee->isExternal() && !isConvertible) return false;
4843 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4844 Callee->isExternal())
4845 return false; // Do not delete arguments unless we have a function body...
4847 // Okay, we decided that this is a safe thing to do: go ahead and start
4848 // inserting cast instructions as necessary...
4849 std::vector<Value*> Args;
4850 Args.reserve(NumActualArgs);
4852 AI = CS.arg_begin();
4853 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4854 const Type *ParamTy = FT->getParamType(i);
4855 if ((*AI)->getType() == ParamTy) {
4856 Args.push_back(*AI);
4858 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4863 // If the function takes more arguments than the call was taking, add them
4865 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4866 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4868 // If we are removing arguments to the function, emit an obnoxious warning...
4869 if (FT->getNumParams() < NumActualArgs)
4870 if (!FT->isVarArg()) {
4871 std::cerr << "WARNING: While resolving call to function '"
4872 << Callee->getName() << "' arguments were dropped!\n";
4874 // Add all of the arguments in their promoted form to the arg list...
4875 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4876 const Type *PTy = getPromotedType((*AI)->getType());
4877 if (PTy != (*AI)->getType()) {
4878 // Must promote to pass through va_arg area!
4879 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4880 InsertNewInstBefore(Cast, *Caller);
4881 Args.push_back(Cast);
4883 Args.push_back(*AI);
4888 if (FT->getReturnType() == Type::VoidTy)
4889 Caller->setName(""); // Void type should not have a name...
4892 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4893 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
4894 Args, Caller->getName(), Caller);
4895 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
4897 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4898 if (cast<CallInst>(Caller)->isTailCall())
4899 cast<CallInst>(NC)->setTailCall();
4900 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
4903 // Insert a cast of the return type as necessary...
4905 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4906 if (NV->getType() != Type::VoidTy) {
4907 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
4909 // If this is an invoke instruction, we should insert it after the first
4910 // non-phi, instruction in the normal successor block.
4911 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4912 BasicBlock::iterator I = II->getNormalDest()->begin();
4913 while (isa<PHINode>(I)) ++I;
4914 InsertNewInstBefore(NC, *I);
4916 // Otherwise, it's a call, just insert cast right after the call instr
4917 InsertNewInstBefore(NC, *Caller);
4919 AddUsersToWorkList(*Caller);
4921 NV = UndefValue::get(Caller->getType());
4925 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4926 Caller->replaceAllUsesWith(NV);
4927 Caller->getParent()->getInstList().erase(Caller);
4928 removeFromWorkList(Caller);
4933 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4934 // operator and they all are only used by the PHI, PHI together their
4935 // inputs, and do the operation once, to the result of the PHI.
4936 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4937 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4939 // Scan the instruction, looking for input operations that can be folded away.
4940 // If all input operands to the phi are the same instruction (e.g. a cast from
4941 // the same type or "+42") we can pull the operation through the PHI, reducing
4942 // code size and simplifying code.
4943 Constant *ConstantOp = 0;
4944 const Type *CastSrcTy = 0;
4945 if (isa<CastInst>(FirstInst)) {
4946 CastSrcTy = FirstInst->getOperand(0)->getType();
4947 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4948 // Can fold binop or shift if the RHS is a constant.
4949 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4950 if (ConstantOp == 0) return 0;
4952 return 0; // Cannot fold this operation.
4955 // Check to see if all arguments are the same operation.
4956 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4957 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4958 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4959 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4962 if (I->getOperand(0)->getType() != CastSrcTy)
4963 return 0; // Cast operation must match.
4964 } else if (I->getOperand(1) != ConstantOp) {
4969 // Okay, they are all the same operation. Create a new PHI node of the
4970 // correct type, and PHI together all of the LHS's of the instructions.
4971 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4972 PN.getName()+".in");
4973 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
4975 Value *InVal = FirstInst->getOperand(0);
4976 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
4978 // Add all operands to the new PHI.
4979 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4980 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4981 if (NewInVal != InVal)
4983 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4988 // The new PHI unions all of the same values together. This is really
4989 // common, so we handle it intelligently here for compile-time speed.
4993 InsertNewInstBefore(NewPN, PN);
4997 // Insert and return the new operation.
4998 if (isa<CastInst>(FirstInst))
4999 return new CastInst(PhiVal, PN.getType());
5000 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
5001 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
5003 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
5004 PhiVal, ConstantOp);
5007 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5009 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5010 if (PN->use_empty()) return true;
5011 if (!PN->hasOneUse()) return false;
5013 // Remember this node, and if we find the cycle, return.
5014 if (!PotentiallyDeadPHIs.insert(PN).second)
5017 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5018 return DeadPHICycle(PU, PotentiallyDeadPHIs);
5023 // PHINode simplification
5025 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
5026 if (Value *V = PN.hasConstantValue())
5027 return ReplaceInstUsesWith(PN, V);
5029 // If the only user of this instruction is a cast instruction, and all of the
5030 // incoming values are constants, change this PHI to merge together the casted
5033 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5034 if (CI->getType() != PN.getType()) { // noop casts will be folded
5035 bool AllConstant = true;
5036 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5037 if (!isa<Constant>(PN.getIncomingValue(i))) {
5038 AllConstant = false;
5042 // Make a new PHI with all casted values.
5043 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5044 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5045 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5046 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5047 PN.getIncomingBlock(i));
5050 // Update the cast instruction.
5051 CI->setOperand(0, New);
5052 WorkList.push_back(CI); // revisit the cast instruction to fold.
5053 WorkList.push_back(New); // Make sure to revisit the new Phi
5054 return &PN; // PN is now dead!
5058 // If all PHI operands are the same operation, pull them through the PHI,
5059 // reducing code size.
5060 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5061 PN.getIncomingValue(0)->hasOneUse())
5062 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5065 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5066 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5067 // PHI)... break the cycle.
5069 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5070 std::set<PHINode*> PotentiallyDeadPHIs;
5071 PotentiallyDeadPHIs.insert(&PN);
5072 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5073 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5079 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5080 Instruction *InsertPoint,
5082 unsigned PS = IC->getTargetData().getPointerSize();
5083 const Type *VTy = V->getType();
5084 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5085 // We must insert a cast to ensure we sign-extend.
5086 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5087 V->getName()), *InsertPoint);
5088 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5093 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
5094 Value *PtrOp = GEP.getOperand(0);
5095 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
5096 // If so, eliminate the noop.
5097 if (GEP.getNumOperands() == 1)
5098 return ReplaceInstUsesWith(GEP, PtrOp);
5100 if (isa<UndefValue>(GEP.getOperand(0)))
5101 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5103 bool HasZeroPointerIndex = false;
5104 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5105 HasZeroPointerIndex = C->isNullValue();
5107 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
5108 return ReplaceInstUsesWith(GEP, PtrOp);
5110 // Eliminate unneeded casts for indices.
5111 bool MadeChange = false;
5112 gep_type_iterator GTI = gep_type_begin(GEP);
5113 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5114 if (isa<SequentialType>(*GTI)) {
5115 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5116 Value *Src = CI->getOperand(0);
5117 const Type *SrcTy = Src->getType();
5118 const Type *DestTy = CI->getType();
5119 if (Src->getType()->isInteger()) {
5120 if (SrcTy->getPrimitiveSizeInBits() ==
5121 DestTy->getPrimitiveSizeInBits()) {
5122 // We can always eliminate a cast from ulong or long to the other.
5123 // We can always eliminate a cast from uint to int or the other on
5124 // 32-bit pointer platforms.
5125 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
5127 GEP.setOperand(i, Src);
5129 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5130 SrcTy->getPrimitiveSize() == 4) {
5131 // We can always eliminate a cast from int to [u]long. We can
5132 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5134 if (SrcTy->isSigned() ||
5135 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
5137 GEP.setOperand(i, Src);
5142 // If we are using a wider index than needed for this platform, shrink it
5143 // to what we need. If the incoming value needs a cast instruction,
5144 // insert it. This explicit cast can make subsequent optimizations more
5146 Value *Op = GEP.getOperand(i);
5147 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
5148 if (Constant *C = dyn_cast<Constant>(Op)) {
5149 GEP.setOperand(i, ConstantExpr::getCast(C,
5150 TD->getIntPtrType()->getSignedVersion()));
5153 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5154 Op->getName()), GEP);
5155 GEP.setOperand(i, Op);
5159 // If this is a constant idx, make sure to canonicalize it to be a signed
5160 // operand, otherwise CSE and other optimizations are pessimized.
5161 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5162 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5163 CUI->getType()->getSignedVersion()));
5167 if (MadeChange) return &GEP;
5169 // Combine Indices - If the source pointer to this getelementptr instruction
5170 // is a getelementptr instruction, combine the indices of the two
5171 // getelementptr instructions into a single instruction.
5173 std::vector<Value*> SrcGEPOperands;
5174 if (User *Src = dyn_castGetElementPtr(PtrOp))
5175 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
5177 if (!SrcGEPOperands.empty()) {
5178 // Note that if our source is a gep chain itself that we wait for that
5179 // chain to be resolved before we perform this transformation. This
5180 // avoids us creating a TON of code in some cases.
5182 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5183 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5184 return 0; // Wait until our source is folded to completion.
5186 std::vector<Value *> Indices;
5188 // Find out whether the last index in the source GEP is a sequential idx.
5189 bool EndsWithSequential = false;
5190 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5191 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
5192 EndsWithSequential = !isa<StructType>(*I);
5194 // Can we combine the two pointer arithmetics offsets?
5195 if (EndsWithSequential) {
5196 // Replace: gep (gep %P, long B), long A, ...
5197 // With: T = long A+B; gep %P, T, ...
5199 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
5200 if (SO1 == Constant::getNullValue(SO1->getType())) {
5202 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5205 // If they aren't the same type, convert both to an integer of the
5206 // target's pointer size.
5207 if (SO1->getType() != GO1->getType()) {
5208 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5209 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5210 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5211 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5213 unsigned PS = TD->getPointerSize();
5214 if (SO1->getType()->getPrimitiveSize() == PS) {
5215 // Convert GO1 to SO1's type.
5216 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5218 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5219 // Convert SO1 to GO1's type.
5220 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5222 const Type *PT = TD->getIntPtrType();
5223 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5224 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5228 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5229 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5231 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5232 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
5236 // Recycle the GEP we already have if possible.
5237 if (SrcGEPOperands.size() == 2) {
5238 GEP.setOperand(0, SrcGEPOperands[0]);
5239 GEP.setOperand(1, Sum);
5242 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5243 SrcGEPOperands.end()-1);
5244 Indices.push_back(Sum);
5245 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5247 } else if (isa<Constant>(*GEP.idx_begin()) &&
5248 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
5249 SrcGEPOperands.size() != 1) {
5250 // Otherwise we can do the fold if the first index of the GEP is a zero
5251 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5252 SrcGEPOperands.end());
5253 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5256 if (!Indices.empty())
5257 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
5259 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
5260 // GEP of global variable. If all of the indices for this GEP are
5261 // constants, we can promote this to a constexpr instead of an instruction.
5263 // Scan for nonconstants...
5264 std::vector<Constant*> Indices;
5265 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5266 for (; I != E && isa<Constant>(*I); ++I)
5267 Indices.push_back(cast<Constant>(*I));
5269 if (I == E) { // If they are all constants...
5270 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
5272 // Replace all uses of the GEP with the new constexpr...
5273 return ReplaceInstUsesWith(GEP, CE);
5275 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5276 if (!isa<PointerType>(X->getType())) {
5277 // Not interesting. Source pointer must be a cast from pointer.
5278 } else if (HasZeroPointerIndex) {
5279 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5280 // into : GEP [10 x ubyte]* X, long 0, ...
5282 // This occurs when the program declares an array extern like "int X[];"
5284 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5285 const PointerType *XTy = cast<PointerType>(X->getType());
5286 if (const ArrayType *XATy =
5287 dyn_cast<ArrayType>(XTy->getElementType()))
5288 if (const ArrayType *CATy =
5289 dyn_cast<ArrayType>(CPTy->getElementType()))
5290 if (CATy->getElementType() == XATy->getElementType()) {
5291 // At this point, we know that the cast source type is a pointer
5292 // to an array of the same type as the destination pointer
5293 // array. Because the array type is never stepped over (there
5294 // is a leading zero) we can fold the cast into this GEP.
5295 GEP.setOperand(0, X);
5298 } else if (GEP.getNumOperands() == 2) {
5299 // Transform things like:
5300 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5301 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
5302 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5303 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5304 if (isa<ArrayType>(SrcElTy) &&
5305 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5306 TD->getTypeSize(ResElTy)) {
5307 Value *V = InsertNewInstBefore(
5308 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5309 GEP.getOperand(1), GEP.getName()), GEP);
5310 return new CastInst(V, GEP.getType());
5313 // Transform things like:
5314 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5315 // (where tmp = 8*tmp2) into:
5316 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5318 if (isa<ArrayType>(SrcElTy) &&
5319 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5320 uint64_t ArrayEltSize =
5321 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5323 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5324 // allow either a mul, shift, or constant here.
5326 ConstantInt *Scale = 0;
5327 if (ArrayEltSize == 1) {
5328 NewIdx = GEP.getOperand(1);
5329 Scale = ConstantInt::get(NewIdx->getType(), 1);
5330 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
5331 NewIdx = ConstantInt::get(CI->getType(), 1);
5333 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5334 if (Inst->getOpcode() == Instruction::Shl &&
5335 isa<ConstantInt>(Inst->getOperand(1))) {
5336 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5337 if (Inst->getType()->isSigned())
5338 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5340 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5341 NewIdx = Inst->getOperand(0);
5342 } else if (Inst->getOpcode() == Instruction::Mul &&
5343 isa<ConstantInt>(Inst->getOperand(1))) {
5344 Scale = cast<ConstantInt>(Inst->getOperand(1));
5345 NewIdx = Inst->getOperand(0);
5349 // If the index will be to exactly the right offset with the scale taken
5350 // out, perform the transformation.
5351 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5352 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5353 Scale = ConstantSInt::get(C->getType(),
5354 (int64_t)C->getRawValue() /
5355 (int64_t)ArrayEltSize);
5357 Scale = ConstantUInt::get(Scale->getType(),
5358 Scale->getRawValue() / ArrayEltSize);
5359 if (Scale->getRawValue() != 1) {
5360 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5361 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5362 NewIdx = InsertNewInstBefore(Sc, GEP);
5365 // Insert the new GEP instruction.
5367 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5368 NewIdx, GEP.getName());
5369 Idx = InsertNewInstBefore(Idx, GEP);
5370 return new CastInst(Idx, GEP.getType());
5379 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5380 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5381 if (AI.isArrayAllocation()) // Check C != 1
5382 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5383 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
5384 AllocationInst *New = 0;
5386 // Create and insert the replacement instruction...
5387 if (isa<MallocInst>(AI))
5388 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
5390 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
5391 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
5394 InsertNewInstBefore(New, AI);
5396 // Scan to the end of the allocation instructions, to skip over a block of
5397 // allocas if possible...
5399 BasicBlock::iterator It = New;
5400 while (isa<AllocationInst>(*It)) ++It;
5402 // Now that I is pointing to the first non-allocation-inst in the block,
5403 // insert our getelementptr instruction...
5405 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5406 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5407 New->getName()+".sub", It);
5409 // Now make everything use the getelementptr instead of the original
5411 return ReplaceInstUsesWith(AI, V);
5412 } else if (isa<UndefValue>(AI.getArraySize())) {
5413 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5416 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5417 // Note that we only do this for alloca's, because malloc should allocate and
5418 // return a unique pointer, even for a zero byte allocation.
5419 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
5420 TD->getTypeSize(AI.getAllocatedType()) == 0)
5421 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5426 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5427 Value *Op = FI.getOperand(0);
5429 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5430 if (CastInst *CI = dyn_cast<CastInst>(Op))
5431 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5432 FI.setOperand(0, CI->getOperand(0));
5436 // free undef -> unreachable.
5437 if (isa<UndefValue>(Op)) {
5438 // Insert a new store to null because we cannot modify the CFG here.
5439 new StoreInst(ConstantBool::True,
5440 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5441 return EraseInstFromFunction(FI);
5444 // If we have 'free null' delete the instruction. This can happen in stl code
5445 // when lots of inlining happens.
5446 if (isa<ConstantPointerNull>(Op))
5447 return EraseInstFromFunction(FI);
5453 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
5454 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5455 User *CI = cast<User>(LI.getOperand(0));
5456 Value *CastOp = CI->getOperand(0);
5458 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5459 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5460 const Type *SrcPTy = SrcTy->getElementType();
5462 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5463 // If the source is an array, the code below will not succeed. Check to
5464 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5466 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5467 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5468 if (ASrcTy->getNumElements() != 0) {
5469 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5470 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5471 SrcTy = cast<PointerType>(CastOp->getType());
5472 SrcPTy = SrcTy->getElementType();
5475 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5476 // Do not allow turning this into a load of an integer, which is then
5477 // casted to a pointer, this pessimizes pointer analysis a lot.
5478 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
5479 IC.getTargetData().getTypeSize(SrcPTy) ==
5480 IC.getTargetData().getTypeSize(DestPTy)) {
5482 // Okay, we are casting from one integer or pointer type to another of
5483 // the same size. Instead of casting the pointer before the load, cast
5484 // the result of the loaded value.
5485 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5487 LI.isVolatile()),LI);
5488 // Now cast the result of the load.
5489 return new CastInst(NewLoad, LI.getType());
5496 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
5497 /// from this value cannot trap. If it is not obviously safe to load from the
5498 /// specified pointer, we do a quick local scan of the basic block containing
5499 /// ScanFrom, to determine if the address is already accessed.
5500 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5501 // If it is an alloca or global variable, it is always safe to load from.
5502 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5504 // Otherwise, be a little bit agressive by scanning the local block where we
5505 // want to check to see if the pointer is already being loaded or stored
5506 // from/to. If so, the previous load or store would have already trapped,
5507 // so there is no harm doing an extra load (also, CSE will later eliminate
5508 // the load entirely).
5509 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5514 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5515 if (LI->getOperand(0) == V) return true;
5516 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5517 if (SI->getOperand(1) == V) return true;
5523 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5524 Value *Op = LI.getOperand(0);
5526 // load (cast X) --> cast (load X) iff safe
5527 if (CastInst *CI = dyn_cast<CastInst>(Op))
5528 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5531 // None of the following transforms are legal for volatile loads.
5532 if (LI.isVolatile()) return 0;
5534 if (&LI.getParent()->front() != &LI) {
5535 BasicBlock::iterator BBI = &LI; --BBI;
5536 // If the instruction immediately before this is a store to the same
5537 // address, do a simple form of store->load forwarding.
5538 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5539 if (SI->getOperand(1) == LI.getOperand(0))
5540 return ReplaceInstUsesWith(LI, SI->getOperand(0));
5541 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5542 if (LIB->getOperand(0) == LI.getOperand(0))
5543 return ReplaceInstUsesWith(LI, LIB);
5546 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5547 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5548 isa<UndefValue>(GEPI->getOperand(0))) {
5549 // Insert a new store to null instruction before the load to indicate
5550 // that this code is not reachable. We do this instead of inserting
5551 // an unreachable instruction directly because we cannot modify the
5553 new StoreInst(UndefValue::get(LI.getType()),
5554 Constant::getNullValue(Op->getType()), &LI);
5555 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5558 if (Constant *C = dyn_cast<Constant>(Op)) {
5559 // load null/undef -> undef
5560 if ((C->isNullValue() || isa<UndefValue>(C))) {
5561 // Insert a new store to null instruction before the load to indicate that
5562 // this code is not reachable. We do this instead of inserting an
5563 // unreachable instruction directly because we cannot modify the CFG.
5564 new StoreInst(UndefValue::get(LI.getType()),
5565 Constant::getNullValue(Op->getType()), &LI);
5566 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5569 // Instcombine load (constant global) into the value loaded.
5570 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5571 if (GV->isConstant() && !GV->isExternal())
5572 return ReplaceInstUsesWith(LI, GV->getInitializer());
5574 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5576 if (CE->getOpcode() == Instruction::GetElementPtr) {
5577 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5578 if (GV->isConstant() && !GV->isExternal())
5580 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
5581 return ReplaceInstUsesWith(LI, V);
5582 if (CE->getOperand(0)->isNullValue()) {
5583 // Insert a new store to null instruction before the load to indicate
5584 // that this code is not reachable. We do this instead of inserting
5585 // an unreachable instruction directly because we cannot modify the
5587 new StoreInst(UndefValue::get(LI.getType()),
5588 Constant::getNullValue(Op->getType()), &LI);
5589 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5592 } else if (CE->getOpcode() == Instruction::Cast) {
5593 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5598 if (Op->hasOneUse()) {
5599 // Change select and PHI nodes to select values instead of addresses: this
5600 // helps alias analysis out a lot, allows many others simplifications, and
5601 // exposes redundancy in the code.
5603 // Note that we cannot do the transformation unless we know that the
5604 // introduced loads cannot trap! Something like this is valid as long as
5605 // the condition is always false: load (select bool %C, int* null, int* %G),
5606 // but it would not be valid if we transformed it to load from null
5609 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5610 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
5611 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5612 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
5613 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
5614 SI->getOperand(1)->getName()+".val"), LI);
5615 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
5616 SI->getOperand(2)->getName()+".val"), LI);
5617 return new SelectInst(SI->getCondition(), V1, V2);
5620 // load (select (cond, null, P)) -> load P
5621 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5622 if (C->isNullValue()) {
5623 LI.setOperand(0, SI->getOperand(2));
5627 // load (select (cond, P, null)) -> load P
5628 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5629 if (C->isNullValue()) {
5630 LI.setOperand(0, SI->getOperand(1));
5634 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5635 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
5636 bool Safe = PN->getParent() == LI.getParent();
5638 // Scan all of the instructions between the PHI and the load to make
5639 // sure there are no instructions that might possibly alter the value
5640 // loaded from the PHI.
5642 BasicBlock::iterator I = &LI;
5643 for (--I; !isa<PHINode>(I); --I)
5644 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5650 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
5651 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
5652 PN->getIncomingBlock(i)->getTerminator()))
5657 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5658 InsertNewInstBefore(NewPN, *PN);
5659 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5661 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5662 BasicBlock *BB = PN->getIncomingBlock(i);
5663 Value *&TheLoad = LoadMap[BB];
5665 Value *InVal = PN->getIncomingValue(i);
5666 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5667 InVal->getName()+".val"),
5668 *BB->getTerminator());
5670 NewPN->addIncoming(TheLoad, BB);
5672 return ReplaceInstUsesWith(LI, NewPN);
5679 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5681 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5682 User *CI = cast<User>(SI.getOperand(1));
5683 Value *CastOp = CI->getOperand(0);
5685 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5686 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5687 const Type *SrcPTy = SrcTy->getElementType();
5689 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5690 // If the source is an array, the code below will not succeed. Check to
5691 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5693 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5694 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5695 if (ASrcTy->getNumElements() != 0) {
5696 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5697 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5698 SrcTy = cast<PointerType>(CastOp->getType());
5699 SrcPTy = SrcTy->getElementType();
5702 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5703 IC.getTargetData().getTypeSize(SrcPTy) ==
5704 IC.getTargetData().getTypeSize(DestPTy)) {
5706 // Okay, we are casting from one integer or pointer type to another of
5707 // the same size. Instead of casting the pointer before the store, cast
5708 // the value to be stored.
5710 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5711 NewCast = ConstantExpr::getCast(C, SrcPTy);
5713 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5715 SI.getOperand(0)->getName()+".c"), SI);
5717 return new StoreInst(NewCast, CastOp);
5724 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5725 Value *Val = SI.getOperand(0);
5726 Value *Ptr = SI.getOperand(1);
5728 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5729 removeFromWorkList(&SI);
5730 SI.eraseFromParent();
5735 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5737 // store X, null -> turns into 'unreachable' in SimplifyCFG
5738 if (isa<ConstantPointerNull>(Ptr)) {
5739 if (!isa<UndefValue>(Val)) {
5740 SI.setOperand(0, UndefValue::get(Val->getType()));
5741 if (Instruction *U = dyn_cast<Instruction>(Val))
5742 WorkList.push_back(U); // Dropped a use.
5745 return 0; // Do not modify these!
5748 // store undef, Ptr -> noop
5749 if (isa<UndefValue>(Val)) {
5750 removeFromWorkList(&SI);
5751 SI.eraseFromParent();
5756 // If the pointer destination is a cast, see if we can fold the cast into the
5758 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5759 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5761 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5762 if (CE->getOpcode() == Instruction::Cast)
5763 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5767 // If this store is the last instruction in the basic block, and if the block
5768 // ends with an unconditional branch, try to move it to the successor block.
5769 BasicBlock::iterator BBI = &SI; ++BBI;
5770 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5771 if (BI->isUnconditional()) {
5772 // Check to see if the successor block has exactly two incoming edges. If
5773 // so, see if the other predecessor contains a store to the same location.
5774 // if so, insert a PHI node (if needed) and move the stores down.
5775 BasicBlock *Dest = BI->getSuccessor(0);
5777 pred_iterator PI = pred_begin(Dest);
5778 BasicBlock *Other = 0;
5779 if (*PI != BI->getParent())
5782 if (PI != pred_end(Dest)) {
5783 if (*PI != BI->getParent())
5788 if (++PI != pred_end(Dest))
5791 if (Other) { // If only one other pred...
5792 BBI = Other->getTerminator();
5793 // Make sure this other block ends in an unconditional branch and that
5794 // there is an instruction before the branch.
5795 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5796 BBI != Other->begin()) {
5798 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5800 // If this instruction is a store to the same location.
5801 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5802 // Okay, we know we can perform this transformation. Insert a PHI
5803 // node now if we need it.
5804 Value *MergedVal = OtherStore->getOperand(0);
5805 if (MergedVal != SI.getOperand(0)) {
5806 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5807 PN->reserveOperandSpace(2);
5808 PN->addIncoming(SI.getOperand(0), SI.getParent());
5809 PN->addIncoming(OtherStore->getOperand(0), Other);
5810 MergedVal = InsertNewInstBefore(PN, Dest->front());
5813 // Advance to a place where it is safe to insert the new store and
5815 BBI = Dest->begin();
5816 while (isa<PHINode>(BBI)) ++BBI;
5817 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5818 OtherStore->isVolatile()), *BBI);
5820 // Nuke the old stores.
5821 removeFromWorkList(&SI);
5822 removeFromWorkList(OtherStore);
5823 SI.eraseFromParent();
5824 OtherStore->eraseFromParent();
5836 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5837 // Change br (not X), label True, label False to: br X, label False, True
5839 BasicBlock *TrueDest;
5840 BasicBlock *FalseDest;
5841 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5842 !isa<Constant>(X)) {
5843 // Swap Destinations and condition...
5845 BI.setSuccessor(0, FalseDest);
5846 BI.setSuccessor(1, TrueDest);
5850 // Cannonicalize setne -> seteq
5851 Instruction::BinaryOps Op; Value *Y;
5852 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5853 TrueDest, FalseDest)))
5854 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5855 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5856 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5857 std::string Name = I->getName(); I->setName("");
5858 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5859 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
5860 // Swap Destinations and condition...
5861 BI.setCondition(NewSCC);
5862 BI.setSuccessor(0, FalseDest);
5863 BI.setSuccessor(1, TrueDest);
5864 removeFromWorkList(I);
5865 I->getParent()->getInstList().erase(I);
5866 WorkList.push_back(cast<Instruction>(NewSCC));
5873 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5874 Value *Cond = SI.getCondition();
5875 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5876 if (I->getOpcode() == Instruction::Add)
5877 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5878 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5879 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
5880 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
5882 SI.setOperand(0, I->getOperand(0));
5883 WorkList.push_back(I);
5890 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
5891 if (ConstantAggregateZero *C =
5892 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
5893 // If packed val is constant 0, replace extract with scalar 0
5894 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
5895 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
5896 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
5898 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
5899 // If packed val is constant with uniform operands, replace EI
5900 // with that operand
5901 Constant *op0 = cast<Constant>(C->getOperand(0));
5902 for (unsigned i = 1; i < C->getNumOperands(); ++i)
5903 if (C->getOperand(i) != op0) return 0;
5904 return ReplaceInstUsesWith(EI, op0);
5906 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
5907 if (I->hasOneUse()) {
5908 // Push extractelement into predecessor operation if legal and
5909 // profitable to do so
5910 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
5911 if (!isa<Constant>(BO->getOperand(0)) &&
5912 !isa<Constant>(BO->getOperand(1)))
5914 ExtractElementInst *newEI0 =
5915 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
5917 ExtractElementInst *newEI1 =
5918 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
5920 InsertNewInstBefore(newEI0, EI);
5921 InsertNewInstBefore(newEI1, EI);
5922 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
5924 switch(I->getOpcode()) {
5925 case Instruction::Load: {
5926 Value *Ptr = InsertCastBefore(I->getOperand(0),
5927 PointerType::get(EI.getType()), EI);
5928 GetElementPtrInst *GEP =
5929 new GetElementPtrInst(Ptr, EI.getOperand(1),
5930 I->getName() + ".gep");
5931 InsertNewInstBefore(GEP, EI);
5932 return new LoadInst(GEP);
5942 void InstCombiner::removeFromWorkList(Instruction *I) {
5943 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5948 /// TryToSinkInstruction - Try to move the specified instruction from its
5949 /// current block into the beginning of DestBlock, which can only happen if it's
5950 /// safe to move the instruction past all of the instructions between it and the
5951 /// end of its block.
5952 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5953 assert(I->hasOneUse() && "Invariants didn't hold!");
5955 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5956 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
5958 // Do not sink alloca instructions out of the entry block.
5959 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5962 // We can only sink load instructions if there is nothing between the load and
5963 // the end of block that could change the value.
5964 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5965 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5967 if (Scan->mayWriteToMemory())
5971 BasicBlock::iterator InsertPos = DestBlock->begin();
5972 while (isa<PHINode>(InsertPos)) ++InsertPos;
5974 I->moveBefore(InsertPos);
5979 bool InstCombiner::runOnFunction(Function &F) {
5980 bool Changed = false;
5981 TD = &getAnalysis<TargetData>();
5984 // Populate the worklist with the reachable instructions.
5985 std::set<BasicBlock*> Visited;
5986 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5987 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5988 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5989 WorkList.push_back(I);
5991 // Do a quick scan over the function. If we find any blocks that are
5992 // unreachable, remove any instructions inside of them. This prevents
5993 // the instcombine code from having to deal with some bad special cases.
5994 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5995 if (!Visited.count(BB)) {
5996 Instruction *Term = BB->getTerminator();
5997 while (Term != BB->begin()) { // Remove instrs bottom-up
5998 BasicBlock::iterator I = Term; --I;
6000 DEBUG(std::cerr << "IC: DCE: " << *I);
6003 if (!I->use_empty())
6004 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6005 I->eraseFromParent();
6010 while (!WorkList.empty()) {
6011 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6012 WorkList.pop_back();
6014 // Check to see if we can DCE or ConstantPropagate the instruction...
6015 // Check to see if we can DIE the instruction...
6016 if (isInstructionTriviallyDead(I)) {
6017 // Add operands to the worklist...
6018 if (I->getNumOperands() < 4)
6019 AddUsesToWorkList(*I);
6022 DEBUG(std::cerr << "IC: DCE: " << *I);
6024 I->eraseFromParent();
6025 removeFromWorkList(I);
6029 // Instruction isn't dead, see if we can constant propagate it...
6030 if (Constant *C = ConstantFoldInstruction(I)) {
6031 Value* Ptr = I->getOperand(0);
6032 if (isa<GetElementPtrInst>(I) &&
6033 cast<Constant>(Ptr)->isNullValue() &&
6034 !isa<ConstantPointerNull>(C) &&
6035 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
6036 // If this is a constant expr gep that is effectively computing an
6037 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6038 bool isFoldableGEP = true;
6039 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6040 if (!isa<ConstantInt>(I->getOperand(i)))
6041 isFoldableGEP = false;
6042 if (isFoldableGEP) {
6043 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
6044 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6045 C = ConstantUInt::get(Type::ULongTy, Offset);
6046 C = ConstantExpr::getCast(C, TD->getIntPtrType());
6047 C = ConstantExpr::getCast(C, I->getType());
6051 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6053 // Add operands to the worklist...
6054 AddUsesToWorkList(*I);
6055 ReplaceInstUsesWith(*I, C);
6058 I->getParent()->getInstList().erase(I);
6059 removeFromWorkList(I);
6063 // See if we can trivially sink this instruction to a successor basic block.
6064 if (I->hasOneUse()) {
6065 BasicBlock *BB = I->getParent();
6066 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6067 if (UserParent != BB) {
6068 bool UserIsSuccessor = false;
6069 // See if the user is one of our successors.
6070 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6071 if (*SI == UserParent) {
6072 UserIsSuccessor = true;
6076 // If the user is one of our immediate successors, and if that successor
6077 // only has us as a predecessors (we'd have to split the critical edge
6078 // otherwise), we can keep going.
6079 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6080 next(pred_begin(UserParent)) == pred_end(UserParent))
6081 // Okay, the CFG is simple enough, try to sink this instruction.
6082 Changed |= TryToSinkInstruction(I, UserParent);
6086 // Now that we have an instruction, try combining it to simplify it...
6087 if (Instruction *Result = visit(*I)) {
6089 // Should we replace the old instruction with a new one?
6091 DEBUG(std::cerr << "IC: Old = " << *I
6092 << " New = " << *Result);
6094 // Everything uses the new instruction now.
6095 I->replaceAllUsesWith(Result);
6097 // Push the new instruction and any users onto the worklist.
6098 WorkList.push_back(Result);
6099 AddUsersToWorkList(*Result);
6101 // Move the name to the new instruction first...
6102 std::string OldName = I->getName(); I->setName("");
6103 Result->setName(OldName);
6105 // Insert the new instruction into the basic block...
6106 BasicBlock *InstParent = I->getParent();
6107 BasicBlock::iterator InsertPos = I;
6109 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6110 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6113 InstParent->getInstList().insert(InsertPos, Result);
6115 // Make sure that we reprocess all operands now that we reduced their
6117 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6118 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6119 WorkList.push_back(OpI);
6121 // Instructions can end up on the worklist more than once. Make sure
6122 // we do not process an instruction that has been deleted.
6123 removeFromWorkList(I);
6125 // Erase the old instruction.
6126 InstParent->getInstList().erase(I);
6128 DEBUG(std::cerr << "IC: MOD = " << *I);
6130 // If the instruction was modified, it's possible that it is now dead.
6131 // if so, remove it.
6132 if (isInstructionTriviallyDead(I)) {
6133 // Make sure we process all operands now that we are reducing their
6135 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6136 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6137 WorkList.push_back(OpI);
6139 // Instructions may end up in the worklist more than once. Erase all
6140 // occurrences of this instruction.
6141 removeFromWorkList(I);
6142 I->eraseFromParent();
6144 WorkList.push_back(Result);
6145 AddUsersToWorkList(*Result);
6155 FunctionPass *llvm::createInstructionCombiningPass() {
6156 return new InstCombiner();