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. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp 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/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
56 using namespace llvm::PatternMatch;
58 STATISTIC(NumCombined , "Number of insts combined");
59 STATISTIC(NumConstProp, "Number of constant folds");
60 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62 STATISTIC(NumSunkInst , "Number of instructions sunk");
65 class VISIBILITY_HIDDEN InstCombiner
66 : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(Value &I) {
77 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
79 WorkList.push_back(cast<Instruction>(*UI));
82 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
91 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92 /// dead. Add all of its operands to the worklist, turning them into
93 /// undef's to reduce the number of uses of those instructions.
95 /// Return the specified operand before it is turned into an undef.
97 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98 Value *R = I.getOperand(op);
100 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102 WorkList.push_back(Op);
103 // Set the operand to undef to drop the use.
104 I.setOperand(i, UndefValue::get(Op->getType()));
110 // removeFromWorkList - remove all instances of I from the worklist.
111 void removeFromWorkList(Instruction *I);
113 virtual bool runOnFunction(Function &F);
115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116 AU.addRequired<TargetData>();
117 AU.addPreservedID(LCSSAID);
118 AU.setPreservesCFG();
121 TargetData &getTargetData() const { return *TD; }
123 // Visitation implementation - Implement instruction combining for different
124 // instruction types. The semantics are as follows:
126 // null - No change was made
127 // I - Change was made, I is still valid, I may be dead though
128 // otherwise - Change was made, replace I with returned instruction
130 Instruction *visitAdd(BinaryOperator &I);
131 Instruction *visitSub(BinaryOperator &I);
132 Instruction *visitMul(BinaryOperator &I);
133 Instruction *visitURem(BinaryOperator &I);
134 Instruction *visitSRem(BinaryOperator &I);
135 Instruction *visitFRem(BinaryOperator &I);
136 Instruction *commonRemTransforms(BinaryOperator &I);
137 Instruction *commonIRemTransforms(BinaryOperator &I);
138 Instruction *commonDivTransforms(BinaryOperator &I);
139 Instruction *commonIDivTransforms(BinaryOperator &I);
140 Instruction *visitUDiv(BinaryOperator &I);
141 Instruction *visitSDiv(BinaryOperator &I);
142 Instruction *visitFDiv(BinaryOperator &I);
143 Instruction *visitAnd(BinaryOperator &I);
144 Instruction *visitOr (BinaryOperator &I);
145 Instruction *visitXor(BinaryOperator &I);
146 Instruction *visitFCmpInst(FCmpInst &I);
147 Instruction *visitICmpInst(ICmpInst &I);
148 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
150 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151 ICmpInst::Predicate Cond, Instruction &I);
152 Instruction *visitShiftInst(ShiftInst &I);
153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
155 Instruction *commonCastTransforms(CastInst &CI);
156 Instruction *commonIntCastTransforms(CastInst &CI);
157 Instruction *visitTrunc(CastInst &CI);
158 Instruction *visitZExt(CastInst &CI);
159 Instruction *visitSExt(CastInst &CI);
160 Instruction *visitFPTrunc(CastInst &CI);
161 Instruction *visitFPExt(CastInst &CI);
162 Instruction *visitFPToUI(CastInst &CI);
163 Instruction *visitFPToSI(CastInst &CI);
164 Instruction *visitUIToFP(CastInst &CI);
165 Instruction *visitSIToFP(CastInst &CI);
166 Instruction *visitPtrToInt(CastInst &CI);
167 Instruction *visitIntToPtr(CastInst &CI);
168 Instruction *visitBitCast(CastInst &CI);
169 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
171 Instruction *visitSelectInst(SelectInst &CI);
172 Instruction *visitCallInst(CallInst &CI);
173 Instruction *visitInvokeInst(InvokeInst &II);
174 Instruction *visitPHINode(PHINode &PN);
175 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
176 Instruction *visitAllocationInst(AllocationInst &AI);
177 Instruction *visitFreeInst(FreeInst &FI);
178 Instruction *visitLoadInst(LoadInst &LI);
179 Instruction *visitStoreInst(StoreInst &SI);
180 Instruction *visitBranchInst(BranchInst &BI);
181 Instruction *visitSwitchInst(SwitchInst &SI);
182 Instruction *visitInsertElementInst(InsertElementInst &IE);
183 Instruction *visitExtractElementInst(ExtractElementInst &EI);
184 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
186 // visitInstruction - Specify what to return for unhandled instructions...
187 Instruction *visitInstruction(Instruction &I) { return 0; }
190 Instruction *visitCallSite(CallSite CS);
191 bool transformConstExprCastCall(CallSite CS);
194 // InsertNewInstBefore - insert an instruction New before instruction Old
195 // in the program. Add the new instruction to the worklist.
197 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
198 assert(New && New->getParent() == 0 &&
199 "New instruction already inserted into a basic block!");
200 BasicBlock *BB = Old.getParent();
201 BB->getInstList().insert(&Old, New); // Insert inst
202 WorkList.push_back(New); // Add to worklist
206 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207 /// This also adds the cast to the worklist. Finally, this returns the
209 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
211 if (V->getType() == Ty) return V;
213 if (Constant *CV = dyn_cast<Constant>(V))
214 return ConstantExpr::getCast(opc, CV, Ty);
216 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
217 WorkList.push_back(C);
221 // ReplaceInstUsesWith - This method is to be used when an instruction is
222 // found to be dead, replacable with another preexisting expression. Here
223 // we add all uses of I to the worklist, replace all uses of I with the new
224 // value, then return I, so that the inst combiner will know that I was
227 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
228 AddUsersToWorkList(I); // Add all modified instrs to worklist
230 I.replaceAllUsesWith(V);
233 // If we are replacing the instruction with itself, this must be in a
234 // segment of unreachable code, so just clobber the instruction.
235 I.replaceAllUsesWith(UndefValue::get(I.getType()));
240 // UpdateValueUsesWith - This method is to be used when an value is
241 // found to be replacable with another preexisting expression or was
242 // updated. Here we add all uses of I to the worklist, replace all uses of
243 // I with the new value (unless the instruction was just updated), then
244 // return true, so that the inst combiner will know that I was modified.
246 bool UpdateValueUsesWith(Value *Old, Value *New) {
247 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
249 Old->replaceAllUsesWith(New);
250 if (Instruction *I = dyn_cast<Instruction>(Old))
251 WorkList.push_back(I);
252 if (Instruction *I = dyn_cast<Instruction>(New))
253 WorkList.push_back(I);
257 // EraseInstFromFunction - When dealing with an instruction that has side
258 // effects or produces a void value, we can't rely on DCE to delete the
259 // instruction. Instead, visit methods should return the value returned by
261 Instruction *EraseInstFromFunction(Instruction &I) {
262 assert(I.use_empty() && "Cannot erase instruction that is used!");
263 AddUsesToWorkList(I);
264 removeFromWorkList(&I);
266 return 0; // Don't do anything with FI
270 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271 /// InsertBefore instruction. This is specialized a bit to avoid inserting
272 /// casts that are known to not do anything...
274 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275 Value *V, const Type *DestTy,
276 Instruction *InsertBefore);
278 /// SimplifyCommutative - This performs a few simplifications for
279 /// commutative operators.
280 bool SimplifyCommutative(BinaryOperator &I);
282 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283 /// most-complex to least-complex order.
284 bool SimplifyCompare(CmpInst &I);
286 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
287 uint64_t &KnownZero, uint64_t &KnownOne,
290 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291 uint64_t &UndefElts, unsigned Depth = 0);
293 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294 // PHI node as operand #0, see if we can fold the instruction into the PHI
295 // (which is only possible if all operands to the PHI are constants).
296 Instruction *FoldOpIntoPhi(Instruction &I);
298 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299 // operator and they all are only used by the PHI, PHI together their
300 // inputs, and do the operation once, to the result of the PHI.
301 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
302 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
305 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
306 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
308 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
309 bool isSub, Instruction &I);
310 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
311 bool isSigned, bool Inside, Instruction &IB);
312 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
313 Instruction *MatchBSwap(BinaryOperator &I);
315 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
318 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
321 // getComplexity: Assign a complexity or rank value to LLVM Values...
322 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
323 static unsigned getComplexity(Value *V) {
324 if (isa<Instruction>(V)) {
325 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
329 if (isa<Argument>(V)) return 3;
330 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
333 // isOnlyUse - Return true if this instruction will be deleted if we stop using
335 static bool isOnlyUse(Value *V) {
336 return V->hasOneUse() || isa<Constant>(V);
339 // getPromotedType - Return the specified type promoted as it would be to pass
340 // though a va_arg area...
341 static const Type *getPromotedType(const Type *Ty) {
342 switch (Ty->getTypeID()) {
344 case Type::Int16TyID: return Type::Int32Ty;
345 case Type::FloatTyID: return Type::DoubleTy;
350 /// getBitCastOperand - If the specified operand is a CastInst or a constant
351 /// expression bitcast, return the operand value, otherwise return null.
352 static Value *getBitCastOperand(Value *V) {
353 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
354 return I->getOperand(0);
355 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
356 if (CE->getOpcode() == Instruction::BitCast)
357 return CE->getOperand(0);
361 /// This function is a wrapper around CastInst::isEliminableCastPair. It
362 /// simply extracts arguments and returns what that function returns.
363 /// @Determine if it is valid to eliminate a Convert pair
364 static Instruction::CastOps
365 isEliminableCastPair(
366 const CastInst *CI, ///< The first cast instruction
367 unsigned opcode, ///< The opcode of the second cast instruction
368 const Type *DstTy, ///< The target type for the second cast instruction
369 TargetData *TD ///< The target data for pointer size
372 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
373 const Type *MidTy = CI->getType(); // B from above
375 // Get the opcodes of the two Cast instructions
376 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
379 return Instruction::CastOps(
380 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381 DstTy, TD->getIntPtrType()));
384 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385 /// in any code being generated. It does not require codegen if V is simple
386 /// enough or if the cast can be folded into other casts.
387 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
388 const Type *Ty, TargetData *TD) {
389 if (V->getType() == Ty || isa<Constant>(V)) return false;
391 // If this is another cast that can be eliminated, it isn't codegen either.
392 if (const CastInst *CI = dyn_cast<CastInst>(V))
393 if (isEliminableCastPair(CI, opcode, Ty, TD))
398 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
399 /// InsertBefore instruction. This is specialized a bit to avoid inserting
400 /// casts that are known to not do anything...
402 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
403 Value *V, const Type *DestTy,
404 Instruction *InsertBefore) {
405 if (V->getType() == DestTy) return V;
406 if (Constant *C = dyn_cast<Constant>(V))
407 return ConstantExpr::getCast(opcode, C, DestTy);
409 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
412 // SimplifyCommutative - This performs a few simplifications for commutative
415 // 1. Order operands such that they are listed from right (least complex) to
416 // left (most complex). This puts constants before unary operators before
419 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
420 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
422 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
423 bool Changed = false;
424 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
425 Changed = !I.swapOperands();
427 if (!I.isAssociative()) return Changed;
428 Instruction::BinaryOps Opcode = I.getOpcode();
429 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
430 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
431 if (isa<Constant>(I.getOperand(1))) {
432 Constant *Folded = ConstantExpr::get(I.getOpcode(),
433 cast<Constant>(I.getOperand(1)),
434 cast<Constant>(Op->getOperand(1)));
435 I.setOperand(0, Op->getOperand(0));
436 I.setOperand(1, Folded);
438 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
439 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
440 isOnlyUse(Op) && isOnlyUse(Op1)) {
441 Constant *C1 = cast<Constant>(Op->getOperand(1));
442 Constant *C2 = cast<Constant>(Op1->getOperand(1));
444 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
445 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
446 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
449 WorkList.push_back(New);
450 I.setOperand(0, New);
451 I.setOperand(1, Folded);
458 /// SimplifyCompare - For a CmpInst this function just orders the operands
459 /// so that theyare listed from right (least complex) to left (most complex).
460 /// This puts constants before unary operators before binary operators.
461 bool InstCombiner::SimplifyCompare(CmpInst &I) {
462 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
465 // Compare instructions are not associative so there's nothing else we can do.
469 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
470 // if the LHS is a constant zero (which is the 'negate' form).
472 static inline Value *dyn_castNegVal(Value *V) {
473 if (BinaryOperator::isNeg(V))
474 return BinaryOperator::getNegArgument(V);
476 // Constants can be considered to be negated values if they can be folded.
477 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
478 return ConstantExpr::getNeg(C);
482 static inline Value *dyn_castNotVal(Value *V) {
483 if (BinaryOperator::isNot(V))
484 return BinaryOperator::getNotArgument(V);
486 // Constants can be considered to be not'ed values...
487 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
488 return ConstantExpr::getNot(C);
492 // dyn_castFoldableMul - If this value is a multiply that can be folded into
493 // other computations (because it has a constant operand), return the
494 // non-constant operand of the multiply, and set CST to point to the multiplier.
495 // Otherwise, return null.
497 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
498 if (V->hasOneUse() && V->getType()->isInteger())
499 if (Instruction *I = dyn_cast<Instruction>(V)) {
500 if (I->getOpcode() == Instruction::Mul)
501 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
502 return I->getOperand(0);
503 if (I->getOpcode() == Instruction::Shl)
504 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
505 // The multiplier is really 1 << CST.
506 Constant *One = ConstantInt::get(V->getType(), 1);
507 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
508 return I->getOperand(0);
514 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
515 /// expression, return it.
516 static User *dyn_castGetElementPtr(Value *V) {
517 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
518 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
519 if (CE->getOpcode() == Instruction::GetElementPtr)
520 return cast<User>(V);
524 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
525 static ConstantInt *AddOne(ConstantInt *C) {
526 return cast<ConstantInt>(ConstantExpr::getAdd(C,
527 ConstantInt::get(C->getType(), 1)));
529 static ConstantInt *SubOne(ConstantInt *C) {
530 return cast<ConstantInt>(ConstantExpr::getSub(C,
531 ConstantInt::get(C->getType(), 1)));
534 /// GetConstantInType - Return a ConstantInt with the specified type and value.
536 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
537 if (Ty->getTypeID() == Type::BoolTyID)
538 return ConstantBool::get(Val);
539 return ConstantInt::get(Ty, Val);
543 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
544 /// known to be either zero or one and return them in the KnownZero/KnownOne
545 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
547 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
548 uint64_t &KnownOne, unsigned Depth = 0) {
549 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
550 // we cannot optimize based on the assumption that it is zero without changing
551 // it to be an explicit zero. If we don't change it to zero, other code could
552 // optimized based on the contradictory assumption that it is non-zero.
553 // Because instcombine aggressively folds operations with undef args anyway,
554 // this won't lose us code quality.
555 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
556 // We know all of the bits for a constant!
557 KnownOne = CI->getZExtValue() & Mask;
558 KnownZero = ~KnownOne & Mask;
562 KnownZero = KnownOne = 0; // Don't know anything.
563 if (Depth == 6 || Mask == 0)
564 return; // Limit search depth.
566 uint64_t KnownZero2, KnownOne2;
567 Instruction *I = dyn_cast<Instruction>(V);
570 Mask &= V->getType()->getIntegralTypeMask();
572 switch (I->getOpcode()) {
573 case Instruction::And:
574 // If either the LHS or the RHS are Zero, the result is zero.
575 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
577 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
578 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
579 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
581 // Output known-1 bits are only known if set in both the LHS & RHS.
582 KnownOne &= KnownOne2;
583 // Output known-0 are known to be clear if zero in either the LHS | RHS.
584 KnownZero |= KnownZero2;
586 case Instruction::Or:
587 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
589 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
590 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
591 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
593 // Output known-0 bits are only known if clear in both the LHS & RHS.
594 KnownZero &= KnownZero2;
595 // Output known-1 are known to be set if set in either the LHS | RHS.
596 KnownOne |= KnownOne2;
598 case Instruction::Xor: {
599 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
600 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
601 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
602 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
604 // Output known-0 bits are known if clear or set in both the LHS & RHS.
605 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
606 // Output known-1 are known to be set if set in only one of the LHS, RHS.
607 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
608 KnownZero = KnownZeroOut;
611 case Instruction::Select:
612 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
613 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
614 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
615 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
617 // Only known if known in both the LHS and RHS.
618 KnownOne &= KnownOne2;
619 KnownZero &= KnownZero2;
621 case Instruction::FPTrunc:
622 case Instruction::FPExt:
623 case Instruction::FPToUI:
624 case Instruction::FPToSI:
625 case Instruction::SIToFP:
626 case Instruction::PtrToInt:
627 case Instruction::UIToFP:
628 case Instruction::IntToPtr:
629 return; // Can't work with floating point or pointers
630 case Instruction::Trunc:
631 // All these have integer operands
632 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
634 case Instruction::BitCast: {
635 const Type *SrcTy = I->getOperand(0)->getType();
636 if (SrcTy->isIntegral()) {
637 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
642 case Instruction::ZExt: {
643 // Compute the bits in the result that are not present in the input.
644 const Type *SrcTy = I->getOperand(0)->getType();
645 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
646 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
648 Mask &= SrcTy->getIntegralTypeMask();
649 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
650 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
651 // The top bits are known to be zero.
652 KnownZero |= NewBits;
655 case Instruction::SExt: {
656 // Compute the bits in the result that are not present in the input.
657 const Type *SrcTy = I->getOperand(0)->getType();
658 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
659 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
661 Mask &= SrcTy->getIntegralTypeMask();
662 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
663 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
665 // If the sign bit of the input is known set or clear, then we know the
666 // top bits of the result.
667 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
668 if (KnownZero & InSignBit) { // Input sign bit known zero
669 KnownZero |= NewBits;
670 KnownOne &= ~NewBits;
671 } else if (KnownOne & InSignBit) { // Input sign bit known set
673 KnownZero &= ~NewBits;
674 } else { // Input sign bit unknown
675 KnownZero &= ~NewBits;
676 KnownOne &= ~NewBits;
680 case Instruction::Shl:
681 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
682 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
683 uint64_t ShiftAmt = SA->getZExtValue();
685 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
686 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
687 KnownZero <<= ShiftAmt;
688 KnownOne <<= ShiftAmt;
689 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
693 case Instruction::LShr:
694 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
695 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
696 // Compute the new bits that are at the top now.
697 uint64_t ShiftAmt = SA->getZExtValue();
698 uint64_t HighBits = (1ULL << ShiftAmt)-1;
699 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
701 // Unsigned shift right.
703 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
704 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
705 KnownZero >>= ShiftAmt;
706 KnownOne >>= ShiftAmt;
707 KnownZero |= HighBits; // high bits known zero.
711 case Instruction::AShr:
712 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
713 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
714 // Compute the new bits that are at the top now.
715 uint64_t ShiftAmt = SA->getZExtValue();
716 uint64_t HighBits = (1ULL << ShiftAmt)-1;
717 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
719 // Signed shift right.
721 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
722 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
723 KnownZero >>= ShiftAmt;
724 KnownOne >>= ShiftAmt;
726 // Handle the sign bits.
727 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
728 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
730 if (KnownZero & SignBit) { // New bits are known zero.
731 KnownZero |= HighBits;
732 } else if (KnownOne & SignBit) { // New bits are known one.
733 KnownOne |= HighBits;
741 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
742 /// this predicate to simplify operations downstream. Mask is known to be zero
743 /// for bits that V cannot have.
744 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
745 uint64_t KnownZero, KnownOne;
746 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
747 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
748 return (KnownZero & Mask) == Mask;
751 /// ShrinkDemandedConstant - Check to see if the specified operand of the
752 /// specified instruction is a constant integer. If so, check to see if there
753 /// are any bits set in the constant that are not demanded. If so, shrink the
754 /// constant and return true.
755 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
757 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
758 if (!OpC) return false;
760 // If there are no bits set that aren't demanded, nothing to do.
761 if ((~Demanded & OpC->getZExtValue()) == 0)
764 // This is producing any bits that are not needed, shrink the RHS.
765 uint64_t Val = Demanded & OpC->getZExtValue();
766 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
770 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
771 // set of known zero and one bits, compute the maximum and minimum values that
772 // could have the specified known zero and known one bits, returning them in
774 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
777 int64_t &Min, int64_t &Max) {
778 uint64_t TypeBits = Ty->getIntegralTypeMask();
779 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
781 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
783 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
784 // bit if it is unknown.
786 Max = KnownOne|UnknownBits;
788 if (SignBit & UnknownBits) { // Sign bit is unknown
793 // Sign extend the min/max values.
794 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
795 Min = (Min << ShAmt) >> ShAmt;
796 Max = (Max << ShAmt) >> ShAmt;
799 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
800 // a set of known zero and one bits, compute the maximum and minimum values that
801 // could have the specified known zero and known one bits, returning them in
803 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
808 uint64_t TypeBits = Ty->getIntegralTypeMask();
809 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
811 // The minimum value is when the unknown bits are all zeros.
813 // The maximum value is when the unknown bits are all ones.
814 Max = KnownOne|UnknownBits;
818 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
819 /// DemandedMask bits of the result of V are ever used downstream. If we can
820 /// use this information to simplify V, do so and return true. Otherwise,
821 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
822 /// the expression (used to simplify the caller). The KnownZero/One bits may
823 /// only be accurate for those bits in the DemandedMask.
824 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
825 uint64_t &KnownZero, uint64_t &KnownOne,
827 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
828 // We know all of the bits for a constant!
829 KnownOne = CI->getZExtValue() & DemandedMask;
830 KnownZero = ~KnownOne & DemandedMask;
834 KnownZero = KnownOne = 0;
835 if (!V->hasOneUse()) { // Other users may use these bits.
836 if (Depth != 0) { // Not at the root.
837 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
838 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
841 // If this is the root being simplified, allow it to have multiple uses,
842 // just set the DemandedMask to all bits.
843 DemandedMask = V->getType()->getIntegralTypeMask();
844 } else if (DemandedMask == 0) { // Not demanding any bits from V.
845 if (V != UndefValue::get(V->getType()))
846 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
848 } else if (Depth == 6) { // Limit search depth.
852 Instruction *I = dyn_cast<Instruction>(V);
853 if (!I) return false; // Only analyze instructions.
855 DemandedMask &= V->getType()->getIntegralTypeMask();
857 uint64_t KnownZero2 = 0, KnownOne2 = 0;
858 switch (I->getOpcode()) {
860 case Instruction::And:
861 // If either the LHS or the RHS are Zero, the result is zero.
862 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
863 KnownZero, KnownOne, Depth+1))
865 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
867 // If something is known zero on the RHS, the bits aren't demanded on the
869 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
870 KnownZero2, KnownOne2, Depth+1))
872 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
874 // If all of the demanded bits are known 1 on one side, return the other.
875 // These bits cannot contribute to the result of the 'and'.
876 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
877 return UpdateValueUsesWith(I, I->getOperand(0));
878 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
879 return UpdateValueUsesWith(I, I->getOperand(1));
881 // If all of the demanded bits in the inputs are known zeros, return zero.
882 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
883 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
885 // If the RHS is a constant, see if we can simplify it.
886 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
887 return UpdateValueUsesWith(I, I);
889 // Output known-1 bits are only known if set in both the LHS & RHS.
890 KnownOne &= KnownOne2;
891 // Output known-0 are known to be clear if zero in either the LHS | RHS.
892 KnownZero |= KnownZero2;
894 case Instruction::Or:
895 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
896 KnownZero, KnownOne, Depth+1))
898 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
899 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
900 KnownZero2, KnownOne2, Depth+1))
902 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
904 // If all of the demanded bits are known zero on one side, return the other.
905 // These bits cannot contribute to the result of the 'or'.
906 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
907 return UpdateValueUsesWith(I, I->getOperand(0));
908 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
909 return UpdateValueUsesWith(I, I->getOperand(1));
911 // If all of the potentially set bits on one side are known to be set on
912 // the other side, just use the 'other' side.
913 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
914 (DemandedMask & (~KnownZero)))
915 return UpdateValueUsesWith(I, I->getOperand(0));
916 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
917 (DemandedMask & (~KnownZero2)))
918 return UpdateValueUsesWith(I, I->getOperand(1));
920 // If the RHS is a constant, see if we can simplify it.
921 if (ShrinkDemandedConstant(I, 1, DemandedMask))
922 return UpdateValueUsesWith(I, I);
924 // Output known-0 bits are only known if clear in both the LHS & RHS.
925 KnownZero &= KnownZero2;
926 // Output known-1 are known to be set if set in either the LHS | RHS.
927 KnownOne |= KnownOne2;
929 case Instruction::Xor: {
930 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
931 KnownZero, KnownOne, Depth+1))
933 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
934 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
935 KnownZero2, KnownOne2, Depth+1))
937 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
939 // If all of the demanded bits are known zero on one side, return the other.
940 // These bits cannot contribute to the result of the 'xor'.
941 if ((DemandedMask & KnownZero) == DemandedMask)
942 return UpdateValueUsesWith(I, I->getOperand(0));
943 if ((DemandedMask & KnownZero2) == DemandedMask)
944 return UpdateValueUsesWith(I, I->getOperand(1));
946 // Output known-0 bits are known if clear or set in both the LHS & RHS.
947 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
948 // Output known-1 are known to be set if set in only one of the LHS, RHS.
949 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
951 // If all of the demanded bits are known to be zero on one side or the
952 // other, turn this into an *inclusive* or.
953 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
954 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
956 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
958 InsertNewInstBefore(Or, *I);
959 return UpdateValueUsesWith(I, Or);
962 // If all of the demanded bits on one side are known, and all of the set
963 // bits on that side are also known to be set on the other side, turn this
964 // into an AND, as we know the bits will be cleared.
965 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
966 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
967 if ((KnownOne & KnownOne2) == KnownOne) {
968 Constant *AndC = GetConstantInType(I->getType(),
969 ~KnownOne & DemandedMask);
971 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
972 InsertNewInstBefore(And, *I);
973 return UpdateValueUsesWith(I, And);
977 // If the RHS is a constant, see if we can simplify it.
978 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
979 if (ShrinkDemandedConstant(I, 1, DemandedMask))
980 return UpdateValueUsesWith(I, I);
982 KnownZero = KnownZeroOut;
983 KnownOne = KnownOneOut;
986 case Instruction::Select:
987 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
988 KnownZero, KnownOne, Depth+1))
990 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
991 KnownZero2, KnownOne2, Depth+1))
993 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
994 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
996 // If the operands are constants, see if we can simplify them.
997 if (ShrinkDemandedConstant(I, 1, DemandedMask))
998 return UpdateValueUsesWith(I, I);
999 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1000 return UpdateValueUsesWith(I, I);
1002 // Only known if known in both the LHS and RHS.
1003 KnownOne &= KnownOne2;
1004 KnownZero &= KnownZero2;
1006 case Instruction::Trunc:
1007 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008 KnownZero, KnownOne, Depth+1))
1010 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1012 case Instruction::BitCast:
1013 if (!I->getOperand(0)->getType()->isIntegral())
1016 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1017 KnownZero, KnownOne, Depth+1))
1019 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1021 case Instruction::ZExt: {
1022 // Compute the bits in the result that are not present in the input.
1023 const Type *SrcTy = I->getOperand(0)->getType();
1024 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1025 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1027 DemandedMask &= SrcTy->getIntegralTypeMask();
1028 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1029 KnownZero, KnownOne, Depth+1))
1031 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1032 // The top bits are known to be zero.
1033 KnownZero |= NewBits;
1036 case Instruction::SExt: {
1037 // Compute the bits in the result that are not present in the input.
1038 const Type *SrcTy = I->getOperand(0)->getType();
1039 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1040 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1042 // Get the sign bit for the source type
1043 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1044 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1046 // If any of the sign extended bits are demanded, we know that the sign
1048 if (NewBits & DemandedMask)
1049 InputDemandedBits |= InSignBit;
1051 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1052 KnownZero, KnownOne, Depth+1))
1054 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1056 // If the sign bit of the input is known set or clear, then we know the
1057 // top bits of the result.
1059 // If the input sign bit is known zero, or if the NewBits are not demanded
1060 // convert this into a zero extension.
1061 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1062 // Convert to ZExt cast
1063 CastInst *NewCast = CastInst::create(
1064 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1065 return UpdateValueUsesWith(I, NewCast);
1066 } else if (KnownOne & InSignBit) { // Input sign bit known set
1067 KnownOne |= NewBits;
1068 KnownZero &= ~NewBits;
1069 } else { // Input sign bit unknown
1070 KnownZero &= ~NewBits;
1071 KnownOne &= ~NewBits;
1075 case Instruction::Add:
1076 // If there is a constant on the RHS, there are a variety of xformations
1078 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1079 // If null, this should be simplified elsewhere. Some of the xforms here
1080 // won't work if the RHS is zero.
1081 if (RHS->isNullValue())
1084 // Figure out what the input bits are. If the top bits of the and result
1085 // are not demanded, then the add doesn't demand them from its input
1088 // Shift the demanded mask up so that it's at the top of the uint64_t.
1089 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1090 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1092 // If the top bit of the output is demanded, demand everything from the
1093 // input. Otherwise, we demand all the input bits except NLZ top bits.
1094 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1096 // Find information about known zero/one bits in the input.
1097 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1098 KnownZero2, KnownOne2, Depth+1))
1101 // If the RHS of the add has bits set that can't affect the input, reduce
1103 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1104 return UpdateValueUsesWith(I, I);
1106 // Avoid excess work.
1107 if (KnownZero2 == 0 && KnownOne2 == 0)
1110 // Turn it into OR if input bits are zero.
1111 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1113 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1115 InsertNewInstBefore(Or, *I);
1116 return UpdateValueUsesWith(I, Or);
1119 // We can say something about the output known-zero and known-one bits,
1120 // depending on potential carries from the input constant and the
1121 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1122 // bits set and the RHS constant is 0x01001, then we know we have a known
1123 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1125 // To compute this, we first compute the potential carry bits. These are
1126 // the bits which may be modified. I'm not aware of a better way to do
1128 uint64_t RHSVal = RHS->getZExtValue();
1130 bool CarryIn = false;
1131 uint64_t CarryBits = 0;
1132 uint64_t CurBit = 1;
1133 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1134 // Record the current carry in.
1135 if (CarryIn) CarryBits |= CurBit;
1139 // This bit has a carry out unless it is "zero + zero" or
1140 // "zero + anything" with no carry in.
1141 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1142 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1143 } else if (!CarryIn &&
1144 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1145 CarryOut = false; // 0 + anything has no carry out if no carry in.
1147 // Otherwise, we have to assume we have a carry out.
1151 // This stage's carry out becomes the next stage's carry-in.
1155 // Now that we know which bits have carries, compute the known-1/0 sets.
1157 // Bits are known one if they are known zero in one operand and one in the
1158 // other, and there is no input carry.
1159 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1161 // Bits are known zero if they are known zero in both operands and there
1162 // is no input carry.
1163 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1166 case Instruction::Shl:
1167 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1168 uint64_t ShiftAmt = SA->getZExtValue();
1169 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
1170 KnownZero, KnownOne, Depth+1))
1172 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1173 KnownZero <<= ShiftAmt;
1174 KnownOne <<= ShiftAmt;
1175 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
1178 case Instruction::LShr:
1179 // For a logical shift right
1180 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1181 unsigned ShiftAmt = SA->getZExtValue();
1183 // Compute the new bits that are at the top now.
1184 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1185 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1186 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1187 // Unsigned shift right.
1188 if (SimplifyDemandedBits(I->getOperand(0),
1189 (DemandedMask << ShiftAmt) & TypeMask,
1190 KnownZero, KnownOne, Depth+1))
1192 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1193 KnownZero &= TypeMask;
1194 KnownOne &= TypeMask;
1195 KnownZero >>= ShiftAmt;
1196 KnownOne >>= ShiftAmt;
1197 KnownZero |= HighBits; // high bits known zero.
1200 case Instruction::AShr:
1201 // If this is an arithmetic shift right and only the low-bit is set, we can
1202 // always convert this into a logical shr, even if the shift amount is
1203 // variable. The low bit of the shift cannot be an input sign bit unless
1204 // the shift amount is >= the size of the datatype, which is undefined.
1205 if (DemandedMask == 1) {
1206 // Perform the logical shift right.
1207 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1208 I->getOperand(1), I->getName());
1209 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1210 return UpdateValueUsesWith(I, NewVal);
1213 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1214 unsigned ShiftAmt = SA->getZExtValue();
1216 // Compute the new bits that are at the top now.
1217 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1218 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1219 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1220 // Signed shift right.
1221 if (SimplifyDemandedBits(I->getOperand(0),
1222 (DemandedMask << ShiftAmt) & TypeMask,
1223 KnownZero, KnownOne, Depth+1))
1225 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1226 KnownZero &= TypeMask;
1227 KnownOne &= TypeMask;
1228 KnownZero >>= ShiftAmt;
1229 KnownOne >>= ShiftAmt;
1231 // Handle the sign bits.
1232 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1233 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
1235 // If the input sign bit is known to be zero, or if none of the top bits
1236 // are demanded, turn this into an unsigned shift right.
1237 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1238 // Perform the logical shift right.
1239 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1241 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1242 return UpdateValueUsesWith(I, NewVal);
1243 } else if (KnownOne & SignBit) { // New bits are known one.
1244 KnownOne |= HighBits;
1250 // If the client is only demanding bits that we know, return the known
1252 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1253 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1258 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1259 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1260 /// actually used by the caller. This method analyzes which elements of the
1261 /// operand are undef and returns that information in UndefElts.
1263 /// If the information about demanded elements can be used to simplify the
1264 /// operation, the operation is simplified, then the resultant value is
1265 /// returned. This returns null if no change was made.
1266 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1267 uint64_t &UndefElts,
1269 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1270 assert(VWidth <= 64 && "Vector too wide to analyze!");
1271 uint64_t EltMask = ~0ULL >> (64-VWidth);
1272 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1273 "Invalid DemandedElts!");
1275 if (isa<UndefValue>(V)) {
1276 // If the entire vector is undefined, just return this info.
1277 UndefElts = EltMask;
1279 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1280 UndefElts = EltMask;
1281 return UndefValue::get(V->getType());
1285 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1286 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1287 Constant *Undef = UndefValue::get(EltTy);
1289 std::vector<Constant*> Elts;
1290 for (unsigned i = 0; i != VWidth; ++i)
1291 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1292 Elts.push_back(Undef);
1293 UndefElts |= (1ULL << i);
1294 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1295 Elts.push_back(Undef);
1296 UndefElts |= (1ULL << i);
1297 } else { // Otherwise, defined.
1298 Elts.push_back(CP->getOperand(i));
1301 // If we changed the constant, return it.
1302 Constant *NewCP = ConstantPacked::get(Elts);
1303 return NewCP != CP ? NewCP : 0;
1304 } else if (isa<ConstantAggregateZero>(V)) {
1305 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1307 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1308 Constant *Zero = Constant::getNullValue(EltTy);
1309 Constant *Undef = UndefValue::get(EltTy);
1310 std::vector<Constant*> Elts;
1311 for (unsigned i = 0; i != VWidth; ++i)
1312 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1313 UndefElts = DemandedElts ^ EltMask;
1314 return ConstantPacked::get(Elts);
1317 if (!V->hasOneUse()) { // Other users may use these bits.
1318 if (Depth != 0) { // Not at the root.
1319 // TODO: Just compute the UndefElts information recursively.
1323 } else if (Depth == 10) { // Limit search depth.
1327 Instruction *I = dyn_cast<Instruction>(V);
1328 if (!I) return false; // Only analyze instructions.
1330 bool MadeChange = false;
1331 uint64_t UndefElts2;
1333 switch (I->getOpcode()) {
1336 case Instruction::InsertElement: {
1337 // If this is a variable index, we don't know which element it overwrites.
1338 // demand exactly the same input as we produce.
1339 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1341 // Note that we can't propagate undef elt info, because we don't know
1342 // which elt is getting updated.
1343 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1344 UndefElts2, Depth+1);
1345 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1349 // If this is inserting an element that isn't demanded, remove this
1351 unsigned IdxNo = Idx->getZExtValue();
1352 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1353 return AddSoonDeadInstToWorklist(*I, 0);
1355 // Otherwise, the element inserted overwrites whatever was there, so the
1356 // input demanded set is simpler than the output set.
1357 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1358 DemandedElts & ~(1ULL << IdxNo),
1359 UndefElts, Depth+1);
1360 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1362 // The inserted element is defined.
1363 UndefElts |= 1ULL << IdxNo;
1367 case Instruction::And:
1368 case Instruction::Or:
1369 case Instruction::Xor:
1370 case Instruction::Add:
1371 case Instruction::Sub:
1372 case Instruction::Mul:
1373 // div/rem demand all inputs, because they don't want divide by zero.
1374 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1375 UndefElts, Depth+1);
1376 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1377 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1378 UndefElts2, Depth+1);
1379 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1381 // Output elements are undefined if both are undefined. Consider things
1382 // like undef&0. The result is known zero, not undef.
1383 UndefElts &= UndefElts2;
1386 case Instruction::Call: {
1387 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1389 switch (II->getIntrinsicID()) {
1392 // Binary vector operations that work column-wise. A dest element is a
1393 // function of the corresponding input elements from the two inputs.
1394 case Intrinsic::x86_sse_sub_ss:
1395 case Intrinsic::x86_sse_mul_ss:
1396 case Intrinsic::x86_sse_min_ss:
1397 case Intrinsic::x86_sse_max_ss:
1398 case Intrinsic::x86_sse2_sub_sd:
1399 case Intrinsic::x86_sse2_mul_sd:
1400 case Intrinsic::x86_sse2_min_sd:
1401 case Intrinsic::x86_sse2_max_sd:
1402 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1403 UndefElts, Depth+1);
1404 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1405 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1406 UndefElts2, Depth+1);
1407 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1409 // If only the low elt is demanded and this is a scalarizable intrinsic,
1410 // scalarize it now.
1411 if (DemandedElts == 1) {
1412 switch (II->getIntrinsicID()) {
1414 case Intrinsic::x86_sse_sub_ss:
1415 case Intrinsic::x86_sse_mul_ss:
1416 case Intrinsic::x86_sse2_sub_sd:
1417 case Intrinsic::x86_sse2_mul_sd:
1418 // TODO: Lower MIN/MAX/ABS/etc
1419 Value *LHS = II->getOperand(1);
1420 Value *RHS = II->getOperand(2);
1421 // Extract the element as scalars.
1422 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1423 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1425 switch (II->getIntrinsicID()) {
1426 default: assert(0 && "Case stmts out of sync!");
1427 case Intrinsic::x86_sse_sub_ss:
1428 case Intrinsic::x86_sse2_sub_sd:
1429 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1430 II->getName()), *II);
1432 case Intrinsic::x86_sse_mul_ss:
1433 case Intrinsic::x86_sse2_mul_sd:
1434 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1435 II->getName()), *II);
1440 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1442 InsertNewInstBefore(New, *II);
1443 AddSoonDeadInstToWorklist(*II, 0);
1448 // Output elements are undefined if both are undefined. Consider things
1449 // like undef&0. The result is known zero, not undef.
1450 UndefElts &= UndefElts2;
1456 return MadeChange ? I : 0;
1459 /// @returns true if the specified compare instruction is
1460 /// true when both operands are equal...
1461 /// @brief Determine if the ICmpInst returns true if both operands are equal
1462 static bool isTrueWhenEqual(ICmpInst &ICI) {
1463 ICmpInst::Predicate pred = ICI.getPredicate();
1464 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1465 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1466 pred == ICmpInst::ICMP_SLE;
1469 /// @returns true if the specified compare instruction is
1470 /// true when both operands are equal...
1471 /// @brief Determine if the FCmpInst returns true if both operands are equal
1472 static bool isTrueWhenEqual(FCmpInst &FCI) {
1473 FCmpInst::Predicate pred = FCI.getPredicate();
1474 return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1475 pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1476 pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
1479 /// AssociativeOpt - Perform an optimization on an associative operator. This
1480 /// function is designed to check a chain of associative operators for a
1481 /// potential to apply a certain optimization. Since the optimization may be
1482 /// applicable if the expression was reassociated, this checks the chain, then
1483 /// reassociates the expression as necessary to expose the optimization
1484 /// opportunity. This makes use of a special Functor, which must define
1485 /// 'shouldApply' and 'apply' methods.
1487 template<typename Functor>
1488 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1489 unsigned Opcode = Root.getOpcode();
1490 Value *LHS = Root.getOperand(0);
1492 // Quick check, see if the immediate LHS matches...
1493 if (F.shouldApply(LHS))
1494 return F.apply(Root);
1496 // Otherwise, if the LHS is not of the same opcode as the root, return.
1497 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1498 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1499 // Should we apply this transform to the RHS?
1500 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1502 // If not to the RHS, check to see if we should apply to the LHS...
1503 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1504 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1508 // If the functor wants to apply the optimization to the RHS of LHSI,
1509 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1511 BasicBlock *BB = Root.getParent();
1513 // Now all of the instructions are in the current basic block, go ahead
1514 // and perform the reassociation.
1515 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1517 // First move the selected RHS to the LHS of the root...
1518 Root.setOperand(0, LHSI->getOperand(1));
1520 // Make what used to be the LHS of the root be the user of the root...
1521 Value *ExtraOperand = TmpLHSI->getOperand(1);
1522 if (&Root == TmpLHSI) {
1523 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1526 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1527 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1528 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1529 BasicBlock::iterator ARI = &Root; ++ARI;
1530 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1533 // Now propagate the ExtraOperand down the chain of instructions until we
1535 while (TmpLHSI != LHSI) {
1536 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1537 // Move the instruction to immediately before the chain we are
1538 // constructing to avoid breaking dominance properties.
1539 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1540 BB->getInstList().insert(ARI, NextLHSI);
1543 Value *NextOp = NextLHSI->getOperand(1);
1544 NextLHSI->setOperand(1, ExtraOperand);
1546 ExtraOperand = NextOp;
1549 // Now that the instructions are reassociated, have the functor perform
1550 // the transformation...
1551 return F.apply(Root);
1554 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1560 // AddRHS - Implements: X + X --> X << 1
1563 AddRHS(Value *rhs) : RHS(rhs) {}
1564 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1565 Instruction *apply(BinaryOperator &Add) const {
1566 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1567 ConstantInt::get(Type::Int8Ty, 1));
1571 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1573 struct AddMaskingAnd {
1575 AddMaskingAnd(Constant *c) : C2(c) {}
1576 bool shouldApply(Value *LHS) const {
1578 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1579 ConstantExpr::getAnd(C1, C2)->isNullValue();
1581 Instruction *apply(BinaryOperator &Add) const {
1582 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1586 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1588 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1589 if (Constant *SOC = dyn_cast<Constant>(SO))
1590 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1592 return IC->InsertNewInstBefore(CastInst::create(
1593 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1596 // Figure out if the constant is the left or the right argument.
1597 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1598 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1600 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1602 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1603 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1606 Value *Op0 = SO, *Op1 = ConstOperand;
1608 std::swap(Op0, Op1);
1610 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1611 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1612 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1613 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1614 SO->getName()+".cmp");
1615 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1616 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1618 assert(0 && "Unknown binary instruction type!");
1621 return IC->InsertNewInstBefore(New, I);
1624 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1625 // constant as the other operand, try to fold the binary operator into the
1626 // select arguments. This also works for Cast instructions, which obviously do
1627 // not have a second operand.
1628 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1630 // Don't modify shared select instructions
1631 if (!SI->hasOneUse()) return 0;
1632 Value *TV = SI->getOperand(1);
1633 Value *FV = SI->getOperand(2);
1635 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1636 // Bool selects with constant operands can be folded to logical ops.
1637 if (SI->getType() == Type::BoolTy) return 0;
1639 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1640 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1642 return new SelectInst(SI->getCondition(), SelectTrueVal,
1649 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1650 /// node as operand #0, see if we can fold the instruction into the PHI (which
1651 /// is only possible if all operands to the PHI are constants).
1652 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1653 PHINode *PN = cast<PHINode>(I.getOperand(0));
1654 unsigned NumPHIValues = PN->getNumIncomingValues();
1655 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1657 // Check to see if all of the operands of the PHI are constants. If there is
1658 // one non-constant value, remember the BB it is. If there is more than one
1660 BasicBlock *NonConstBB = 0;
1661 for (unsigned i = 0; i != NumPHIValues; ++i)
1662 if (!isa<Constant>(PN->getIncomingValue(i))) {
1663 if (NonConstBB) return 0; // More than one non-const value.
1664 NonConstBB = PN->getIncomingBlock(i);
1666 // If the incoming non-constant value is in I's block, we have an infinite
1668 if (NonConstBB == I.getParent())
1672 // If there is exactly one non-constant value, we can insert a copy of the
1673 // operation in that block. However, if this is a critical edge, we would be
1674 // inserting the computation one some other paths (e.g. inside a loop). Only
1675 // do this if the pred block is unconditionally branching into the phi block.
1677 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1678 if (!BI || !BI->isUnconditional()) return 0;
1681 // Okay, we can do the transformation: create the new PHI node.
1682 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1684 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1685 InsertNewInstBefore(NewPN, *PN);
1687 // Next, add all of the operands to the PHI.
1688 if (I.getNumOperands() == 2) {
1689 Constant *C = cast<Constant>(I.getOperand(1));
1690 for (unsigned i = 0; i != NumPHIValues; ++i) {
1692 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1693 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1694 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1696 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1698 assert(PN->getIncomingBlock(i) == NonConstBB);
1699 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1700 InV = BinaryOperator::create(BO->getOpcode(),
1701 PN->getIncomingValue(i), C, "phitmp",
1702 NonConstBB->getTerminator());
1703 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1704 InV = CmpInst::create(CI->getOpcode(),
1706 PN->getIncomingValue(i), C, "phitmp",
1707 NonConstBB->getTerminator());
1708 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1709 InV = new ShiftInst(SI->getOpcode(),
1710 PN->getIncomingValue(i), C, "phitmp",
1711 NonConstBB->getTerminator());
1713 assert(0 && "Unknown binop!");
1715 WorkList.push_back(cast<Instruction>(InV));
1717 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1720 CastInst *CI = cast<CastInst>(&I);
1721 const Type *RetTy = CI->getType();
1722 for (unsigned i = 0; i != NumPHIValues; ++i) {
1724 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1725 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1727 assert(PN->getIncomingBlock(i) == NonConstBB);
1728 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1729 I.getType(), "phitmp",
1730 NonConstBB->getTerminator());
1731 WorkList.push_back(cast<Instruction>(InV));
1733 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1736 return ReplaceInstUsesWith(I, NewPN);
1739 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1740 bool Changed = SimplifyCommutative(I);
1741 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1743 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1744 // X + undef -> undef
1745 if (isa<UndefValue>(RHS))
1746 return ReplaceInstUsesWith(I, RHS);
1749 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1750 if (RHSC->isNullValue())
1751 return ReplaceInstUsesWith(I, LHS);
1752 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1753 if (CFP->isExactlyValue(-0.0))
1754 return ReplaceInstUsesWith(I, LHS);
1757 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1758 // X + (signbit) --> X ^ signbit
1759 uint64_t Val = CI->getZExtValue();
1760 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1761 return BinaryOperator::createXor(LHS, RHS);
1763 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1764 // (X & 254)+1 -> (X&254)|1
1765 uint64_t KnownZero, KnownOne;
1766 if (!isa<PackedType>(I.getType()) &&
1767 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1768 KnownZero, KnownOne))
1772 if (isa<PHINode>(LHS))
1773 if (Instruction *NV = FoldOpIntoPhi(I))
1776 ConstantInt *XorRHS = 0;
1778 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1779 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1780 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1781 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1783 uint64_t C0080Val = 1ULL << 31;
1784 int64_t CFF80Val = -C0080Val;
1787 if (TySizeBits > Size) {
1789 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1790 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1791 if (RHSSExt == CFF80Val) {
1792 if (XorRHS->getZExtValue() == C0080Val)
1794 } else if (RHSZExt == C0080Val) {
1795 if (XorRHS->getSExtValue() == CFF80Val)
1799 // This is a sign extend if the top bits are known zero.
1800 uint64_t Mask = ~0ULL;
1801 Mask <<= 64-(TySizeBits-Size);
1802 Mask &= XorLHS->getType()->getIntegralTypeMask();
1803 if (!MaskedValueIsZero(XorLHS, Mask))
1804 Size = 0; // Not a sign ext, but can't be any others either.
1811 } while (Size >= 8);
1814 const Type *MiddleType = 0;
1817 case 32: MiddleType = Type::Int32Ty; break;
1818 case 16: MiddleType = Type::Int16Ty; break;
1819 case 8: MiddleType = Type::Int8Ty; break;
1822 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1823 InsertNewInstBefore(NewTrunc, I);
1824 return new SExtInst(NewTrunc, I.getType());
1830 if (I.getType()->isInteger()) {
1831 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1833 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1834 if (RHSI->getOpcode() == Instruction::Sub)
1835 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1836 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1838 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1839 if (LHSI->getOpcode() == Instruction::Sub)
1840 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1841 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1846 if (Value *V = dyn_castNegVal(LHS))
1847 return BinaryOperator::createSub(RHS, V);
1850 if (!isa<Constant>(RHS))
1851 if (Value *V = dyn_castNegVal(RHS))
1852 return BinaryOperator::createSub(LHS, V);
1856 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1857 if (X == RHS) // X*C + X --> X * (C+1)
1858 return BinaryOperator::createMul(RHS, AddOne(C2));
1860 // X*C1 + X*C2 --> X * (C1+C2)
1862 if (X == dyn_castFoldableMul(RHS, C1))
1863 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1866 // X + X*C --> X * (C+1)
1867 if (dyn_castFoldableMul(RHS, C2) == LHS)
1868 return BinaryOperator::createMul(LHS, AddOne(C2));
1870 // X + ~X --> -1 since ~X = -X-1
1871 if (dyn_castNotVal(LHS) == RHS ||
1872 dyn_castNotVal(RHS) == LHS)
1873 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1876 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1877 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1878 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1881 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1883 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1884 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1885 return BinaryOperator::createSub(C, X);
1888 // (X & FF00) + xx00 -> (X+xx00) & FF00
1889 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1890 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1891 if (Anded == CRHS) {
1892 // See if all bits from the first bit set in the Add RHS up are included
1893 // in the mask. First, get the rightmost bit.
1894 uint64_t AddRHSV = CRHS->getZExtValue();
1896 // Form a mask of all bits from the lowest bit added through the top.
1897 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1898 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1900 // See if the and mask includes all of these bits.
1901 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1903 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1904 // Okay, the xform is safe. Insert the new add pronto.
1905 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1906 LHS->getName()), I);
1907 return BinaryOperator::createAnd(NewAdd, C2);
1912 // Try to fold constant add into select arguments.
1913 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1914 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1918 // add (cast *A to intptrtype) B ->
1919 // cast (GEP (cast *A to sbyte*) B) ->
1922 CastInst *CI = dyn_cast<CastInst>(LHS);
1925 CI = dyn_cast<CastInst>(RHS);
1928 if (CI && CI->getType()->isSized() &&
1929 (CI->getType()->getPrimitiveSize() ==
1930 TD->getIntPtrType()->getPrimitiveSize())
1931 && isa<PointerType>(CI->getOperand(0)->getType())) {
1932 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1933 PointerType::get(Type::Int8Ty), I);
1934 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1935 return new PtrToIntInst(I2, CI->getType());
1939 return Changed ? &I : 0;
1942 // isSignBit - Return true if the value represented by the constant only has the
1943 // highest order bit set.
1944 static bool isSignBit(ConstantInt *CI) {
1945 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1946 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1949 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1951 static Value *RemoveNoopCast(Value *V) {
1952 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1953 const Type *CTy = CI->getType();
1954 const Type *OpTy = CI->getOperand(0)->getType();
1955 if (CTy->isInteger() && OpTy->isInteger()) {
1956 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1957 return RemoveNoopCast(CI->getOperand(0));
1958 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1959 return RemoveNoopCast(CI->getOperand(0));
1964 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1965 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1967 if (Op0 == Op1) // sub X, X -> 0
1968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1970 // If this is a 'B = x-(-A)', change to B = x+A...
1971 if (Value *V = dyn_castNegVal(Op1))
1972 return BinaryOperator::createAdd(Op0, V);
1974 if (isa<UndefValue>(Op0))
1975 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1976 if (isa<UndefValue>(Op1))
1977 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1979 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1980 // Replace (-1 - A) with (~A)...
1981 if (C->isAllOnesValue())
1982 return BinaryOperator::createNot(Op1);
1984 // C - ~X == X + (1+C)
1986 if (match(Op1, m_Not(m_Value(X))))
1987 return BinaryOperator::createAdd(X,
1988 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1989 // -((uint)X >> 31) -> ((int)X >> 31)
1990 // -((int)X >> 31) -> ((uint)X >> 31)
1991 if (C->isNullValue()) {
1992 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1993 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1994 if (SI->getOpcode() == Instruction::LShr) {
1995 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1996 // Check to see if we are shifting out everything but the sign bit.
1997 if (CU->getZExtValue() ==
1998 SI->getType()->getPrimitiveSizeInBits()-1) {
1999 // Ok, the transformation is safe. Insert AShr.
2000 // FIXME: Once integer types are signless, this cast should be
2002 Value *ShiftOp = SI->getOperand(0);
2003 return new ShiftInst(Instruction::AShr, ShiftOp, CU,
2008 else if (SI->getOpcode() == Instruction::AShr) {
2009 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2010 // Check to see if we are shifting out everything but the sign bit.
2011 if (CU->getZExtValue() ==
2012 SI->getType()->getPrimitiveSizeInBits()-1) {
2014 // Ok, the transformation is safe. Insert LShr.
2015 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
2022 // Try to fold constant sub into select arguments.
2023 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2024 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2027 if (isa<PHINode>(Op0))
2028 if (Instruction *NV = FoldOpIntoPhi(I))
2032 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2033 if (Op1I->getOpcode() == Instruction::Add &&
2034 !Op0->getType()->isFPOrFPVector()) {
2035 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2036 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2037 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2038 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2039 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2040 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2041 // C1-(X+C2) --> (C1-C2)-X
2042 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2043 Op1I->getOperand(0));
2047 if (Op1I->hasOneUse()) {
2048 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2049 // is not used by anyone else...
2051 if (Op1I->getOpcode() == Instruction::Sub &&
2052 !Op1I->getType()->isFPOrFPVector()) {
2053 // Swap the two operands of the subexpr...
2054 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2055 Op1I->setOperand(0, IIOp1);
2056 Op1I->setOperand(1, IIOp0);
2058 // Create the new top level add instruction...
2059 return BinaryOperator::createAdd(Op0, Op1);
2062 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2064 if (Op1I->getOpcode() == Instruction::And &&
2065 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2066 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2069 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2070 return BinaryOperator::createAnd(Op0, NewNot);
2073 // 0 - (X sdiv C) -> (X sdiv -C)
2074 if (Op1I->getOpcode() == Instruction::SDiv)
2075 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2076 if (CSI->isNullValue())
2077 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2078 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2079 ConstantExpr::getNeg(DivRHS));
2081 // X - X*C --> X * (1-C)
2082 ConstantInt *C2 = 0;
2083 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2085 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2086 return BinaryOperator::createMul(Op0, CP1);
2091 if (!Op0->getType()->isFPOrFPVector())
2092 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2093 if (Op0I->getOpcode() == Instruction::Add) {
2094 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2095 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2096 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2097 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2098 } else if (Op0I->getOpcode() == Instruction::Sub) {
2099 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2100 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2104 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2105 if (X == Op1) { // X*C - X --> X * (C-1)
2106 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2107 return BinaryOperator::createMul(Op1, CP1);
2110 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2111 if (X == dyn_castFoldableMul(Op1, C2))
2112 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2117 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2118 /// really just returns true if the most significant (sign) bit is set.
2119 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2121 case ICmpInst::ICMP_SLT:
2122 // True if LHS s< RHS and RHS == 0
2123 return RHS->isNullValue();
2124 case ICmpInst::ICMP_SLE:
2125 // True if LHS s<= RHS and RHS == -1
2126 return RHS->isAllOnesValue();
2127 case ICmpInst::ICMP_UGE:
2128 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2129 return RHS->getZExtValue() == (1ULL <<
2130 (RHS->getType()->getPrimitiveSizeInBits()-1));
2131 case ICmpInst::ICMP_UGT:
2132 // True if LHS u> RHS and RHS == high-bit-mask - 1
2133 return RHS->getZExtValue() ==
2134 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2140 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2141 bool Changed = SimplifyCommutative(I);
2142 Value *Op0 = I.getOperand(0);
2144 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2145 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2147 // Simplify mul instructions with a constant RHS...
2148 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2151 // ((X << C1)*C2) == (X * (C2 << C1))
2152 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2153 if (SI->getOpcode() == Instruction::Shl)
2154 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2155 return BinaryOperator::createMul(SI->getOperand(0),
2156 ConstantExpr::getShl(CI, ShOp));
2158 if (CI->isNullValue())
2159 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2160 if (CI->equalsInt(1)) // X * 1 == X
2161 return ReplaceInstUsesWith(I, Op0);
2162 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2163 return BinaryOperator::createNeg(Op0, I.getName());
2165 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2166 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2167 uint64_t C = Log2_64(Val);
2168 return new ShiftInst(Instruction::Shl, Op0,
2169 ConstantInt::get(Type::Int8Ty, C));
2171 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2172 if (Op1F->isNullValue())
2173 return ReplaceInstUsesWith(I, Op1);
2175 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2176 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2177 if (Op1F->getValue() == 1.0)
2178 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2181 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2182 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2183 isa<ConstantInt>(Op0I->getOperand(1))) {
2184 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2185 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2187 InsertNewInstBefore(Add, I);
2188 Value *C1C2 = ConstantExpr::getMul(Op1,
2189 cast<Constant>(Op0I->getOperand(1)));
2190 return BinaryOperator::createAdd(Add, C1C2);
2194 // Try to fold constant mul into select arguments.
2195 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2196 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2199 if (isa<PHINode>(Op0))
2200 if (Instruction *NV = FoldOpIntoPhi(I))
2204 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2205 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2206 return BinaryOperator::createMul(Op0v, Op1v);
2208 // If one of the operands of the multiply is a cast from a boolean value, then
2209 // we know the bool is either zero or one, so this is a 'masking' multiply.
2210 // See if we can simplify things based on how the boolean was originally
2212 CastInst *BoolCast = 0;
2213 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2214 if (CI->getOperand(0)->getType() == Type::BoolTy)
2217 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2218 if (CI->getOperand(0)->getType() == Type::BoolTy)
2221 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2222 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2223 const Type *SCOpTy = SCIOp0->getType();
2225 // If the icmp is true iff the sign bit of X is set, then convert this
2226 // multiply into a shift/and combination.
2227 if (isa<ConstantInt>(SCIOp1) &&
2228 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2229 // Shift the X value right to turn it into "all signbits".
2230 Constant *Amt = ConstantInt::get(Type::Int8Ty,
2231 SCOpTy->getPrimitiveSizeInBits()-1);
2233 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2234 BoolCast->getOperand(0)->getName()+
2237 // If the multiply type is not the same as the source type, sign extend
2238 // or truncate to the multiply type.
2239 if (I.getType() != V->getType()) {
2240 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2241 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2242 Instruction::CastOps opcode =
2243 (SrcBits == DstBits ? Instruction::BitCast :
2244 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2245 V = InsertCastBefore(opcode, V, I.getType(), I);
2248 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2249 return BinaryOperator::createAnd(V, OtherOp);
2254 return Changed ? &I : 0;
2257 /// This function implements the transforms on div instructions that work
2258 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2259 /// used by the visitors to those instructions.
2260 /// @brief Transforms common to all three div instructions
2261 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2265 if (isa<UndefValue>(Op0))
2266 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2268 // X / undef -> undef
2269 if (isa<UndefValue>(Op1))
2270 return ReplaceInstUsesWith(I, Op1);
2272 // Handle cases involving: div X, (select Cond, Y, Z)
2273 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2274 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2275 // same basic block, then we replace the select with Y, and the condition
2276 // of the select with false (if the cond value is in the same BB). If the
2277 // select has uses other than the div, this allows them to be simplified
2278 // also. Note that div X, Y is just as good as div X, 0 (undef)
2279 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2280 if (ST->isNullValue()) {
2281 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2282 if (CondI && CondI->getParent() == I.getParent())
2283 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2284 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2285 I.setOperand(1, SI->getOperand(2));
2287 UpdateValueUsesWith(SI, SI->getOperand(2));
2291 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2292 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2293 if (ST->isNullValue()) {
2294 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2295 if (CondI && CondI->getParent() == I.getParent())
2296 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2297 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2298 I.setOperand(1, SI->getOperand(1));
2300 UpdateValueUsesWith(SI, SI->getOperand(1));
2308 /// This function implements the transforms common to both integer division
2309 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2310 /// division instructions.
2311 /// @brief Common integer divide transforms
2312 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2313 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2315 if (Instruction *Common = commonDivTransforms(I))
2318 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2320 if (RHS->equalsInt(1))
2321 return ReplaceInstUsesWith(I, Op0);
2323 // (X / C1) / C2 -> X / (C1*C2)
2324 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2325 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2326 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2327 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2328 ConstantExpr::getMul(RHS, LHSRHS));
2331 if (!RHS->isNullValue()) { // avoid X udiv 0
2332 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2333 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2335 if (isa<PHINode>(Op0))
2336 if (Instruction *NV = FoldOpIntoPhi(I))
2341 // 0 / X == 0, we don't need to preserve faults!
2342 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2343 if (LHS->equalsInt(0))
2344 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2349 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2350 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2352 // Handle the integer div common cases
2353 if (Instruction *Common = commonIDivTransforms(I))
2356 // X udiv C^2 -> X >> C
2357 // Check to see if this is an unsigned division with an exact power of 2,
2358 // if so, convert to a right shift.
2359 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2360 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2361 if (isPowerOf2_64(Val)) {
2362 uint64_t ShiftAmt = Log2_64(Val);
2363 return new ShiftInst(Instruction::LShr, Op0,
2364 ConstantInt::get(Type::Int8Ty, ShiftAmt));
2368 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2369 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2370 if (RHSI->getOpcode() == Instruction::Shl &&
2371 isa<ConstantInt>(RHSI->getOperand(0))) {
2372 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2373 if (isPowerOf2_64(C1)) {
2374 Value *N = RHSI->getOperand(1);
2375 const Type *NTy = N->getType();
2376 if (uint64_t C2 = Log2_64(C1)) {
2377 Constant *C2V = ConstantInt::get(NTy, C2);
2378 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2380 return new ShiftInst(Instruction::LShr, Op0, N);
2385 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2386 // where C1&C2 are powers of two.
2387 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2388 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2389 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2390 if (!STO->isNullValue() && !STO->isNullValue()) {
2391 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2392 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2393 // Compute the shift amounts
2394 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2395 // Construct the "on true" case of the select
2396 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
2398 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2399 TSI = InsertNewInstBefore(TSI, I);
2401 // Construct the "on false" case of the select
2402 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
2404 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2405 FSI = InsertNewInstBefore(FSI, I);
2407 // construct the select instruction and return it.
2408 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2415 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2416 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2418 // Handle the integer div common cases
2419 if (Instruction *Common = commonIDivTransforms(I))
2422 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2424 if (RHS->isAllOnesValue())
2425 return BinaryOperator::createNeg(Op0);
2428 if (Value *LHSNeg = dyn_castNegVal(Op0))
2429 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2432 // If the sign bits of both operands are zero (i.e. we can prove they are
2433 // unsigned inputs), turn this into a udiv.
2434 if (I.getType()->isInteger()) {
2435 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2436 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2437 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2444 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2445 return commonDivTransforms(I);
2448 /// GetFactor - If we can prove that the specified value is at least a multiple
2449 /// of some factor, return that factor.
2450 static Constant *GetFactor(Value *V) {
2451 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2454 // Unless we can be tricky, we know this is a multiple of 1.
2455 Constant *Result = ConstantInt::get(V->getType(), 1);
2457 Instruction *I = dyn_cast<Instruction>(V);
2458 if (!I) return Result;
2460 if (I->getOpcode() == Instruction::Mul) {
2461 // Handle multiplies by a constant, etc.
2462 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2463 GetFactor(I->getOperand(1)));
2464 } else if (I->getOpcode() == Instruction::Shl) {
2465 // (X<<C) -> X * (1 << C)
2466 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2467 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2468 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2470 } else if (I->getOpcode() == Instruction::And) {
2471 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2472 // X & 0xFFF0 is known to be a multiple of 16.
2473 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2474 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2475 return ConstantExpr::getShl(Result,
2476 ConstantInt::get(Type::Int8Ty, Zeros));
2478 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2479 // Only handle int->int casts.
2480 if (!CI->isIntegerCast())
2482 Value *Op = CI->getOperand(0);
2483 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2488 /// This function implements the transforms on rem instructions that work
2489 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2490 /// is used by the visitors to those instructions.
2491 /// @brief Transforms common to all three rem instructions
2492 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2493 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2495 // 0 % X == 0, we don't need to preserve faults!
2496 if (Constant *LHS = dyn_cast<Constant>(Op0))
2497 if (LHS->isNullValue())
2498 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2500 if (isa<UndefValue>(Op0)) // undef % X -> 0
2501 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2502 if (isa<UndefValue>(Op1))
2503 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2505 // Handle cases involving: rem X, (select Cond, Y, Z)
2506 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2507 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2508 // the same basic block, then we replace the select with Y, and the
2509 // condition of the select with false (if the cond value is in the same
2510 // BB). If the select has uses other than the div, this allows them to be
2512 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2513 if (ST->isNullValue()) {
2514 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2515 if (CondI && CondI->getParent() == I.getParent())
2516 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2517 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2518 I.setOperand(1, SI->getOperand(2));
2520 UpdateValueUsesWith(SI, SI->getOperand(2));
2523 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2524 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2525 if (ST->isNullValue()) {
2526 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2527 if (CondI && CondI->getParent() == I.getParent())
2528 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2529 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2530 I.setOperand(1, SI->getOperand(1));
2532 UpdateValueUsesWith(SI, SI->getOperand(1));
2540 /// This function implements the transforms common to both integer remainder
2541 /// instructions (urem and srem). It is called by the visitors to those integer
2542 /// remainder instructions.
2543 /// @brief Common integer remainder transforms
2544 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2545 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2547 if (Instruction *common = commonRemTransforms(I))
2550 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2551 // X % 0 == undef, we don't need to preserve faults!
2552 if (RHS->equalsInt(0))
2553 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2555 if (RHS->equalsInt(1)) // X % 1 == 0
2556 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2558 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2559 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2560 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2562 } else if (isa<PHINode>(Op0I)) {
2563 if (Instruction *NV = FoldOpIntoPhi(I))
2566 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2567 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2568 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2575 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2578 if (Instruction *common = commonIRemTransforms(I))
2581 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2582 // X urem C^2 -> X and C
2583 // Check to see if this is an unsigned remainder with an exact power of 2,
2584 // if so, convert to a bitwise and.
2585 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2586 if (isPowerOf2_64(C->getZExtValue()))
2587 return BinaryOperator::createAnd(Op0, SubOne(C));
2590 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2591 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2592 if (RHSI->getOpcode() == Instruction::Shl &&
2593 isa<ConstantInt>(RHSI->getOperand(0))) {
2594 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2595 if (isPowerOf2_64(C1)) {
2596 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2597 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2599 return BinaryOperator::createAnd(Op0, Add);
2604 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2605 // where C1&C2 are powers of two.
2606 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2607 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2608 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2609 // STO == 0 and SFO == 0 handled above.
2610 if (isPowerOf2_64(STO->getZExtValue()) &&
2611 isPowerOf2_64(SFO->getZExtValue())) {
2612 Value *TrueAnd = InsertNewInstBefore(
2613 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2614 Value *FalseAnd = InsertNewInstBefore(
2615 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2616 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2624 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2625 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2627 if (Instruction *common = commonIRemTransforms(I))
2630 if (Value *RHSNeg = dyn_castNegVal(Op1))
2631 if (!isa<ConstantInt>(RHSNeg) ||
2632 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2634 AddUsesToWorkList(I);
2635 I.setOperand(1, RHSNeg);
2639 // If the top bits of both operands are zero (i.e. we can prove they are
2640 // unsigned inputs), turn this into a urem.
2641 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2642 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2643 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2644 return BinaryOperator::createURem(Op0, Op1, I.getName());
2650 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2651 return commonRemTransforms(I);
2654 // isMaxValueMinusOne - return true if this is Max-1
2655 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2657 // Calculate 0111111111..11111
2658 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2659 int64_t Val = INT64_MAX; // All ones
2660 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2661 return C->getSExtValue() == Val-1;
2663 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2666 // isMinValuePlusOne - return true if this is Min+1
2667 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2669 // Calculate 1111111111000000000000
2670 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2671 int64_t Val = -1; // All ones
2672 Val <<= TypeBits-1; // Shift over to the right spot
2673 return C->getSExtValue() == Val+1;
2675 return C->getZExtValue() == 1; // unsigned
2678 // isOneBitSet - Return true if there is exactly one bit set in the specified
2680 static bool isOneBitSet(const ConstantInt *CI) {
2681 uint64_t V = CI->getZExtValue();
2682 return V && (V & (V-1)) == 0;
2685 #if 0 // Currently unused
2686 // isLowOnes - Return true if the constant is of the form 0+1+.
2687 static bool isLowOnes(const ConstantInt *CI) {
2688 uint64_t V = CI->getZExtValue();
2690 // There won't be bits set in parts that the type doesn't contain.
2691 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2693 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2694 return U && V && (U & V) == 0;
2698 // isHighOnes - Return true if the constant is of the form 1+0+.
2699 // This is the same as lowones(~X).
2700 static bool isHighOnes(const ConstantInt *CI) {
2701 uint64_t V = ~CI->getZExtValue();
2702 if (~V == 0) return false; // 0's does not match "1+"
2704 // There won't be bits set in parts that the type doesn't contain.
2705 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2707 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2708 return U && V && (U & V) == 0;
2711 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2712 /// are carefully arranged to allow folding of expressions such as:
2714 /// (A < B) | (A > B) --> (A != B)
2716 /// Note that this is only valid if the first and second predicates have the
2717 /// same sign. Is illegal to do: (A u< B) | (A s> B)
2719 /// Three bits are used to represent the condition, as follows:
2724 /// <=> Value Definition
2725 /// 000 0 Always false
2732 /// 111 7 Always true
2734 static unsigned getICmpCode(const ICmpInst *ICI) {
2735 switch (ICI->getPredicate()) {
2737 case ICmpInst::ICMP_UGT: return 1; // 001
2738 case ICmpInst::ICMP_SGT: return 1; // 001
2739 case ICmpInst::ICMP_EQ: return 2; // 010
2740 case ICmpInst::ICMP_UGE: return 3; // 011
2741 case ICmpInst::ICMP_SGE: return 3; // 011
2742 case ICmpInst::ICMP_ULT: return 4; // 100
2743 case ICmpInst::ICMP_SLT: return 4; // 100
2744 case ICmpInst::ICMP_NE: return 5; // 101
2745 case ICmpInst::ICMP_ULE: return 6; // 110
2746 case ICmpInst::ICMP_SLE: return 6; // 110
2749 assert(0 && "Invalid ICmp predicate!");
2754 /// getICmpValue - This is the complement of getICmpCode, which turns an
2755 /// opcode and two operands into either a constant true or false, or a brand
2756 /// new /// ICmp instruction. The sign is passed in to determine which kind
2757 /// of predicate to use in new icmp instructions.
2758 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2760 default: assert(0 && "Illegal ICmp code!");
2761 case 0: return ConstantBool::getFalse();
2764 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2766 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2767 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2770 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2772 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2775 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2777 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2778 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2781 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2783 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2784 case 7: return ConstantBool::getTrue();
2788 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2789 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2790 (ICmpInst::isSignedPredicate(p1) &&
2791 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2792 (ICmpInst::isSignedPredicate(p2) &&
2793 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2797 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2798 struct FoldICmpLogical {
2801 ICmpInst::Predicate pred;
2802 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2803 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2804 pred(ICI->getPredicate()) {}
2805 bool shouldApply(Value *V) const {
2806 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2807 if (PredicatesFoldable(pred, ICI->getPredicate()))
2808 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2809 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2812 Instruction *apply(Instruction &Log) const {
2813 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2814 if (ICI->getOperand(0) != LHS) {
2815 assert(ICI->getOperand(1) == LHS);
2816 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
2819 unsigned LHSCode = getICmpCode(ICI);
2820 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2822 switch (Log.getOpcode()) {
2823 case Instruction::And: Code = LHSCode & RHSCode; break;
2824 case Instruction::Or: Code = LHSCode | RHSCode; break;
2825 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2826 default: assert(0 && "Illegal logical opcode!"); return 0;
2829 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2830 if (Instruction *I = dyn_cast<Instruction>(RV))
2832 // Otherwise, it's a constant boolean value...
2833 return IC.ReplaceInstUsesWith(Log, RV);
2836 } // end anonymous namespace
2838 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2839 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2840 // guaranteed to be either a shift instruction or a binary operator.
2841 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2842 ConstantIntegral *OpRHS,
2843 ConstantIntegral *AndRHS,
2844 BinaryOperator &TheAnd) {
2845 Value *X = Op->getOperand(0);
2846 Constant *Together = 0;
2847 if (!isa<ShiftInst>(Op))
2848 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2850 switch (Op->getOpcode()) {
2851 case Instruction::Xor:
2852 if (Op->hasOneUse()) {
2853 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2854 std::string OpName = Op->getName(); Op->setName("");
2855 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2856 InsertNewInstBefore(And, TheAnd);
2857 return BinaryOperator::createXor(And, Together);
2860 case Instruction::Or:
2861 if (Together == AndRHS) // (X | C) & C --> C
2862 return ReplaceInstUsesWith(TheAnd, AndRHS);
2864 if (Op->hasOneUse() && Together != OpRHS) {
2865 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2866 std::string Op0Name = Op->getName(); Op->setName("");
2867 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2868 InsertNewInstBefore(Or, TheAnd);
2869 return BinaryOperator::createAnd(Or, AndRHS);
2872 case Instruction::Add:
2873 if (Op->hasOneUse()) {
2874 // Adding a one to a single bit bit-field should be turned into an XOR
2875 // of the bit. First thing to check is to see if this AND is with a
2876 // single bit constant.
2877 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2879 // Clear bits that are not part of the constant.
2880 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2882 // If there is only one bit set...
2883 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2884 // Ok, at this point, we know that we are masking the result of the
2885 // ADD down to exactly one bit. If the constant we are adding has
2886 // no bits set below this bit, then we can eliminate the ADD.
2887 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2889 // Check to see if any bits below the one bit set in AndRHSV are set.
2890 if ((AddRHS & (AndRHSV-1)) == 0) {
2891 // If not, the only thing that can effect the output of the AND is
2892 // the bit specified by AndRHSV. If that bit is set, the effect of
2893 // the XOR is to toggle the bit. If it is clear, then the ADD has
2895 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2896 TheAnd.setOperand(0, X);
2899 std::string Name = Op->getName(); Op->setName("");
2900 // Pull the XOR out of the AND.
2901 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2902 InsertNewInstBefore(NewAnd, TheAnd);
2903 return BinaryOperator::createXor(NewAnd, AndRHS);
2910 case Instruction::Shl: {
2911 // We know that the AND will not produce any of the bits shifted in, so if
2912 // the anded constant includes them, clear them now!
2914 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2915 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2916 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2918 if (CI == ShlMask) { // Masking out bits that the shift already masks
2919 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2920 } else if (CI != AndRHS) { // Reducing bits set in and.
2921 TheAnd.setOperand(1, CI);
2926 case Instruction::LShr:
2928 // We know that the AND will not produce any of the bits shifted in, so if
2929 // the anded constant includes them, clear them now! This only applies to
2930 // unsigned shifts, because a signed shr may bring in set bits!
2932 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2933 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2934 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2936 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2937 return ReplaceInstUsesWith(TheAnd, Op);
2938 } else if (CI != AndRHS) {
2939 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2944 case Instruction::AShr:
2946 // See if this is shifting in some sign extension, then masking it out
2948 if (Op->hasOneUse()) {
2949 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2950 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2951 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2952 if (C == AndRHS) { // Masking out bits shifted in.
2953 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2954 // Make the argument unsigned.
2955 Value *ShVal = Op->getOperand(0);
2956 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2957 OpRHS, Op->getName()), TheAnd);
2958 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2967 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2968 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2969 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2970 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2971 /// insert new instructions.
2972 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2973 bool isSigned, bool Inside,
2975 assert(cast<ConstantBool>(ConstantExpr::getICmp((isSigned ?
2976 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getValue() &&
2977 "Lo is not <= Hi in range emission code!");
2980 if (Lo == Hi) // Trivially false.
2981 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2983 // V >= Min && V < Hi --> V < Hi
2984 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
2985 ICmpInst::Predicate pred = (isSigned ?
2986 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2987 return new ICmpInst(pred, V, Hi);
2990 // Emit V-Lo <u Hi-Lo
2991 Constant *NegLo = ConstantExpr::getNeg(Lo);
2992 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2993 InsertNewInstBefore(Add, IB);
2994 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2995 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2998 if (Lo == Hi) // Trivially true.
2999 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3001 // V < Min || V >= Hi ->'V > Hi-1'
3002 Hi = SubOne(cast<ConstantInt>(Hi));
3003 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
3004 ICmpInst::Predicate pred = (isSigned ?
3005 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3006 return new ICmpInst(pred, V, Hi);
3009 // Emit V-Lo > Hi-1-Lo
3010 Constant *NegLo = ConstantExpr::getNeg(Lo);
3011 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3012 InsertNewInstBefore(Add, IB);
3013 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3014 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3017 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3018 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3019 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3020 // not, since all 1s are not contiguous.
3021 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
3022 uint64_t V = Val->getZExtValue();
3023 if (!isShiftedMask_64(V)) return false;
3025 // look for the first zero bit after the run of ones
3026 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3027 // look for the first non-zero bit
3028 ME = 64-CountLeadingZeros_64(V);
3034 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3035 /// where isSub determines whether the operator is a sub. If we can fold one of
3036 /// the following xforms:
3038 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3039 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3040 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3042 /// return (A +/- B).
3044 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3045 ConstantIntegral *Mask, bool isSub,
3047 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3048 if (!LHSI || LHSI->getNumOperands() != 2 ||
3049 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3051 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3053 switch (LHSI->getOpcode()) {
3055 case Instruction::And:
3056 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3057 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3058 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3061 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3062 // part, we don't need any explicit masks to take them out of A. If that
3063 // is all N is, ignore it.
3065 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3066 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3068 if (MaskedValueIsZero(RHS, Mask))
3073 case Instruction::Or:
3074 case Instruction::Xor:
3075 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3076 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3077 ConstantExpr::getAnd(N, Mask)->isNullValue())
3084 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3086 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3087 return InsertNewInstBefore(New, I);
3090 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3091 bool Changed = SimplifyCommutative(I);
3092 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3094 if (isa<UndefValue>(Op1)) // X & undef -> 0
3095 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3099 return ReplaceInstUsesWith(I, Op1);
3101 // See if we can simplify any instructions used by the instruction whose sole
3102 // purpose is to compute bits we don't care about.
3103 uint64_t KnownZero, KnownOne;
3104 if (!isa<PackedType>(I.getType()) &&
3105 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3106 KnownZero, KnownOne))
3109 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
3110 uint64_t AndRHSMask = AndRHS->getZExtValue();
3111 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
3112 uint64_t NotAndRHS = AndRHSMask^TypeMask;
3114 // Optimize a variety of ((val OP C1) & C2) combinations...
3115 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3116 Instruction *Op0I = cast<Instruction>(Op0);
3117 Value *Op0LHS = Op0I->getOperand(0);
3118 Value *Op0RHS = Op0I->getOperand(1);
3119 switch (Op0I->getOpcode()) {
3120 case Instruction::Xor:
3121 case Instruction::Or:
3122 // If the mask is only needed on one incoming arm, push it up.
3123 if (Op0I->hasOneUse()) {
3124 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3125 // Not masking anything out for the LHS, move to RHS.
3126 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3127 Op0RHS->getName()+".masked");
3128 InsertNewInstBefore(NewRHS, I);
3129 return BinaryOperator::create(
3130 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3132 if (!isa<Constant>(Op0RHS) &&
3133 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3134 // Not masking anything out for the RHS, move to LHS.
3135 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3136 Op0LHS->getName()+".masked");
3137 InsertNewInstBefore(NewLHS, I);
3138 return BinaryOperator::create(
3139 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3144 case Instruction::Add:
3145 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3146 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3147 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3148 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3149 return BinaryOperator::createAnd(V, AndRHS);
3150 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3151 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3154 case Instruction::Sub:
3155 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3156 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3157 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3158 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3159 return BinaryOperator::createAnd(V, AndRHS);
3163 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3164 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3166 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3167 // If this is an integer truncation or change from signed-to-unsigned, and
3168 // if the source is an and/or with immediate, transform it. This
3169 // frequently occurs for bitfield accesses.
3170 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3171 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3172 CastOp->getNumOperands() == 2)
3173 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3174 if (CastOp->getOpcode() == Instruction::And) {
3175 // Change: and (cast (and X, C1) to T), C2
3176 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3177 // This will fold the two constants together, which may allow
3178 // other simplifications.
3179 Instruction *NewCast = CastInst::createTruncOrBitCast(
3180 CastOp->getOperand(0), I.getType(),
3181 CastOp->getName()+".shrunk");
3182 NewCast = InsertNewInstBefore(NewCast, I);
3183 // trunc_or_bitcast(C1)&C2
3184 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3185 C3 = ConstantExpr::getAnd(C3, AndRHS);
3186 return BinaryOperator::createAnd(NewCast, C3);
3187 } else if (CastOp->getOpcode() == Instruction::Or) {
3188 // Change: and (cast (or X, C1) to T), C2
3189 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3190 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3191 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3192 return ReplaceInstUsesWith(I, AndRHS);
3197 // Try to fold constant and into select arguments.
3198 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3199 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3201 if (isa<PHINode>(Op0))
3202 if (Instruction *NV = FoldOpIntoPhi(I))
3206 Value *Op0NotVal = dyn_castNotVal(Op0);
3207 Value *Op1NotVal = dyn_castNotVal(Op1);
3209 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3210 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3212 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3213 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3214 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3215 I.getName()+".demorgan");
3216 InsertNewInstBefore(Or, I);
3217 return BinaryOperator::createNot(Or);
3221 Value *A = 0, *B = 0;
3222 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3223 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3224 return ReplaceInstUsesWith(I, Op1);
3225 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3226 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3227 return ReplaceInstUsesWith(I, Op0);
3229 if (Op0->hasOneUse() &&
3230 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3231 if (A == Op1) { // (A^B)&A -> A&(A^B)
3232 I.swapOperands(); // Simplify below
3233 std::swap(Op0, Op1);
3234 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3235 cast<BinaryOperator>(Op0)->swapOperands();
3236 I.swapOperands(); // Simplify below
3237 std::swap(Op0, Op1);
3240 if (Op1->hasOneUse() &&
3241 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3242 if (B == Op0) { // B&(A^B) -> B&(B^A)
3243 cast<BinaryOperator>(Op1)->swapOperands();
3246 if (A == Op0) { // A&(A^B) -> A & ~B
3247 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3248 InsertNewInstBefore(NotB, I);
3249 return BinaryOperator::createAnd(A, NotB);
3254 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3255 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3256 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3259 Value *LHSVal, *RHSVal;
3260 ConstantInt *LHSCst, *RHSCst;
3261 ICmpInst::Predicate LHSCC, RHSCC;
3262 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3263 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3264 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3265 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3266 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3267 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3268 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3269 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3270 // Ensure that the larger constant is on the RHS.
3271 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3272 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3273 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3274 ICmpInst *LHS = cast<ICmpInst>(Op0);
3275 if (cast<ConstantBool>(Cmp)->getValue()) {
3276 std::swap(LHS, RHS);
3277 std::swap(LHSCst, RHSCst);
3278 std::swap(LHSCC, RHSCC);
3281 // At this point, we know we have have two icmp instructions
3282 // comparing a value against two constants and and'ing the result
3283 // together. Because of the above check, we know that we only have
3284 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3285 // (from the FoldICmpLogical check above), that the two constants
3286 // are not equal and that the larger constant is on the RHS
3287 assert(LHSCst != RHSCst && "Compares not folded above?");
3290 default: assert(0 && "Unknown integer condition code!");
3291 case ICmpInst::ICMP_EQ:
3293 default: assert(0 && "Unknown integer condition code!");
3294 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3295 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3296 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3297 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3298 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3299 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3300 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3301 return ReplaceInstUsesWith(I, LHS);
3303 case ICmpInst::ICMP_NE:
3305 default: assert(0 && "Unknown integer condition code!");
3306 case ICmpInst::ICMP_ULT:
3307 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3308 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3309 break; // (X != 13 & X u< 15) -> no change
3310 case ICmpInst::ICMP_SLT:
3311 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3312 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3313 break; // (X != 13 & X s< 15) -> no change
3314 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3315 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3316 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3317 return ReplaceInstUsesWith(I, RHS);
3318 case ICmpInst::ICMP_NE:
3319 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3320 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3321 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3322 LHSVal->getName()+".off");
3323 InsertNewInstBefore(Add, I);
3324 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
3326 break; // (X != 13 & X != 15) -> no change
3329 case ICmpInst::ICMP_ULT:
3331 default: assert(0 && "Unknown integer condition code!");
3332 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3333 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3334 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3335 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3337 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3338 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3339 return ReplaceInstUsesWith(I, LHS);
3340 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3344 case ICmpInst::ICMP_SLT:
3346 default: assert(0 && "Unknown integer condition code!");
3347 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3348 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3349 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3350 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3352 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3353 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3354 return ReplaceInstUsesWith(I, LHS);
3355 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3359 case ICmpInst::ICMP_UGT:
3361 default: assert(0 && "Unknown integer condition code!");
3362 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3363 return ReplaceInstUsesWith(I, LHS);
3364 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3365 return ReplaceInstUsesWith(I, RHS);
3366 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3368 case ICmpInst::ICMP_NE:
3369 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3370 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3371 break; // (X u> 13 & X != 15) -> no change
3372 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3373 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3375 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3379 case ICmpInst::ICMP_SGT:
3381 default: assert(0 && "Unknown integer condition code!");
3382 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3383 return ReplaceInstUsesWith(I, LHS);
3384 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3385 return ReplaceInstUsesWith(I, RHS);
3386 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3388 case ICmpInst::ICMP_NE:
3389 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3390 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3391 break; // (X s> 13 & X != 15) -> no change
3392 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3393 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3395 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3403 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3404 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3405 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3406 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3407 const Type *SrcTy = Op0C->getOperand(0)->getType();
3408 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3409 // Only do this if the casts both really cause code to be generated.
3410 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3412 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3414 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3415 Op1C->getOperand(0),
3417 InsertNewInstBefore(NewOp, I);
3418 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3422 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3423 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3424 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3425 if (SI0->getOpcode() == SI1->getOpcode() &&
3426 SI0->getOperand(1) == SI1->getOperand(1) &&
3427 (SI0->hasOneUse() || SI1->hasOneUse())) {
3428 Instruction *NewOp =
3429 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3431 SI0->getName()), I);
3432 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3436 return Changed ? &I : 0;
3439 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3440 /// in the result. If it does, and if the specified byte hasn't been filled in
3441 /// yet, fill it in and return false.
3442 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3443 Instruction *I = dyn_cast<Instruction>(V);
3444 if (I == 0) return true;
3446 // If this is an or instruction, it is an inner node of the bswap.
3447 if (I->getOpcode() == Instruction::Or)
3448 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3449 CollectBSwapParts(I->getOperand(1), ByteValues);
3451 // If this is a shift by a constant int, and it is "24", then its operand
3452 // defines a byte. We only handle unsigned types here.
3453 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3454 // Not shifting the entire input by N-1 bytes?
3455 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3456 8*(ByteValues.size()-1))
3460 if (I->getOpcode() == Instruction::Shl) {
3461 // X << 24 defines the top byte with the lowest of the input bytes.
3462 DestNo = ByteValues.size()-1;
3464 // X >>u 24 defines the low byte with the highest of the input bytes.
3468 // If the destination byte value is already defined, the values are or'd
3469 // together, which isn't a bswap (unless it's an or of the same bits).
3470 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3472 ByteValues[DestNo] = I->getOperand(0);
3476 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3478 Value *Shift = 0, *ShiftLHS = 0;
3479 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3480 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3481 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3483 Instruction *SI = cast<Instruction>(Shift);
3485 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3486 if (ShiftAmt->getZExtValue() & 7 ||
3487 ShiftAmt->getZExtValue() > 8*ByteValues.size())
3490 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3492 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3493 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3495 // Unknown mask for bswap.
3496 if (DestByte == ByteValues.size()) return true;
3498 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3500 if (SI->getOpcode() == Instruction::Shl)
3501 SrcByte = DestByte - ShiftBytes;
3503 SrcByte = DestByte + ShiftBytes;
3505 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3506 if (SrcByte != ByteValues.size()-DestByte-1)
3509 // If the destination byte value is already defined, the values are or'd
3510 // together, which isn't a bswap (unless it's an or of the same bits).
3511 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3513 ByteValues[DestByte] = SI->getOperand(0);
3517 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3518 /// If so, insert the new bswap intrinsic and return it.
3519 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3520 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3521 if (I.getType() == Type::Int8Ty)
3524 /// ByteValues - For each byte of the result, we keep track of which value
3525 /// defines each byte.
3526 std::vector<Value*> ByteValues;
3527 ByteValues.resize(I.getType()->getPrimitiveSize());
3529 // Try to find all the pieces corresponding to the bswap.
3530 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3531 CollectBSwapParts(I.getOperand(1), ByteValues))
3534 // Check to see if all of the bytes come from the same value.
3535 Value *V = ByteValues[0];
3536 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3538 // Check to make sure that all of the bytes come from the same value.
3539 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3540 if (ByteValues[i] != V)
3543 // If they do then *success* we can turn this into a bswap. Figure out what
3544 // bswap to make it into.
3545 Module *M = I.getParent()->getParent()->getParent();
3546 const char *FnName = 0;
3547 if (I.getType() == Type::Int16Ty)
3548 FnName = "llvm.bswap.i16";
3549 else if (I.getType() == Type::Int32Ty)
3550 FnName = "llvm.bswap.i32";
3551 else if (I.getType() == Type::Int64Ty)
3552 FnName = "llvm.bswap.i64";
3554 assert(0 && "Unknown integer type!");
3555 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3556 return new CallInst(F, V);
3560 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3561 bool Changed = SimplifyCommutative(I);
3562 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3564 if (isa<UndefValue>(Op1))
3565 return ReplaceInstUsesWith(I, // X | undef -> -1
3566 ConstantIntegral::getAllOnesValue(I.getType()));
3570 return ReplaceInstUsesWith(I, Op0);
3572 // See if we can simplify any instructions used by the instruction whose sole
3573 // purpose is to compute bits we don't care about.
3574 uint64_t KnownZero, KnownOne;
3575 if (!isa<PackedType>(I.getType()) &&
3576 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3577 KnownZero, KnownOne))
3581 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3582 ConstantInt *C1 = 0; Value *X = 0;
3583 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3584 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3585 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3587 InsertNewInstBefore(Or, I);
3588 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3591 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3592 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3593 std::string Op0Name = Op0->getName(); Op0->setName("");
3594 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3595 InsertNewInstBefore(Or, I);
3596 return BinaryOperator::createXor(Or,
3597 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3600 // Try to fold constant and into select arguments.
3601 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3602 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3604 if (isa<PHINode>(Op0))
3605 if (Instruction *NV = FoldOpIntoPhi(I))
3609 Value *A = 0, *B = 0;
3610 ConstantInt *C1 = 0, *C2 = 0;
3612 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3613 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3614 return ReplaceInstUsesWith(I, Op1);
3615 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3616 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3617 return ReplaceInstUsesWith(I, Op0);
3619 // (A | B) | C and A | (B | C) -> bswap if possible.
3620 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3621 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3622 match(Op1, m_Or(m_Value(), m_Value())) ||
3623 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3624 match(Op1, m_Shift(m_Value(), m_Value())))) {
3625 if (Instruction *BSwap = MatchBSwap(I))
3629 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3630 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3631 MaskedValueIsZero(Op1, C1->getZExtValue())) {
3632 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3634 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3637 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3638 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3639 MaskedValueIsZero(Op0, C1->getZExtValue())) {
3640 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3642 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3645 // (A & C1)|(B & C2)
3646 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3647 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3649 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3650 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3653 // If we have: ((V + N) & C1) | (V & C2)
3654 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3655 // replace with V+N.
3656 if (C1 == ConstantExpr::getNot(C2)) {
3657 Value *V1 = 0, *V2 = 0;
3658 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3659 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3660 // Add commutes, try both ways.
3661 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3662 return ReplaceInstUsesWith(I, A);
3663 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3664 return ReplaceInstUsesWith(I, A);
3666 // Or commutes, try both ways.
3667 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3668 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3669 // Add commutes, try both ways.
3670 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3671 return ReplaceInstUsesWith(I, B);
3672 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3673 return ReplaceInstUsesWith(I, B);
3678 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3679 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3680 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3681 if (SI0->getOpcode() == SI1->getOpcode() &&
3682 SI0->getOperand(1) == SI1->getOperand(1) &&
3683 (SI0->hasOneUse() || SI1->hasOneUse())) {
3684 Instruction *NewOp =
3685 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3687 SI0->getName()), I);
3688 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3692 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3693 if (A == Op1) // ~A | A == -1
3694 return ReplaceInstUsesWith(I,
3695 ConstantIntegral::getAllOnesValue(I.getType()));
3699 // Note, A is still live here!
3700 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3702 return ReplaceInstUsesWith(I,
3703 ConstantIntegral::getAllOnesValue(I.getType()));
3705 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3706 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3707 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3708 I.getName()+".demorgan"), I);
3709 return BinaryOperator::createNot(And);
3713 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3714 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3715 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3718 Value *LHSVal, *RHSVal;
3719 ConstantInt *LHSCst, *RHSCst;
3720 ICmpInst::Predicate LHSCC, RHSCC;
3721 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3722 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3723 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3724 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3725 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3726 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3727 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3728 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3729 // Ensure that the larger constant is on the RHS.
3730 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3731 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3732 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3733 ICmpInst *LHS = cast<ICmpInst>(Op0);
3734 if (cast<ConstantBool>(Cmp)->getValue()) {
3735 std::swap(LHS, RHS);
3736 std::swap(LHSCst, RHSCst);
3737 std::swap(LHSCC, RHSCC);
3740 // At this point, we know we have have two icmp instructions
3741 // comparing a value against two constants and or'ing the result
3742 // together. Because of the above check, we know that we only have
3743 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3744 // FoldICmpLogical check above), that the two constants are not
3746 assert(LHSCst != RHSCst && "Compares not folded above?");
3749 default: assert(0 && "Unknown integer condition code!");
3750 case ICmpInst::ICMP_EQ:
3752 default: assert(0 && "Unknown integer condition code!");
3753 case ICmpInst::ICMP_EQ:
3754 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3755 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3756 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3757 LHSVal->getName()+".off");
3758 InsertNewInstBefore(Add, I);
3759 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3760 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3762 break; // (X == 13 | X == 15) -> no change
3763 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3764 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
3766 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3767 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3768 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
3769 return ReplaceInstUsesWith(I, RHS);
3772 case ICmpInst::ICMP_NE:
3774 default: assert(0 && "Unknown integer condition code!");
3775 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3776 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3777 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
3778 return ReplaceInstUsesWith(I, LHS);
3779 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3780 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3781 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
3782 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3785 case ICmpInst::ICMP_ULT:
3787 default: assert(0 && "Unknown integer condition code!");
3788 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
3790 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3791 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3793 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3795 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3796 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
3797 return ReplaceInstUsesWith(I, RHS);
3798 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3802 case ICmpInst::ICMP_SLT:
3804 default: assert(0 && "Unknown integer condition code!");
3805 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3807 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3808 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3810 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3812 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3813 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3814 return ReplaceInstUsesWith(I, RHS);
3815 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3819 case ICmpInst::ICMP_UGT:
3821 default: assert(0 && "Unknown integer condition code!");
3822 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3823 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3824 return ReplaceInstUsesWith(I, LHS);
3825 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3827 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3828 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
3829 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3830 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3834 case ICmpInst::ICMP_SGT:
3836 default: assert(0 && "Unknown integer condition code!");
3837 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3838 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3839 return ReplaceInstUsesWith(I, LHS);
3840 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3842 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3843 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
3844 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3845 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3853 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3854 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3855 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3856 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3857 const Type *SrcTy = Op0C->getOperand(0)->getType();
3858 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3859 // Only do this if the casts both really cause code to be generated.
3860 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3862 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3864 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3865 Op1C->getOperand(0),
3867 InsertNewInstBefore(NewOp, I);
3868 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3873 return Changed ? &I : 0;
3876 // XorSelf - Implements: X ^ X --> 0
3879 XorSelf(Value *rhs) : RHS(rhs) {}
3880 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3881 Instruction *apply(BinaryOperator &Xor) const {
3887 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3888 bool Changed = SimplifyCommutative(I);
3889 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3891 if (isa<UndefValue>(Op1))
3892 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3894 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3895 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3896 assert(Result == &I && "AssociativeOpt didn't work?");
3897 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3900 // See if we can simplify any instructions used by the instruction whose sole
3901 // purpose is to compute bits we don't care about.
3902 uint64_t KnownZero, KnownOne;
3903 if (!isa<PackedType>(I.getType()) &&
3904 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3905 KnownZero, KnownOne))
3908 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3909 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3910 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3911 if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3912 return new ICmpInst(ICI->getInversePredicate(),
3913 ICI->getOperand(0), ICI->getOperand(1));
3915 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3916 // ~(c-X) == X-c-1 == X+(-c-1)
3917 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3918 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3919 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3920 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3921 ConstantInt::get(I.getType(), 1));
3922 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3925 // ~(~X & Y) --> (X | ~Y)
3926 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3927 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3928 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3930 BinaryOperator::createNot(Op0I->getOperand(1),
3931 Op0I->getOperand(1)->getName()+".not");
3932 InsertNewInstBefore(NotY, I);
3933 return BinaryOperator::createOr(Op0NotVal, NotY);
3937 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3938 if (Op0I->getOpcode() == Instruction::Add) {
3939 // ~(X-c) --> (-c-1)-X
3940 if (RHS->isAllOnesValue()) {
3941 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3942 return BinaryOperator::createSub(
3943 ConstantExpr::getSub(NegOp0CI,
3944 ConstantInt::get(I.getType(), 1)),
3945 Op0I->getOperand(0));
3947 } else if (Op0I->getOpcode() == Instruction::Or) {
3948 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3949 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3950 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3951 // Anything in both C1 and C2 is known to be zero, remove it from
3953 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3954 NewRHS = ConstantExpr::getAnd(NewRHS,
3955 ConstantExpr::getNot(CommonBits));
3956 WorkList.push_back(Op0I);
3957 I.setOperand(0, Op0I->getOperand(0));
3958 I.setOperand(1, NewRHS);
3964 // Try to fold constant and into select arguments.
3965 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3966 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3968 if (isa<PHINode>(Op0))
3969 if (Instruction *NV = FoldOpIntoPhi(I))
3973 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
3975 return ReplaceInstUsesWith(I,
3976 ConstantIntegral::getAllOnesValue(I.getType()));
3978 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
3980 return ReplaceInstUsesWith(I,
3981 ConstantIntegral::getAllOnesValue(I.getType()));
3983 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3984 if (Op1I->getOpcode() == Instruction::Or) {
3985 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
3986 Op1I->swapOperands();
3988 std::swap(Op0, Op1);
3989 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
3990 I.swapOperands(); // Simplified below.
3991 std::swap(Op0, Op1);
3993 } else if (Op1I->getOpcode() == Instruction::Xor) {
3994 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3995 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3996 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3997 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3998 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3999 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4000 Op1I->swapOperands();
4001 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4002 I.swapOperands(); // Simplified below.
4003 std::swap(Op0, Op1);
4007 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
4008 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
4009 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
4010 Op0I->swapOperands();
4011 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
4012 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4013 InsertNewInstBefore(NotB, I);
4014 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
4016 } else if (Op0I->getOpcode() == Instruction::Xor) {
4017 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4018 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4019 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4020 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
4021 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4022 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4023 Op0I->swapOperands();
4024 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4025 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4026 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4027 InsertNewInstBefore(N, I);
4028 return BinaryOperator::createAnd(N, Op1);
4032 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4033 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4034 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4037 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4038 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4039 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4040 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4041 const Type *SrcTy = Op0C->getOperand(0)->getType();
4042 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4043 // Only do this if the casts both really cause code to be generated.
4044 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4046 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4048 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4049 Op1C->getOperand(0),
4051 InsertNewInstBefore(NewOp, I);
4052 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4056 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4057 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4058 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4059 if (SI0->getOpcode() == SI1->getOpcode() &&
4060 SI0->getOperand(1) == SI1->getOperand(1) &&
4061 (SI0->hasOneUse() || SI1->hasOneUse())) {
4062 Instruction *NewOp =
4063 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4065 SI0->getName()), I);
4066 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4070 return Changed ? &I : 0;
4073 static bool isPositive(ConstantInt *C) {
4074 return C->getSExtValue() >= 0;
4077 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4078 /// overflowed for this type.
4079 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4081 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4083 return cast<ConstantInt>(Result)->getZExtValue() <
4084 cast<ConstantInt>(In1)->getZExtValue();
4087 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4088 /// code necessary to compute the offset from the base pointer (without adding
4089 /// in the base pointer). Return the result as a signed integer of intptr size.
4090 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4091 TargetData &TD = IC.getTargetData();
4092 gep_type_iterator GTI = gep_type_begin(GEP);
4093 const Type *IntPtrTy = TD.getIntPtrType();
4094 Value *Result = Constant::getNullValue(IntPtrTy);
4096 // Build a mask for high order bits.
4097 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4099 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4100 Value *Op = GEP->getOperand(i);
4101 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4102 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4103 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4104 if (!OpC->isNullValue()) {
4105 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4106 Scale = ConstantExpr::getMul(OpC, Scale);
4107 if (Constant *RC = dyn_cast<Constant>(Result))
4108 Result = ConstantExpr::getAdd(RC, Scale);
4110 // Emit an add instruction.
4111 Result = IC.InsertNewInstBefore(
4112 BinaryOperator::createAdd(Result, Scale,
4113 GEP->getName()+".offs"), I);
4117 // Convert to correct type.
4118 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4119 Op->getName()+".c"), I);
4121 // We'll let instcombine(mul) convert this to a shl if possible.
4122 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4123 GEP->getName()+".idx"), I);
4125 // Emit an add instruction.
4126 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4127 GEP->getName()+".offs"), I);
4133 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4134 /// else. At this point we know that the GEP is on the LHS of the comparison.
4135 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4136 ICmpInst::Predicate Cond,
4138 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4140 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4141 if (isa<PointerType>(CI->getOperand(0)->getType()))
4142 RHS = CI->getOperand(0);
4144 Value *PtrBase = GEPLHS->getOperand(0);
4145 if (PtrBase == RHS) {
4146 // As an optimization, we don't actually have to compute the actual value of
4147 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4148 // each index is zero or not.
4149 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4150 Instruction *InVal = 0;
4151 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4152 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4154 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4155 if (isa<UndefValue>(C)) // undef index -> undef.
4156 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4157 if (C->isNullValue())
4159 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4160 EmitIt = false; // This is indexing into a zero sized array?
4161 } else if (isa<ConstantInt>(C))
4162 return ReplaceInstUsesWith(I, // No comparison is needed here.
4163 ConstantBool::get(Cond == ICmpInst::ICMP_NE));
4168 new ICmpInst(Cond, GEPLHS->getOperand(i),
4169 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4173 InVal = InsertNewInstBefore(InVal, I);
4174 InsertNewInstBefore(Comp, I);
4175 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
4176 InVal = BinaryOperator::createOr(InVal, Comp);
4177 else // True if all are equal
4178 InVal = BinaryOperator::createAnd(InVal, Comp);
4186 // No comparison is needed here, all indexes = 0
4187 ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
4190 // Only lower this if the icmp is the only user of the GEP or if we expect
4191 // the result to fold to a constant!
4192 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4193 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4194 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4195 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4196 Constant::getNullValue(Offset->getType()));
4198 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4199 // If the base pointers are different, but the indices are the same, just
4200 // compare the base pointer.
4201 if (PtrBase != GEPRHS->getOperand(0)) {
4202 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4203 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4204 GEPRHS->getOperand(0)->getType();
4206 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4207 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4208 IndicesTheSame = false;
4212 // If all indices are the same, just compare the base pointers.
4214 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4215 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4217 // Otherwise, the base pointers are different and the indices are
4218 // different, bail out.
4222 // If one of the GEPs has all zero indices, recurse.
4223 bool AllZeros = true;
4224 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4225 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4226 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4231 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4232 ICmpInst::getSwappedPredicate(Cond), I);
4234 // If the other GEP has all zero indices, recurse.
4236 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4237 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4238 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4243 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4245 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4246 // If the GEPs only differ by one index, compare it.
4247 unsigned NumDifferences = 0; // Keep track of # differences.
4248 unsigned DiffOperand = 0; // The operand that differs.
4249 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4250 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4251 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4252 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4253 // Irreconcilable differences.
4257 if (NumDifferences++) break;
4262 if (NumDifferences == 0) // SAME GEP?
4263 return ReplaceInstUsesWith(I, // No comparison is needed here.
4264 ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
4265 else if (NumDifferences == 1) {
4266 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4267 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4268 // Make sure we do a signed comparison here.
4269 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4273 // Only lower this if the icmp is the only user of the GEP or if we expect
4274 // the result to fold to a constant!
4275 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4276 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4277 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4278 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4279 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4280 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4286 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4287 bool Changed = SimplifyCompare(I);
4288 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4292 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4294 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
4295 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4297 // Handle fcmp with constant RHS
4298 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4299 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4300 switch (LHSI->getOpcode()) {
4301 case Instruction::PHI:
4302 if (Instruction *NV = FoldOpIntoPhi(I))
4305 case Instruction::Select:
4306 // If either operand of the select is a constant, we can fold the
4307 // comparison into the select arms, which will cause one to be
4308 // constant folded and the select turned into a bitwise or.
4309 Value *Op1 = 0, *Op2 = 0;
4310 if (LHSI->hasOneUse()) {
4311 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4312 // Fold the known value into the constant operand.
4313 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4314 // Insert a new FCmp of the other select operand.
4315 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4316 LHSI->getOperand(2), RHSC,
4318 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4319 // Fold the known value into the constant operand.
4320 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4321 // Insert a new FCmp of the other select operand.
4322 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4323 LHSI->getOperand(1), RHSC,
4329 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4334 return Changed ? &I : 0;
4337 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4338 bool Changed = SimplifyCompare(I);
4339 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4340 const Type *Ty = Op0->getType();
4344 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4346 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4347 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4349 // icmp of GlobalValues can never equal each other as long as they aren't
4350 // external weak linkage type.
4351 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4352 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4353 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4354 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4356 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4357 // addresses never equal each other! We already know that Op0 != Op1.
4358 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4359 isa<ConstantPointerNull>(Op0)) &&
4360 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4361 isa<ConstantPointerNull>(Op1)))
4362 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4364 // icmp's with boolean values can always be turned into bitwise operations
4365 if (Ty == Type::BoolTy) {
4366 switch (I.getPredicate()) {
4367 default: assert(0 && "Invalid icmp instruction!");
4368 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
4369 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4370 InsertNewInstBefore(Xor, I);
4371 return BinaryOperator::createNot(Xor);
4373 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
4374 return BinaryOperator::createXor(Op0, Op1);
4376 case ICmpInst::ICMP_UGT:
4377 case ICmpInst::ICMP_SGT:
4378 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
4380 case ICmpInst::ICMP_ULT:
4381 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
4382 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4383 InsertNewInstBefore(Not, I);
4384 return BinaryOperator::createAnd(Not, Op1);
4386 case ICmpInst::ICMP_UGE:
4387 case ICmpInst::ICMP_SGE:
4388 std::swap(Op0, Op1); // Change icmp ge -> icmp le
4390 case ICmpInst::ICMP_ULE:
4391 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
4392 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4393 InsertNewInstBefore(Not, I);
4394 return BinaryOperator::createOr(Not, Op1);
4399 // See if we are doing a comparison between a constant and an instruction that
4400 // can be folded into the comparison.
4401 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4402 switch (I.getPredicate()) {
4404 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4405 if (CI->isMinValue(false))
4406 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4407 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4408 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4409 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4410 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4413 case ICmpInst::ICMP_SLT:
4414 if (CI->isMinValue(true)) // A <s MIN -> FALSE
4415 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4416 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4417 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4418 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4419 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4422 case ICmpInst::ICMP_UGT:
4423 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4424 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4425 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4426 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4427 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4428 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4431 case ICmpInst::ICMP_SGT:
4432 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4433 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4434 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4435 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4436 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4437 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4440 case ICmpInst::ICMP_ULE:
4441 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
4442 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4443 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4444 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4445 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4446 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4449 case ICmpInst::ICMP_SLE:
4450 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4451 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4452 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4453 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4454 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4455 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4458 case ICmpInst::ICMP_UGE:
4459 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4460 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4461 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4462 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4463 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4464 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4467 case ICmpInst::ICMP_SGE:
4468 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4469 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4470 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4471 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4472 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4473 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4477 // If we still have a icmp le or icmp ge instruction, turn it into the
4478 // appropriate icmp lt or icmp gt instruction. Since the border cases have
4479 // already been handled above, this requires little checking.
4481 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4482 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4483 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4484 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4485 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4486 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4487 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4488 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4490 // See if we can fold the comparison based on bits known to be zero or one
4492 uint64_t KnownZero, KnownOne;
4493 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4494 KnownZero, KnownOne, 0))
4497 // Given the known and unknown bits, compute a range that the LHS could be
4499 if (KnownOne | KnownZero) {
4500 // Compute the Min, Max and RHS values based on the known bits. For the
4501 // EQ and NE we use unsigned values.
4502 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4503 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4504 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4505 SRHSVal = CI->getSExtValue();
4506 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4509 URHSVal = CI->getZExtValue();
4510 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4513 switch (I.getPredicate()) { // LE/GE have been folded already.
4514 default: assert(0 && "Unknown icmp opcode!");
4515 case ICmpInst::ICMP_EQ:
4516 if (UMax < URHSVal || UMin > URHSVal)
4517 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4519 case ICmpInst::ICMP_NE:
4520 if (UMax < URHSVal || UMin > URHSVal)
4521 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4523 case ICmpInst::ICMP_ULT:
4525 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4527 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4529 case ICmpInst::ICMP_UGT:
4531 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4533 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4535 case ICmpInst::ICMP_SLT:
4537 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4539 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4541 case ICmpInst::ICMP_SGT:
4543 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4545 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4550 // Since the RHS is a ConstantInt (CI), if the left hand side is an
4551 // instruction, see if that instruction also has constants so that the
4552 // instruction can be folded into the icmp
4553 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4554 switch (LHSI->getOpcode()) {
4555 case Instruction::And:
4556 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4557 LHSI->getOperand(0)->hasOneUse()) {
4558 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4560 // If the LHS is an AND of a truncating cast, we can widen the
4561 // and/compare to be the input width without changing the value
4562 // produced, eliminating a cast.
4563 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4564 // We can do this transformation if either the AND constant does not
4565 // have its sign bit set or if it is an equality comparison.
4566 // Extending a relational comparison when we're checking the sign
4567 // bit would not work.
4568 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4570 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4571 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4572 ConstantInt *NewCST;
4574 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4575 AndCST->getZExtValue());
4576 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4577 CI->getZExtValue());
4578 Instruction *NewAnd =
4579 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4581 InsertNewInstBefore(NewAnd, I);
4582 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4586 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4587 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4588 // happens a LOT in code produced by the C front-end, for bitfield
4590 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4592 // Check to see if there is a noop-cast between the shift and the and.
4594 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4595 if (CI->getOpcode() == Instruction::BitCast)
4596 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4600 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4601 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4602 const Type *AndTy = AndCST->getType(); // Type of the and.
4604 // We can fold this as long as we can't shift unknown bits
4605 // into the mask. This can only happen with signed shift
4606 // rights, as they sign-extend.
4608 bool CanFold = Shift->isLogicalShift();
4610 // To test for the bad case of the signed shr, see if any
4611 // of the bits shifted in could be tested after the mask.
4612 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4613 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4615 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
4617 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4619 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4625 if (Shift->getOpcode() == Instruction::Shl)
4626 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4628 NewCst = ConstantExpr::getShl(CI, ShAmt);
4630 // Check to see if we are shifting out any of the bits being
4632 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4633 // If we shifted bits out, the fold is not going to work out.
4634 // As a special case, check to see if this means that the
4635 // result is always true or false now.
4636 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4637 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4638 if (I.getPredicate() == ICmpInst::ICMP_NE)
4639 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4641 I.setOperand(1, NewCst);
4642 Constant *NewAndCST;
4643 if (Shift->getOpcode() == Instruction::Shl)
4644 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4646 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4647 LHSI->setOperand(1, NewAndCST);
4648 LHSI->setOperand(0, Shift->getOperand(0));
4649 WorkList.push_back(Shift); // Shift is dead.
4650 AddUsesToWorkList(I);
4656 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4657 // preferable because it allows the C<<Y expression to be hoisted out
4658 // of a loop if Y is invariant and X is not.
4659 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4660 I.isEquality() && !Shift->isArithmeticShift() &&
4661 isa<Instruction>(Shift->getOperand(0))) {
4664 if (Shift->getOpcode() == Instruction::LShr) {
4665 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4668 // Insert a logical shift.
4669 NS = new ShiftInst(Instruction::LShr, AndCST,
4670 Shift->getOperand(1), "tmp");
4672 InsertNewInstBefore(cast<Instruction>(NS), I);
4674 // Compute X & (C << Y).
4675 Instruction *NewAnd = BinaryOperator::createAnd(
4676 Shift->getOperand(0), NS, LHSI->getName());
4677 InsertNewInstBefore(NewAnd, I);
4679 I.setOperand(0, NewAnd);
4685 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
4686 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4687 if (I.isEquality()) {
4688 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4690 // Check that the shift amount is in range. If not, don't perform
4691 // undefined shifts. When the shift is visited it will be
4693 if (ShAmt->getZExtValue() >= TypeBits)
4696 // If we are comparing against bits always shifted out, the
4697 // comparison cannot succeed.
4699 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4700 if (Comp != CI) {// Comparing against a bit that we know is zero.
4701 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4702 Constant *Cst = ConstantBool::get(IsICMP_NE);
4703 return ReplaceInstUsesWith(I, Cst);
4706 if (LHSI->hasOneUse()) {
4707 // Otherwise strength reduce the shift into an and.
4708 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4709 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4710 Constant *Mask = ConstantInt::get(CI->getType(), Val);
4713 BinaryOperator::createAnd(LHSI->getOperand(0),
4714 Mask, LHSI->getName()+".mask");
4715 Value *And = InsertNewInstBefore(AndI, I);
4716 return new ICmpInst(I.getPredicate(), And,
4717 ConstantExpr::getLShr(CI, ShAmt));
4723 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
4724 case Instruction::AShr:
4725 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4726 if (I.isEquality()) {
4727 // Check that the shift amount is in range. If not, don't perform
4728 // undefined shifts. When the shift is visited it will be
4730 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4731 if (ShAmt->getZExtValue() >= TypeBits)
4734 // If we are comparing against bits always shifted out, the
4735 // comparison cannot succeed.
4737 if (LHSI->getOpcode() == Instruction::LShr)
4738 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4741 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4744 if (Comp != CI) {// Comparing against a bit that we know is zero.
4745 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4746 Constant *Cst = ConstantBool::get(IsICMP_NE);
4747 return ReplaceInstUsesWith(I, Cst);
4750 if (LHSI->hasOneUse() || CI->isNullValue()) {
4751 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4753 // Otherwise strength reduce the shift into an and.
4754 uint64_t Val = ~0ULL; // All ones.
4755 Val <<= ShAmtVal; // Shift over to the right spot.
4756 Val &= ~0ULL >> (64-TypeBits);
4757 Constant *Mask = ConstantInt::get(CI->getType(), Val);
4760 BinaryOperator::createAnd(LHSI->getOperand(0),
4761 Mask, LHSI->getName()+".mask");
4762 Value *And = InsertNewInstBefore(AndI, I);
4763 return new ICmpInst(I.getPredicate(), And,
4764 ConstantExpr::getShl(CI, ShAmt));
4770 case Instruction::SDiv:
4771 case Instruction::UDiv:
4772 // Fold: icmp pred ([us]div X, C1), C2 -> range test
4773 // Fold this div into the comparison, producing a range check.
4774 // Determine, based on the divide type, what the range is being
4775 // checked. If there is an overflow on the low or high side, remember
4776 // it, otherwise compute the range [low, hi) bounding the new value.
4777 // See: InsertRangeTest above for the kinds of replacements possible.
4778 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4779 // FIXME: If the operand types don't match the type of the divide
4780 // then don't attempt this transform. The code below doesn't have the
4781 // logic to deal with a signed divide and an unsigned compare (and
4782 // vice versa). This is because (x /s C1) <s C2 produces different
4783 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4784 // (x /u C1) <u C2. Simply casting the operands and result won't
4785 // work. :( The if statement below tests that condition and bails
4787 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4788 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4791 // Initialize the variables that will indicate the nature of the
4793 bool LoOverflow = false, HiOverflow = false;
4794 ConstantInt *LoBound = 0, *HiBound = 0;
4796 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4797 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4798 // C2 (CI). By solving for X we can turn this into a range check
4799 // instead of computing a divide.
4801 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4803 // Determine if the product overflows by seeing if the product is
4804 // not equal to the divide. Make sure we do the same kind of divide
4805 // as in the LHS instruction that we're folding.
4806 bool ProdOV = !DivRHS->isNullValue() &&
4807 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
4808 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4810 // Get the ICmp opcode
4811 ICmpInst::Predicate predicate = I.getPredicate();
4813 if (DivRHS->isNullValue()) {
4814 // Don't hack on divide by zeros!
4815 } else if (!DivIsSigned) { // udiv
4817 LoOverflow = ProdOV;
4818 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4819 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4820 if (CI->isNullValue()) { // (X / pos) op 0
4822 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4824 } else if (isPositive(CI)) { // (X / pos) op pos
4826 LoOverflow = ProdOV;
4827 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4828 } else { // (X / pos) op neg
4829 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4830 LoOverflow = AddWithOverflow(LoBound, Prod,
4831 cast<ConstantInt>(DivRHSH));
4833 HiOverflow = ProdOV;
4835 } else { // Divisor is < 0.
4836 if (CI->isNullValue()) { // (X / neg) op 0
4837 LoBound = AddOne(DivRHS);
4838 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4839 if (HiBound == DivRHS)
4840 LoBound = 0; // - INTMIN = INTMIN
4841 } else if (isPositive(CI)) { // (X / neg) op pos
4842 HiOverflow = LoOverflow = ProdOV;
4844 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4845 HiBound = AddOne(Prod);
4846 } else { // (X / neg) op neg
4848 LoOverflow = HiOverflow = ProdOV;
4849 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4852 // Dividing by a negate swaps the condition.
4853 predicate = ICmpInst::getSwappedPredicate(predicate);
4857 Value *X = LHSI->getOperand(0);
4858 switch (predicate) {
4859 default: assert(0 && "Unhandled icmp opcode!");
4860 case ICmpInst::ICMP_EQ:
4861 if (LoOverflow && HiOverflow)
4862 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4863 else if (HiOverflow)
4864 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4865 ICmpInst::ICMP_UGE, X, LoBound);
4866 else if (LoOverflow)
4867 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4868 ICmpInst::ICMP_ULT, X, HiBound);
4870 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4872 case ICmpInst::ICMP_NE:
4873 if (LoOverflow && HiOverflow)
4874 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4875 else if (HiOverflow)
4876 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4877 ICmpInst::ICMP_ULT, X, LoBound);
4878 else if (LoOverflow)
4879 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4880 ICmpInst::ICMP_UGE, X, HiBound);
4882 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4884 case ICmpInst::ICMP_ULT:
4885 case ICmpInst::ICMP_SLT:
4887 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4888 return new ICmpInst(predicate, X, LoBound);
4889 case ICmpInst::ICMP_UGT:
4890 case ICmpInst::ICMP_SGT:
4892 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4893 if (predicate == ICmpInst::ICMP_UGT)
4894 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4896 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4903 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4904 if (I.isEquality()) {
4905 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4907 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4908 // the second operand is a constant, simplify a bit.
4909 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4910 switch (BO->getOpcode()) {
4911 case Instruction::SRem:
4912 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4913 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4915 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4916 if (V > 1 && isPowerOf2_64(V)) {
4917 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4918 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4919 return new ICmpInst(I.getPredicate(), NewRem,
4920 Constant::getNullValue(BO->getType()));
4924 case Instruction::Add:
4925 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4926 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4927 if (BO->hasOneUse())
4928 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4929 ConstantExpr::getSub(CI, BOp1C));
4930 } else if (CI->isNullValue()) {
4931 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4932 // efficiently invertible, or if the add has just this one use.
4933 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4935 if (Value *NegVal = dyn_castNegVal(BOp1))
4936 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4937 else if (Value *NegVal = dyn_castNegVal(BOp0))
4938 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4939 else if (BO->hasOneUse()) {
4940 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4942 InsertNewInstBefore(Neg, I);
4943 return new ICmpInst(I.getPredicate(), BOp0, Neg);
4947 case Instruction::Xor:
4948 // For the xor case, we can xor two constants together, eliminating
4949 // the explicit xor.
4950 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4951 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4952 ConstantExpr::getXor(CI, BOC));
4955 case Instruction::Sub:
4956 // Replace (([sub|xor] A, B) != 0) with (A != B)
4957 if (CI->isNullValue())
4958 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4962 case Instruction::Or:
4963 // If bits are being or'd in that are not present in the constant we
4964 // are comparing against, then the comparison could never succeed!
4965 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4966 Constant *NotCI = ConstantExpr::getNot(CI);
4967 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4968 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
4972 case Instruction::And:
4973 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4974 // If bits are being compared against that are and'd out, then the
4975 // comparison can never succeed!
4976 if (!ConstantExpr::getAnd(CI,
4977 ConstantExpr::getNot(BOC))->isNullValue())
4978 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
4980 // If we have ((X & C) == C), turn it into ((X & C) != 0).
4981 if (CI == BOC && isOneBitSet(CI))
4982 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4983 ICmpInst::ICMP_NE, Op0,
4984 Constant::getNullValue(CI->getType()));
4986 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
4987 if (isSignBit(BOC)) {
4988 Value *X = BO->getOperand(0);
4989 Constant *Zero = Constant::getNullValue(X->getType());
4990 ICmpInst::Predicate pred = isICMP_NE ?
4991 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4992 return new ICmpInst(pred, X, Zero);
4995 // ((X & ~7) == 0) --> X < 8
4996 if (CI->isNullValue() && isHighOnes(BOC)) {
4997 Value *X = BO->getOperand(0);
4998 Constant *NegX = ConstantExpr::getNeg(BOC);
4999 ICmpInst::Predicate pred = isICMP_NE ?
5000 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5001 return new ICmpInst(pred, X, NegX);
5007 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5008 // Handle set{eq|ne} <intrinsic>, intcst.
5009 switch (II->getIntrinsicID()) {
5011 case Intrinsic::bswap_i16:
5012 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5013 WorkList.push_back(II); // Dead?
5014 I.setOperand(0, II->getOperand(1));
5015 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5016 ByteSwap_16(CI->getZExtValue())));
5018 case Intrinsic::bswap_i32:
5019 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5020 WorkList.push_back(II); // Dead?
5021 I.setOperand(0, II->getOperand(1));
5022 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5023 ByteSwap_32(CI->getZExtValue())));
5025 case Intrinsic::bswap_i64:
5026 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5027 WorkList.push_back(II); // Dead?
5028 I.setOperand(0, II->getOperand(1));
5029 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5030 ByteSwap_64(CI->getZExtValue())));
5034 } else { // Not a ICMP_EQ/ICMP_NE
5035 // If the LHS is a cast from an integral value of the same size, then
5036 // since we know the RHS is a constant, try to simlify.
5037 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5038 Value *CastOp = Cast->getOperand(0);
5039 const Type *SrcTy = CastOp->getType();
5040 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5041 if (SrcTy->isInteger() &&
5042 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5043 // If this is an unsigned comparison, try to make the comparison use
5044 // smaller constant values.
5045 switch (I.getPredicate()) {
5047 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5048 ConstantInt *CUI = cast<ConstantInt>(CI);
5049 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5050 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5051 ConstantInt::get(SrcTy, -1));
5054 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5055 ConstantInt *CUI = cast<ConstantInt>(CI);
5056 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5057 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5058 Constant::getNullValue(SrcTy));
5068 // Handle icmp with constant RHS
5069 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5070 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5071 switch (LHSI->getOpcode()) {
5072 case Instruction::GetElementPtr:
5073 if (RHSC->isNullValue()) {
5074 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5075 bool isAllZeros = true;
5076 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5077 if (!isa<Constant>(LHSI->getOperand(i)) ||
5078 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5083 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5084 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5088 case Instruction::PHI:
5089 if (Instruction *NV = FoldOpIntoPhi(I))
5092 case Instruction::Select:
5093 // If either operand of the select is a constant, we can fold the
5094 // comparison into the select arms, which will cause one to be
5095 // constant folded and the select turned into a bitwise or.
5096 Value *Op1 = 0, *Op2 = 0;
5097 if (LHSI->hasOneUse()) {
5098 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5099 // Fold the known value into the constant operand.
5100 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5101 // Insert a new ICmp of the other select operand.
5102 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5103 LHSI->getOperand(2), RHSC,
5105 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5106 // Fold the known value into the constant operand.
5107 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5108 // Insert a new ICmp of the other select operand.
5109 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5110 LHSI->getOperand(1), RHSC,
5116 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5121 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5122 if (User *GEP = dyn_castGetElementPtr(Op0))
5123 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5125 if (User *GEP = dyn_castGetElementPtr(Op1))
5126 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5127 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5130 // Test to see if the operands of the icmp are casted versions of other
5131 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5133 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5134 if (isa<PointerType>(Op0->getType()) &&
5135 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5136 // We keep moving the cast from the left operand over to the right
5137 // operand, where it can often be eliminated completely.
5138 Op0 = CI->getOperand(0);
5140 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5141 // so eliminate it as well.
5142 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5143 Op1 = CI2->getOperand(0);
5145 // If Op1 is a constant, we can fold the cast into the constant.
5146 if (Op0->getType() != Op1->getType())
5147 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5148 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5150 // Otherwise, cast the RHS right before the icmp
5151 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5153 return new ICmpInst(I.getPredicate(), Op0, Op1);
5157 if (isa<CastInst>(Op0)) {
5158 // Handle the special case of: icmp (cast bool to X), <cst>
5159 // This comes up when you have code like
5162 // For generality, we handle any zero-extension of any operand comparison
5163 // with a constant or another cast from the same type.
5164 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5165 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5169 if (I.isEquality()) {
5170 Value *A, *B, *C, *D;
5171 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5172 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5173 Value *OtherVal = A == Op1 ? B : A;
5174 return new ICmpInst(I.getPredicate(), OtherVal,
5175 Constant::getNullValue(A->getType()));
5178 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5179 // A^c1 == C^c2 --> A == C^(c1^c2)
5180 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5181 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5182 if (Op1->hasOneUse()) {
5183 Constant *NC = ConstantExpr::getXor(C1, C2);
5184 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5185 return new ICmpInst(I.getPredicate(), A,
5186 InsertNewInstBefore(Xor, I));
5189 // A^B == A^D -> B == D
5190 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5191 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5192 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5193 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5197 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5198 (A == Op0 || B == Op0)) {
5199 // A == (A^B) -> B == 0
5200 Value *OtherVal = A == Op0 ? B : A;
5201 return new ICmpInst(I.getPredicate(), OtherVal,
5202 Constant::getNullValue(A->getType()));
5204 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5205 // (A-B) == A -> B == 0
5206 return new ICmpInst(I.getPredicate(), B,
5207 Constant::getNullValue(B->getType()));
5209 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5210 // A == (A-B) -> B == 0
5211 return new ICmpInst(I.getPredicate(), B,
5212 Constant::getNullValue(B->getType()));
5215 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5216 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5217 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5218 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5219 Value *X = 0, *Y = 0, *Z = 0;
5222 X = B; Y = D; Z = A;
5223 } else if (A == D) {
5224 X = B; Y = C; Z = A;
5225 } else if (B == C) {
5226 X = A; Y = D; Z = B;
5227 } else if (B == D) {
5228 X = A; Y = C; Z = B;
5231 if (X) { // Build (X^Y) & Z
5232 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5233 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5234 I.setOperand(0, Op1);
5235 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5240 return Changed ? &I : 0;
5243 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5244 // We only handle extending casts so far.
5246 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5247 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5248 Value *LHSCIOp = LHSCI->getOperand(0);
5249 const Type *SrcTy = LHSCIOp->getType();
5250 const Type *DestTy = LHSCI->getType();
5253 // We only handle extension cast instructions, so far. Enforce this.
5254 if (LHSCI->getOpcode() != Instruction::ZExt &&
5255 LHSCI->getOpcode() != Instruction::SExt)
5258 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5259 bool isSignedCmp = ICI.isSignedPredicate();
5261 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5262 // Not an extension from the same type?
5263 RHSCIOp = CI->getOperand(0);
5264 if (RHSCIOp->getType() != LHSCIOp->getType())
5267 // Okay, just insert a compare of the reduced operands now!
5268 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5271 // If we aren't dealing with a constant on the RHS, exit early
5272 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5276 // Compute the constant that would happen if we truncated to SrcTy then
5277 // reextended to DestTy.
5278 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5279 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5281 // If the re-extended constant didn't change...
5283 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5284 // For example, we might have:
5285 // %A = sext short %X to uint
5286 // %B = icmp ugt uint %A, 1330
5287 // It is incorrect to transform this into
5288 // %B = icmp ugt short %X, 1330
5289 // because %A may have negative value.
5291 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5292 // OR operation is EQ/NE.
5293 if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5294 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5299 // The re-extended constant changed so the constant cannot be represented
5300 // in the shorter type. Consequently, we cannot emit a simple comparison.
5302 // First, handle some easy cases. We know the result cannot be equal at this
5303 // point so handle the ICI.isEquality() cases
5304 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5305 return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5306 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5307 return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5309 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5310 // should have been folded away previously and not enter in here.
5313 // We're performing a signed comparison.
5314 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5315 Result = ConstantBool::getFalse(); // X < (small) --> false
5317 Result = ConstantBool::getTrue(); // X < (large) --> true
5319 // We're performing an unsigned comparison.
5321 // We're performing an unsigned comp with a sign extended value.
5322 // This is true if the input is >= 0. [aka >s -1]
5323 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5324 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5325 NegOne, ICI.getName()), ICI);
5327 // Unsigned extend & unsigned compare -> always true.
5328 Result = ConstantBool::getTrue();
5332 // Finally, return the value computed.
5333 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5334 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5335 return ReplaceInstUsesWith(ICI, Result);
5337 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5338 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5339 "ICmp should be folded!");
5340 if (Constant *CI = dyn_cast<Constant>(Result))
5341 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5343 return BinaryOperator::createNot(Result);
5347 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5348 assert(I.getOperand(1)->getType() == Type::Int8Ty);
5349 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5351 // shl X, 0 == X and shr X, 0 == X
5352 // shl 0, X == 0 and shr 0, X == 0
5353 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
5354 Op0 == Constant::getNullValue(Op0->getType()))
5355 return ReplaceInstUsesWith(I, Op0);
5357 if (isa<UndefValue>(Op0)) {
5358 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5359 return ReplaceInstUsesWith(I, Op0);
5360 else // undef << X -> 0, undef >>u X -> 0
5361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5363 if (isa<UndefValue>(Op1)) {
5364 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5365 return ReplaceInstUsesWith(I, Op0);
5366 else // X << undef, X >>u undef -> 0
5367 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5370 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5371 if (I.getOpcode() == Instruction::AShr)
5372 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5373 if (CSI->isAllOnesValue())
5374 return ReplaceInstUsesWith(I, CSI);
5376 // Try to fold constant and into select arguments.
5377 if (isa<Constant>(Op0))
5378 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5379 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5382 // See if we can turn a signed shr into an unsigned shr.
5383 if (I.isArithmeticShift()) {
5384 if (MaskedValueIsZero(Op0,
5385 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5386 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5390 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5391 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5396 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5398 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5399 bool isSignedShift = I.getOpcode() == Instruction::AShr;
5400 bool isUnsignedShift = !isSignedShift;
5402 // See if we can simplify any instructions used by the instruction whose sole
5403 // purpose is to compute bits we don't care about.
5404 uint64_t KnownZero, KnownOne;
5405 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5406 KnownZero, KnownOne))
5409 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5410 // of a signed value.
5412 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5413 if (Op1->getZExtValue() >= TypeBits) {
5414 if (isUnsignedShift || isLeftShift)
5415 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5417 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
5422 // ((X*C1) << C2) == (X * (C1 << C2))
5423 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5424 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5425 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5426 return BinaryOperator::createMul(BO->getOperand(0),
5427 ConstantExpr::getShl(BOOp, Op1));
5429 // Try to fold constant and into select arguments.
5430 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5431 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5433 if (isa<PHINode>(Op0))
5434 if (Instruction *NV = FoldOpIntoPhi(I))
5437 if (Op0->hasOneUse()) {
5438 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5439 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5442 switch (Op0BO->getOpcode()) {
5444 case Instruction::Add:
5445 case Instruction::And:
5446 case Instruction::Or:
5447 case Instruction::Xor:
5448 // These operators commute.
5449 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
5450 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5451 match(Op0BO->getOperand(1),
5452 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5453 Instruction *YS = new ShiftInst(Instruction::Shl,
5454 Op0BO->getOperand(0), Op1,
5456 InsertNewInstBefore(YS, I); // (Y << C)
5458 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5459 Op0BO->getOperand(1)->getName());
5460 InsertNewInstBefore(X, I); // (X + (Y << C))
5461 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5462 C2 = ConstantExpr::getShl(C2, Op1);
5463 return BinaryOperator::createAnd(X, C2);
5466 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5467 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5468 match(Op0BO->getOperand(1),
5469 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5470 m_ConstantInt(CC))) && V2 == Op1 &&
5471 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5472 Instruction *YS = new ShiftInst(Instruction::Shl,
5473 Op0BO->getOperand(0), Op1,
5475 InsertNewInstBefore(YS, I); // (Y << C)
5477 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5478 V1->getName()+".mask");
5479 InsertNewInstBefore(XM, I); // X & (CC << C)
5481 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5485 case Instruction::Sub:
5486 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5487 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5488 match(Op0BO->getOperand(0),
5489 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5490 Instruction *YS = new ShiftInst(Instruction::Shl,
5491 Op0BO->getOperand(1), Op1,
5493 InsertNewInstBefore(YS, I); // (Y << C)
5495 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5496 Op0BO->getOperand(0)->getName());
5497 InsertNewInstBefore(X, I); // (X + (Y << C))
5498 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5499 C2 = ConstantExpr::getShl(C2, Op1);
5500 return BinaryOperator::createAnd(X, C2);
5503 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
5504 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5505 match(Op0BO->getOperand(0),
5506 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5507 m_ConstantInt(CC))) && V2 == Op1 &&
5508 cast<BinaryOperator>(Op0BO->getOperand(0))
5509 ->getOperand(0)->hasOneUse()) {
5510 Instruction *YS = new ShiftInst(Instruction::Shl,
5511 Op0BO->getOperand(1), Op1,
5513 InsertNewInstBefore(YS, I); // (Y << C)
5515 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5516 V1->getName()+".mask");
5517 InsertNewInstBefore(XM, I); // X & (CC << C)
5519 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5526 // If the operand is an bitwise operator with a constant RHS, and the
5527 // shift is the only use, we can pull it out of the shift.
5528 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5529 bool isValid = true; // Valid only for And, Or, Xor
5530 bool highBitSet = false; // Transform if high bit of constant set?
5532 switch (Op0BO->getOpcode()) {
5533 default: isValid = false; break; // Do not perform transform!
5534 case Instruction::Add:
5535 isValid = isLeftShift;
5537 case Instruction::Or:
5538 case Instruction::Xor:
5541 case Instruction::And:
5546 // If this is a signed shift right, and the high bit is modified
5547 // by the logical operation, do not perform the transformation.
5548 // The highBitSet boolean indicates the value of the high bit of
5549 // the constant which would cause it to be modified for this
5552 if (isValid && !isLeftShift && isSignedShift) {
5553 uint64_t Val = Op0C->getZExtValue();
5554 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5558 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5560 Instruction *NewShift =
5561 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5564 InsertNewInstBefore(NewShift, I);
5566 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5573 // Find out if this is a shift of a shift by a constant.
5574 ShiftInst *ShiftOp = 0;
5575 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5577 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5578 // If this is a noop-integer cast of a shift instruction, use the shift.
5579 if (isa<ShiftInst>(CI->getOperand(0))) {
5580 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5584 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5585 // Find the operands and properties of the input shift. Note that the
5586 // signedness of the input shift may differ from the current shift if there
5587 // is a noop cast between the two.
5588 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5589 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5590 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5592 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5594 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5595 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5597 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5598 if (isLeftShift == isShiftOfLeftShift) {
5599 // Do not fold these shifts if the first one is signed and the second one
5600 // is unsigned and this is a right shift. Further, don't do any folding
5602 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5605 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5606 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5607 Amt = Op0->getType()->getPrimitiveSizeInBits();
5609 Value *Op = ShiftOp->getOperand(0);
5610 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5611 ConstantInt::get(Type::Int8Ty, Amt));
5612 if (I.getType() == ShiftResult->getType())
5614 InsertNewInstBefore(ShiftResult, I);
5615 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5618 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5619 // signed types, we can only support the (A >> c1) << c2 configuration,
5620 // because it can not turn an arbitrary bit of A into a sign bit.
5621 if (isUnsignedShift || isLeftShift) {
5622 // Calculate bitmask for what gets shifted off the edge.
5623 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5625 C = ConstantExpr::getShl(C, ShiftAmt1C);
5627 C = ConstantExpr::getLShr(C, ShiftAmt1C);
5629 Value *Op = ShiftOp->getOperand(0);
5632 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5633 InsertNewInstBefore(Mask, I);
5635 // Figure out what flavor of shift we should use...
5636 if (ShiftAmt1 == ShiftAmt2) {
5637 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
5638 } else if (ShiftAmt1 < ShiftAmt2) {
5639 return new ShiftInst(I.getOpcode(), Mask,
5640 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
5641 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5642 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5643 return new ShiftInst(Instruction::LShr, Mask,
5644 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5646 return new ShiftInst(ShiftOp->getOpcode(), Mask,
5647 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5650 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
5651 Instruction *Shift =
5652 new ShiftInst(ShiftOp->getOpcode(), Mask,
5653 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5654 InsertNewInstBefore(Shift, I);
5656 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5657 C = ConstantExpr::getShl(C, Op1);
5658 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5661 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
5662 // this case, C1 == C2 and C1 is 8, 16, or 32.
5663 if (ShiftAmt1 == ShiftAmt2) {
5664 const Type *SExtType = 0;
5665 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5666 case 8 : SExtType = Type::Int8Ty; break;
5667 case 16: SExtType = Type::Int16Ty; break;
5668 case 32: SExtType = Type::Int32Ty; break;
5672 Instruction *NewTrunc =
5673 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5674 InsertNewInstBefore(NewTrunc, I);
5675 return new SExtInst(NewTrunc, I.getType());
5684 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5685 /// expression. If so, decompose it, returning some value X, such that Val is
5688 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5690 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5691 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5692 Offset = CI->getZExtValue();
5694 return ConstantInt::get(Type::Int32Ty, 0);
5695 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5696 if (I->getNumOperands() == 2) {
5697 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5698 if (I->getOpcode() == Instruction::Shl) {
5699 // This is a value scaled by '1 << the shift amt'.
5700 Scale = 1U << CUI->getZExtValue();
5702 return I->getOperand(0);
5703 } else if (I->getOpcode() == Instruction::Mul) {
5704 // This value is scaled by 'CUI'.
5705 Scale = CUI->getZExtValue();
5707 return I->getOperand(0);
5708 } else if (I->getOpcode() == Instruction::Add) {
5709 // We have X+C. Check to see if we really have (X*C2)+C1,
5710 // where C1 is divisible by C2.
5713 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5714 Offset += CUI->getZExtValue();
5715 if (SubScale > 1 && (Offset % SubScale == 0)) {
5724 // Otherwise, we can't look past this.
5731 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5732 /// try to eliminate the cast by moving the type information into the alloc.
5733 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5734 AllocationInst &AI) {
5735 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5736 if (!PTy) return 0; // Not casting the allocation to a pointer type.
5738 // Remove any uses of AI that are dead.
5739 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5740 std::vector<Instruction*> DeadUsers;
5741 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5742 Instruction *User = cast<Instruction>(*UI++);
5743 if (isInstructionTriviallyDead(User)) {
5744 while (UI != E && *UI == User)
5745 ++UI; // If this instruction uses AI more than once, don't break UI.
5747 // Add operands to the worklist.
5748 AddUsesToWorkList(*User);
5750 DOUT << "IC: DCE: " << *User;
5752 User->eraseFromParent();
5753 removeFromWorkList(User);
5757 // Get the type really allocated and the type casted to.
5758 const Type *AllocElTy = AI.getAllocatedType();
5759 const Type *CastElTy = PTy->getElementType();
5760 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5762 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5763 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5764 if (CastElTyAlign < AllocElTyAlign) return 0;
5766 // If the allocation has multiple uses, only promote it if we are strictly
5767 // increasing the alignment of the resultant allocation. If we keep it the
5768 // same, we open the door to infinite loops of various kinds.
5769 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5771 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5772 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5773 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5775 // See if we can satisfy the modulus by pulling a scale out of the array
5777 unsigned ArraySizeScale, ArrayOffset;
5778 Value *NumElements = // See if the array size is a decomposable linear expr.
5779 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5781 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5783 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5784 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
5786 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5791 // If the allocation size is constant, form a constant mul expression
5792 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5793 if (isa<ConstantInt>(NumElements))
5794 Amt = ConstantExpr::getMul(
5795 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5796 // otherwise multiply the amount and the number of elements
5797 else if (Scale != 1) {
5798 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5799 Amt = InsertNewInstBefore(Tmp, AI);
5803 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5804 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5805 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5806 Amt = InsertNewInstBefore(Tmp, AI);
5809 std::string Name = AI.getName(); AI.setName("");
5810 AllocationInst *New;
5811 if (isa<MallocInst>(AI))
5812 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5814 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5815 InsertNewInstBefore(New, AI);
5817 // If the allocation has multiple uses, insert a cast and change all things
5818 // that used it to use the new cast. This will also hack on CI, but it will
5820 if (!AI.hasOneUse()) {
5821 AddUsesToWorkList(AI);
5822 // New is the allocation instruction, pointer typed. AI is the original
5823 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5824 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5825 InsertNewInstBefore(NewCast, AI);
5826 AI.replaceAllUsesWith(NewCast);
5828 return ReplaceInstUsesWith(CI, New);
5831 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5832 /// and return it without inserting any new casts. This is used by code that
5833 /// tries to decide whether promoting or shrinking integer operations to wider
5834 /// or smaller types will allow us to eliminate a truncate or extend.
5835 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5836 int &NumCastsRemoved) {
5837 if (isa<Constant>(V)) return true;
5839 Instruction *I = dyn_cast<Instruction>(V);
5840 if (!I || !I->hasOneUse()) return false;
5842 switch (I->getOpcode()) {
5843 case Instruction::And:
5844 case Instruction::Or:
5845 case Instruction::Xor:
5846 // These operators can all arbitrarily be extended or truncated.
5847 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5848 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5849 case Instruction::AShr:
5850 case Instruction::LShr:
5851 case Instruction::Shl:
5852 // If this is just a bitcast changing the sign of the operation, we can
5853 // convert if the operand can be converted.
5854 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5855 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5857 case Instruction::Trunc:
5858 case Instruction::ZExt:
5859 case Instruction::SExt:
5860 case Instruction::BitCast:
5861 // If this is a cast from the destination type, we can trivially eliminate
5862 // it, and this will remove a cast overall.
5863 if (I->getOperand(0)->getType() == Ty) {
5864 // If the first operand is itself a cast, and is eliminable, do not count
5865 // this as an eliminable cast. We would prefer to eliminate those two
5867 if (isa<CastInst>(I->getOperand(0)))
5875 // TODO: Can handle more cases here.
5882 /// EvaluateInDifferentType - Given an expression that
5883 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5884 /// evaluate the expression.
5885 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5887 if (Constant *C = dyn_cast<Constant>(V))
5888 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5890 // Otherwise, it must be an instruction.
5891 Instruction *I = cast<Instruction>(V);
5892 Instruction *Res = 0;
5893 switch (I->getOpcode()) {
5894 case Instruction::And:
5895 case Instruction::Or:
5896 case Instruction::Xor: {
5897 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5898 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5899 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5900 LHS, RHS, I->getName());
5903 case Instruction::AShr:
5904 case Instruction::LShr:
5905 case Instruction::Shl: {
5906 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5907 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5908 I->getOperand(1), I->getName());
5911 case Instruction::Trunc:
5912 case Instruction::ZExt:
5913 case Instruction::SExt:
5914 case Instruction::BitCast:
5915 // If the source type of the cast is the type we're trying for then we can
5916 // just return the source. There's no need to insert it because its not new.
5917 if (I->getOperand(0)->getType() == Ty)
5918 return I->getOperand(0);
5920 // Some other kind of cast, which shouldn't happen, so just ..
5923 // TODO: Can handle more cases here.
5924 assert(0 && "Unreachable!");
5928 return InsertNewInstBefore(Res, *I);
5931 /// @brief Implement the transforms common to all CastInst visitors.
5932 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5933 Value *Src = CI.getOperand(0);
5935 // Casting undef to anything results in undef so might as just replace it and
5936 // get rid of the cast.
5937 if (isa<UndefValue>(Src)) // cast undef -> undef
5938 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5940 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5941 // eliminate it now.
5942 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5943 if (Instruction::CastOps opc =
5944 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5945 // The first cast (CSrc) is eliminable so we need to fix up or replace
5946 // the second cast (CI). CSrc will then have a good chance of being dead.
5947 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5951 // If casting the result of a getelementptr instruction with no offset, turn
5952 // this into a cast of the original pointer!
5954 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5955 bool AllZeroOperands = true;
5956 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5957 if (!isa<Constant>(GEP->getOperand(i)) ||
5958 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5959 AllZeroOperands = false;
5962 if (AllZeroOperands) {
5963 // Changing the cast operand is usually not a good idea but it is safe
5964 // here because the pointer operand is being replaced with another
5965 // pointer operand so the opcode doesn't need to change.
5966 CI.setOperand(0, GEP->getOperand(0));
5971 // If we are casting a malloc or alloca to a pointer to a type of the same
5972 // size, rewrite the allocation instruction to allocate the "right" type.
5973 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5974 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5977 // If we are casting a select then fold the cast into the select
5978 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5979 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5982 // If we are casting a PHI then fold the cast into the PHI
5983 if (isa<PHINode>(Src))
5984 if (Instruction *NV = FoldOpIntoPhi(CI))
5990 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5991 /// integers. This function implements the common transforms for all those
5993 /// @brief Implement the transforms common to CastInst with integer operands
5994 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5995 if (Instruction *Result = commonCastTransforms(CI))
5998 Value *Src = CI.getOperand(0);
5999 const Type *SrcTy = Src->getType();
6000 const Type *DestTy = CI.getType();
6001 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6002 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6004 // See if we can simplify any instructions used by the LHS whose sole
6005 // purpose is to compute bits we don't care about.
6006 uint64_t KnownZero = 0, KnownOne = 0;
6007 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6008 KnownZero, KnownOne))
6011 // If the source isn't an instruction or has more than one use then we
6012 // can't do anything more.
6013 Instruction *SrcI = dyn_cast<Instruction>(Src);
6014 if (!SrcI || !Src->hasOneUse())
6017 // Attempt to propagate the cast into the instruction.
6018 int NumCastsRemoved = 0;
6019 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6020 // If this cast is a truncate, evaluting in a different type always
6021 // eliminates the cast, so it is always a win. If this is a noop-cast
6022 // this just removes a noop cast which isn't pointful, but simplifies
6023 // the code. If this is a zero-extension, we need to do an AND to
6024 // maintain the clear top-part of the computation, so we require that
6025 // the input have eliminated at least one cast. If this is a sign
6026 // extension, we insert two new casts (to do the extension) so we
6027 // require that two casts have been eliminated.
6028 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6030 switch (CI.getOpcode()) {
6031 case Instruction::Trunc:
6034 case Instruction::ZExt:
6035 DoXForm = NumCastsRemoved >= 1;
6037 case Instruction::SExt:
6038 DoXForm = NumCastsRemoved >= 2;
6040 case Instruction::BitCast:
6044 // All the others use floating point so we shouldn't actually
6045 // get here because of the check above.
6046 assert(!"Unknown cast type .. unreachable");
6052 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6053 CI.getOpcode() == Instruction::SExt);
6054 assert(Res->getType() == DestTy);
6055 switch (CI.getOpcode()) {
6056 default: assert(0 && "Unknown cast type!");
6057 case Instruction::Trunc:
6058 case Instruction::BitCast:
6059 // Just replace this cast with the result.
6060 return ReplaceInstUsesWith(CI, Res);
6061 case Instruction::ZExt: {
6062 // We need to emit an AND to clear the high bits.
6063 assert(SrcBitSize < DestBitSize && "Not a zext?");
6065 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6066 if (DestBitSize < 64)
6067 C = ConstantExpr::getTrunc(C, DestTy);
6068 return BinaryOperator::createAnd(Res, C);
6070 case Instruction::SExt:
6071 // We need to emit a cast to truncate, then a cast to sext.
6072 return CastInst::create(Instruction::SExt,
6073 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6079 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6080 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6082 switch (SrcI->getOpcode()) {
6083 case Instruction::Add:
6084 case Instruction::Mul:
6085 case Instruction::And:
6086 case Instruction::Or:
6087 case Instruction::Xor:
6088 // If we are discarding information, or just changing the sign,
6090 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6091 // Don't insert two casts if they cannot be eliminated. We allow
6092 // two casts to be inserted if the sizes are the same. This could
6093 // only be converting signedness, which is a noop.
6094 if (DestBitSize == SrcBitSize ||
6095 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6096 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6097 Instruction::CastOps opcode = CI.getOpcode();
6098 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6099 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6100 return BinaryOperator::create(
6101 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6105 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6106 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6107 SrcI->getOpcode() == Instruction::Xor &&
6108 Op1 == ConstantBool::getTrue() &&
6109 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6110 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6111 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6114 case Instruction::SDiv:
6115 case Instruction::UDiv:
6116 case Instruction::SRem:
6117 case Instruction::URem:
6118 // If we are just changing the sign, rewrite.
6119 if (DestBitSize == SrcBitSize) {
6120 // Don't insert two casts if they cannot be eliminated. We allow
6121 // two casts to be inserted if the sizes are the same. This could
6122 // only be converting signedness, which is a noop.
6123 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6124 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6125 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6127 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6129 return BinaryOperator::create(
6130 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6135 case Instruction::Shl:
6136 // Allow changing the sign of the source operand. Do not allow
6137 // changing the size of the shift, UNLESS the shift amount is a
6138 // constant. We must not change variable sized shifts to a smaller
6139 // size, because it is undefined to shift more bits out than exist
6141 if (DestBitSize == SrcBitSize ||
6142 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6143 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6144 Instruction::BitCast : Instruction::Trunc);
6145 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6146 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6149 case Instruction::AShr:
6150 // If this is a signed shr, and if all bits shifted in are about to be
6151 // truncated off, turn it into an unsigned shr to allow greater
6153 if (DestBitSize < SrcBitSize &&
6154 isa<ConstantInt>(Op1)) {
6155 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6156 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6157 // Insert the new logical shift right.
6158 return new ShiftInst(Instruction::LShr, Op0, Op1);
6163 case Instruction::ICmp:
6164 // If we are just checking for a icmp eq of a single bit and casting it
6165 // to an integer, then shift the bit to the appropriate place and then
6166 // cast to integer to avoid the comparison.
6167 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6168 uint64_t Op1CV = Op1C->getZExtValue();
6169 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6170 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6171 // cast (X == 1) to int --> X iff X has only the low bit set.
6172 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6173 // cast (X != 0) to int --> X iff X has only the low bit set.
6174 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6175 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6176 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6177 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6178 // If Op1C some other power of two, convert:
6179 uint64_t KnownZero, KnownOne;
6180 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6181 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6183 // This only works for EQ and NE
6184 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6185 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6188 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6189 bool isNE = pred == ICmpInst::ICMP_NE;
6190 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6191 // (X&4) == 2 --> false
6192 // (X&4) != 2 --> true
6193 Constant *Res = ConstantBool::get(isNE);
6194 Res = ConstantExpr::getZExt(Res, CI.getType());
6195 return ReplaceInstUsesWith(CI, Res);
6198 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6201 // Perform a logical shr by shiftamt.
6202 // Insert the shift to put the result in the low bit.
6203 In = InsertNewInstBefore(
6204 new ShiftInst(Instruction::LShr, In,
6205 ConstantInt::get(Type::Int8Ty, ShiftAmt),
6206 In->getName()+".lobit"), CI);
6209 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6210 Constant *One = ConstantInt::get(In->getType(), 1);
6211 In = BinaryOperator::createXor(In, One, "tmp");
6212 InsertNewInstBefore(cast<Instruction>(In), CI);
6215 if (CI.getType() == In->getType())
6216 return ReplaceInstUsesWith(CI, In);
6218 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6227 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6228 if (Instruction *Result = commonIntCastTransforms(CI))
6231 Value *Src = CI.getOperand(0);
6232 const Type *Ty = CI.getType();
6233 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6235 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6236 switch (SrcI->getOpcode()) {
6238 case Instruction::LShr:
6239 // We can shrink lshr to something smaller if we know the bits shifted in
6240 // are already zeros.
6241 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6242 unsigned ShAmt = ShAmtV->getZExtValue();
6244 // Get a mask for the bits shifting in.
6245 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6246 Value* SrcIOp0 = SrcI->getOperand(0);
6247 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6248 if (ShAmt >= DestBitWidth) // All zeros.
6249 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6251 // Okay, we can shrink this. Truncate the input, then return a new
6253 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6254 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6256 } else { // This is a variable shr.
6258 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6259 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6260 // loop-invariant and CSE'd.
6261 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6262 Value *One = ConstantInt::get(SrcI->getType(), 1);
6264 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6265 SrcI->getOperand(1),
6267 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6268 SrcI->getOperand(0),
6270 Value *Zero = Constant::getNullValue(V->getType());
6271 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6281 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6282 // If one of the common conversion will work ..
6283 if (Instruction *Result = commonIntCastTransforms(CI))
6286 Value *Src = CI.getOperand(0);
6288 // If this is a cast of a cast
6289 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6290 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6291 // types and if the sizes are just right we can convert this into a logical
6292 // 'and' which will be much cheaper than the pair of casts.
6293 if (isa<TruncInst>(CSrc)) {
6294 // Get the sizes of the types involved
6295 Value *A = CSrc->getOperand(0);
6296 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6297 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6298 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6299 // If we're actually extending zero bits and the trunc is a no-op
6300 if (MidSize < DstSize && SrcSize == DstSize) {
6301 // Replace both of the casts with an And of the type mask.
6302 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6303 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6305 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6306 // Unfortunately, if the type changed, we need to cast it back.
6307 if (And->getType() != CI.getType()) {
6308 And->setName(CSrc->getName()+".mask");
6309 InsertNewInstBefore(And, CI);
6310 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6320 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6321 return commonIntCastTransforms(CI);
6324 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6325 return commonCastTransforms(CI);
6328 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6329 return commonCastTransforms(CI);
6332 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6333 return commonCastTransforms(CI);
6336 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6337 return commonCastTransforms(CI);
6340 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6341 return commonCastTransforms(CI);
6344 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6345 return commonCastTransforms(CI);
6348 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6349 return commonCastTransforms(CI);
6352 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6353 return commonCastTransforms(CI);
6356 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6358 // If the operands are integer typed then apply the integer transforms,
6359 // otherwise just apply the common ones.
6360 Value *Src = CI.getOperand(0);
6361 const Type *SrcTy = Src->getType();
6362 const Type *DestTy = CI.getType();
6364 if (SrcTy->isInteger() && DestTy->isInteger()) {
6365 if (Instruction *Result = commonIntCastTransforms(CI))
6368 if (Instruction *Result = commonCastTransforms(CI))
6373 // Get rid of casts from one type to the same type. These are useless and can
6374 // be replaced by the operand.
6375 if (DestTy == Src->getType())
6376 return ReplaceInstUsesWith(CI, Src);
6378 // If the source and destination are pointers, and this cast is equivalent to
6379 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6380 // This can enhance SROA and other transforms that want type-safe pointers.
6381 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6382 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6383 const Type *DstElTy = DstPTy->getElementType();
6384 const Type *SrcElTy = SrcPTy->getElementType();
6386 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6387 unsigned NumZeros = 0;
6388 while (SrcElTy != DstElTy &&
6389 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6390 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6391 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6395 // If we found a path from the src to dest, create the getelementptr now.
6396 if (SrcElTy == DstElTy) {
6397 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6398 return new GetElementPtrInst(Src, Idxs);
6403 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6404 if (SVI->hasOneUse()) {
6405 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6406 // a bitconvert to a vector with the same # elts.
6407 if (isa<PackedType>(DestTy) &&
6408 cast<PackedType>(DestTy)->getNumElements() ==
6409 SVI->getType()->getNumElements()) {
6411 // If either of the operands is a cast from CI.getType(), then
6412 // evaluating the shuffle in the casted destination's type will allow
6413 // us to eliminate at least one cast.
6414 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6415 Tmp->getOperand(0)->getType() == DestTy) ||
6416 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6417 Tmp->getOperand(0)->getType() == DestTy)) {
6418 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6419 SVI->getOperand(0), DestTy, &CI);
6420 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6421 SVI->getOperand(1), DestTy, &CI);
6422 // Return a new shuffle vector. Use the same element ID's, as we
6423 // know the vector types match #elts.
6424 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6432 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6434 /// %D = select %cond, %C, %A
6436 /// %C = select %cond, %B, 0
6439 /// Assuming that the specified instruction is an operand to the select, return
6440 /// a bitmask indicating which operands of this instruction are foldable if they
6441 /// equal the other incoming value of the select.
6443 static unsigned GetSelectFoldableOperands(Instruction *I) {
6444 switch (I->getOpcode()) {
6445 case Instruction::Add:
6446 case Instruction::Mul:
6447 case Instruction::And:
6448 case Instruction::Or:
6449 case Instruction::Xor:
6450 return 3; // Can fold through either operand.
6451 case Instruction::Sub: // Can only fold on the amount subtracted.
6452 case Instruction::Shl: // Can only fold on the shift amount.
6453 case Instruction::LShr:
6454 case Instruction::AShr:
6457 return 0; // Cannot fold
6461 /// GetSelectFoldableConstant - For the same transformation as the previous
6462 /// function, return the identity constant that goes into the select.
6463 static Constant *GetSelectFoldableConstant(Instruction *I) {
6464 switch (I->getOpcode()) {
6465 default: assert(0 && "This cannot happen!"); abort();
6466 case Instruction::Add:
6467 case Instruction::Sub:
6468 case Instruction::Or:
6469 case Instruction::Xor:
6470 return Constant::getNullValue(I->getType());
6471 case Instruction::Shl:
6472 case Instruction::LShr:
6473 case Instruction::AShr:
6474 return Constant::getNullValue(Type::Int8Ty);
6475 case Instruction::And:
6476 return ConstantInt::getAllOnesValue(I->getType());
6477 case Instruction::Mul:
6478 return ConstantInt::get(I->getType(), 1);
6482 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6483 /// have the same opcode and only one use each. Try to simplify this.
6484 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6486 if (TI->getNumOperands() == 1) {
6487 // If this is a non-volatile load or a cast from the same type,
6490 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6493 return 0; // unknown unary op.
6496 // Fold this by inserting a select from the input values.
6497 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6498 FI->getOperand(0), SI.getName()+".v");
6499 InsertNewInstBefore(NewSI, SI);
6500 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6504 // Only handle binary, compare and shift operators here.
6505 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6508 // Figure out if the operations have any operands in common.
6509 Value *MatchOp, *OtherOpT, *OtherOpF;
6511 if (TI->getOperand(0) == FI->getOperand(0)) {
6512 MatchOp = TI->getOperand(0);
6513 OtherOpT = TI->getOperand(1);
6514 OtherOpF = FI->getOperand(1);
6515 MatchIsOpZero = true;
6516 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6517 MatchOp = TI->getOperand(1);
6518 OtherOpT = TI->getOperand(0);
6519 OtherOpF = FI->getOperand(0);
6520 MatchIsOpZero = false;
6521 } else if (!TI->isCommutative()) {
6523 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6524 MatchOp = TI->getOperand(0);
6525 OtherOpT = TI->getOperand(1);
6526 OtherOpF = FI->getOperand(0);
6527 MatchIsOpZero = true;
6528 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6529 MatchOp = TI->getOperand(1);
6530 OtherOpT = TI->getOperand(0);
6531 OtherOpF = FI->getOperand(1);
6532 MatchIsOpZero = true;
6537 // If we reach here, they do have operations in common.
6538 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6539 OtherOpF, SI.getName()+".v");
6540 InsertNewInstBefore(NewSI, SI);
6542 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6544 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6546 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6549 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6551 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6553 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6556 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6557 Value *CondVal = SI.getCondition();
6558 Value *TrueVal = SI.getTrueValue();
6559 Value *FalseVal = SI.getFalseValue();
6561 // select true, X, Y -> X
6562 // select false, X, Y -> Y
6563 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6564 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6566 // select C, X, X -> X
6567 if (TrueVal == FalseVal)
6568 return ReplaceInstUsesWith(SI, TrueVal);
6570 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6571 return ReplaceInstUsesWith(SI, FalseVal);
6572 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6573 return ReplaceInstUsesWith(SI, TrueVal);
6574 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6575 if (isa<Constant>(TrueVal))
6576 return ReplaceInstUsesWith(SI, TrueVal);
6578 return ReplaceInstUsesWith(SI, FalseVal);
6581 if (SI.getType() == Type::BoolTy)
6582 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6583 if (C->getValue()) {
6584 // Change: A = select B, true, C --> A = or B, C
6585 return BinaryOperator::createOr(CondVal, FalseVal);
6587 // Change: A = select B, false, C --> A = and !B, C
6589 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6590 "not."+CondVal->getName()), SI);
6591 return BinaryOperator::createAnd(NotCond, FalseVal);
6593 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6594 if (C->getValue() == false) {
6595 // Change: A = select B, C, false --> A = and B, C
6596 return BinaryOperator::createAnd(CondVal, TrueVal);
6598 // Change: A = select B, C, true --> A = or !B, C
6600 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6601 "not."+CondVal->getName()), SI);
6602 return BinaryOperator::createOr(NotCond, TrueVal);
6606 // Selecting between two integer constants?
6607 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6608 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6609 // select C, 1, 0 -> cast C to int
6610 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6611 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6612 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6613 // select C, 0, 1 -> cast !C to int
6615 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6616 "not."+CondVal->getName()), SI);
6617 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6620 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6622 // (x <s 0) ? -1 : 0 -> ashr x, 31
6623 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6624 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6625 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6626 bool CanXForm = false;
6627 if (IC->isSignedPredicate())
6628 CanXForm = CmpCst->isNullValue() &&
6629 IC->getPredicate() == ICmpInst::ICMP_SLT;
6631 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6632 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6633 IC->getPredicate() == ICmpInst::ICMP_UGT;
6637 // The comparison constant and the result are not neccessarily the
6638 // same width. Make an all-ones value by inserting a AShr.
6639 Value *X = IC->getOperand(0);
6640 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6641 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
6642 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6644 InsertNewInstBefore(SRA, SI);
6646 // Finally, convert to the type of the select RHS. We figure out
6647 // if this requires a SExt, Trunc or BitCast based on the sizes.
6648 Instruction::CastOps opc = Instruction::BitCast;
6649 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6650 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6651 if (SRASize < SISize)
6652 opc = Instruction::SExt;
6653 else if (SRASize > SISize)
6654 opc = Instruction::Trunc;
6655 return CastInst::create(opc, SRA, SI.getType());
6660 // If one of the constants is zero (we know they can't both be) and we
6661 // have a fcmp instruction with zero, and we have an 'and' with the
6662 // non-constant value, eliminate this whole mess. This corresponds to
6663 // cases like this: ((X & 27) ? 27 : 0)
6664 if (TrueValC->isNullValue() || FalseValC->isNullValue())
6665 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6666 cast<Constant>(IC->getOperand(1))->isNullValue())
6667 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6668 if (ICA->getOpcode() == Instruction::And &&
6669 isa<ConstantInt>(ICA->getOperand(1)) &&
6670 (ICA->getOperand(1) == TrueValC ||
6671 ICA->getOperand(1) == FalseValC) &&
6672 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6673 // Okay, now we know that everything is set up, we just don't
6674 // know whether we have a icmp_ne or icmp_eq and whether the
6675 // true or false val is the zero.
6676 bool ShouldNotVal = !TrueValC->isNullValue();
6677 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6680 V = InsertNewInstBefore(BinaryOperator::create(
6681 Instruction::Xor, V, ICA->getOperand(1)), SI);
6682 return ReplaceInstUsesWith(SI, V);
6687 // See if we are selecting two values based on a comparison of the two values.
6688 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6689 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6690 // Transform (X == Y) ? X : Y -> Y
6691 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6692 return ReplaceInstUsesWith(SI, FalseVal);
6693 // Transform (X != Y) ? X : Y -> X
6694 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6695 return ReplaceInstUsesWith(SI, TrueVal);
6696 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6698 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6699 // Transform (X == Y) ? Y : X -> X
6700 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6701 return ReplaceInstUsesWith(SI, FalseVal);
6702 // Transform (X != Y) ? Y : X -> Y
6703 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6704 return ReplaceInstUsesWith(SI, TrueVal);
6705 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6709 // See if we are selecting two values based on a comparison of the two values.
6710 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6711 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6712 // Transform (X == Y) ? X : Y -> Y
6713 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6714 return ReplaceInstUsesWith(SI, FalseVal);
6715 // Transform (X != Y) ? X : Y -> X
6716 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6717 return ReplaceInstUsesWith(SI, TrueVal);
6718 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6720 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6721 // Transform (X == Y) ? Y : X -> X
6722 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6723 return ReplaceInstUsesWith(SI, FalseVal);
6724 // Transform (X != Y) ? Y : X -> Y
6725 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6726 return ReplaceInstUsesWith(SI, TrueVal);
6727 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6731 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6732 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6733 if (TI->hasOneUse() && FI->hasOneUse()) {
6734 Instruction *AddOp = 0, *SubOp = 0;
6736 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6737 if (TI->getOpcode() == FI->getOpcode())
6738 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6741 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6742 // even legal for FP.
6743 if (TI->getOpcode() == Instruction::Sub &&
6744 FI->getOpcode() == Instruction::Add) {
6745 AddOp = FI; SubOp = TI;
6746 } else if (FI->getOpcode() == Instruction::Sub &&
6747 TI->getOpcode() == Instruction::Add) {
6748 AddOp = TI; SubOp = FI;
6752 Value *OtherAddOp = 0;
6753 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6754 OtherAddOp = AddOp->getOperand(1);
6755 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6756 OtherAddOp = AddOp->getOperand(0);
6760 // So at this point we know we have (Y -> OtherAddOp):
6761 // select C, (add X, Y), (sub X, Z)
6762 Value *NegVal; // Compute -Z
6763 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6764 NegVal = ConstantExpr::getNeg(C);
6766 NegVal = InsertNewInstBefore(
6767 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6770 Value *NewTrueOp = OtherAddOp;
6771 Value *NewFalseOp = NegVal;
6773 std::swap(NewTrueOp, NewFalseOp);
6774 Instruction *NewSel =
6775 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6777 NewSel = InsertNewInstBefore(NewSel, SI);
6778 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6783 // See if we can fold the select into one of our operands.
6784 if (SI.getType()->isInteger()) {
6785 // See the comment above GetSelectFoldableOperands for a description of the
6786 // transformation we are doing here.
6787 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6788 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6789 !isa<Constant>(FalseVal))
6790 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6791 unsigned OpToFold = 0;
6792 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6794 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6799 Constant *C = GetSelectFoldableConstant(TVI);
6800 std::string Name = TVI->getName(); TVI->setName("");
6801 Instruction *NewSel =
6802 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6804 InsertNewInstBefore(NewSel, SI);
6805 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6806 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6807 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6808 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6810 assert(0 && "Unknown instruction!!");
6815 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6816 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6817 !isa<Constant>(TrueVal))
6818 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6819 unsigned OpToFold = 0;
6820 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6822 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6827 Constant *C = GetSelectFoldableConstant(FVI);
6828 std::string Name = FVI->getName(); FVI->setName("");
6829 Instruction *NewSel =
6830 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6832 InsertNewInstBefore(NewSel, SI);
6833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6834 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6835 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6836 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6838 assert(0 && "Unknown instruction!!");
6844 if (BinaryOperator::isNot(CondVal)) {
6845 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6846 SI.setOperand(1, FalseVal);
6847 SI.setOperand(2, TrueVal);
6854 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6855 /// determine, return it, otherwise return 0.
6856 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6857 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6858 unsigned Align = GV->getAlignment();
6859 if (Align == 0 && TD)
6860 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6862 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6863 unsigned Align = AI->getAlignment();
6864 if (Align == 0 && TD) {
6865 if (isa<AllocaInst>(AI))
6866 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6867 else if (isa<MallocInst>(AI)) {
6868 // Malloc returns maximally aligned memory.
6869 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6870 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6871 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
6875 } else if (isa<BitCastInst>(V) ||
6876 (isa<ConstantExpr>(V) &&
6877 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6878 User *CI = cast<User>(V);
6879 if (isa<PointerType>(CI->getOperand(0)->getType()))
6880 return GetKnownAlignment(CI->getOperand(0), TD);
6882 } else if (isa<GetElementPtrInst>(V) ||
6883 (isa<ConstantExpr>(V) &&
6884 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6885 User *GEPI = cast<User>(V);
6886 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6887 if (BaseAlignment == 0) return 0;
6889 // If all indexes are zero, it is just the alignment of the base pointer.
6890 bool AllZeroOperands = true;
6891 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6892 if (!isa<Constant>(GEPI->getOperand(i)) ||
6893 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6894 AllZeroOperands = false;
6897 if (AllZeroOperands)
6898 return BaseAlignment;
6900 // Otherwise, if the base alignment is >= the alignment we expect for the
6901 // base pointer type, then we know that the resultant pointer is aligned at
6902 // least as much as its type requires.
6905 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6906 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6908 const Type *GEPTy = GEPI->getType();
6909 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6917 /// visitCallInst - CallInst simplification. This mostly only handles folding
6918 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6919 /// the heavy lifting.
6921 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6922 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6923 if (!II) return visitCallSite(&CI);
6925 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6927 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6928 bool Changed = false;
6930 // memmove/cpy/set of zero bytes is a noop.
6931 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6932 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6934 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6935 if (CI->getZExtValue() == 1) {
6936 // Replace the instruction with just byte operations. We would
6937 // transform other cases to loads/stores, but we don't know if
6938 // alignment is sufficient.
6942 // If we have a memmove and the source operation is a constant global,
6943 // then the source and dest pointers can't alias, so we can change this
6944 // into a call to memcpy.
6945 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6946 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6947 if (GVSrc->isConstant()) {
6948 Module *M = CI.getParent()->getParent()->getParent();
6950 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
6952 Name = "llvm.memcpy.i32";
6954 Name = "llvm.memcpy.i64";
6955 Constant *MemCpy = M->getOrInsertFunction(Name,
6956 CI.getCalledFunction()->getFunctionType());
6957 CI.setOperand(0, MemCpy);
6962 // If we can determine a pointer alignment that is bigger than currently
6963 // set, update the alignment.
6964 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6965 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6966 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6967 unsigned Align = std::min(Alignment1, Alignment2);
6968 if (MI->getAlignment()->getZExtValue() < Align) {
6969 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
6972 } else if (isa<MemSetInst>(MI)) {
6973 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6974 if (MI->getAlignment()->getZExtValue() < Alignment) {
6975 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
6980 if (Changed) return II;
6982 switch (II->getIntrinsicID()) {
6984 case Intrinsic::ppc_altivec_lvx:
6985 case Intrinsic::ppc_altivec_lvxl:
6986 case Intrinsic::x86_sse_loadu_ps:
6987 case Intrinsic::x86_sse2_loadu_pd:
6988 case Intrinsic::x86_sse2_loadu_dq:
6989 // Turn PPC lvx -> load if the pointer is known aligned.
6990 // Turn X86 loadups -> load if the pointer is known aligned.
6991 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6992 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
6993 PointerType::get(II->getType()), CI);
6994 return new LoadInst(Ptr);
6997 case Intrinsic::ppc_altivec_stvx:
6998 case Intrinsic::ppc_altivec_stvxl:
6999 // Turn stvx -> store if the pointer is known aligned.
7000 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7001 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7002 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7004 return new StoreInst(II->getOperand(1), Ptr);
7007 case Intrinsic::x86_sse_storeu_ps:
7008 case Intrinsic::x86_sse2_storeu_pd:
7009 case Intrinsic::x86_sse2_storeu_dq:
7010 case Intrinsic::x86_sse2_storel_dq:
7011 // Turn X86 storeu -> store if the pointer is known aligned.
7012 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7013 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7014 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7016 return new StoreInst(II->getOperand(2), Ptr);
7020 case Intrinsic::x86_sse_cvttss2si: {
7021 // These intrinsics only demands the 0th element of its input vector. If
7022 // we can simplify the input based on that, do so now.
7024 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7026 II->setOperand(1, V);
7032 case Intrinsic::ppc_altivec_vperm:
7033 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7034 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7035 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7037 // Check that all of the elements are integer constants or undefs.
7038 bool AllEltsOk = true;
7039 for (unsigned i = 0; i != 16; ++i) {
7040 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7041 !isa<UndefValue>(Mask->getOperand(i))) {
7048 // Cast the input vectors to byte vectors.
7049 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7050 II->getOperand(1), Mask->getType(), CI);
7051 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7052 II->getOperand(2), Mask->getType(), CI);
7053 Value *Result = UndefValue::get(Op0->getType());
7055 // Only extract each element once.
7056 Value *ExtractedElts[32];
7057 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7059 for (unsigned i = 0; i != 16; ++i) {
7060 if (isa<UndefValue>(Mask->getOperand(i)))
7062 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7063 Idx &= 31; // Match the hardware behavior.
7065 if (ExtractedElts[Idx] == 0) {
7067 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7068 InsertNewInstBefore(Elt, CI);
7069 ExtractedElts[Idx] = Elt;
7072 // Insert this value into the result vector.
7073 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7074 InsertNewInstBefore(cast<Instruction>(Result), CI);
7076 return CastInst::create(Instruction::BitCast, Result, CI.getType());
7081 case Intrinsic::stackrestore: {
7082 // If the save is right next to the restore, remove the restore. This can
7083 // happen when variable allocas are DCE'd.
7084 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7085 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7086 BasicBlock::iterator BI = SS;
7088 return EraseInstFromFunction(CI);
7092 // If the stack restore is in a return/unwind block and if there are no
7093 // allocas or calls between the restore and the return, nuke the restore.
7094 TerminatorInst *TI = II->getParent()->getTerminator();
7095 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7096 BasicBlock::iterator BI = II;
7097 bool CannotRemove = false;
7098 for (++BI; &*BI != TI; ++BI) {
7099 if (isa<AllocaInst>(BI) ||
7100 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7101 CannotRemove = true;
7106 return EraseInstFromFunction(CI);
7113 return visitCallSite(II);
7116 // InvokeInst simplification
7118 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7119 return visitCallSite(&II);
7122 // visitCallSite - Improvements for call and invoke instructions.
7124 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7125 bool Changed = false;
7127 // If the callee is a constexpr cast of a function, attempt to move the cast
7128 // to the arguments of the call/invoke.
7129 if (transformConstExprCastCall(CS)) return 0;
7131 Value *Callee = CS.getCalledValue();
7133 if (Function *CalleeF = dyn_cast<Function>(Callee))
7134 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7135 Instruction *OldCall = CS.getInstruction();
7136 // If the call and callee calling conventions don't match, this call must
7137 // be unreachable, as the call is undefined.
7138 new StoreInst(ConstantBool::getTrue(),
7139 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7140 if (!OldCall->use_empty())
7141 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7142 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7143 return EraseInstFromFunction(*OldCall);
7147 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7148 // This instruction is not reachable, just remove it. We insert a store to
7149 // undef so that we know that this code is not reachable, despite the fact
7150 // that we can't modify the CFG here.
7151 new StoreInst(ConstantBool::getTrue(),
7152 UndefValue::get(PointerType::get(Type::BoolTy)),
7153 CS.getInstruction());
7155 if (!CS.getInstruction()->use_empty())
7156 CS.getInstruction()->
7157 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7159 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7160 // Don't break the CFG, insert a dummy cond branch.
7161 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7162 ConstantBool::getTrue(), II);
7164 return EraseInstFromFunction(*CS.getInstruction());
7167 const PointerType *PTy = cast<PointerType>(Callee->getType());
7168 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7169 if (FTy->isVarArg()) {
7170 // See if we can optimize any arguments passed through the varargs area of
7172 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7173 E = CS.arg_end(); I != E; ++I)
7174 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7175 // If this cast does not effect the value passed through the varargs
7176 // area, we can eliminate the use of the cast.
7177 Value *Op = CI->getOperand(0);
7178 if (CI->isLosslessCast()) {
7185 return Changed ? CS.getInstruction() : 0;
7188 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7189 // attempt to move the cast to the arguments of the call/invoke.
7191 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7192 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7193 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7194 if (CE->getOpcode() != Instruction::BitCast ||
7195 !isa<Function>(CE->getOperand(0)))
7197 Function *Callee = cast<Function>(CE->getOperand(0));
7198 Instruction *Caller = CS.getInstruction();
7200 // Okay, this is a cast from a function to a different type. Unless doing so
7201 // would cause a type conversion of one of our arguments, change this call to
7202 // be a direct call with arguments casted to the appropriate types.
7204 const FunctionType *FT = Callee->getFunctionType();
7205 const Type *OldRetTy = Caller->getType();
7207 // Check to see if we are changing the return type...
7208 if (OldRetTy != FT->getReturnType()) {
7209 if (Callee->isExternal() && !Caller->use_empty() &&
7210 OldRetTy != FT->getReturnType() &&
7211 // Conversion is ok if changing from pointer to int of same size.
7212 !(isa<PointerType>(FT->getReturnType()) &&
7213 TD->getIntPtrType() == OldRetTy))
7214 return false; // Cannot transform this return value.
7216 // If the callsite is an invoke instruction, and the return value is used by
7217 // a PHI node in a successor, we cannot change the return type of the call
7218 // because there is no place to put the cast instruction (without breaking
7219 // the critical edge). Bail out in this case.
7220 if (!Caller->use_empty())
7221 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7222 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7224 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7225 if (PN->getParent() == II->getNormalDest() ||
7226 PN->getParent() == II->getUnwindDest())
7230 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7231 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7233 CallSite::arg_iterator AI = CS.arg_begin();
7234 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7235 const Type *ParamTy = FT->getParamType(i);
7236 const Type *ActTy = (*AI)->getType();
7237 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7238 //Either we can cast directly, or we can upconvert the argument
7239 bool isConvertible = ActTy == ParamTy ||
7240 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7241 (ParamTy->isIntegral() && ActTy->isIntegral() &&
7242 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7243 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
7244 c->getSExtValue() > 0);
7245 if (Callee->isExternal() && !isConvertible) return false;
7248 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7249 Callee->isExternal())
7250 return false; // Do not delete arguments unless we have a function body...
7252 // Okay, we decided that this is a safe thing to do: go ahead and start
7253 // inserting cast instructions as necessary...
7254 std::vector<Value*> Args;
7255 Args.reserve(NumActualArgs);
7257 AI = CS.arg_begin();
7258 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7259 const Type *ParamTy = FT->getParamType(i);
7260 if ((*AI)->getType() == ParamTy) {
7261 Args.push_back(*AI);
7263 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7264 false, ParamTy, false);
7265 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7266 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7270 // If the function takes more arguments than the call was taking, add them
7272 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7273 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7275 // If we are removing arguments to the function, emit an obnoxious warning...
7276 if (FT->getNumParams() < NumActualArgs)
7277 if (!FT->isVarArg()) {
7278 cerr << "WARNING: While resolving call to function '"
7279 << Callee->getName() << "' arguments were dropped!\n";
7281 // Add all of the arguments in their promoted form to the arg list...
7282 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7283 const Type *PTy = getPromotedType((*AI)->getType());
7284 if (PTy != (*AI)->getType()) {
7285 // Must promote to pass through va_arg area!
7286 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7288 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7289 InsertNewInstBefore(Cast, *Caller);
7290 Args.push_back(Cast);
7292 Args.push_back(*AI);
7297 if (FT->getReturnType() == Type::VoidTy)
7298 Caller->setName(""); // Void type should not have a name...
7301 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7302 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7303 Args, Caller->getName(), Caller);
7304 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7306 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7307 if (cast<CallInst>(Caller)->isTailCall())
7308 cast<CallInst>(NC)->setTailCall();
7309 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7312 // Insert a cast of the return type as necessary...
7314 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7315 if (NV->getType() != Type::VoidTy) {
7316 const Type *CallerTy = Caller->getType();
7317 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7319 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7321 // If this is an invoke instruction, we should insert it after the first
7322 // non-phi, instruction in the normal successor block.
7323 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7324 BasicBlock::iterator I = II->getNormalDest()->begin();
7325 while (isa<PHINode>(I)) ++I;
7326 InsertNewInstBefore(NC, *I);
7328 // Otherwise, it's a call, just insert cast right after the call instr
7329 InsertNewInstBefore(NC, *Caller);
7331 AddUsersToWorkList(*Caller);
7333 NV = UndefValue::get(Caller->getType());
7337 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7338 Caller->replaceAllUsesWith(NV);
7339 Caller->getParent()->getInstList().erase(Caller);
7340 removeFromWorkList(Caller);
7344 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7345 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7346 /// and a single binop.
7347 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7348 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7349 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7350 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7351 unsigned Opc = FirstInst->getOpcode();
7352 Value *LHSVal = FirstInst->getOperand(0);
7353 Value *RHSVal = FirstInst->getOperand(1);
7355 const Type *LHSType = LHSVal->getType();
7356 const Type *RHSType = RHSVal->getType();
7358 // Scan to see if all operands are the same opcode, all have one use, and all
7359 // kill their operands (i.e. the operands have one use).
7360 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7361 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7362 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7363 // Verify type of the LHS matches so we don't fold cmp's of different
7364 // types or GEP's with different index types.
7365 I->getOperand(0)->getType() != LHSType ||
7366 I->getOperand(1)->getType() != RHSType)
7369 // If they are CmpInst instructions, check their predicates
7370 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7371 if (cast<CmpInst>(I)->getPredicate() !=
7372 cast<CmpInst>(FirstInst)->getPredicate())
7375 // Keep track of which operand needs a phi node.
7376 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7377 if (I->getOperand(1) != RHSVal) RHSVal = 0;
7380 // Otherwise, this is safe to transform, determine if it is profitable.
7382 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7383 // Indexes are often folded into load/store instructions, so we don't want to
7384 // hide them behind a phi.
7385 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7388 Value *InLHS = FirstInst->getOperand(0);
7389 Value *InRHS = FirstInst->getOperand(1);
7390 PHINode *NewLHS = 0, *NewRHS = 0;
7392 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7393 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7394 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7395 InsertNewInstBefore(NewLHS, PN);
7400 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7401 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7402 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7403 InsertNewInstBefore(NewRHS, PN);
7407 // Add all operands to the new PHIs.
7408 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7410 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7411 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7414 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7415 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7419 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7420 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7421 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7422 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7424 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7425 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7427 assert(isa<GetElementPtrInst>(FirstInst));
7428 return new GetElementPtrInst(LHSVal, RHSVal);
7432 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7433 /// of the block that defines it. This means that it must be obvious the value
7434 /// of the load is not changed from the point of the load to the end of the
7436 static bool isSafeToSinkLoad(LoadInst *L) {
7437 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7439 for (++BBI; BBI != E; ++BBI)
7440 if (BBI->mayWriteToMemory())
7446 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7447 // operator and they all are only used by the PHI, PHI together their
7448 // inputs, and do the operation once, to the result of the PHI.
7449 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7450 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7452 // Scan the instruction, looking for input operations that can be folded away.
7453 // If all input operands to the phi are the same instruction (e.g. a cast from
7454 // the same type or "+42") we can pull the operation through the PHI, reducing
7455 // code size and simplifying code.
7456 Constant *ConstantOp = 0;
7457 const Type *CastSrcTy = 0;
7458 bool isVolatile = false;
7459 if (isa<CastInst>(FirstInst)) {
7460 CastSrcTy = FirstInst->getOperand(0)->getType();
7461 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7462 isa<CmpInst>(FirstInst)) {
7463 // Can fold binop, compare or shift here if the RHS is a constant,
7464 // otherwise call FoldPHIArgBinOpIntoPHI.
7465 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7466 if (ConstantOp == 0)
7467 return FoldPHIArgBinOpIntoPHI(PN);
7468 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7469 isVolatile = LI->isVolatile();
7470 // We can't sink the load if the loaded value could be modified between the
7471 // load and the PHI.
7472 if (LI->getParent() != PN.getIncomingBlock(0) ||
7473 !isSafeToSinkLoad(LI))
7475 } else if (isa<GetElementPtrInst>(FirstInst)) {
7476 if (FirstInst->getNumOperands() == 2)
7477 return FoldPHIArgBinOpIntoPHI(PN);
7478 // Can't handle general GEPs yet.
7481 return 0; // Cannot fold this operation.
7484 // Check to see if all arguments are the same operation.
7485 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7486 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7487 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7488 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7491 if (I->getOperand(0)->getType() != CastSrcTy)
7492 return 0; // Cast operation must match.
7493 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7494 // We can't sink the load if the loaded value could be modified between
7495 // the load and the PHI.
7496 if (LI->isVolatile() != isVolatile ||
7497 LI->getParent() != PN.getIncomingBlock(i) ||
7498 !isSafeToSinkLoad(LI))
7500 } else if (I->getOperand(1) != ConstantOp) {
7505 // Okay, they are all the same operation. Create a new PHI node of the
7506 // correct type, and PHI together all of the LHS's of the instructions.
7507 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7508 PN.getName()+".in");
7509 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7511 Value *InVal = FirstInst->getOperand(0);
7512 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7514 // Add all operands to the new PHI.
7515 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7516 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7517 if (NewInVal != InVal)
7519 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7524 // The new PHI unions all of the same values together. This is really
7525 // common, so we handle it intelligently here for compile-time speed.
7529 InsertNewInstBefore(NewPN, PN);
7533 // Insert and return the new operation.
7534 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7535 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7536 else if (isa<LoadInst>(FirstInst))
7537 return new LoadInst(PhiVal, "", isVolatile);
7538 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7539 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7540 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7541 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7542 PhiVal, ConstantOp);
7544 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7545 PhiVal, ConstantOp);
7548 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7550 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7551 if (PN->use_empty()) return true;
7552 if (!PN->hasOneUse()) return false;
7554 // Remember this node, and if we find the cycle, return.
7555 if (!PotentiallyDeadPHIs.insert(PN).second)
7558 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7559 return DeadPHICycle(PU, PotentiallyDeadPHIs);
7564 // PHINode simplification
7566 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7567 // If LCSSA is around, don't mess with Phi nodes
7568 if (mustPreserveAnalysisID(LCSSAID)) return 0;
7570 if (Value *V = PN.hasConstantValue())
7571 return ReplaceInstUsesWith(PN, V);
7573 // If all PHI operands are the same operation, pull them through the PHI,
7574 // reducing code size.
7575 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7576 PN.getIncomingValue(0)->hasOneUse())
7577 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7580 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7581 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7582 // PHI)... break the cycle.
7584 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7585 std::set<PHINode*> PotentiallyDeadPHIs;
7586 PotentiallyDeadPHIs.insert(&PN);
7587 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7588 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7594 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7595 Instruction *InsertPoint,
7597 unsigned PtrSize = DTy->getPrimitiveSize();
7598 unsigned VTySize = V->getType()->getPrimitiveSize();
7599 // We must cast correctly to the pointer type. Ensure that we
7600 // sign extend the integer value if it is smaller as this is
7601 // used for address computation.
7602 Instruction::CastOps opcode =
7603 (VTySize < PtrSize ? Instruction::SExt :
7604 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7605 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7609 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7610 Value *PtrOp = GEP.getOperand(0);
7611 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
7612 // If so, eliminate the noop.
7613 if (GEP.getNumOperands() == 1)
7614 return ReplaceInstUsesWith(GEP, PtrOp);
7616 if (isa<UndefValue>(GEP.getOperand(0)))
7617 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7619 bool HasZeroPointerIndex = false;
7620 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7621 HasZeroPointerIndex = C->isNullValue();
7623 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7624 return ReplaceInstUsesWith(GEP, PtrOp);
7626 // Eliminate unneeded casts for indices.
7627 bool MadeChange = false;
7628 gep_type_iterator GTI = gep_type_begin(GEP);
7629 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7630 if (isa<SequentialType>(*GTI)) {
7631 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7632 Value *Src = CI->getOperand(0);
7633 const Type *SrcTy = Src->getType();
7634 const Type *DestTy = CI->getType();
7635 if (Src->getType()->isInteger()) {
7636 if (SrcTy->getPrimitiveSizeInBits() ==
7637 DestTy->getPrimitiveSizeInBits()) {
7638 // We can always eliminate a cast from ulong or long to the other.
7639 // We can always eliminate a cast from uint to int or the other on
7640 // 32-bit pointer platforms.
7641 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7643 GEP.setOperand(i, Src);
7645 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7646 SrcTy->getPrimitiveSize() == 4) {
7647 // We can eliminate a cast from [u]int to [u]long iff the target
7648 // is a 32-bit pointer target.
7649 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7651 GEP.setOperand(i, Src);
7656 // If we are using a wider index than needed for this platform, shrink it
7657 // to what we need. If the incoming value needs a cast instruction,
7658 // insert it. This explicit cast can make subsequent optimizations more
7660 Value *Op = GEP.getOperand(i);
7661 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7662 if (Constant *C = dyn_cast<Constant>(Op)) {
7663 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7666 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7668 GEP.setOperand(i, Op);
7672 if (MadeChange) return &GEP;
7674 // Combine Indices - If the source pointer to this getelementptr instruction
7675 // is a getelementptr instruction, combine the indices of the two
7676 // getelementptr instructions into a single instruction.
7678 std::vector<Value*> SrcGEPOperands;
7679 if (User *Src = dyn_castGetElementPtr(PtrOp))
7680 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7682 if (!SrcGEPOperands.empty()) {
7683 // Note that if our source is a gep chain itself that we wait for that
7684 // chain to be resolved before we perform this transformation. This
7685 // avoids us creating a TON of code in some cases.
7687 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7688 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7689 return 0; // Wait until our source is folded to completion.
7691 std::vector<Value *> Indices;
7693 // Find out whether the last index in the source GEP is a sequential idx.
7694 bool EndsWithSequential = false;
7695 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7696 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7697 EndsWithSequential = !isa<StructType>(*I);
7699 // Can we combine the two pointer arithmetics offsets?
7700 if (EndsWithSequential) {
7701 // Replace: gep (gep %P, long B), long A, ...
7702 // With: T = long A+B; gep %P, T, ...
7704 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7705 if (SO1 == Constant::getNullValue(SO1->getType())) {
7707 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7710 // If they aren't the same type, convert both to an integer of the
7711 // target's pointer size.
7712 if (SO1->getType() != GO1->getType()) {
7713 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7714 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7715 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7716 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7718 unsigned PS = TD->getPointerSize();
7719 if (SO1->getType()->getPrimitiveSize() == PS) {
7720 // Convert GO1 to SO1's type.
7721 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7723 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7724 // Convert SO1 to GO1's type.
7725 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7727 const Type *PT = TD->getIntPtrType();
7728 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7729 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7733 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7734 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7736 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7737 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7741 // Recycle the GEP we already have if possible.
7742 if (SrcGEPOperands.size() == 2) {
7743 GEP.setOperand(0, SrcGEPOperands[0]);
7744 GEP.setOperand(1, Sum);
7747 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7748 SrcGEPOperands.end()-1);
7749 Indices.push_back(Sum);
7750 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7752 } else if (isa<Constant>(*GEP.idx_begin()) &&
7753 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7754 SrcGEPOperands.size() != 1) {
7755 // Otherwise we can do the fold if the first index of the GEP is a zero
7756 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7757 SrcGEPOperands.end());
7758 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7761 if (!Indices.empty())
7762 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7764 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7765 // GEP of global variable. If all of the indices for this GEP are
7766 // constants, we can promote this to a constexpr instead of an instruction.
7768 // Scan for nonconstants...
7769 std::vector<Constant*> Indices;
7770 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7771 for (; I != E && isa<Constant>(*I); ++I)
7772 Indices.push_back(cast<Constant>(*I));
7774 if (I == E) { // If they are all constants...
7775 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7777 // Replace all uses of the GEP with the new constexpr...
7778 return ReplaceInstUsesWith(GEP, CE);
7780 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
7781 if (!isa<PointerType>(X->getType())) {
7782 // Not interesting. Source pointer must be a cast from pointer.
7783 } else if (HasZeroPointerIndex) {
7784 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7785 // into : GEP [10 x ubyte]* X, long 0, ...
7787 // This occurs when the program declares an array extern like "int X[];"
7789 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7790 const PointerType *XTy = cast<PointerType>(X->getType());
7791 if (const ArrayType *XATy =
7792 dyn_cast<ArrayType>(XTy->getElementType()))
7793 if (const ArrayType *CATy =
7794 dyn_cast<ArrayType>(CPTy->getElementType()))
7795 if (CATy->getElementType() == XATy->getElementType()) {
7796 // At this point, we know that the cast source type is a pointer
7797 // to an array of the same type as the destination pointer
7798 // array. Because the array type is never stepped over (there
7799 // is a leading zero) we can fold the cast into this GEP.
7800 GEP.setOperand(0, X);
7803 } else if (GEP.getNumOperands() == 2) {
7804 // Transform things like:
7805 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7806 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7807 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7808 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7809 if (isa<ArrayType>(SrcElTy) &&
7810 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7811 TD->getTypeSize(ResElTy)) {
7812 Value *V = InsertNewInstBefore(
7813 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7814 GEP.getOperand(1), GEP.getName()), GEP);
7815 // V and GEP are both pointer types --> BitCast
7816 return new BitCastInst(V, GEP.getType());
7819 // Transform things like:
7820 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7821 // (where tmp = 8*tmp2) into:
7822 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7824 if (isa<ArrayType>(SrcElTy) &&
7825 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7826 uint64_t ArrayEltSize =
7827 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7829 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7830 // allow either a mul, shift, or constant here.
7832 ConstantInt *Scale = 0;
7833 if (ArrayEltSize == 1) {
7834 NewIdx = GEP.getOperand(1);
7835 Scale = ConstantInt::get(NewIdx->getType(), 1);
7836 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7837 NewIdx = ConstantInt::get(CI->getType(), 1);
7839 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7840 if (Inst->getOpcode() == Instruction::Shl &&
7841 isa<ConstantInt>(Inst->getOperand(1))) {
7843 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7844 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7845 NewIdx = Inst->getOperand(0);
7846 } else if (Inst->getOpcode() == Instruction::Mul &&
7847 isa<ConstantInt>(Inst->getOperand(1))) {
7848 Scale = cast<ConstantInt>(Inst->getOperand(1));
7849 NewIdx = Inst->getOperand(0);
7853 // If the index will be to exactly the right offset with the scale taken
7854 // out, perform the transformation.
7855 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7856 if (isa<ConstantInt>(Scale))
7857 Scale = ConstantInt::get(Scale->getType(),
7858 Scale->getZExtValue() / ArrayEltSize);
7859 if (Scale->getZExtValue() != 1) {
7860 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7862 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7863 NewIdx = InsertNewInstBefore(Sc, GEP);
7866 // Insert the new GEP instruction.
7867 Instruction *NewGEP =
7868 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7869 NewIdx, GEP.getName());
7870 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7871 // The NewGEP must be pointer typed, so must the old one -> BitCast
7872 return new BitCastInst(NewGEP, GEP.getType());
7881 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7882 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7883 if (AI.isArrayAllocation()) // Check C != 1
7884 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7886 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7887 AllocationInst *New = 0;
7889 // Create and insert the replacement instruction...
7890 if (isa<MallocInst>(AI))
7891 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7893 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7894 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7897 InsertNewInstBefore(New, AI);
7899 // Scan to the end of the allocation instructions, to skip over a block of
7900 // allocas if possible...
7902 BasicBlock::iterator It = New;
7903 while (isa<AllocationInst>(*It)) ++It;
7905 // Now that I is pointing to the first non-allocation-inst in the block,
7906 // insert our getelementptr instruction...
7908 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7909 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7910 New->getName()+".sub", It);
7912 // Now make everything use the getelementptr instead of the original
7914 return ReplaceInstUsesWith(AI, V);
7915 } else if (isa<UndefValue>(AI.getArraySize())) {
7916 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7919 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7920 // Note that we only do this for alloca's, because malloc should allocate and
7921 // return a unique pointer, even for a zero byte allocation.
7922 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7923 TD->getTypeSize(AI.getAllocatedType()) == 0)
7924 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7929 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7930 Value *Op = FI.getOperand(0);
7932 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7933 if (CastInst *CI = dyn_cast<CastInst>(Op))
7934 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7935 FI.setOperand(0, CI->getOperand(0));
7939 // free undef -> unreachable.
7940 if (isa<UndefValue>(Op)) {
7941 // Insert a new store to null because we cannot modify the CFG here.
7942 new StoreInst(ConstantBool::getTrue(),
7943 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7944 return EraseInstFromFunction(FI);
7947 // If we have 'free null' delete the instruction. This can happen in stl code
7948 // when lots of inlining happens.
7949 if (isa<ConstantPointerNull>(Op))
7950 return EraseInstFromFunction(FI);
7956 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7957 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7958 User *CI = cast<User>(LI.getOperand(0));
7959 Value *CastOp = CI->getOperand(0);
7961 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7962 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7963 const Type *SrcPTy = SrcTy->getElementType();
7965 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7966 isa<PackedType>(DestPTy)) {
7967 // If the source is an array, the code below will not succeed. Check to
7968 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7970 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7971 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7972 if (ASrcTy->getNumElements() != 0) {
7973 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
7974 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7975 SrcTy = cast<PointerType>(CastOp->getType());
7976 SrcPTy = SrcTy->getElementType();
7979 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7980 isa<PackedType>(SrcPTy)) &&
7981 // Do not allow turning this into a load of an integer, which is then
7982 // casted to a pointer, this pessimizes pointer analysis a lot.
7983 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7984 IC.getTargetData().getTypeSize(SrcPTy) ==
7985 IC.getTargetData().getTypeSize(DestPTy)) {
7987 // Okay, we are casting from one integer or pointer type to another of
7988 // the same size. Instead of casting the pointer before the load, cast
7989 // the result of the loaded value.
7990 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7992 LI.isVolatile()),LI);
7993 // Now cast the result of the load.
7994 return new BitCastInst(NewLoad, LI.getType());
8001 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8002 /// from this value cannot trap. If it is not obviously safe to load from the
8003 /// specified pointer, we do a quick local scan of the basic block containing
8004 /// ScanFrom, to determine if the address is already accessed.
8005 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8006 // If it is an alloca or global variable, it is always safe to load from.
8007 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8009 // Otherwise, be a little bit agressive by scanning the local block where we
8010 // want to check to see if the pointer is already being loaded or stored
8011 // from/to. If so, the previous load or store would have already trapped,
8012 // so there is no harm doing an extra load (also, CSE will later eliminate
8013 // the load entirely).
8014 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8019 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8020 if (LI->getOperand(0) == V) return true;
8021 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8022 if (SI->getOperand(1) == V) return true;
8028 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8029 Value *Op = LI.getOperand(0);
8031 // load (cast X) --> cast (load X) iff safe
8032 if (isa<CastInst>(Op))
8033 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8036 // None of the following transforms are legal for volatile loads.
8037 if (LI.isVolatile()) return 0;
8039 if (&LI.getParent()->front() != &LI) {
8040 BasicBlock::iterator BBI = &LI; --BBI;
8041 // If the instruction immediately before this is a store to the same
8042 // address, do a simple form of store->load forwarding.
8043 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8044 if (SI->getOperand(1) == LI.getOperand(0))
8045 return ReplaceInstUsesWith(LI, SI->getOperand(0));
8046 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8047 if (LIB->getOperand(0) == LI.getOperand(0))
8048 return ReplaceInstUsesWith(LI, LIB);
8051 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8052 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8053 isa<UndefValue>(GEPI->getOperand(0))) {
8054 // Insert a new store to null instruction before the load to indicate
8055 // that this code is not reachable. We do this instead of inserting
8056 // an unreachable instruction directly because we cannot modify the
8058 new StoreInst(UndefValue::get(LI.getType()),
8059 Constant::getNullValue(Op->getType()), &LI);
8060 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8063 if (Constant *C = dyn_cast<Constant>(Op)) {
8064 // load null/undef -> undef
8065 if ((C->isNullValue() || isa<UndefValue>(C))) {
8066 // Insert a new store to null instruction before the load to indicate that
8067 // this code is not reachable. We do this instead of inserting an
8068 // unreachable instruction directly because we cannot modify the CFG.
8069 new StoreInst(UndefValue::get(LI.getType()),
8070 Constant::getNullValue(Op->getType()), &LI);
8071 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8074 // Instcombine load (constant global) into the value loaded.
8075 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8076 if (GV->isConstant() && !GV->isExternal())
8077 return ReplaceInstUsesWith(LI, GV->getInitializer());
8079 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8080 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8081 if (CE->getOpcode() == Instruction::GetElementPtr) {
8082 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8083 if (GV->isConstant() && !GV->isExternal())
8085 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8086 return ReplaceInstUsesWith(LI, V);
8087 if (CE->getOperand(0)->isNullValue()) {
8088 // Insert a new store to null instruction before the load to indicate
8089 // that this code is not reachable. We do this instead of inserting
8090 // an unreachable instruction directly because we cannot modify the
8092 new StoreInst(UndefValue::get(LI.getType()),
8093 Constant::getNullValue(Op->getType()), &LI);
8094 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8097 } else if (CE->isCast()) {
8098 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8103 if (Op->hasOneUse()) {
8104 // Change select and PHI nodes to select values instead of addresses: this
8105 // helps alias analysis out a lot, allows many others simplifications, and
8106 // exposes redundancy in the code.
8108 // Note that we cannot do the transformation unless we know that the
8109 // introduced loads cannot trap! Something like this is valid as long as
8110 // the condition is always false: load (select bool %C, int* null, int* %G),
8111 // but it would not be valid if we transformed it to load from null
8114 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8115 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
8116 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8117 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8118 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8119 SI->getOperand(1)->getName()+".val"), LI);
8120 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8121 SI->getOperand(2)->getName()+".val"), LI);
8122 return new SelectInst(SI->getCondition(), V1, V2);
8125 // load (select (cond, null, P)) -> load P
8126 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8127 if (C->isNullValue()) {
8128 LI.setOperand(0, SI->getOperand(2));
8132 // load (select (cond, P, null)) -> load P
8133 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8134 if (C->isNullValue()) {
8135 LI.setOperand(0, SI->getOperand(1));
8143 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8145 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8146 User *CI = cast<User>(SI.getOperand(1));
8147 Value *CastOp = CI->getOperand(0);
8149 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8150 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8151 const Type *SrcPTy = SrcTy->getElementType();
8153 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8154 // If the source is an array, the code below will not succeed. Check to
8155 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8157 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8158 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8159 if (ASrcTy->getNumElements() != 0) {
8160 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
8161 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8162 SrcTy = cast<PointerType>(CastOp->getType());
8163 SrcPTy = SrcTy->getElementType();
8166 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8167 IC.getTargetData().getTypeSize(SrcPTy) ==
8168 IC.getTargetData().getTypeSize(DestPTy)) {
8170 // Okay, we are casting from one integer or pointer type to another of
8171 // the same size. Instead of casting the pointer before the store, cast
8172 // the value to be stored.
8174 Instruction::CastOps opcode = Instruction::BitCast;
8175 Value *SIOp0 = SI.getOperand(0);
8176 if (isa<PointerType>(SrcPTy)) {
8177 if (SIOp0->getType()->isIntegral())
8178 opcode = Instruction::IntToPtr;
8179 } else if (SrcPTy->isIntegral()) {
8180 if (isa<PointerType>(SIOp0->getType()))
8181 opcode = Instruction::PtrToInt;
8183 if (Constant *C = dyn_cast<Constant>(SIOp0))
8184 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
8186 NewCast = IC.InsertNewInstBefore(
8187 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
8188 return new StoreInst(NewCast, CastOp);
8195 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8196 Value *Val = SI.getOperand(0);
8197 Value *Ptr = SI.getOperand(1);
8199 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
8200 EraseInstFromFunction(SI);
8205 // Do really simple DSE, to catch cases where there are several consequtive
8206 // stores to the same location, separated by a few arithmetic operations. This
8207 // situation often occurs with bitfield accesses.
8208 BasicBlock::iterator BBI = &SI;
8209 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8213 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8214 // Prev store isn't volatile, and stores to the same location?
8215 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8218 EraseInstFromFunction(*PrevSI);
8224 // If this is a load, we have to stop. However, if the loaded value is from
8225 // the pointer we're loading and is producing the pointer we're storing,
8226 // then *this* store is dead (X = load P; store X -> P).
8227 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8228 if (LI == Val && LI->getOperand(0) == Ptr) {
8229 EraseInstFromFunction(SI);
8233 // Otherwise, this is a load from some other location. Stores before it
8238 // Don't skip over loads or things that can modify memory.
8239 if (BBI->mayWriteToMemory())
8244 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
8246 // store X, null -> turns into 'unreachable' in SimplifyCFG
8247 if (isa<ConstantPointerNull>(Ptr)) {
8248 if (!isa<UndefValue>(Val)) {
8249 SI.setOperand(0, UndefValue::get(Val->getType()));
8250 if (Instruction *U = dyn_cast<Instruction>(Val))
8251 WorkList.push_back(U); // Dropped a use.
8254 return 0; // Do not modify these!
8257 // store undef, Ptr -> noop
8258 if (isa<UndefValue>(Val)) {
8259 EraseInstFromFunction(SI);
8264 // If the pointer destination is a cast, see if we can fold the cast into the
8266 if (isa<CastInst>(Ptr))
8267 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8269 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8271 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8275 // If this store is the last instruction in the basic block, and if the block
8276 // ends with an unconditional branch, try to move it to the successor block.
8278 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8279 if (BI->isUnconditional()) {
8280 // Check to see if the successor block has exactly two incoming edges. If
8281 // so, see if the other predecessor contains a store to the same location.
8282 // if so, insert a PHI node (if needed) and move the stores down.
8283 BasicBlock *Dest = BI->getSuccessor(0);
8285 pred_iterator PI = pred_begin(Dest);
8286 BasicBlock *Other = 0;
8287 if (*PI != BI->getParent())
8290 if (PI != pred_end(Dest)) {
8291 if (*PI != BI->getParent())
8296 if (++PI != pred_end(Dest))
8299 if (Other) { // If only one other pred...
8300 BBI = Other->getTerminator();
8301 // Make sure this other block ends in an unconditional branch and that
8302 // there is an instruction before the branch.
8303 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8304 BBI != Other->begin()) {
8306 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8308 // If this instruction is a store to the same location.
8309 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8310 // Okay, we know we can perform this transformation. Insert a PHI
8311 // node now if we need it.
8312 Value *MergedVal = OtherStore->getOperand(0);
8313 if (MergedVal != SI.getOperand(0)) {
8314 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8315 PN->reserveOperandSpace(2);
8316 PN->addIncoming(SI.getOperand(0), SI.getParent());
8317 PN->addIncoming(OtherStore->getOperand(0), Other);
8318 MergedVal = InsertNewInstBefore(PN, Dest->front());
8321 // Advance to a place where it is safe to insert the new store and
8323 BBI = Dest->begin();
8324 while (isa<PHINode>(BBI)) ++BBI;
8325 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8326 OtherStore->isVolatile()), *BBI);
8328 // Nuke the old stores.
8329 EraseInstFromFunction(SI);
8330 EraseInstFromFunction(*OtherStore);
8342 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8343 // Change br (not X), label True, label False to: br X, label False, True
8345 BasicBlock *TrueDest;
8346 BasicBlock *FalseDest;
8347 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8348 !isa<Constant>(X)) {
8349 // Swap Destinations and condition...
8351 BI.setSuccessor(0, FalseDest);
8352 BI.setSuccessor(1, TrueDest);
8356 // Cannonicalize fcmp_one -> fcmp_oeq
8357 FCmpInst::Predicate FPred; Value *Y;
8358 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8359 TrueDest, FalseDest)))
8360 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8361 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8362 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8363 std::string Name = I->getName(); I->setName("");
8364 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8365 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8366 // Swap Destinations and condition...
8367 BI.setCondition(NewSCC);
8368 BI.setSuccessor(0, FalseDest);
8369 BI.setSuccessor(1, TrueDest);
8370 removeFromWorkList(I);
8371 I->getParent()->getInstList().erase(I);
8372 WorkList.push_back(cast<Instruction>(NewSCC));
8376 // Cannonicalize icmp_ne -> icmp_eq
8377 ICmpInst::Predicate IPred;
8378 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8379 TrueDest, FalseDest)))
8380 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8381 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8382 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8383 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8384 std::string Name = I->getName(); I->setName("");
8385 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8386 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8387 // Swap Destinations and condition...
8388 BI.setCondition(NewSCC);
8389 BI.setSuccessor(0, FalseDest);
8390 BI.setSuccessor(1, TrueDest);
8391 removeFromWorkList(I);
8392 I->getParent()->getInstList().erase(I);
8393 WorkList.push_back(cast<Instruction>(NewSCC));
8400 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8401 Value *Cond = SI.getCondition();
8402 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8403 if (I->getOpcode() == Instruction::Add)
8404 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8405 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8406 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8407 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8409 SI.setOperand(0, I->getOperand(0));
8410 WorkList.push_back(I);
8417 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8418 /// is to leave as a vector operation.
8419 static bool CheapToScalarize(Value *V, bool isConstant) {
8420 if (isa<ConstantAggregateZero>(V))
8422 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8423 if (isConstant) return true;
8424 // If all elts are the same, we can extract.
8425 Constant *Op0 = C->getOperand(0);
8426 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8427 if (C->getOperand(i) != Op0)
8431 Instruction *I = dyn_cast<Instruction>(V);
8432 if (!I) return false;
8434 // Insert element gets simplified to the inserted element or is deleted if
8435 // this is constant idx extract element and its a constant idx insertelt.
8436 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8437 isa<ConstantInt>(I->getOperand(2)))
8439 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8441 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8442 if (BO->hasOneUse() &&
8443 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8444 CheapToScalarize(BO->getOperand(1), isConstant)))
8446 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8447 if (CI->hasOneUse() &&
8448 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8449 CheapToScalarize(CI->getOperand(1), isConstant)))
8455 /// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8456 /// elements into values that are larger than the #elts in the input.
8457 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8458 unsigned NElts = SVI->getType()->getNumElements();
8459 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8460 return std::vector<unsigned>(NElts, 0);
8461 if (isa<UndefValue>(SVI->getOperand(2)))
8462 return std::vector<unsigned>(NElts, 2*NElts);
8464 std::vector<unsigned> Result;
8465 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8466 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8467 if (isa<UndefValue>(CP->getOperand(i)))
8468 Result.push_back(NElts*2); // undef -> 8
8470 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8474 /// FindScalarElement - Given a vector and an element number, see if the scalar
8475 /// value is already around as a register, for example if it were inserted then
8476 /// extracted from the vector.
8477 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8478 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8479 const PackedType *PTy = cast<PackedType>(V->getType());
8480 unsigned Width = PTy->getNumElements();
8481 if (EltNo >= Width) // Out of range access.
8482 return UndefValue::get(PTy->getElementType());
8484 if (isa<UndefValue>(V))
8485 return UndefValue::get(PTy->getElementType());
8486 else if (isa<ConstantAggregateZero>(V))
8487 return Constant::getNullValue(PTy->getElementType());
8488 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8489 return CP->getOperand(EltNo);
8490 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8491 // If this is an insert to a variable element, we don't know what it is.
8492 if (!isa<ConstantInt>(III->getOperand(2)))
8494 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8496 // If this is an insert to the element we are looking for, return the
8499 return III->getOperand(1);
8501 // Otherwise, the insertelement doesn't modify the value, recurse on its
8503 return FindScalarElement(III->getOperand(0), EltNo);
8504 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8505 unsigned InEl = getShuffleMask(SVI)[EltNo];
8507 return FindScalarElement(SVI->getOperand(0), InEl);
8508 else if (InEl < Width*2)
8509 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8511 return UndefValue::get(PTy->getElementType());
8514 // Otherwise, we don't know.
8518 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8520 // If packed val is undef, replace extract with scalar undef.
8521 if (isa<UndefValue>(EI.getOperand(0)))
8522 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8524 // If packed val is constant 0, replace extract with scalar 0.
8525 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8526 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8528 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8529 // If packed val is constant with uniform operands, replace EI
8530 // with that operand
8531 Constant *op0 = C->getOperand(0);
8532 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8533 if (C->getOperand(i) != op0) {
8538 return ReplaceInstUsesWith(EI, op0);
8541 // If extracting a specified index from the vector, see if we can recursively
8542 // find a previously computed scalar that was inserted into the vector.
8543 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8544 // This instruction only demands the single element from the input vector.
8545 // If the input vector has a single use, simplify it based on this use
8547 uint64_t IndexVal = IdxC->getZExtValue();
8548 if (EI.getOperand(0)->hasOneUse()) {
8550 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8553 EI.setOperand(0, V);
8558 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8559 return ReplaceInstUsesWith(EI, Elt);
8562 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8563 if (I->hasOneUse()) {
8564 // Push extractelement into predecessor operation if legal and
8565 // profitable to do so
8566 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8567 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8568 if (CheapToScalarize(BO, isConstantElt)) {
8569 ExtractElementInst *newEI0 =
8570 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8571 EI.getName()+".lhs");
8572 ExtractElementInst *newEI1 =
8573 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8574 EI.getName()+".rhs");
8575 InsertNewInstBefore(newEI0, EI);
8576 InsertNewInstBefore(newEI1, EI);
8577 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8579 } else if (isa<LoadInst>(I)) {
8580 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8581 PointerType::get(EI.getType()), EI);
8582 GetElementPtrInst *GEP =
8583 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8584 InsertNewInstBefore(GEP, EI);
8585 return new LoadInst(GEP);
8588 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8589 // Extracting the inserted element?
8590 if (IE->getOperand(2) == EI.getOperand(1))
8591 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8592 // If the inserted and extracted elements are constants, they must not
8593 // be the same value, extract from the pre-inserted value instead.
8594 if (isa<Constant>(IE->getOperand(2)) &&
8595 isa<Constant>(EI.getOperand(1))) {
8596 AddUsesToWorkList(EI);
8597 EI.setOperand(0, IE->getOperand(0));
8600 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8601 // If this is extracting an element from a shufflevector, figure out where
8602 // it came from and extract from the appropriate input element instead.
8603 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8604 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8606 if (SrcIdx < SVI->getType()->getNumElements())
8607 Src = SVI->getOperand(0);
8608 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8609 SrcIdx -= SVI->getType()->getNumElements();
8610 Src = SVI->getOperand(1);
8612 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8614 return new ExtractElementInst(Src, SrcIdx);
8621 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8622 /// elements from either LHS or RHS, return the shuffle mask and true.
8623 /// Otherwise, return false.
8624 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8625 std::vector<Constant*> &Mask) {
8626 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8627 "Invalid CollectSingleShuffleElements");
8628 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8630 if (isa<UndefValue>(V)) {
8631 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8633 } else if (V == LHS) {
8634 for (unsigned i = 0; i != NumElts; ++i)
8635 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8637 } else if (V == RHS) {
8638 for (unsigned i = 0; i != NumElts; ++i)
8639 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8641 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8642 // If this is an insert of an extract from some other vector, include it.
8643 Value *VecOp = IEI->getOperand(0);
8644 Value *ScalarOp = IEI->getOperand(1);
8645 Value *IdxOp = IEI->getOperand(2);
8647 if (!isa<ConstantInt>(IdxOp))
8649 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8651 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8652 // Okay, we can handle this if the vector we are insertinting into is
8654 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8655 // If so, update the mask to reflect the inserted undef.
8656 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8659 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8660 if (isa<ConstantInt>(EI->getOperand(1)) &&
8661 EI->getOperand(0)->getType() == V->getType()) {
8662 unsigned ExtractedIdx =
8663 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8665 // This must be extracting from either LHS or RHS.
8666 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8667 // Okay, we can handle this if the vector we are insertinting into is
8669 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8670 // If so, update the mask to reflect the inserted value.
8671 if (EI->getOperand(0) == LHS) {
8672 Mask[InsertedIdx & (NumElts-1)] =
8673 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8675 assert(EI->getOperand(0) == RHS);
8676 Mask[InsertedIdx & (NumElts-1)] =
8677 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8686 // TODO: Handle shufflevector here!
8691 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8692 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8693 /// that computes V and the LHS value of the shuffle.
8694 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8696 assert(isa<PackedType>(V->getType()) &&
8697 (RHS == 0 || V->getType() == RHS->getType()) &&
8698 "Invalid shuffle!");
8699 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8701 if (isa<UndefValue>(V)) {
8702 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8704 } else if (isa<ConstantAggregateZero>(V)) {
8705 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8707 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8708 // If this is an insert of an extract from some other vector, include it.
8709 Value *VecOp = IEI->getOperand(0);
8710 Value *ScalarOp = IEI->getOperand(1);
8711 Value *IdxOp = IEI->getOperand(2);
8713 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8714 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8715 EI->getOperand(0)->getType() == V->getType()) {
8716 unsigned ExtractedIdx =
8717 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8718 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8720 // Either the extracted from or inserted into vector must be RHSVec,
8721 // otherwise we'd end up with a shuffle of three inputs.
8722 if (EI->getOperand(0) == RHS || RHS == 0) {
8723 RHS = EI->getOperand(0);
8724 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8725 Mask[InsertedIdx & (NumElts-1)] =
8726 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8731 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8732 // Everything but the extracted element is replaced with the RHS.
8733 for (unsigned i = 0; i != NumElts; ++i) {
8734 if (i != InsertedIdx)
8735 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8740 // If this insertelement is a chain that comes from exactly these two
8741 // vectors, return the vector and the effective shuffle.
8742 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8743 return EI->getOperand(0);
8748 // TODO: Handle shufflevector here!
8750 // Otherwise, can't do anything fancy. Return an identity vector.
8751 for (unsigned i = 0; i != NumElts; ++i)
8752 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8756 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8757 Value *VecOp = IE.getOperand(0);
8758 Value *ScalarOp = IE.getOperand(1);
8759 Value *IdxOp = IE.getOperand(2);
8761 // If the inserted element was extracted from some other vector, and if the
8762 // indexes are constant, try to turn this into a shufflevector operation.
8763 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8764 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8765 EI->getOperand(0)->getType() == IE.getType()) {
8766 unsigned NumVectorElts = IE.getType()->getNumElements();
8767 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8768 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8770 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8771 return ReplaceInstUsesWith(IE, VecOp);
8773 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8774 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8776 // If we are extracting a value from a vector, then inserting it right
8777 // back into the same place, just use the input vector.
8778 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8779 return ReplaceInstUsesWith(IE, VecOp);
8781 // We could theoretically do this for ANY input. However, doing so could
8782 // turn chains of insertelement instructions into a chain of shufflevector
8783 // instructions, and right now we do not merge shufflevectors. As such,
8784 // only do this in a situation where it is clear that there is benefit.
8785 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8786 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8787 // the values of VecOp, except then one read from EIOp0.
8788 // Build a new shuffle mask.
8789 std::vector<Constant*> Mask;
8790 if (isa<UndefValue>(VecOp))
8791 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8793 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8794 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8797 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8798 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8799 ConstantPacked::get(Mask));
8802 // If this insertelement isn't used by some other insertelement, turn it
8803 // (and any insertelements it points to), into one big shuffle.
8804 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8805 std::vector<Constant*> Mask;
8807 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8808 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8809 // We now have a shuffle of LHS, RHS, Mask.
8810 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8819 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8820 Value *LHS = SVI.getOperand(0);
8821 Value *RHS = SVI.getOperand(1);
8822 std::vector<unsigned> Mask = getShuffleMask(&SVI);
8824 bool MadeChange = false;
8826 // Undefined shuffle mask -> undefined value.
8827 if (isa<UndefValue>(SVI.getOperand(2)))
8828 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8830 // If we have shuffle(x, undef, mask) and any elements of mask refer to
8831 // the undef, change them to undefs.
8832 if (isa<UndefValue>(SVI.getOperand(1))) {
8833 // Scan to see if there are any references to the RHS. If so, replace them
8834 // with undef element refs and set MadeChange to true.
8835 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8836 if (Mask[i] >= e && Mask[i] != 2*e) {
8843 // Remap any references to RHS to use LHS.
8844 std::vector<Constant*> Elts;
8845 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8847 Elts.push_back(UndefValue::get(Type::Int32Ty));
8849 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8851 SVI.setOperand(2, ConstantPacked::get(Elts));
8855 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8856 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8857 if (LHS == RHS || isa<UndefValue>(LHS)) {
8858 if (isa<UndefValue>(LHS) && LHS == RHS) {
8859 // shuffle(undef,undef,mask) -> undef.
8860 return ReplaceInstUsesWith(SVI, LHS);
8863 // Remap any references to RHS to use LHS.
8864 std::vector<Constant*> Elts;
8865 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8867 Elts.push_back(UndefValue::get(Type::Int32Ty));
8869 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8870 (Mask[i] < e && isa<UndefValue>(LHS)))
8871 Mask[i] = 2*e; // Turn into undef.
8873 Mask[i] &= (e-1); // Force to LHS.
8874 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8877 SVI.setOperand(0, SVI.getOperand(1));
8878 SVI.setOperand(1, UndefValue::get(RHS->getType()));
8879 SVI.setOperand(2, ConstantPacked::get(Elts));
8880 LHS = SVI.getOperand(0);
8881 RHS = SVI.getOperand(1);
8885 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8886 bool isLHSID = true, isRHSID = true;
8888 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8889 if (Mask[i] >= e*2) continue; // Ignore undef values.
8890 // Is this an identity shuffle of the LHS value?
8891 isLHSID &= (Mask[i] == i);
8893 // Is this an identity shuffle of the RHS value?
8894 isRHSID &= (Mask[i]-e == i);
8897 // Eliminate identity shuffles.
8898 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8899 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8901 // If the LHS is a shufflevector itself, see if we can combine it with this
8902 // one without producing an unusual shuffle. Here we are really conservative:
8903 // we are absolutely afraid of producing a shuffle mask not in the input
8904 // program, because the code gen may not be smart enough to turn a merged
8905 // shuffle into two specific shuffles: it may produce worse code. As such,
8906 // we only merge two shuffles if the result is one of the two input shuffle
8907 // masks. In this case, merging the shuffles just removes one instruction,
8908 // which we know is safe. This is good for things like turning:
8909 // (splat(splat)) -> splat.
8910 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8911 if (isa<UndefValue>(RHS)) {
8912 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8914 std::vector<unsigned> NewMask;
8915 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8917 NewMask.push_back(2*e);
8919 NewMask.push_back(LHSMask[Mask[i]]);
8921 // If the result mask is equal to the src shuffle or this shuffle mask, do
8923 if (NewMask == LHSMask || NewMask == Mask) {
8924 std::vector<Constant*> Elts;
8925 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8926 if (NewMask[i] >= e*2) {
8927 Elts.push_back(UndefValue::get(Type::Int32Ty));
8929 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
8932 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8933 LHSSVI->getOperand(1),
8934 ConstantPacked::get(Elts));
8939 return MadeChange ? &SVI : 0;
8944 void InstCombiner::removeFromWorkList(Instruction *I) {
8945 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8950 /// TryToSinkInstruction - Try to move the specified instruction from its
8951 /// current block into the beginning of DestBlock, which can only happen if it's
8952 /// safe to move the instruction past all of the instructions between it and the
8953 /// end of its block.
8954 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8955 assert(I->hasOneUse() && "Invariants didn't hold!");
8957 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8958 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8960 // Do not sink alloca instructions out of the entry block.
8961 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8964 // We can only sink load instructions if there is nothing between the load and
8965 // the end of block that could change the value.
8966 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8967 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8969 if (Scan->mayWriteToMemory())
8973 BasicBlock::iterator InsertPos = DestBlock->begin();
8974 while (isa<PHINode>(InsertPos)) ++InsertPos;
8976 I->moveBefore(InsertPos);
8981 /// OptimizeConstantExpr - Given a constant expression and target data layout
8982 /// information, symbolically evaluate the constant expr to something simpler
8984 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8987 Constant *Ptr = CE->getOperand(0);
8988 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8989 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8990 // If this is a constant expr gep that is effectively computing an
8991 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8992 bool isFoldableGEP = true;
8993 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8994 if (!isa<ConstantInt>(CE->getOperand(i)))
8995 isFoldableGEP = false;
8996 if (isFoldableGEP) {
8997 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8998 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8999 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
9000 return ConstantExpr::getIntToPtr(C, CE->getType());
9008 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9009 /// all reachable code to the worklist.
9011 /// This has a couple of tricks to make the code faster and more powerful. In
9012 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9013 /// them to the worklist (this significantly speeds up instcombine on code where
9014 /// many instructions are dead or constant). Additionally, if we find a branch
9015 /// whose condition is a known constant, we only visit the reachable successors.
9017 static void AddReachableCodeToWorklist(BasicBlock *BB,
9018 std::set<BasicBlock*> &Visited,
9019 std::vector<Instruction*> &WorkList,
9020 const TargetData *TD) {
9021 // We have now visited this block! If we've already been here, bail out.
9022 if (!Visited.insert(BB).second) return;
9024 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9025 Instruction *Inst = BBI++;
9027 // DCE instruction if trivially dead.
9028 if (isInstructionTriviallyDead(Inst)) {
9030 DOUT << "IC: DCE: " << *Inst;
9031 Inst->eraseFromParent();
9035 // ConstantProp instruction if trivially constant.
9036 if (Constant *C = ConstantFoldInstruction(Inst)) {
9037 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9038 C = OptimizeConstantExpr(CE, TD);
9039 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9040 Inst->replaceAllUsesWith(C);
9042 Inst->eraseFromParent();
9046 WorkList.push_back(Inst);
9049 // Recursively visit successors. If this is a branch or switch on a constant,
9050 // only visit the reachable successor.
9051 TerminatorInst *TI = BB->getTerminator();
9052 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9053 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9054 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
9055 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9059 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9060 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9061 // See if this is an explicit destination.
9062 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9063 if (SI->getCaseValue(i) == Cond) {
9064 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9068 // Otherwise it is the default destination.
9069 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9074 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9075 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9078 bool InstCombiner::runOnFunction(Function &F) {
9079 bool Changed = false;
9080 TD = &getAnalysis<TargetData>();
9083 // Do a depth-first traversal of the function, populate the worklist with
9084 // the reachable instructions. Ignore blocks that are not reachable. Keep
9085 // track of which blocks we visit.
9086 std::set<BasicBlock*> Visited;
9087 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9089 // Do a quick scan over the function. If we find any blocks that are
9090 // unreachable, remove any instructions inside of them. This prevents
9091 // the instcombine code from having to deal with some bad special cases.
9092 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9093 if (!Visited.count(BB)) {
9094 Instruction *Term = BB->getTerminator();
9095 while (Term != BB->begin()) { // Remove instrs bottom-up
9096 BasicBlock::iterator I = Term; --I;
9098 DOUT << "IC: DCE: " << *I;
9101 if (!I->use_empty())
9102 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9103 I->eraseFromParent();
9108 while (!WorkList.empty()) {
9109 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9110 WorkList.pop_back();
9112 // Check to see if we can DCE the instruction.
9113 if (isInstructionTriviallyDead(I)) {
9114 // Add operands to the worklist.
9115 if (I->getNumOperands() < 4)
9116 AddUsesToWorkList(*I);
9119 DOUT << "IC: DCE: " << *I;
9121 I->eraseFromParent();
9122 removeFromWorkList(I);
9126 // Instruction isn't dead, see if we can constant propagate it.
9127 if (Constant *C = ConstantFoldInstruction(I)) {
9128 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9129 C = OptimizeConstantExpr(CE, TD);
9130 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9132 // Add operands to the worklist.
9133 AddUsesToWorkList(*I);
9134 ReplaceInstUsesWith(*I, C);
9137 I->eraseFromParent();
9138 removeFromWorkList(I);
9142 // See if we can trivially sink this instruction to a successor basic block.
9143 if (I->hasOneUse()) {
9144 BasicBlock *BB = I->getParent();
9145 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9146 if (UserParent != BB) {
9147 bool UserIsSuccessor = false;
9148 // See if the user is one of our successors.
9149 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9150 if (*SI == UserParent) {
9151 UserIsSuccessor = true;
9155 // If the user is one of our immediate successors, and if that successor
9156 // only has us as a predecessors (we'd have to split the critical edge
9157 // otherwise), we can keep going.
9158 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9159 next(pred_begin(UserParent)) == pred_end(UserParent))
9160 // Okay, the CFG is simple enough, try to sink this instruction.
9161 Changed |= TryToSinkInstruction(I, UserParent);
9165 // Now that we have an instruction, try combining it to simplify it...
9166 if (Instruction *Result = visit(*I)) {
9168 // Should we replace the old instruction with a new one?
9170 DOUT << "IC: Old = " << *I
9171 << " New = " << *Result;
9173 // Everything uses the new instruction now.
9174 I->replaceAllUsesWith(Result);
9176 // Push the new instruction and any users onto the worklist.
9177 WorkList.push_back(Result);
9178 AddUsersToWorkList(*Result);
9180 // Move the name to the new instruction first...
9181 std::string OldName = I->getName(); I->setName("");
9182 Result->setName(OldName);
9184 // Insert the new instruction into the basic block...
9185 BasicBlock *InstParent = I->getParent();
9186 BasicBlock::iterator InsertPos = I;
9188 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9189 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9192 InstParent->getInstList().insert(InsertPos, Result);
9194 // Make sure that we reprocess all operands now that we reduced their
9196 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9197 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9198 WorkList.push_back(OpI);
9200 // Instructions can end up on the worklist more than once. Make sure
9201 // we do not process an instruction that has been deleted.
9202 removeFromWorkList(I);
9204 // Erase the old instruction.
9205 InstParent->getInstList().erase(I);
9207 DOUT << "IC: MOD = " << *I;
9209 // If the instruction was modified, it's possible that it is now dead.
9210 // if so, remove it.
9211 if (isInstructionTriviallyDead(I)) {
9212 // Make sure we process all operands now that we are reducing their
9214 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9215 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9216 WorkList.push_back(OpI);
9218 // Instructions may end up in the worklist more than once. Erase all
9219 // occurrences of this instruction.
9220 removeFromWorkList(I);
9221 I->eraseFromParent();
9223 WorkList.push_back(Result);
9224 AddUsersToWorkList(*Result);
9234 FunctionPass *llvm::createInstructionCombiningPass() {
9235 return new InstCombiner();