1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All SetCC instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
56 using namespace llvm::PatternMatch;
59 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
63 Statistic<> NumSunkInst ("instcombine", "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 *visitSetCondInst(SetCondInst &I);
147 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
149 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
150 Instruction::BinaryOps Cond, Instruction &I);
151 Instruction *visitShiftInst(ShiftInst &I);
152 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
154 Instruction *commonCastTransforms(CastInst &CI);
155 Instruction *commonIntCastTransforms(CastInst &CI);
156 Instruction *visitTrunc(CastInst &CI);
157 Instruction *visitZExt(CastInst &CI);
158 Instruction *visitSExt(CastInst &CI);
159 Instruction *visitFPTrunc(CastInst &CI);
160 Instruction *visitFPExt(CastInst &CI);
161 Instruction *visitFPToUI(CastInst &CI);
162 Instruction *visitFPToSI(CastInst &CI);
163 Instruction *visitUIToFP(CastInst &CI);
164 Instruction *visitSIToFP(CastInst &CI);
165 Instruction *visitPtrToInt(CastInst &CI);
166 Instruction *visitIntToPtr(CastInst &CI);
167 Instruction *visitBitCast(CastInst &CI);
168 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170 Instruction *visitSelectInst(SelectInst &CI);
171 Instruction *visitCallInst(CallInst &CI);
172 Instruction *visitInvokeInst(InvokeInst &II);
173 Instruction *visitPHINode(PHINode &PN);
174 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
175 Instruction *visitAllocationInst(AllocationInst &AI);
176 Instruction *visitFreeInst(FreeInst &FI);
177 Instruction *visitLoadInst(LoadInst &LI);
178 Instruction *visitStoreInst(StoreInst &SI);
179 Instruction *visitBranchInst(BranchInst &BI);
180 Instruction *visitSwitchInst(SwitchInst &SI);
181 Instruction *visitInsertElementInst(InsertElementInst &IE);
182 Instruction *visitExtractElementInst(ExtractElementInst &EI);
183 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
185 // visitInstruction - Specify what to return for unhandled instructions...
186 Instruction *visitInstruction(Instruction &I) { return 0; }
189 Instruction *visitCallSite(CallSite CS);
190 bool transformConstExprCastCall(CallSite CS);
193 // InsertNewInstBefore - insert an instruction New before instruction Old
194 // in the program. Add the new instruction to the worklist.
196 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
197 assert(New && New->getParent() == 0 &&
198 "New instruction already inserted into a basic block!");
199 BasicBlock *BB = Old.getParent();
200 BB->getInstList().insert(&Old, New); // Insert inst
201 WorkList.push_back(New); // Add to worklist
205 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
206 /// This also adds the cast to the worklist. Finally, this returns the
208 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
209 if (V->getType() == Ty) return V;
211 if (Constant *CV = dyn_cast<Constant>(V))
212 return ConstantExpr::getCast(CV, Ty);
214 Instruction *C = CastInst::createInferredCast(V, Ty, V->getName(), &Pos);
215 WorkList.push_back(C);
219 // ReplaceInstUsesWith - This method is to be used when an instruction is
220 // found to be dead, replacable with another preexisting expression. Here
221 // we add all uses of I to the worklist, replace all uses of I with the new
222 // value, then return I, so that the inst combiner will know that I was
225 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
226 AddUsersToWorkList(I); // Add all modified instrs to worklist
228 I.replaceAllUsesWith(V);
231 // If we are replacing the instruction with itself, this must be in a
232 // segment of unreachable code, so just clobber the instruction.
233 I.replaceAllUsesWith(UndefValue::get(I.getType()));
238 // UpdateValueUsesWith - This method is to be used when an value is
239 // found to be replacable with another preexisting expression or was
240 // updated. Here we add all uses of I to the worklist, replace all uses of
241 // I with the new value (unless the instruction was just updated), then
242 // return true, so that the inst combiner will know that I was modified.
244 bool UpdateValueUsesWith(Value *Old, Value *New) {
245 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
247 Old->replaceAllUsesWith(New);
248 if (Instruction *I = dyn_cast<Instruction>(Old))
249 WorkList.push_back(I);
250 if (Instruction *I = dyn_cast<Instruction>(New))
251 WorkList.push_back(I);
255 // EraseInstFromFunction - When dealing with an instruction that has side
256 // effects or produces a void value, we can't rely on DCE to delete the
257 // instruction. Instead, visit methods should return the value returned by
259 Instruction *EraseInstFromFunction(Instruction &I) {
260 assert(I.use_empty() && "Cannot erase instruction that is used!");
261 AddUsesToWorkList(I);
262 removeFromWorkList(&I);
264 return 0; // Don't do anything with FI
268 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
269 /// InsertBefore instruction. This is specialized a bit to avoid inserting
270 /// casts that are known to not do anything...
272 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
273 Instruction *InsertBefore);
275 // SimplifyCommutative - This performs a few simplifications for commutative
277 bool SimplifyCommutative(BinaryOperator &I);
279 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
280 uint64_t &KnownZero, uint64_t &KnownOne,
283 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
284 uint64_t &UndefElts, unsigned Depth = 0);
286 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
287 // PHI node as operand #0, see if we can fold the instruction into the PHI
288 // (which is only possible if all operands to the PHI are constants).
289 Instruction *FoldOpIntoPhi(Instruction &I);
291 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
292 // operator and they all are only used by the PHI, PHI together their
293 // inputs, and do the operation once, to the result of the PHI.
294 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
295 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
298 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
299 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
301 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
302 bool isSub, Instruction &I);
303 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
304 bool Inside, Instruction &IB);
305 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
306 Instruction *MatchBSwap(BinaryOperator &I);
308 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
311 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
314 // getComplexity: Assign a complexity or rank value to LLVM Values...
315 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
316 static unsigned getComplexity(Value *V) {
317 if (isa<Instruction>(V)) {
318 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
322 if (isa<Argument>(V)) return 3;
323 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
326 // isOnlyUse - Return true if this instruction will be deleted if we stop using
328 static bool isOnlyUse(Value *V) {
329 return V->hasOneUse() || isa<Constant>(V);
332 // getPromotedType - Return the specified type promoted as it would be to pass
333 // though a va_arg area...
334 static const Type *getPromotedType(const Type *Ty) {
335 switch (Ty->getTypeID()) {
336 case Type::SByteTyID:
337 case Type::ShortTyID: return Type::IntTy;
338 case Type::UByteTyID:
339 case Type::UShortTyID: return Type::UIntTy;
340 case Type::FloatTyID: return Type::DoubleTy;
345 /// getBitCastOperand - If the specified operand is a CastInst or a constant
346 /// expression bitcast, return the operand value, otherwise return null.
347 static Value *getBitCastOperand(Value *V) {
348 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
349 return I->getOperand(0);
350 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
351 if (CE->getOpcode() == Instruction::BitCast)
352 return CE->getOperand(0);
356 /// This function is a wrapper around CastInst::isEliminableCastPair. It
357 /// simply extracts arguments and returns what that function returns.
358 /// @Determine if it is valid to eliminate a Convert pair
359 static Instruction::CastOps
360 isEliminableCastPair(
361 const CastInst *CI, ///< The first cast instruction
362 unsigned opcode, ///< The opcode of the second cast instruction
363 const Type *DstTy, ///< The target type for the second cast instruction
364 TargetData *TD ///< The target data for pointer size
367 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
368 const Type *MidTy = CI->getType(); // B from above
370 // Get the opcodes of the two Cast instructions
371 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
372 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
374 return Instruction::CastOps(
375 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
376 DstTy, TD->getIntPtrType()));
379 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
380 /// in any code being generated. It does not require codegen if V is simple
381 /// enough or if the cast can be folded into other casts.
382 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
383 if (V->getType() == Ty || isa<Constant>(V)) return false;
385 // If this is a noop cast, it isn't real codegen.
386 if (V->getType()->canLosslesslyBitCastTo(Ty))
389 // If this is another cast that can be eliminated, it isn't codegen either.
390 if (const CastInst *CI = dyn_cast<CastInst>(V))
391 if (isEliminableCastPair(CI, CastInst::getCastOpcode(V, Ty), Ty, TD))
396 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
397 /// InsertBefore instruction. This is specialized a bit to avoid inserting
398 /// casts that are known to not do anything...
400 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
401 Instruction *InsertBefore) {
402 if (V->getType() == DestTy) return V;
403 if (Constant *C = dyn_cast<Constant>(V))
404 return ConstantExpr::getCast(C, DestTy);
406 return InsertCastBefore(V, DestTy, *InsertBefore);
409 // SimplifyCommutative - This performs a few simplifications for commutative
412 // 1. Order operands such that they are listed from right (least complex) to
413 // left (most complex). This puts constants before unary operators before
416 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
417 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
419 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
420 bool Changed = false;
421 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
422 Changed = !I.swapOperands();
424 if (!I.isAssociative()) return Changed;
425 Instruction::BinaryOps Opcode = I.getOpcode();
426 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
427 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
428 if (isa<Constant>(I.getOperand(1))) {
429 Constant *Folded = ConstantExpr::get(I.getOpcode(),
430 cast<Constant>(I.getOperand(1)),
431 cast<Constant>(Op->getOperand(1)));
432 I.setOperand(0, Op->getOperand(0));
433 I.setOperand(1, Folded);
435 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
436 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
437 isOnlyUse(Op) && isOnlyUse(Op1)) {
438 Constant *C1 = cast<Constant>(Op->getOperand(1));
439 Constant *C2 = cast<Constant>(Op1->getOperand(1));
441 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
442 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
443 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
446 WorkList.push_back(New);
447 I.setOperand(0, New);
448 I.setOperand(1, Folded);
455 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
456 // if the LHS is a constant zero (which is the 'negate' form).
458 static inline Value *dyn_castNegVal(Value *V) {
459 if (BinaryOperator::isNeg(V))
460 return BinaryOperator::getNegArgument(V);
462 // Constants can be considered to be negated values if they can be folded.
463 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
464 return ConstantExpr::getNeg(C);
468 static inline Value *dyn_castNotVal(Value *V) {
469 if (BinaryOperator::isNot(V))
470 return BinaryOperator::getNotArgument(V);
472 // Constants can be considered to be not'ed values...
473 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
474 return ConstantExpr::getNot(C);
478 // dyn_castFoldableMul - If this value is a multiply that can be folded into
479 // other computations (because it has a constant operand), return the
480 // non-constant operand of the multiply, and set CST to point to the multiplier.
481 // Otherwise, return null.
483 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
484 if (V->hasOneUse() && V->getType()->isInteger())
485 if (Instruction *I = dyn_cast<Instruction>(V)) {
486 if (I->getOpcode() == Instruction::Mul)
487 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
488 return I->getOperand(0);
489 if (I->getOpcode() == Instruction::Shl)
490 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
491 // The multiplier is really 1 << CST.
492 Constant *One = ConstantInt::get(V->getType(), 1);
493 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
494 return I->getOperand(0);
500 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
501 /// expression, return it.
502 static User *dyn_castGetElementPtr(Value *V) {
503 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
504 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
505 if (CE->getOpcode() == Instruction::GetElementPtr)
506 return cast<User>(V);
510 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
511 static ConstantInt *AddOne(ConstantInt *C) {
512 return cast<ConstantInt>(ConstantExpr::getAdd(C,
513 ConstantInt::get(C->getType(), 1)));
515 static ConstantInt *SubOne(ConstantInt *C) {
516 return cast<ConstantInt>(ConstantExpr::getSub(C,
517 ConstantInt::get(C->getType(), 1)));
520 /// GetConstantInType - Return a ConstantInt with the specified type and value.
522 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
523 if (Ty->isUnsigned())
524 return ConstantInt::get(Ty, Val);
525 else if (Ty->getTypeID() == Type::BoolTyID)
526 return ConstantBool::get(Val);
528 SVal <<= 64-Ty->getPrimitiveSizeInBits();
529 SVal >>= 64-Ty->getPrimitiveSizeInBits();
530 return ConstantInt::get(Ty, SVal);
534 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
535 /// known to be either zero or one and return them in the KnownZero/KnownOne
536 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
538 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
539 uint64_t &KnownOne, unsigned Depth = 0) {
540 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
541 // we cannot optimize based on the assumption that it is zero without changing
542 // it to be an explicit zero. If we don't change it to zero, other code could
543 // optimized based on the contradictory assumption that it is non-zero.
544 // Because instcombine aggressively folds operations with undef args anyway,
545 // this won't lose us code quality.
546 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
547 // We know all of the bits for a constant!
548 KnownOne = CI->getZExtValue() & Mask;
549 KnownZero = ~KnownOne & Mask;
553 KnownZero = KnownOne = 0; // Don't know anything.
554 if (Depth == 6 || Mask == 0)
555 return; // Limit search depth.
557 uint64_t KnownZero2, KnownOne2;
558 Instruction *I = dyn_cast<Instruction>(V);
561 Mask &= V->getType()->getIntegralTypeMask();
563 switch (I->getOpcode()) {
564 case Instruction::And:
565 // If either the LHS or the RHS are Zero, the result is zero.
566 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
568 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
569 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
570 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
572 // Output known-1 bits are only known if set in both the LHS & RHS.
573 KnownOne &= KnownOne2;
574 // Output known-0 are known to be clear if zero in either the LHS | RHS.
575 KnownZero |= KnownZero2;
577 case Instruction::Or:
578 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
580 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
581 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
582 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
584 // Output known-0 bits are only known if clear in both the LHS & RHS.
585 KnownZero &= KnownZero2;
586 // Output known-1 are known to be set if set in either the LHS | RHS.
587 KnownOne |= KnownOne2;
589 case Instruction::Xor: {
590 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
591 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
592 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
593 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
595 // Output known-0 bits are known if clear or set in both the LHS & RHS.
596 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
597 // Output known-1 are known to be set if set in only one of the LHS, RHS.
598 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
599 KnownZero = KnownZeroOut;
602 case Instruction::Select:
603 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
604 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
605 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
606 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
608 // Only known if known in both the LHS and RHS.
609 KnownOne &= KnownOne2;
610 KnownZero &= KnownZero2;
612 case Instruction::FPTrunc:
613 case Instruction::FPExt:
614 case Instruction::FPToUI:
615 case Instruction::FPToSI:
616 case Instruction::SIToFP:
617 case Instruction::PtrToInt:
618 case Instruction::UIToFP:
619 case Instruction::IntToPtr:
620 return; // Can't work with floating point or pointers
621 case Instruction::Trunc:
622 // All these have integer operands
623 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
625 case Instruction::BitCast: {
626 const Type *SrcTy = I->getOperand(0)->getType();
627 if (SrcTy->isIntegral()) {
628 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
633 case Instruction::ZExt: {
634 // Compute the bits in the result that are not present in the input.
635 const Type *SrcTy = I->getOperand(0)->getType();
636 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
637 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
639 Mask &= SrcTy->getIntegralTypeMask();
640 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
641 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
642 // The top bits are known to be zero.
643 KnownZero |= NewBits;
646 case Instruction::SExt: {
647 // Compute the bits in the result that are not present in the input.
648 const Type *SrcTy = I->getOperand(0)->getType();
649 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
650 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
652 Mask &= SrcTy->getIntegralTypeMask();
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
656 // If the sign bit of the input is known set or clear, then we know the
657 // top bits of the result.
658 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
659 if (KnownZero & InSignBit) { // Input sign bit known zero
660 KnownZero |= NewBits;
661 KnownOne &= ~NewBits;
662 } else if (KnownOne & InSignBit) { // Input sign bit known set
664 KnownZero &= ~NewBits;
665 } else { // Input sign bit unknown
666 KnownZero &= ~NewBits;
667 KnownOne &= ~NewBits;
671 case Instruction::Shl:
672 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
673 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
674 uint64_t ShiftAmt = SA->getZExtValue();
676 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
677 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
678 KnownZero <<= ShiftAmt;
679 KnownOne <<= ShiftAmt;
680 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
684 case Instruction::LShr:
685 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
686 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
687 // Compute the new bits that are at the top now.
688 uint64_t ShiftAmt = SA->getZExtValue();
689 uint64_t HighBits = (1ULL << ShiftAmt)-1;
690 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
692 // Unsigned shift right.
694 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
695 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
696 KnownZero >>= ShiftAmt;
697 KnownOne >>= ShiftAmt;
698 KnownZero |= HighBits; // high bits known zero.
702 case Instruction::AShr:
703 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
704 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
705 // Compute the new bits that are at the top now.
706 uint64_t ShiftAmt = SA->getZExtValue();
707 uint64_t HighBits = (1ULL << ShiftAmt)-1;
708 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
710 // Signed shift right.
712 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
714 KnownZero >>= ShiftAmt;
715 KnownOne >>= ShiftAmt;
717 // Handle the sign bits.
718 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
719 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
721 if (KnownZero & SignBit) { // New bits are known zero.
722 KnownZero |= HighBits;
723 } else if (KnownOne & SignBit) { // New bits are known one.
724 KnownOne |= HighBits;
732 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
733 /// this predicate to simplify operations downstream. Mask is known to be zero
734 /// for bits that V cannot have.
735 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
736 uint64_t KnownZero, KnownOne;
737 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
738 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
739 return (KnownZero & Mask) == Mask;
742 /// ShrinkDemandedConstant - Check to see if the specified operand of the
743 /// specified instruction is a constant integer. If so, check to see if there
744 /// are any bits set in the constant that are not demanded. If so, shrink the
745 /// constant and return true.
746 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
748 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
749 if (!OpC) return false;
751 // If there are no bits set that aren't demanded, nothing to do.
752 if ((~Demanded & OpC->getZExtValue()) == 0)
755 // This is producing any bits that are not needed, shrink the RHS.
756 uint64_t Val = Demanded & OpC->getZExtValue();
757 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
761 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
762 // set of known zero and one bits, compute the maximum and minimum values that
763 // could have the specified known zero and known one bits, returning them in
765 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
768 int64_t &Min, int64_t &Max) {
769 uint64_t TypeBits = Ty->getIntegralTypeMask();
770 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
772 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
774 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
775 // bit if it is unknown.
777 Max = KnownOne|UnknownBits;
779 if (SignBit & UnknownBits) { // Sign bit is unknown
784 // Sign extend the min/max values.
785 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
786 Min = (Min << ShAmt) >> ShAmt;
787 Max = (Max << ShAmt) >> ShAmt;
790 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
791 // a set of known zero and one bits, compute the maximum and minimum values that
792 // could have the specified known zero and known one bits, returning them in
794 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
799 uint64_t TypeBits = Ty->getIntegralTypeMask();
800 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
802 // The minimum value is when the unknown bits are all zeros.
804 // The maximum value is when the unknown bits are all ones.
805 Max = KnownOne|UnknownBits;
809 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
810 /// DemandedMask bits of the result of V are ever used downstream. If we can
811 /// use this information to simplify V, do so and return true. Otherwise,
812 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
813 /// the expression (used to simplify the caller). The KnownZero/One bits may
814 /// only be accurate for those bits in the DemandedMask.
815 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
816 uint64_t &KnownZero, uint64_t &KnownOne,
818 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
819 // We know all of the bits for a constant!
820 KnownOne = CI->getZExtValue() & DemandedMask;
821 KnownZero = ~KnownOne & DemandedMask;
825 KnownZero = KnownOne = 0;
826 if (!V->hasOneUse()) { // Other users may use these bits.
827 if (Depth != 0) { // Not at the root.
828 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
829 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
832 // If this is the root being simplified, allow it to have multiple uses,
833 // just set the DemandedMask to all bits.
834 DemandedMask = V->getType()->getIntegralTypeMask();
835 } else if (DemandedMask == 0) { // Not demanding any bits from V.
836 if (V != UndefValue::get(V->getType()))
837 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
839 } else if (Depth == 6) { // Limit search depth.
843 Instruction *I = dyn_cast<Instruction>(V);
844 if (!I) return false; // Only analyze instructions.
846 DemandedMask &= V->getType()->getIntegralTypeMask();
848 uint64_t KnownZero2 = 0, KnownOne2 = 0;
849 switch (I->getOpcode()) {
851 case Instruction::And:
852 // If either the LHS or the RHS are Zero, the result is zero.
853 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
854 KnownZero, KnownOne, Depth+1))
856 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
858 // If something is known zero on the RHS, the bits aren't demanded on the
860 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
861 KnownZero2, KnownOne2, Depth+1))
863 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
865 // If all of the demanded bits are known 1 on one side, return the other.
866 // These bits cannot contribute to the result of the 'and'.
867 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
868 return UpdateValueUsesWith(I, I->getOperand(0));
869 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
870 return UpdateValueUsesWith(I, I->getOperand(1));
872 // If all of the demanded bits in the inputs are known zeros, return zero.
873 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
874 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
876 // If the RHS is a constant, see if we can simplify it.
877 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
878 return UpdateValueUsesWith(I, I);
880 // Output known-1 bits are only known if set in both the LHS & RHS.
881 KnownOne &= KnownOne2;
882 // Output known-0 are known to be clear if zero in either the LHS | RHS.
883 KnownZero |= KnownZero2;
885 case Instruction::Or:
886 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
887 KnownZero, KnownOne, Depth+1))
889 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
890 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
891 KnownZero2, KnownOne2, Depth+1))
893 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
895 // If all of the demanded bits are known zero on one side, return the other.
896 // These bits cannot contribute to the result of the 'or'.
897 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
898 return UpdateValueUsesWith(I, I->getOperand(0));
899 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
900 return UpdateValueUsesWith(I, I->getOperand(1));
902 // If all of the potentially set bits on one side are known to be set on
903 // the other side, just use the 'other' side.
904 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
905 (DemandedMask & (~KnownZero)))
906 return UpdateValueUsesWith(I, I->getOperand(0));
907 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
908 (DemandedMask & (~KnownZero2)))
909 return UpdateValueUsesWith(I, I->getOperand(1));
911 // If the RHS is a constant, see if we can simplify it.
912 if (ShrinkDemandedConstant(I, 1, DemandedMask))
913 return UpdateValueUsesWith(I, I);
915 // Output known-0 bits are only known if clear in both the LHS & RHS.
916 KnownZero &= KnownZero2;
917 // Output known-1 are known to be set if set in either the LHS | RHS.
918 KnownOne |= KnownOne2;
920 case Instruction::Xor: {
921 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
922 KnownZero, KnownOne, Depth+1))
924 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
925 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
926 KnownZero2, KnownOne2, Depth+1))
928 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
930 // If all of the demanded bits are known zero on one side, return the other.
931 // These bits cannot contribute to the result of the 'xor'.
932 if ((DemandedMask & KnownZero) == DemandedMask)
933 return UpdateValueUsesWith(I, I->getOperand(0));
934 if ((DemandedMask & KnownZero2) == DemandedMask)
935 return UpdateValueUsesWith(I, I->getOperand(1));
937 // Output known-0 bits are known if clear or set in both the LHS & RHS.
938 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
939 // Output known-1 are known to be set if set in only one of the LHS, RHS.
940 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
942 // If all of the demanded bits are known to be zero on one side or the
943 // other, turn this into an *inclusive* or.
944 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
945 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
947 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
949 InsertNewInstBefore(Or, *I);
950 return UpdateValueUsesWith(I, Or);
953 // If all of the demanded bits on one side are known, and all of the set
954 // bits on that side are also known to be set on the other side, turn this
955 // into an AND, as we know the bits will be cleared.
956 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
957 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
958 if ((KnownOne & KnownOne2) == KnownOne) {
959 Constant *AndC = GetConstantInType(I->getType(),
960 ~KnownOne & DemandedMask);
962 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
963 InsertNewInstBefore(And, *I);
964 return UpdateValueUsesWith(I, And);
968 // If the RHS is a constant, see if we can simplify it.
969 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
970 if (ShrinkDemandedConstant(I, 1, DemandedMask))
971 return UpdateValueUsesWith(I, I);
973 KnownZero = KnownZeroOut;
974 KnownOne = KnownOneOut;
977 case Instruction::Select:
978 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
979 KnownZero, KnownOne, Depth+1))
981 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
982 KnownZero2, KnownOne2, Depth+1))
984 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
985 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
987 // If the operands are constants, see if we can simplify them.
988 if (ShrinkDemandedConstant(I, 1, DemandedMask))
989 return UpdateValueUsesWith(I, I);
990 if (ShrinkDemandedConstant(I, 2, DemandedMask))
991 return UpdateValueUsesWith(I, I);
993 // Only known if known in both the LHS and RHS.
994 KnownOne &= KnownOne2;
995 KnownZero &= KnownZero2;
997 case Instruction::Trunc:
998 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999 KnownZero, KnownOne, Depth+1))
1001 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1003 case Instruction::BitCast:
1004 if (!I->getOperand(0)->getType()->isIntegral())
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::ZExt: {
1013 // Compute the bits in the result that are not present in the input.
1014 const Type *SrcTy = I->getOperand(0)->getType();
1015 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1016 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1018 DemandedMask &= SrcTy->getIntegralTypeMask();
1019 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020 KnownZero, KnownOne, Depth+1))
1022 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1023 // The top bits are known to be zero.
1024 KnownZero |= NewBits;
1027 case Instruction::SExt: {
1028 // Compute the bits in the result that are not present in the input.
1029 const Type *SrcTy = I->getOperand(0)->getType();
1030 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1031 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1033 // Get the sign bit for the source type
1034 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1035 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1037 // If any of the sign extended bits are demanded, we know that the sign
1039 if (NewBits & DemandedMask)
1040 InputDemandedBits |= InSignBit;
1042 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1043 KnownZero, KnownOne, Depth+1))
1045 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1047 // If the sign bit of the input is known set or clear, then we know the
1048 // top bits of the result.
1050 // If the input sign bit is known zero, or if the NewBits are not demanded
1051 // convert this into a zero extension.
1052 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1053 // Convert to ZExt cast
1054 CastInst *NewCast = CastInst::create(
1055 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1056 return UpdateValueUsesWith(I, NewCast);
1057 } else if (KnownOne & InSignBit) { // Input sign bit known set
1058 KnownOne |= NewBits;
1059 KnownZero &= ~NewBits;
1060 } else { // Input sign bit unknown
1061 KnownZero &= ~NewBits;
1062 KnownOne &= ~NewBits;
1066 case Instruction::Add:
1067 // If there is a constant on the RHS, there are a variety of xformations
1069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070 // If null, this should be simplified elsewhere. Some of the xforms here
1071 // won't work if the RHS is zero.
1072 if (RHS->isNullValue())
1075 // Figure out what the input bits are. If the top bits of the and result
1076 // are not demanded, then the add doesn't demand them from its input
1079 // Shift the demanded mask up so that it's at the top of the uint64_t.
1080 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1081 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1083 // If the top bit of the output is demanded, demand everything from the
1084 // input. Otherwise, we demand all the input bits except NLZ top bits.
1085 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1087 // Find information about known zero/one bits in the input.
1088 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1089 KnownZero2, KnownOne2, Depth+1))
1092 // If the RHS of the add has bits set that can't affect the input, reduce
1094 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1095 return UpdateValueUsesWith(I, I);
1097 // Avoid excess work.
1098 if (KnownZero2 == 0 && KnownOne2 == 0)
1101 // Turn it into OR if input bits are zero.
1102 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1104 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1106 InsertNewInstBefore(Or, *I);
1107 return UpdateValueUsesWith(I, Or);
1110 // We can say something about the output known-zero and known-one bits,
1111 // depending on potential carries from the input constant and the
1112 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1113 // bits set and the RHS constant is 0x01001, then we know we have a known
1114 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1116 // To compute this, we first compute the potential carry bits. These are
1117 // the bits which may be modified. I'm not aware of a better way to do
1119 uint64_t RHSVal = RHS->getZExtValue();
1121 bool CarryIn = false;
1122 uint64_t CarryBits = 0;
1123 uint64_t CurBit = 1;
1124 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1125 // Record the current carry in.
1126 if (CarryIn) CarryBits |= CurBit;
1130 // This bit has a carry out unless it is "zero + zero" or
1131 // "zero + anything" with no carry in.
1132 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1133 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1134 } else if (!CarryIn &&
1135 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1136 CarryOut = false; // 0 + anything has no carry out if no carry in.
1138 // Otherwise, we have to assume we have a carry out.
1142 // This stage's carry out becomes the next stage's carry-in.
1146 // Now that we know which bits have carries, compute the known-1/0 sets.
1148 // Bits are known one if they are known zero in one operand and one in the
1149 // other, and there is no input carry.
1150 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1152 // Bits are known zero if they are known zero in both operands and there
1153 // is no input carry.
1154 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1157 case Instruction::Shl:
1158 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159 uint64_t ShiftAmt = SA->getZExtValue();
1160 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
1161 KnownZero, KnownOne, Depth+1))
1163 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1164 KnownZero <<= ShiftAmt;
1165 KnownOne <<= ShiftAmt;
1166 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
1169 case Instruction::LShr:
1170 // For a logical shift right
1171 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172 unsigned ShiftAmt = SA->getZExtValue();
1174 // Compute the new bits that are at the top now.
1175 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1176 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1177 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1178 // Unsigned shift right.
1179 if (SimplifyDemandedBits(I->getOperand(0),
1180 (DemandedMask << ShiftAmt) & TypeMask,
1181 KnownZero, KnownOne, Depth+1))
1183 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1184 KnownZero &= TypeMask;
1185 KnownOne &= TypeMask;
1186 KnownZero >>= ShiftAmt;
1187 KnownOne >>= ShiftAmt;
1188 KnownZero |= HighBits; // high bits known zero.
1191 case Instruction::AShr:
1192 // If this is an arithmetic shift right and only the low-bit is set, we can
1193 // always convert this into a logical shr, even if the shift amount is
1194 // variable. The low bit of the shift cannot be an input sign bit unless
1195 // the shift amount is >= the size of the datatype, which is undefined.
1196 if (DemandedMask == 1) {
1197 // Perform the logical shift right.
1198 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1199 I->getOperand(1), I->getName());
1200 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1201 return UpdateValueUsesWith(I, NewVal);
1204 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1205 unsigned ShiftAmt = SA->getZExtValue();
1207 // Compute the new bits that are at the top now.
1208 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1209 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1210 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1211 // Signed shift right.
1212 if (SimplifyDemandedBits(I->getOperand(0),
1213 (DemandedMask << ShiftAmt) & TypeMask,
1214 KnownZero, KnownOne, Depth+1))
1216 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1217 KnownZero &= TypeMask;
1218 KnownOne &= TypeMask;
1219 KnownZero >>= ShiftAmt;
1220 KnownOne >>= ShiftAmt;
1222 // Handle the sign bits.
1223 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1224 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
1226 // If the input sign bit is known to be zero, or if none of the top bits
1227 // are demanded, turn this into an unsigned shift right.
1228 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1229 // Perform the logical shift right.
1230 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1232 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1233 return UpdateValueUsesWith(I, NewVal);
1234 } else if (KnownOne & SignBit) { // New bits are known one.
1235 KnownOne |= HighBits;
1241 // If the client is only demanding bits that we know, return the known
1243 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1244 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1249 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1250 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1251 /// actually used by the caller. This method analyzes which elements of the
1252 /// operand are undef and returns that information in UndefElts.
1254 /// If the information about demanded elements can be used to simplify the
1255 /// operation, the operation is simplified, then the resultant value is
1256 /// returned. This returns null if no change was made.
1257 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1258 uint64_t &UndefElts,
1260 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1261 assert(VWidth <= 64 && "Vector too wide to analyze!");
1262 uint64_t EltMask = ~0ULL >> (64-VWidth);
1263 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1264 "Invalid DemandedElts!");
1266 if (isa<UndefValue>(V)) {
1267 // If the entire vector is undefined, just return this info.
1268 UndefElts = EltMask;
1270 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1271 UndefElts = EltMask;
1272 return UndefValue::get(V->getType());
1276 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1277 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1278 Constant *Undef = UndefValue::get(EltTy);
1280 std::vector<Constant*> Elts;
1281 for (unsigned i = 0; i != VWidth; ++i)
1282 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1283 Elts.push_back(Undef);
1284 UndefElts |= (1ULL << i);
1285 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1286 Elts.push_back(Undef);
1287 UndefElts |= (1ULL << i);
1288 } else { // Otherwise, defined.
1289 Elts.push_back(CP->getOperand(i));
1292 // If we changed the constant, return it.
1293 Constant *NewCP = ConstantPacked::get(Elts);
1294 return NewCP != CP ? NewCP : 0;
1295 } else if (isa<ConstantAggregateZero>(V)) {
1296 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1298 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1299 Constant *Zero = Constant::getNullValue(EltTy);
1300 Constant *Undef = UndefValue::get(EltTy);
1301 std::vector<Constant*> Elts;
1302 for (unsigned i = 0; i != VWidth; ++i)
1303 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1304 UndefElts = DemandedElts ^ EltMask;
1305 return ConstantPacked::get(Elts);
1308 if (!V->hasOneUse()) { // Other users may use these bits.
1309 if (Depth != 0) { // Not at the root.
1310 // TODO: Just compute the UndefElts information recursively.
1314 } else if (Depth == 10) { // Limit search depth.
1318 Instruction *I = dyn_cast<Instruction>(V);
1319 if (!I) return false; // Only analyze instructions.
1321 bool MadeChange = false;
1322 uint64_t UndefElts2;
1324 switch (I->getOpcode()) {
1327 case Instruction::InsertElement: {
1328 // If this is a variable index, we don't know which element it overwrites.
1329 // demand exactly the same input as we produce.
1330 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1332 // Note that we can't propagate undef elt info, because we don't know
1333 // which elt is getting updated.
1334 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1335 UndefElts2, Depth+1);
1336 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1340 // If this is inserting an element that isn't demanded, remove this
1342 unsigned IdxNo = Idx->getZExtValue();
1343 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1344 return AddSoonDeadInstToWorklist(*I, 0);
1346 // Otherwise, the element inserted overwrites whatever was there, so the
1347 // input demanded set is simpler than the output set.
1348 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1349 DemandedElts & ~(1ULL << IdxNo),
1350 UndefElts, Depth+1);
1351 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1353 // The inserted element is defined.
1354 UndefElts |= 1ULL << IdxNo;
1358 case Instruction::And:
1359 case Instruction::Or:
1360 case Instruction::Xor:
1361 case Instruction::Add:
1362 case Instruction::Sub:
1363 case Instruction::Mul:
1364 // div/rem demand all inputs, because they don't want divide by zero.
1365 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1366 UndefElts, Depth+1);
1367 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1368 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1369 UndefElts2, Depth+1);
1370 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1372 // Output elements are undefined if both are undefined. Consider things
1373 // like undef&0. The result is known zero, not undef.
1374 UndefElts &= UndefElts2;
1377 case Instruction::Call: {
1378 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1380 switch (II->getIntrinsicID()) {
1383 // Binary vector operations that work column-wise. A dest element is a
1384 // function of the corresponding input elements from the two inputs.
1385 case Intrinsic::x86_sse_sub_ss:
1386 case Intrinsic::x86_sse_mul_ss:
1387 case Intrinsic::x86_sse_min_ss:
1388 case Intrinsic::x86_sse_max_ss:
1389 case Intrinsic::x86_sse2_sub_sd:
1390 case Intrinsic::x86_sse2_mul_sd:
1391 case Intrinsic::x86_sse2_min_sd:
1392 case Intrinsic::x86_sse2_max_sd:
1393 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1394 UndefElts, Depth+1);
1395 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1396 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1397 UndefElts2, Depth+1);
1398 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1400 // If only the low elt is demanded and this is a scalarizable intrinsic,
1401 // scalarize it now.
1402 if (DemandedElts == 1) {
1403 switch (II->getIntrinsicID()) {
1405 case Intrinsic::x86_sse_sub_ss:
1406 case Intrinsic::x86_sse_mul_ss:
1407 case Intrinsic::x86_sse2_sub_sd:
1408 case Intrinsic::x86_sse2_mul_sd:
1409 // TODO: Lower MIN/MAX/ABS/etc
1410 Value *LHS = II->getOperand(1);
1411 Value *RHS = II->getOperand(2);
1412 // Extract the element as scalars.
1413 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1414 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1416 switch (II->getIntrinsicID()) {
1417 default: assert(0 && "Case stmts out of sync!");
1418 case Intrinsic::x86_sse_sub_ss:
1419 case Intrinsic::x86_sse2_sub_sd:
1420 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1421 II->getName()), *II);
1423 case Intrinsic::x86_sse_mul_ss:
1424 case Intrinsic::x86_sse2_mul_sd:
1425 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1426 II->getName()), *II);
1431 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1433 InsertNewInstBefore(New, *II);
1434 AddSoonDeadInstToWorklist(*II, 0);
1439 // Output elements are undefined if both are undefined. Consider things
1440 // like undef&0. The result is known zero, not undef.
1441 UndefElts &= UndefElts2;
1447 return MadeChange ? I : 0;
1450 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1451 // true when both operands are equal...
1453 static bool isTrueWhenEqual(Instruction &I) {
1454 return I.getOpcode() == Instruction::SetEQ ||
1455 I.getOpcode() == Instruction::SetGE ||
1456 I.getOpcode() == Instruction::SetLE;
1459 /// AssociativeOpt - Perform an optimization on an associative operator. This
1460 /// function is designed to check a chain of associative operators for a
1461 /// potential to apply a certain optimization. Since the optimization may be
1462 /// applicable if the expression was reassociated, this checks the chain, then
1463 /// reassociates the expression as necessary to expose the optimization
1464 /// opportunity. This makes use of a special Functor, which must define
1465 /// 'shouldApply' and 'apply' methods.
1467 template<typename Functor>
1468 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1469 unsigned Opcode = Root.getOpcode();
1470 Value *LHS = Root.getOperand(0);
1472 // Quick check, see if the immediate LHS matches...
1473 if (F.shouldApply(LHS))
1474 return F.apply(Root);
1476 // Otherwise, if the LHS is not of the same opcode as the root, return.
1477 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1478 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1479 // Should we apply this transform to the RHS?
1480 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1482 // If not to the RHS, check to see if we should apply to the LHS...
1483 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1484 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1488 // If the functor wants to apply the optimization to the RHS of LHSI,
1489 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1491 BasicBlock *BB = Root.getParent();
1493 // Now all of the instructions are in the current basic block, go ahead
1494 // and perform the reassociation.
1495 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1497 // First move the selected RHS to the LHS of the root...
1498 Root.setOperand(0, LHSI->getOperand(1));
1500 // Make what used to be the LHS of the root be the user of the root...
1501 Value *ExtraOperand = TmpLHSI->getOperand(1);
1502 if (&Root == TmpLHSI) {
1503 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1506 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1507 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1508 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1509 BasicBlock::iterator ARI = &Root; ++ARI;
1510 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1513 // Now propagate the ExtraOperand down the chain of instructions until we
1515 while (TmpLHSI != LHSI) {
1516 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1517 // Move the instruction to immediately before the chain we are
1518 // constructing to avoid breaking dominance properties.
1519 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1520 BB->getInstList().insert(ARI, NextLHSI);
1523 Value *NextOp = NextLHSI->getOperand(1);
1524 NextLHSI->setOperand(1, ExtraOperand);
1526 ExtraOperand = NextOp;
1529 // Now that the instructions are reassociated, have the functor perform
1530 // the transformation...
1531 return F.apply(Root);
1534 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1540 // AddRHS - Implements: X + X --> X << 1
1543 AddRHS(Value *rhs) : RHS(rhs) {}
1544 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1545 Instruction *apply(BinaryOperator &Add) const {
1546 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1547 ConstantInt::get(Type::UByteTy, 1));
1551 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1553 struct AddMaskingAnd {
1555 AddMaskingAnd(Constant *c) : C2(c) {}
1556 bool shouldApply(Value *LHS) const {
1558 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1559 ConstantExpr::getAnd(C1, C2)->isNullValue();
1561 Instruction *apply(BinaryOperator &Add) const {
1562 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1566 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1568 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1569 if (Constant *SOC = dyn_cast<Constant>(SO))
1570 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1572 return IC->InsertNewInstBefore(CastInst::create(
1573 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1576 // Figure out if the constant is the left or the right argument.
1577 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1578 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1580 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1582 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1583 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1586 Value *Op0 = SO, *Op1 = ConstOperand;
1588 std::swap(Op0, Op1);
1590 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1591 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1592 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1593 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1595 assert(0 && "Unknown binary instruction type!");
1598 return IC->InsertNewInstBefore(New, I);
1601 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1602 // constant as the other operand, try to fold the binary operator into the
1603 // select arguments. This also works for Cast instructions, which obviously do
1604 // not have a second operand.
1605 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1607 // Don't modify shared select instructions
1608 if (!SI->hasOneUse()) return 0;
1609 Value *TV = SI->getOperand(1);
1610 Value *FV = SI->getOperand(2);
1612 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1613 // Bool selects with constant operands can be folded to logical ops.
1614 if (SI->getType() == Type::BoolTy) return 0;
1616 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1617 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1619 return new SelectInst(SI->getCondition(), SelectTrueVal,
1626 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1627 /// node as operand #0, see if we can fold the instruction into the PHI (which
1628 /// is only possible if all operands to the PHI are constants).
1629 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1630 PHINode *PN = cast<PHINode>(I.getOperand(0));
1631 unsigned NumPHIValues = PN->getNumIncomingValues();
1632 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1634 // Check to see if all of the operands of the PHI are constants. If there is
1635 // one non-constant value, remember the BB it is. If there is more than one
1637 BasicBlock *NonConstBB = 0;
1638 for (unsigned i = 0; i != NumPHIValues; ++i)
1639 if (!isa<Constant>(PN->getIncomingValue(i))) {
1640 if (NonConstBB) return 0; // More than one non-const value.
1641 NonConstBB = PN->getIncomingBlock(i);
1643 // If the incoming non-constant value is in I's block, we have an infinite
1645 if (NonConstBB == I.getParent())
1649 // If there is exactly one non-constant value, we can insert a copy of the
1650 // operation in that block. However, if this is a critical edge, we would be
1651 // inserting the computation one some other paths (e.g. inside a loop). Only
1652 // do this if the pred block is unconditionally branching into the phi block.
1654 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1655 if (!BI || !BI->isUnconditional()) return 0;
1658 // Okay, we can do the transformation: create the new PHI node.
1659 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1661 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1662 InsertNewInstBefore(NewPN, *PN);
1664 // Next, add all of the operands to the PHI.
1665 if (I.getNumOperands() == 2) {
1666 Constant *C = cast<Constant>(I.getOperand(1));
1667 for (unsigned i = 0; i != NumPHIValues; ++i) {
1669 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1670 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1672 assert(PN->getIncomingBlock(i) == NonConstBB);
1673 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1674 InV = BinaryOperator::create(BO->getOpcode(),
1675 PN->getIncomingValue(i), C, "phitmp",
1676 NonConstBB->getTerminator());
1677 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1678 InV = new ShiftInst(SI->getOpcode(),
1679 PN->getIncomingValue(i), C, "phitmp",
1680 NonConstBB->getTerminator());
1682 assert(0 && "Unknown binop!");
1684 WorkList.push_back(cast<Instruction>(InV));
1686 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1689 CastInst *CI = cast<CastInst>(&I);
1690 const Type *RetTy = CI->getType();
1691 for (unsigned i = 0; i != NumPHIValues; ++i) {
1693 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1694 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1696 assert(PN->getIncomingBlock(i) == NonConstBB);
1697 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1698 I.getType(), "phitmp",
1699 NonConstBB->getTerminator());
1700 WorkList.push_back(cast<Instruction>(InV));
1702 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1705 return ReplaceInstUsesWith(I, NewPN);
1708 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1709 bool Changed = SimplifyCommutative(I);
1710 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1712 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1713 // X + undef -> undef
1714 if (isa<UndefValue>(RHS))
1715 return ReplaceInstUsesWith(I, RHS);
1718 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1719 if (RHSC->isNullValue())
1720 return ReplaceInstUsesWith(I, LHS);
1721 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1722 if (CFP->isExactlyValue(-0.0))
1723 return ReplaceInstUsesWith(I, LHS);
1726 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1727 // X + (signbit) --> X ^ signbit
1728 uint64_t Val = CI->getZExtValue();
1729 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1730 return BinaryOperator::createXor(LHS, RHS);
1732 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1733 // (X & 254)+1 -> (X&254)|1
1734 uint64_t KnownZero, KnownOne;
1735 if (!isa<PackedType>(I.getType()) &&
1736 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1737 KnownZero, KnownOne))
1741 if (isa<PHINode>(LHS))
1742 if (Instruction *NV = FoldOpIntoPhi(I))
1745 ConstantInt *XorRHS = 0;
1747 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1748 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1749 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1750 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1752 uint64_t C0080Val = 1ULL << 31;
1753 int64_t CFF80Val = -C0080Val;
1756 if (TySizeBits > Size) {
1758 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1759 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1760 if (RHSSExt == CFF80Val) {
1761 if (XorRHS->getZExtValue() == C0080Val)
1763 } else if (RHSZExt == C0080Val) {
1764 if (XorRHS->getSExtValue() == CFF80Val)
1768 // This is a sign extend if the top bits are known zero.
1769 uint64_t Mask = ~0ULL;
1770 Mask <<= 64-(TySizeBits-Size);
1771 Mask &= XorLHS->getType()->getIntegralTypeMask();
1772 if (!MaskedValueIsZero(XorLHS, Mask))
1773 Size = 0; // Not a sign ext, but can't be any others either.
1780 } while (Size >= 8);
1783 const Type *MiddleType = 0;
1786 case 32: MiddleType = Type::IntTy; break;
1787 case 16: MiddleType = Type::ShortTy; break;
1788 case 8: MiddleType = Type::SByteTy; break;
1791 Instruction *NewTrunc =
1792 CastInst::createInferredCast(XorLHS, MiddleType, "sext");
1793 InsertNewInstBefore(NewTrunc, I);
1794 return new SExtInst(NewTrunc, I.getType());
1800 if (I.getType()->isInteger()) {
1801 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1803 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1804 if (RHSI->getOpcode() == Instruction::Sub)
1805 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1806 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1808 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1809 if (LHSI->getOpcode() == Instruction::Sub)
1810 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1811 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1816 if (Value *V = dyn_castNegVal(LHS))
1817 return BinaryOperator::createSub(RHS, V);
1820 if (!isa<Constant>(RHS))
1821 if (Value *V = dyn_castNegVal(RHS))
1822 return BinaryOperator::createSub(LHS, V);
1826 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1827 if (X == RHS) // X*C + X --> X * (C+1)
1828 return BinaryOperator::createMul(RHS, AddOne(C2));
1830 // X*C1 + X*C2 --> X * (C1+C2)
1832 if (X == dyn_castFoldableMul(RHS, C1))
1833 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1836 // X + X*C --> X * (C+1)
1837 if (dyn_castFoldableMul(RHS, C2) == LHS)
1838 return BinaryOperator::createMul(LHS, AddOne(C2));
1841 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1842 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1843 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1845 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1847 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1848 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1849 return BinaryOperator::createSub(C, X);
1852 // (X & FF00) + xx00 -> (X+xx00) & FF00
1853 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1854 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1855 if (Anded == CRHS) {
1856 // See if all bits from the first bit set in the Add RHS up are included
1857 // in the mask. First, get the rightmost bit.
1858 uint64_t AddRHSV = CRHS->getZExtValue();
1860 // Form a mask of all bits from the lowest bit added through the top.
1861 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1862 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1864 // See if the and mask includes all of these bits.
1865 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1867 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1868 // Okay, the xform is safe. Insert the new add pronto.
1869 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1870 LHS->getName()), I);
1871 return BinaryOperator::createAnd(NewAdd, C2);
1876 // Try to fold constant add into select arguments.
1877 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1878 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1882 // add (cast *A to intptrtype) B ->
1883 // cast (GEP (cast *A to sbyte*) B) ->
1886 CastInst *CI = dyn_cast<CastInst>(LHS);
1889 CI = dyn_cast<CastInst>(RHS);
1892 if (CI && CI->getType()->isSized() &&
1893 (CI->getType()->getPrimitiveSize() ==
1894 TD->getIntPtrType()->getPrimitiveSize())
1895 && isa<PointerType>(CI->getOperand(0)->getType())) {
1896 Value *I2 = InsertCastBefore(CI->getOperand(0),
1897 PointerType::get(Type::SByteTy), I);
1898 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1899 return new PtrToIntInst(I2, CI->getType());
1903 return Changed ? &I : 0;
1906 // isSignBit - Return true if the value represented by the constant only has the
1907 // highest order bit set.
1908 static bool isSignBit(ConstantInt *CI) {
1909 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1910 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1913 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1915 static Value *RemoveNoopCast(Value *V) {
1916 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1917 const Type *CTy = CI->getType();
1918 const Type *OpTy = CI->getOperand(0)->getType();
1919 if (CTy->isInteger() && OpTy->isInteger()) {
1920 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1921 return RemoveNoopCast(CI->getOperand(0));
1922 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1923 return RemoveNoopCast(CI->getOperand(0));
1928 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1929 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1931 if (Op0 == Op1) // sub X, X -> 0
1932 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1934 // If this is a 'B = x-(-A)', change to B = x+A...
1935 if (Value *V = dyn_castNegVal(Op1))
1936 return BinaryOperator::createAdd(Op0, V);
1938 if (isa<UndefValue>(Op0))
1939 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1940 if (isa<UndefValue>(Op1))
1941 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1943 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1944 // Replace (-1 - A) with (~A)...
1945 if (C->isAllOnesValue())
1946 return BinaryOperator::createNot(Op1);
1948 // C - ~X == X + (1+C)
1950 if (match(Op1, m_Not(m_Value(X))))
1951 return BinaryOperator::createAdd(X,
1952 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1953 // -((uint)X >> 31) -> ((int)X >> 31)
1954 // -((int)X >> 31) -> ((uint)X >> 31)
1955 if (C->isNullValue()) {
1956 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1957 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1958 if (SI->getOpcode() == Instruction::LShr) {
1959 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1960 // Check to see if we are shifting out everything but the sign bit.
1961 if (CU->getZExtValue() ==
1962 SI->getType()->getPrimitiveSizeInBits()-1) {
1963 // Ok, the transformation is safe. Insert AShr.
1964 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
1969 else if (SI->getOpcode() == Instruction::AShr) {
1970 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1971 // Check to see if we are shifting out everything but the sign bit.
1972 if (CU->getZExtValue() ==
1973 SI->getType()->getPrimitiveSizeInBits()-1) {
1974 // Ok, the transformation is safe. Insert LShr.
1975 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
1982 // Try to fold constant sub into select arguments.
1983 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1984 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1987 if (isa<PHINode>(Op0))
1988 if (Instruction *NV = FoldOpIntoPhi(I))
1992 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1993 if (Op1I->getOpcode() == Instruction::Add &&
1994 !Op0->getType()->isFloatingPoint()) {
1995 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1996 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1997 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1998 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1999 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2000 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2001 // C1-(X+C2) --> (C1-C2)-X
2002 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2003 Op1I->getOperand(0));
2007 if (Op1I->hasOneUse()) {
2008 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2009 // is not used by anyone else...
2011 if (Op1I->getOpcode() == Instruction::Sub &&
2012 !Op1I->getType()->isFloatingPoint()) {
2013 // Swap the two operands of the subexpr...
2014 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2015 Op1I->setOperand(0, IIOp1);
2016 Op1I->setOperand(1, IIOp0);
2018 // Create the new top level add instruction...
2019 return BinaryOperator::createAdd(Op0, Op1);
2022 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2024 if (Op1I->getOpcode() == Instruction::And &&
2025 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2026 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2029 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2030 return BinaryOperator::createAnd(Op0, NewNot);
2033 // 0 - (X sdiv C) -> (X sdiv -C)
2034 if (Op1I->getOpcode() == Instruction::SDiv)
2035 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2036 if (CSI->isNullValue())
2037 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2038 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2039 ConstantExpr::getNeg(DivRHS));
2041 // X - X*C --> X * (1-C)
2042 ConstantInt *C2 = 0;
2043 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2045 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2046 return BinaryOperator::createMul(Op0, CP1);
2051 if (!Op0->getType()->isFloatingPoint())
2052 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2053 if (Op0I->getOpcode() == Instruction::Add) {
2054 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2055 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2056 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2057 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2058 } else if (Op0I->getOpcode() == Instruction::Sub) {
2059 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2060 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2064 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2065 if (X == Op1) { // X*C - X --> X * (C-1)
2066 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2067 return BinaryOperator::createMul(Op1, CP1);
2070 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2071 if (X == dyn_castFoldableMul(Op1, C2))
2072 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2077 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2078 /// really just returns true if the most significant (sign) bit is set.
2079 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2080 if (RHS->getType()->isSigned()) {
2081 // True if source is LHS < 0 or LHS <= -1
2082 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2083 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2085 ConstantInt *RHSC = cast<ConstantInt>(RHS);
2086 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2087 // the size of the integer type.
2088 if (Opcode == Instruction::SetGE)
2089 return RHSC->getZExtValue() ==
2090 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
2091 if (Opcode == Instruction::SetGT)
2092 return RHSC->getZExtValue() ==
2093 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2098 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2099 bool Changed = SimplifyCommutative(I);
2100 Value *Op0 = I.getOperand(0);
2102 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2103 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2105 // Simplify mul instructions with a constant RHS...
2106 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2107 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2109 // ((X << C1)*C2) == (X * (C2 << C1))
2110 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2111 if (SI->getOpcode() == Instruction::Shl)
2112 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2113 return BinaryOperator::createMul(SI->getOperand(0),
2114 ConstantExpr::getShl(CI, ShOp));
2116 if (CI->isNullValue())
2117 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2118 if (CI->equalsInt(1)) // X * 1 == X
2119 return ReplaceInstUsesWith(I, Op0);
2120 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2121 return BinaryOperator::createNeg(Op0, I.getName());
2123 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2124 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2125 uint64_t C = Log2_64(Val);
2126 return new ShiftInst(Instruction::Shl, Op0,
2127 ConstantInt::get(Type::UByteTy, C));
2129 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2130 if (Op1F->isNullValue())
2131 return ReplaceInstUsesWith(I, Op1);
2133 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2134 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2135 if (Op1F->getValue() == 1.0)
2136 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2139 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2140 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2141 isa<ConstantInt>(Op0I->getOperand(1))) {
2142 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2143 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2145 InsertNewInstBefore(Add, I);
2146 Value *C1C2 = ConstantExpr::getMul(Op1,
2147 cast<Constant>(Op0I->getOperand(1)));
2148 return BinaryOperator::createAdd(Add, C1C2);
2152 // Try to fold constant mul into select arguments.
2153 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2154 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2157 if (isa<PHINode>(Op0))
2158 if (Instruction *NV = FoldOpIntoPhi(I))
2162 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2163 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2164 return BinaryOperator::createMul(Op0v, Op1v);
2166 // If one of the operands of the multiply is a cast from a boolean value, then
2167 // we know the bool is either zero or one, so this is a 'masking' multiply.
2168 // See if we can simplify things based on how the boolean was originally
2170 CastInst *BoolCast = 0;
2171 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2172 if (CI->getOperand(0)->getType() == Type::BoolTy)
2175 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2176 if (CI->getOperand(0)->getType() == Type::BoolTy)
2179 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2180 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2181 const Type *SCOpTy = SCIOp0->getType();
2183 // If the setcc is true iff the sign bit of X is set, then convert this
2184 // multiply into a shift/and combination.
2185 if (isa<ConstantInt>(SCIOp1) &&
2186 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
2187 // Shift the X value right to turn it into "all signbits".
2188 Constant *Amt = ConstantInt::get(Type::UByteTy,
2189 SCOpTy->getPrimitiveSizeInBits()-1);
2190 if (SCIOp0->getType()->isUnsigned()) {
2191 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
2192 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
2196 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2197 BoolCast->getOperand(0)->getName()+
2200 // If the multiply type is not the same as the source type, sign extend
2201 // or truncate to the multiply type.
2202 if (I.getType() != V->getType())
2203 V = InsertCastBefore(V, I.getType(), I);
2205 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2206 return BinaryOperator::createAnd(V, OtherOp);
2211 return Changed ? &I : 0;
2214 /// This function implements the transforms on div instructions that work
2215 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2216 /// used by the visitors to those instructions.
2217 /// @brief Transforms common to all three div instructions
2218 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2219 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2222 if (isa<UndefValue>(Op0))
2223 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2225 // X / undef -> undef
2226 if (isa<UndefValue>(Op1))
2227 return ReplaceInstUsesWith(I, Op1);
2229 // Handle cases involving: div X, (select Cond, Y, Z)
2230 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2231 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2232 // same basic block, then we replace the select with Y, and the condition
2233 // of the select with false (if the cond value is in the same BB). If the
2234 // select has uses other than the div, this allows them to be simplified
2235 // also. Note that div X, Y is just as good as div X, 0 (undef)
2236 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2237 if (ST->isNullValue()) {
2238 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2239 if (CondI && CondI->getParent() == I.getParent())
2240 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2241 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2242 I.setOperand(1, SI->getOperand(2));
2244 UpdateValueUsesWith(SI, SI->getOperand(2));
2248 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2249 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2250 if (ST->isNullValue()) {
2251 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2252 if (CondI && CondI->getParent() == I.getParent())
2253 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2254 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2255 I.setOperand(1, SI->getOperand(1));
2257 UpdateValueUsesWith(SI, SI->getOperand(1));
2265 /// This function implements the transforms common to both integer division
2266 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2267 /// division instructions.
2268 /// @brief Common integer divide transforms
2269 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2272 if (Instruction *Common = commonDivTransforms(I))
2275 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2277 if (RHS->equalsInt(1))
2278 return ReplaceInstUsesWith(I, Op0);
2280 // (X / C1) / C2 -> X / (C1*C2)
2281 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2282 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2283 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2284 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2285 ConstantExpr::getMul(RHS, LHSRHS));
2288 if (!RHS->isNullValue()) { // avoid X udiv 0
2289 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2290 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2292 if (isa<PHINode>(Op0))
2293 if (Instruction *NV = FoldOpIntoPhi(I))
2298 // 0 / X == 0, we don't need to preserve faults!
2299 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2300 if (LHS->equalsInt(0))
2301 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2306 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2307 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2309 // Handle the integer div common cases
2310 if (Instruction *Common = commonIDivTransforms(I))
2313 // X udiv C^2 -> X >> C
2314 // Check to see if this is an unsigned division with an exact power of 2,
2315 // if so, convert to a right shift.
2316 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2317 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2318 if (isPowerOf2_64(Val)) {
2319 uint64_t ShiftAmt = Log2_64(Val);
2320 return new ShiftInst(Instruction::LShr, Op0,
2321 ConstantInt::get(Type::UByteTy, ShiftAmt));
2325 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2326 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2327 if (RHSI->getOpcode() == Instruction::Shl &&
2328 isa<ConstantInt>(RHSI->getOperand(0))) {
2329 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2330 if (isPowerOf2_64(C1)) {
2331 Value *N = RHSI->getOperand(1);
2332 const Type *NTy = N->getType();
2333 if (uint64_t C2 = Log2_64(C1)) {
2334 Constant *C2V = ConstantInt::get(NTy, C2);
2335 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2337 return new ShiftInst(Instruction::LShr, Op0, N);
2342 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2343 // where C1&C2 are powers of two.
2344 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2345 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2346 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2347 if (!STO->isNullValue() && !STO->isNullValue()) {
2348 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2349 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2350 // Compute the shift amounts
2351 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2352 // Construct the "on true" case of the select
2353 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2355 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2356 TSI = InsertNewInstBefore(TSI, I);
2358 // Construct the "on false" case of the select
2359 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2361 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2362 FSI = InsertNewInstBefore(FSI, I);
2364 // construct the select instruction and return it.
2365 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2372 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2373 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2375 // Handle the integer div common cases
2376 if (Instruction *Common = commonIDivTransforms(I))
2379 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2381 if (RHS->isAllOnesValue())
2382 return BinaryOperator::createNeg(Op0);
2385 if (Value *LHSNeg = dyn_castNegVal(Op0))
2386 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2389 // If the sign bits of both operands are zero (i.e. we can prove they are
2390 // unsigned inputs), turn this into a udiv.
2391 if (I.getType()->isInteger()) {
2392 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2393 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2394 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2401 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2402 return commonDivTransforms(I);
2405 /// GetFactor - If we can prove that the specified value is at least a multiple
2406 /// of some factor, return that factor.
2407 static Constant *GetFactor(Value *V) {
2408 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2411 // Unless we can be tricky, we know this is a multiple of 1.
2412 Constant *Result = ConstantInt::get(V->getType(), 1);
2414 Instruction *I = dyn_cast<Instruction>(V);
2415 if (!I) return Result;
2417 if (I->getOpcode() == Instruction::Mul) {
2418 // Handle multiplies by a constant, etc.
2419 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2420 GetFactor(I->getOperand(1)));
2421 } else if (I->getOpcode() == Instruction::Shl) {
2422 // (X<<C) -> X * (1 << C)
2423 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2424 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2425 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2427 } else if (I->getOpcode() == Instruction::And) {
2428 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2429 // X & 0xFFF0 is known to be a multiple of 16.
2430 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2431 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2432 return ConstantExpr::getShl(Result,
2433 ConstantInt::get(Type::UByteTy, Zeros));
2435 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2436 // Only handle int->int casts.
2437 if (!CI->isIntegerCast())
2439 Value *Op = CI->getOperand(0);
2440 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2445 /// This function implements the transforms on rem instructions that work
2446 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2447 /// is used by the visitors to those instructions.
2448 /// @brief Transforms common to all three rem instructions
2449 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2450 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2452 // 0 % X == 0, we don't need to preserve faults!
2453 if (Constant *LHS = dyn_cast<Constant>(Op0))
2454 if (LHS->isNullValue())
2455 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2457 if (isa<UndefValue>(Op0)) // undef % X -> 0
2458 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2459 if (isa<UndefValue>(Op1))
2460 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2462 // Handle cases involving: rem X, (select Cond, Y, Z)
2463 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2464 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2465 // the same basic block, then we replace the select with Y, and the
2466 // condition of the select with false (if the cond value is in the same
2467 // BB). If the select has uses other than the div, this allows them to be
2469 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2470 if (ST->isNullValue()) {
2471 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2472 if (CondI && CondI->getParent() == I.getParent())
2473 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2474 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2475 I.setOperand(1, SI->getOperand(2));
2477 UpdateValueUsesWith(SI, SI->getOperand(2));
2480 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2481 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2482 if (ST->isNullValue()) {
2483 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2484 if (CondI && CondI->getParent() == I.getParent())
2485 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2486 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2487 I.setOperand(1, SI->getOperand(1));
2489 UpdateValueUsesWith(SI, SI->getOperand(1));
2497 /// This function implements the transforms common to both integer remainder
2498 /// instructions (urem and srem). It is called by the visitors to those integer
2499 /// remainder instructions.
2500 /// @brief Common integer remainder transforms
2501 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2502 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2504 if (Instruction *common = commonRemTransforms(I))
2507 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2508 // X % 0 == undef, we don't need to preserve faults!
2509 if (RHS->equalsInt(0))
2510 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2512 if (RHS->equalsInt(1)) // X % 1 == 0
2513 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2515 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2516 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2517 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2519 } else if (isa<PHINode>(Op0I)) {
2520 if (Instruction *NV = FoldOpIntoPhi(I))
2523 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2524 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2525 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2532 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2533 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2535 if (Instruction *common = commonIRemTransforms(I))
2538 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2539 // X urem C^2 -> X and C
2540 // Check to see if this is an unsigned remainder with an exact power of 2,
2541 // if so, convert to a bitwise and.
2542 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2543 if (isPowerOf2_64(C->getZExtValue()))
2544 return BinaryOperator::createAnd(Op0, SubOne(C));
2547 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2548 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2549 if (RHSI->getOpcode() == Instruction::Shl &&
2550 isa<ConstantInt>(RHSI->getOperand(0))) {
2551 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2552 if (isPowerOf2_64(C1)) {
2553 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2554 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2556 return BinaryOperator::createAnd(Op0, Add);
2561 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2562 // where C1&C2 are powers of two.
2563 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2564 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2565 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2566 // STO == 0 and SFO == 0 handled above.
2567 if (isPowerOf2_64(STO->getZExtValue()) &&
2568 isPowerOf2_64(SFO->getZExtValue())) {
2569 Value *TrueAnd = InsertNewInstBefore(
2570 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2571 Value *FalseAnd = InsertNewInstBefore(
2572 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2573 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2581 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2582 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2584 if (Instruction *common = commonIRemTransforms(I))
2587 if (Value *RHSNeg = dyn_castNegVal(Op1))
2588 if (!isa<ConstantInt>(RHSNeg) ||
2589 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2591 AddUsesToWorkList(I);
2592 I.setOperand(1, RHSNeg);
2596 // If the top bits of both operands are zero (i.e. we can prove they are
2597 // unsigned inputs), turn this into a urem.
2598 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2599 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2600 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2601 return BinaryOperator::createURem(Op0, Op1, I.getName());
2607 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2608 return commonRemTransforms(I);
2611 // isMaxValueMinusOne - return true if this is Max-1
2612 static bool isMaxValueMinusOne(const ConstantInt *C) {
2613 if (C->getType()->isUnsigned())
2614 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2616 // Calculate 0111111111..11111
2617 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2618 int64_t Val = INT64_MAX; // All ones
2619 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2620 return C->getSExtValue() == Val-1;
2623 // isMinValuePlusOne - return true if this is Min+1
2624 static bool isMinValuePlusOne(const ConstantInt *C) {
2625 if (C->getType()->isUnsigned())
2626 return C->getZExtValue() == 1;
2628 // Calculate 1111111111000000000000
2629 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2630 int64_t Val = -1; // All ones
2631 Val <<= TypeBits-1; // Shift over to the right spot
2632 return C->getSExtValue() == Val+1;
2635 // isOneBitSet - Return true if there is exactly one bit set in the specified
2637 static bool isOneBitSet(const ConstantInt *CI) {
2638 uint64_t V = CI->getZExtValue();
2639 return V && (V & (V-1)) == 0;
2642 #if 0 // Currently unused
2643 // isLowOnes - Return true if the constant is of the form 0+1+.
2644 static bool isLowOnes(const ConstantInt *CI) {
2645 uint64_t V = CI->getZExtValue();
2647 // There won't be bits set in parts that the type doesn't contain.
2648 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2650 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2651 return U && V && (U & V) == 0;
2655 // isHighOnes - Return true if the constant is of the form 1+0+.
2656 // This is the same as lowones(~X).
2657 static bool isHighOnes(const ConstantInt *CI) {
2658 uint64_t V = ~CI->getZExtValue();
2659 if (~V == 0) return false; // 0's does not match "1+"
2661 // There won't be bits set in parts that the type doesn't contain.
2662 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2664 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2665 return U && V && (U & V) == 0;
2669 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2670 /// are carefully arranged to allow folding of expressions such as:
2672 /// (A < B) | (A > B) --> (A != B)
2674 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2675 /// represents that the comparison is true if A == B, and bit value '1' is true
2678 static unsigned getSetCondCode(const SetCondInst *SCI) {
2679 switch (SCI->getOpcode()) {
2681 case Instruction::SetGT: return 1;
2682 case Instruction::SetEQ: return 2;
2683 case Instruction::SetGE: return 3;
2684 case Instruction::SetLT: return 4;
2685 case Instruction::SetNE: return 5;
2686 case Instruction::SetLE: return 6;
2689 assert(0 && "Invalid SetCC opcode!");
2694 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2695 /// opcode and two operands into either a constant true or false, or a brand new
2696 /// SetCC instruction.
2697 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2699 case 0: return ConstantBool::getFalse();
2700 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2701 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2702 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2703 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2704 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2705 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2706 case 7: return ConstantBool::getTrue();
2707 default: assert(0 && "Illegal SetCCCode!"); return 0;
2711 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2713 struct FoldSetCCLogical {
2716 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2717 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2718 bool shouldApply(Value *V) const {
2719 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2720 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2721 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2724 Instruction *apply(BinaryOperator &Log) const {
2725 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2726 if (SCI->getOperand(0) != LHS) {
2727 assert(SCI->getOperand(1) == LHS);
2728 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2731 unsigned LHSCode = getSetCondCode(SCI);
2732 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2734 switch (Log.getOpcode()) {
2735 case Instruction::And: Code = LHSCode & RHSCode; break;
2736 case Instruction::Or: Code = LHSCode | RHSCode; break;
2737 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2738 default: assert(0 && "Illegal logical opcode!"); return 0;
2741 Value *RV = getSetCCValue(Code, LHS, RHS);
2742 if (Instruction *I = dyn_cast<Instruction>(RV))
2744 // Otherwise, it's a constant boolean value...
2745 return IC.ReplaceInstUsesWith(Log, RV);
2748 } // end anonymous namespace
2750 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2751 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2752 // guaranteed to be either a shift instruction or a binary operator.
2753 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2754 ConstantIntegral *OpRHS,
2755 ConstantIntegral *AndRHS,
2756 BinaryOperator &TheAnd) {
2757 Value *X = Op->getOperand(0);
2758 Constant *Together = 0;
2759 if (!isa<ShiftInst>(Op))
2760 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2762 switch (Op->getOpcode()) {
2763 case Instruction::Xor:
2764 if (Op->hasOneUse()) {
2765 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2766 std::string OpName = Op->getName(); Op->setName("");
2767 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2768 InsertNewInstBefore(And, TheAnd);
2769 return BinaryOperator::createXor(And, Together);
2772 case Instruction::Or:
2773 if (Together == AndRHS) // (X | C) & C --> C
2774 return ReplaceInstUsesWith(TheAnd, AndRHS);
2776 if (Op->hasOneUse() && Together != OpRHS) {
2777 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2778 std::string Op0Name = Op->getName(); Op->setName("");
2779 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2780 InsertNewInstBefore(Or, TheAnd);
2781 return BinaryOperator::createAnd(Or, AndRHS);
2784 case Instruction::Add:
2785 if (Op->hasOneUse()) {
2786 // Adding a one to a single bit bit-field should be turned into an XOR
2787 // of the bit. First thing to check is to see if this AND is with a
2788 // single bit constant.
2789 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2791 // Clear bits that are not part of the constant.
2792 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2794 // If there is only one bit set...
2795 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2796 // Ok, at this point, we know that we are masking the result of the
2797 // ADD down to exactly one bit. If the constant we are adding has
2798 // no bits set below this bit, then we can eliminate the ADD.
2799 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2801 // Check to see if any bits below the one bit set in AndRHSV are set.
2802 if ((AddRHS & (AndRHSV-1)) == 0) {
2803 // If not, the only thing that can effect the output of the AND is
2804 // the bit specified by AndRHSV. If that bit is set, the effect of
2805 // the XOR is to toggle the bit. If it is clear, then the ADD has
2807 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2808 TheAnd.setOperand(0, X);
2811 std::string Name = Op->getName(); Op->setName("");
2812 // Pull the XOR out of the AND.
2813 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2814 InsertNewInstBefore(NewAnd, TheAnd);
2815 return BinaryOperator::createXor(NewAnd, AndRHS);
2822 case Instruction::Shl: {
2823 // We know that the AND will not produce any of the bits shifted in, so if
2824 // the anded constant includes them, clear them now!
2826 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2827 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2828 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2830 if (CI == ShlMask) { // Masking out bits that the shift already masks
2831 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2832 } else if (CI != AndRHS) { // Reducing bits set in and.
2833 TheAnd.setOperand(1, CI);
2838 case Instruction::LShr:
2840 // We know that the AND will not produce any of the bits shifted in, so if
2841 // the anded constant includes them, clear them now! This only applies to
2842 // unsigned shifts, because a signed shr may bring in set bits!
2844 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2845 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2846 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2848 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2849 return ReplaceInstUsesWith(TheAnd, Op);
2850 } else if (CI != AndRHS) {
2851 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2856 case Instruction::AShr:
2858 // See if this is shifting in some sign extension, then masking it out
2860 if (Op->hasOneUse()) {
2861 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2862 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2863 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2864 if (CI == AndRHS) { // Masking out bits shifted in.
2865 // Make the argument unsigned.
2866 Value *ShVal = Op->getOperand(0);
2867 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2868 OpRHS, Op->getName()),
2870 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2871 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
2880 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2881 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2882 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2883 /// insert new instructions.
2884 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2885 bool Inside, Instruction &IB) {
2886 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2887 "Lo is not <= Hi in range emission code!");
2889 if (Lo == Hi) // Trivially false.
2890 return new SetCondInst(Instruction::SetNE, V, V);
2891 if (cast<ConstantIntegral>(Lo)->isMinValue())
2892 return new SetCondInst(Instruction::SetLT, V, Hi);
2894 Constant *AddCST = ConstantExpr::getNeg(Lo);
2895 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2896 InsertNewInstBefore(Add, IB);
2897 // Convert to unsigned for the comparison.
2898 const Type *UnsType = Add->getType()->getUnsignedVersion();
2899 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2900 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2901 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2902 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2905 if (Lo == Hi) // Trivially true.
2906 return new SetCondInst(Instruction::SetEQ, V, V);
2908 Hi = SubOne(cast<ConstantInt>(Hi));
2910 // V < 0 || V >= Hi ->'V > Hi-1'
2911 if (cast<ConstantIntegral>(Lo)->isMinValue())
2912 return new SetCondInst(Instruction::SetGT, V, Hi);
2914 // Emit X-Lo > Hi-Lo-1
2915 Constant *AddCST = ConstantExpr::getNeg(Lo);
2916 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2917 InsertNewInstBefore(Add, IB);
2918 // Convert to unsigned for the comparison.
2919 const Type *UnsType = Add->getType()->getUnsignedVersion();
2920 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2921 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2922 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2923 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2926 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2927 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2928 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2929 // not, since all 1s are not contiguous.
2930 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2931 uint64_t V = Val->getZExtValue();
2932 if (!isShiftedMask_64(V)) return false;
2934 // look for the first zero bit after the run of ones
2935 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2936 // look for the first non-zero bit
2937 ME = 64-CountLeadingZeros_64(V);
2943 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2944 /// where isSub determines whether the operator is a sub. If we can fold one of
2945 /// the following xforms:
2947 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2948 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2949 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2951 /// return (A +/- B).
2953 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2954 ConstantIntegral *Mask, bool isSub,
2956 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2957 if (!LHSI || LHSI->getNumOperands() != 2 ||
2958 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2960 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2962 switch (LHSI->getOpcode()) {
2964 case Instruction::And:
2965 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2966 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2967 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
2970 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2971 // part, we don't need any explicit masks to take them out of A. If that
2972 // is all N is, ignore it.
2974 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2975 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2977 if (MaskedValueIsZero(RHS, Mask))
2982 case Instruction::Or:
2983 case Instruction::Xor:
2984 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2985 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
2986 ConstantExpr::getAnd(N, Mask)->isNullValue())
2993 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2995 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2996 return InsertNewInstBefore(New, I);
2999 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3000 bool Changed = SimplifyCommutative(I);
3001 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3003 if (isa<UndefValue>(Op1)) // X & undef -> 0
3004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3008 return ReplaceInstUsesWith(I, Op1);
3010 // See if we can simplify any instructions used by the instruction whose sole
3011 // purpose is to compute bits we don't care about.
3012 uint64_t KnownZero, KnownOne;
3013 if (!isa<PackedType>(I.getType()) &&
3014 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3015 KnownZero, KnownOne))
3018 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
3019 uint64_t AndRHSMask = AndRHS->getZExtValue();
3020 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
3021 uint64_t NotAndRHS = AndRHSMask^TypeMask;
3023 // Optimize a variety of ((val OP C1) & C2) combinations...
3024 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3025 Instruction *Op0I = cast<Instruction>(Op0);
3026 Value *Op0LHS = Op0I->getOperand(0);
3027 Value *Op0RHS = Op0I->getOperand(1);
3028 switch (Op0I->getOpcode()) {
3029 case Instruction::Xor:
3030 case Instruction::Or:
3031 // If the mask is only needed on one incoming arm, push it up.
3032 if (Op0I->hasOneUse()) {
3033 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3034 // Not masking anything out for the LHS, move to RHS.
3035 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3036 Op0RHS->getName()+".masked");
3037 InsertNewInstBefore(NewRHS, I);
3038 return BinaryOperator::create(
3039 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3041 if (!isa<Constant>(Op0RHS) &&
3042 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3043 // Not masking anything out for the RHS, move to LHS.
3044 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3045 Op0LHS->getName()+".masked");
3046 InsertNewInstBefore(NewLHS, I);
3047 return BinaryOperator::create(
3048 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3053 case Instruction::Add:
3054 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3055 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3056 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3057 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3058 return BinaryOperator::createAnd(V, AndRHS);
3059 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3060 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3063 case Instruction::Sub:
3064 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3065 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3066 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3067 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3068 return BinaryOperator::createAnd(V, AndRHS);
3072 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3073 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3075 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3076 // If this is an integer truncation or change from signed-to-unsigned, and
3077 // if the source is an and/or with immediate, transform it. This
3078 // frequently occurs for bitfield accesses.
3079 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3080 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3081 CastOp->getNumOperands() == 2)
3082 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3083 if (CastOp->getOpcode() == Instruction::And) {
3084 // Change: and (cast (and X, C1) to T), C2
3085 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3086 // This will fold the two constants together, which may allow
3087 // other simplifications.
3088 Instruction *NewCast =
3089 CastInst::createInferredCast(CastOp->getOperand(0), I.getType(),
3090 CastOp->getName()+".shrunk");
3091 NewCast = InsertNewInstBefore(NewCast, I);
3092 // trunc_or_bitcast(C1)&C2
3093 Instruction::CastOps opc = (
3094 AndCI->getType()->getPrimitiveSizeInBits() ==
3095 I.getType()->getPrimitiveSizeInBits() ?
3096 Instruction::BitCast : Instruction::Trunc);
3097 Constant *C3 = ConstantExpr::getCast(opc, AndCI, I.getType());
3098 C3 = ConstantExpr::getAnd(C3, AndRHS);
3099 return BinaryOperator::createAnd(NewCast, C3);
3100 } else if (CastOp->getOpcode() == Instruction::Or) {
3101 // Change: and (cast (or X, C1) to T), C2
3102 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3103 Constant *C3 = ConstantExpr::getCast(AndCI, I.getType());
3104 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3105 return ReplaceInstUsesWith(I, AndRHS);
3110 // Try to fold constant and into select arguments.
3111 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3112 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3114 if (isa<PHINode>(Op0))
3115 if (Instruction *NV = FoldOpIntoPhi(I))
3119 Value *Op0NotVal = dyn_castNotVal(Op0);
3120 Value *Op1NotVal = dyn_castNotVal(Op1);
3122 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3125 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3126 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3127 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3128 I.getName()+".demorgan");
3129 InsertNewInstBefore(Or, I);
3130 return BinaryOperator::createNot(Or);
3134 Value *A = 0, *B = 0;
3135 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3136 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3137 return ReplaceInstUsesWith(I, Op1);
3138 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3139 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3140 return ReplaceInstUsesWith(I, Op0);
3142 if (Op0->hasOneUse() &&
3143 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3144 if (A == Op1) { // (A^B)&A -> A&(A^B)
3145 I.swapOperands(); // Simplify below
3146 std::swap(Op0, Op1);
3147 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3148 cast<BinaryOperator>(Op0)->swapOperands();
3149 I.swapOperands(); // Simplify below
3150 std::swap(Op0, Op1);
3153 if (Op1->hasOneUse() &&
3154 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3155 if (B == Op0) { // B&(A^B) -> B&(B^A)
3156 cast<BinaryOperator>(Op1)->swapOperands();
3159 if (A == Op0) { // A&(A^B) -> A & ~B
3160 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3161 InsertNewInstBefore(NotB, I);
3162 return BinaryOperator::createAnd(A, NotB);
3168 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3169 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
3170 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3173 Value *LHSVal, *RHSVal;
3174 ConstantInt *LHSCst, *RHSCst;
3175 Instruction::BinaryOps LHSCC, RHSCC;
3176 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3177 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3178 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3179 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3180 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3181 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3182 // Ensure that the larger constant is on the RHS.
3183 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3184 SetCondInst *LHS = cast<SetCondInst>(Op0);
3185 if (cast<ConstantBool>(Cmp)->getValue()) {
3186 std::swap(LHS, RHS);
3187 std::swap(LHSCst, RHSCst);
3188 std::swap(LHSCC, RHSCC);
3191 // At this point, we know we have have two setcc instructions
3192 // comparing a value against two constants and and'ing the result
3193 // together. Because of the above check, we know that we only have
3194 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3195 // FoldSetCCLogical check above), that the two constants are not
3197 assert(LHSCst != RHSCst && "Compares not folded above?");
3200 default: assert(0 && "Unknown integer condition code!");
3201 case Instruction::SetEQ:
3203 default: assert(0 && "Unknown integer condition code!");
3204 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3205 case Instruction::SetGT: // (X == 13 & X > 15) -> false
3206 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3207 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3208 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3209 return ReplaceInstUsesWith(I, LHS);
3211 case Instruction::SetNE:
3213 default: assert(0 && "Unknown integer condition code!");
3214 case Instruction::SetLT:
3215 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3216 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3217 break; // (X != 13 & X < 15) -> no change
3218 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3219 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3220 return ReplaceInstUsesWith(I, RHS);
3221 case Instruction::SetNE:
3222 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3223 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3224 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3225 LHSVal->getName()+".off");
3226 InsertNewInstBefore(Add, I);
3227 const Type *UnsType = Add->getType()->getUnsignedVersion();
3228 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3229 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3230 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3231 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3233 break; // (X != 13 & X != 15) -> no change
3236 case Instruction::SetLT:
3238 default: assert(0 && "Unknown integer condition code!");
3239 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3240 case Instruction::SetGT: // (X < 13 & X > 15) -> false
3241 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3242 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3243 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3244 return ReplaceInstUsesWith(I, LHS);
3246 case Instruction::SetGT:
3248 default: assert(0 && "Unknown integer condition code!");
3249 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3250 return ReplaceInstUsesWith(I, LHS);
3251 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3252 return ReplaceInstUsesWith(I, RHS);
3253 case Instruction::SetNE:
3254 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3255 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3256 break; // (X > 13 & X != 15) -> no change
3257 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3258 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
3264 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3265 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
3266 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3267 const Type *SrcTy = Op0C->getOperand(0)->getType();
3268 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3269 // Only do this if the casts both really cause code to be generated.
3270 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3271 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3272 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3273 Op1C->getOperand(0),
3275 InsertNewInstBefore(NewOp, I);
3276 return CastInst::createInferredCast(NewOp, I.getType());
3281 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3282 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3283 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3284 if (SI0->getOpcode() == SI1->getOpcode() &&
3285 SI0->getOperand(1) == SI1->getOperand(1) &&
3286 (SI0->hasOneUse() || SI1->hasOneUse())) {
3287 Instruction *NewOp =
3288 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3290 SI0->getName()), I);
3291 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3295 return Changed ? &I : 0;
3298 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3299 /// in the result. If it does, and if the specified byte hasn't been filled in
3300 /// yet, fill it in and return false.
3301 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3302 Instruction *I = dyn_cast<Instruction>(V);
3303 if (I == 0) return true;
3305 // If this is an or instruction, it is an inner node of the bswap.
3306 if (I->getOpcode() == Instruction::Or)
3307 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3308 CollectBSwapParts(I->getOperand(1), ByteValues);
3310 // If this is a shift by a constant int, and it is "24", then its operand
3311 // defines a byte. We only handle unsigned types here.
3312 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3313 // Not shifting the entire input by N-1 bytes?
3314 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3315 8*(ByteValues.size()-1))
3319 if (I->getOpcode() == Instruction::Shl) {
3320 // X << 24 defines the top byte with the lowest of the input bytes.
3321 DestNo = ByteValues.size()-1;
3323 // X >>u 24 defines the low byte with the highest of the input bytes.
3327 // If the destination byte value is already defined, the values are or'd
3328 // together, which isn't a bswap (unless it's an or of the same bits).
3329 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3331 ByteValues[DestNo] = I->getOperand(0);
3335 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3337 Value *Shift = 0, *ShiftLHS = 0;
3338 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3339 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3340 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3342 Instruction *SI = cast<Instruction>(Shift);
3344 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3345 if (ShiftAmt->getZExtValue() & 7 ||
3346 ShiftAmt->getZExtValue() > 8*ByteValues.size())
3349 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3351 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3352 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3354 // Unknown mask for bswap.
3355 if (DestByte == ByteValues.size()) return true;
3357 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3359 if (SI->getOpcode() == Instruction::Shl)
3360 SrcByte = DestByte - ShiftBytes;
3362 SrcByte = DestByte + ShiftBytes;
3364 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3365 if (SrcByte != ByteValues.size()-DestByte-1)
3368 // If the destination byte value is already defined, the values are or'd
3369 // together, which isn't a bswap (unless it's an or of the same bits).
3370 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3372 ByteValues[DestByte] = SI->getOperand(0);
3376 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3377 /// If so, insert the new bswap intrinsic and return it.
3378 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3379 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3380 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3383 /// ByteValues - For each byte of the result, we keep track of which value
3384 /// defines each byte.
3385 std::vector<Value*> ByteValues;
3386 ByteValues.resize(I.getType()->getPrimitiveSize());
3388 // Try to find all the pieces corresponding to the bswap.
3389 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3390 CollectBSwapParts(I.getOperand(1), ByteValues))
3393 // Check to see if all of the bytes come from the same value.
3394 Value *V = ByteValues[0];
3395 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3397 // Check to make sure that all of the bytes come from the same value.
3398 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3399 if (ByteValues[i] != V)
3402 // If they do then *success* we can turn this into a bswap. Figure out what
3403 // bswap to make it into.
3404 Module *M = I.getParent()->getParent()->getParent();
3405 const char *FnName = 0;
3406 if (I.getType() == Type::UShortTy)
3407 FnName = "llvm.bswap.i16";
3408 else if (I.getType() == Type::UIntTy)
3409 FnName = "llvm.bswap.i32";
3410 else if (I.getType() == Type::ULongTy)
3411 FnName = "llvm.bswap.i64";
3413 assert(0 && "Unknown integer type!");
3414 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3416 return new CallInst(F, V);
3420 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3421 bool Changed = SimplifyCommutative(I);
3422 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3424 if (isa<UndefValue>(Op1))
3425 return ReplaceInstUsesWith(I, // X | undef -> -1
3426 ConstantIntegral::getAllOnesValue(I.getType()));
3430 return ReplaceInstUsesWith(I, Op0);
3432 // See if we can simplify any instructions used by the instruction whose sole
3433 // purpose is to compute bits we don't care about.
3434 uint64_t KnownZero, KnownOne;
3435 if (!isa<PackedType>(I.getType()) &&
3436 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3437 KnownZero, KnownOne))
3441 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3442 ConstantInt *C1 = 0; Value *X = 0;
3443 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3444 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3445 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3447 InsertNewInstBefore(Or, I);
3448 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3451 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3452 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3453 std::string Op0Name = Op0->getName(); Op0->setName("");
3454 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3455 InsertNewInstBefore(Or, I);
3456 return BinaryOperator::createXor(Or,
3457 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3460 // Try to fold constant and into select arguments.
3461 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3462 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3464 if (isa<PHINode>(Op0))
3465 if (Instruction *NV = FoldOpIntoPhi(I))
3469 Value *A = 0, *B = 0;
3470 ConstantInt *C1 = 0, *C2 = 0;
3472 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3473 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3474 return ReplaceInstUsesWith(I, Op1);
3475 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3476 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3477 return ReplaceInstUsesWith(I, Op0);
3479 // (A | B) | C and A | (B | C) -> bswap if possible.
3480 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3481 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3482 match(Op1, m_Or(m_Value(), m_Value())) ||
3483 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3484 match(Op1, m_Shift(m_Value(), m_Value())))) {
3485 if (Instruction *BSwap = MatchBSwap(I))
3489 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3490 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3491 MaskedValueIsZero(Op1, C1->getZExtValue())) {
3492 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3494 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3497 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3498 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3499 MaskedValueIsZero(Op0, C1->getZExtValue())) {
3500 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3502 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3505 // (A & C1)|(B & C2)
3506 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3507 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3509 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3510 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3513 // If we have: ((V + N) & C1) | (V & C2)
3514 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3515 // replace with V+N.
3516 if (C1 == ConstantExpr::getNot(C2)) {
3517 Value *V1 = 0, *V2 = 0;
3518 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3519 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3520 // Add commutes, try both ways.
3521 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3522 return ReplaceInstUsesWith(I, A);
3523 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3524 return ReplaceInstUsesWith(I, A);
3526 // Or commutes, try both ways.
3527 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3528 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3529 // Add commutes, try both ways.
3530 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3531 return ReplaceInstUsesWith(I, B);
3532 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3533 return ReplaceInstUsesWith(I, B);
3538 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3539 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3540 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3541 if (SI0->getOpcode() == SI1->getOpcode() &&
3542 SI0->getOperand(1) == SI1->getOperand(1) &&
3543 (SI0->hasOneUse() || SI1->hasOneUse())) {
3544 Instruction *NewOp =
3545 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3547 SI0->getName()), I);
3548 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3552 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3553 if (A == Op1) // ~A | A == -1
3554 return ReplaceInstUsesWith(I,
3555 ConstantIntegral::getAllOnesValue(I.getType()));
3559 // Note, A is still live here!
3560 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3562 return ReplaceInstUsesWith(I,
3563 ConstantIntegral::getAllOnesValue(I.getType()));
3565 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3566 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3567 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3568 I.getName()+".demorgan"), I);
3569 return BinaryOperator::createNot(And);
3573 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3574 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3575 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3578 Value *LHSVal, *RHSVal;
3579 ConstantInt *LHSCst, *RHSCst;
3580 Instruction::BinaryOps LHSCC, RHSCC;
3581 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3582 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3583 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3584 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3585 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3586 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3587 // Ensure that the larger constant is on the RHS.
3588 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3589 SetCondInst *LHS = cast<SetCondInst>(Op0);
3590 if (cast<ConstantBool>(Cmp)->getValue()) {
3591 std::swap(LHS, RHS);
3592 std::swap(LHSCst, RHSCst);
3593 std::swap(LHSCC, RHSCC);
3596 // At this point, we know we have have two setcc instructions
3597 // comparing a value against two constants and or'ing the result
3598 // together. Because of the above check, we know that we only have
3599 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3600 // FoldSetCCLogical check above), that the two constants are not
3602 assert(LHSCst != RHSCst && "Compares not folded above?");
3605 default: assert(0 && "Unknown integer condition code!");
3606 case Instruction::SetEQ:
3608 default: assert(0 && "Unknown integer condition code!");
3609 case Instruction::SetEQ:
3610 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3611 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3612 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3613 LHSVal->getName()+".off");
3614 InsertNewInstBefore(Add, I);
3615 const Type *UnsType = Add->getType()->getUnsignedVersion();
3616 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3617 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3618 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3619 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3621 break; // (X == 13 | X == 15) -> no change
3623 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3625 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3626 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3627 return ReplaceInstUsesWith(I, RHS);
3630 case Instruction::SetNE:
3632 default: assert(0 && "Unknown integer condition code!");
3633 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3634 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3635 return ReplaceInstUsesWith(I, LHS);
3636 case Instruction::SetNE: // (X != 13 | X != 15) -> true
3637 case Instruction::SetLT: // (X != 13 | X < 15) -> true
3638 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3641 case Instruction::SetLT:
3643 default: assert(0 && "Unknown integer condition code!");
3644 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3646 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3647 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3648 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3649 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3650 return ReplaceInstUsesWith(I, RHS);
3653 case Instruction::SetGT:
3655 default: assert(0 && "Unknown integer condition code!");
3656 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3657 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3658 return ReplaceInstUsesWith(I, LHS);
3659 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3660 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3661 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3667 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3668 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3669 const Type *SrcTy = Op0C->getOperand(0)->getType();
3670 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3671 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3672 // Only do this if the casts both really cause code to be generated.
3673 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3674 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3675 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3676 Op1C->getOperand(0),
3678 InsertNewInstBefore(NewOp, I);
3679 return CastInst::createInferredCast(NewOp, I.getType());
3684 return Changed ? &I : 0;
3687 // XorSelf - Implements: X ^ X --> 0
3690 XorSelf(Value *rhs) : RHS(rhs) {}
3691 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3692 Instruction *apply(BinaryOperator &Xor) const {
3698 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3699 bool Changed = SimplifyCommutative(I);
3700 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3702 if (isa<UndefValue>(Op1))
3703 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3705 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3706 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3707 assert(Result == &I && "AssociativeOpt didn't work?");
3708 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3711 // See if we can simplify any instructions used by the instruction whose sole
3712 // purpose is to compute bits we don't care about.
3713 uint64_t KnownZero, KnownOne;
3714 if (!isa<PackedType>(I.getType()) &&
3715 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3716 KnownZero, KnownOne))
3719 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3720 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3721 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3722 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3723 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
3724 return new SetCondInst(SCI->getInverseCondition(),
3725 SCI->getOperand(0), SCI->getOperand(1));
3727 // ~(c-X) == X-c-1 == X+(-c-1)
3728 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3729 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3730 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3731 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3732 ConstantInt::get(I.getType(), 1));
3733 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3736 // ~(~X & Y) --> (X | ~Y)
3737 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3738 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3739 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3741 BinaryOperator::createNot(Op0I->getOperand(1),
3742 Op0I->getOperand(1)->getName()+".not");
3743 InsertNewInstBefore(NotY, I);
3744 return BinaryOperator::createOr(Op0NotVal, NotY);
3748 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3749 if (Op0I->getOpcode() == Instruction::Add) {
3750 // ~(X-c) --> (-c-1)-X
3751 if (RHS->isAllOnesValue()) {
3752 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3753 return BinaryOperator::createSub(
3754 ConstantExpr::getSub(NegOp0CI,
3755 ConstantInt::get(I.getType(), 1)),
3756 Op0I->getOperand(0));
3758 } else if (Op0I->getOpcode() == Instruction::Or) {
3759 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3760 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3761 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3762 // Anything in both C1 and C2 is known to be zero, remove it from
3764 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3765 NewRHS = ConstantExpr::getAnd(NewRHS,
3766 ConstantExpr::getNot(CommonBits));
3767 WorkList.push_back(Op0I);
3768 I.setOperand(0, Op0I->getOperand(0));
3769 I.setOperand(1, NewRHS);
3775 // Try to fold constant and into select arguments.
3776 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3777 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3779 if (isa<PHINode>(Op0))
3780 if (Instruction *NV = FoldOpIntoPhi(I))
3784 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
3786 return ReplaceInstUsesWith(I,
3787 ConstantIntegral::getAllOnesValue(I.getType()));
3789 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
3791 return ReplaceInstUsesWith(I,
3792 ConstantIntegral::getAllOnesValue(I.getType()));
3794 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3795 if (Op1I->getOpcode() == Instruction::Or) {
3796 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
3797 Op1I->swapOperands();
3799 std::swap(Op0, Op1);
3800 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
3801 I.swapOperands(); // Simplified below.
3802 std::swap(Op0, Op1);
3804 } else if (Op1I->getOpcode() == Instruction::Xor) {
3805 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3806 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3807 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3808 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3809 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3810 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3811 Op1I->swapOperands();
3812 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3813 I.swapOperands(); // Simplified below.
3814 std::swap(Op0, Op1);
3818 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3819 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3820 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3821 Op0I->swapOperands();
3822 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3823 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3824 InsertNewInstBefore(NotB, I);
3825 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3827 } else if (Op0I->getOpcode() == Instruction::Xor) {
3828 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3829 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3830 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3831 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3832 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3833 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3834 Op0I->swapOperands();
3835 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3836 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3837 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3838 InsertNewInstBefore(N, I);
3839 return BinaryOperator::createAnd(N, Op1);
3843 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3844 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3845 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3848 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3849 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3850 const Type *SrcTy = Op0C->getOperand(0)->getType();
3851 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3852 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3853 // Only do this if the casts both really cause code to be generated.
3854 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3855 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3856 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3857 Op1C->getOperand(0),
3859 InsertNewInstBefore(NewOp, I);
3860 return CastInst::createInferredCast(NewOp, I.getType());
3864 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3865 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3866 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3867 if (SI0->getOpcode() == SI1->getOpcode() &&
3868 SI0->getOperand(1) == SI1->getOperand(1) &&
3869 (SI0->hasOneUse() || SI1->hasOneUse())) {
3870 Instruction *NewOp =
3871 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3873 SI0->getName()), I);
3874 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3878 return Changed ? &I : 0;
3881 static bool isPositive(ConstantInt *C) {
3882 return C->getSExtValue() >= 0;
3885 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3886 /// overflowed for this type.
3887 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3889 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3891 if (In1->getType()->isUnsigned())
3892 return cast<ConstantInt>(Result)->getZExtValue() <
3893 cast<ConstantInt>(In1)->getZExtValue();
3894 if (isPositive(In1) != isPositive(In2))
3896 if (isPositive(In1))
3897 return cast<ConstantInt>(Result)->getSExtValue() <
3898 cast<ConstantInt>(In1)->getSExtValue();
3899 return cast<ConstantInt>(Result)->getSExtValue() >
3900 cast<ConstantInt>(In1)->getSExtValue();
3903 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3904 /// code necessary to compute the offset from the base pointer (without adding
3905 /// in the base pointer). Return the result as a signed integer of intptr size.
3906 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3907 TargetData &TD = IC.getTargetData();
3908 gep_type_iterator GTI = gep_type_begin(GEP);
3909 const Type *UIntPtrTy = TD.getIntPtrType();
3910 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3911 Value *Result = Constant::getNullValue(SIntPtrTy);
3913 // Build a mask for high order bits.
3914 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3916 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3917 Value *Op = GEP->getOperand(i);
3918 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3919 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
3921 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3922 if (!OpC->isNullValue()) {
3923 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3924 Scale = ConstantExpr::getMul(OpC, Scale);
3925 if (Constant *RC = dyn_cast<Constant>(Result))
3926 Result = ConstantExpr::getAdd(RC, Scale);
3928 // Emit an add instruction.
3929 Result = IC.InsertNewInstBefore(
3930 BinaryOperator::createAdd(Result, Scale,
3931 GEP->getName()+".offs"), I);
3935 // Convert to correct type.
3936 Op = IC.InsertNewInstBefore(CastInst::createInferredCast(Op, SIntPtrTy,
3937 Op->getName()+".c"), I);
3939 // We'll let instcombine(mul) convert this to a shl if possible.
3940 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3941 GEP->getName()+".idx"), I);
3943 // Emit an add instruction.
3944 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3945 GEP->getName()+".offs"), I);
3951 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3952 /// else. At this point we know that the GEP is on the LHS of the comparison.
3953 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3954 Instruction::BinaryOps Cond,
3956 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3958 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3959 if (isa<PointerType>(CI->getOperand(0)->getType()))
3960 RHS = CI->getOperand(0);
3962 Value *PtrBase = GEPLHS->getOperand(0);
3963 if (PtrBase == RHS) {
3964 // As an optimization, we don't actually have to compute the actual value of
3965 // OFFSET if this is a seteq or setne comparison, just return whether each
3966 // index is zero or not.
3967 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3968 Instruction *InVal = 0;
3969 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3970 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3972 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3973 if (isa<UndefValue>(C)) // undef index -> undef.
3974 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3975 if (C->isNullValue())
3977 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3978 EmitIt = false; // This is indexing into a zero sized array?
3979 } else if (isa<ConstantInt>(C))
3980 return ReplaceInstUsesWith(I, // No comparison is needed here.
3981 ConstantBool::get(Cond == Instruction::SetNE));
3986 new SetCondInst(Cond, GEPLHS->getOperand(i),
3987 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3991 InVal = InsertNewInstBefore(InVal, I);
3992 InsertNewInstBefore(Comp, I);
3993 if (Cond == Instruction::SetNE) // True if any are unequal
3994 InVal = BinaryOperator::createOr(InVal, Comp);
3995 else // True if all are equal
3996 InVal = BinaryOperator::createAnd(InVal, Comp);
4004 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4005 ConstantBool::get(Cond == Instruction::SetEQ));
4008 // Only lower this if the setcc is the only user of the GEP or if we expect
4009 // the result to fold to a constant!
4010 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4011 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4012 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4013 return new SetCondInst(Cond, Offset,
4014 Constant::getNullValue(Offset->getType()));
4016 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4017 // If the base pointers are different, but the indices are the same, just
4018 // compare the base pointer.
4019 if (PtrBase != GEPRHS->getOperand(0)) {
4020 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4021 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4022 GEPRHS->getOperand(0)->getType();
4024 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4025 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4026 IndicesTheSame = false;
4030 // If all indices are the same, just compare the base pointers.
4032 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4033 GEPRHS->getOperand(0));
4035 // Otherwise, the base pointers are different and the indices are
4036 // different, bail out.
4040 // If one of the GEPs has all zero indices, recurse.
4041 bool AllZeros = true;
4042 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4043 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4044 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4049 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4050 SetCondInst::getSwappedCondition(Cond), I);
4052 // If the other GEP has all zero indices, recurse.
4054 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4055 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4056 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4061 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4063 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4064 // If the GEPs only differ by one index, compare it.
4065 unsigned NumDifferences = 0; // Keep track of # differences.
4066 unsigned DiffOperand = 0; // The operand that differs.
4067 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4068 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4069 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4070 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4071 // Irreconcilable differences.
4075 if (NumDifferences++) break;
4080 if (NumDifferences == 0) // SAME GEP?
4081 return ReplaceInstUsesWith(I, // No comparison is needed here.
4082 ConstantBool::get(Cond == Instruction::SetEQ));
4083 else if (NumDifferences == 1) {
4084 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4085 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4087 // Convert the operands to signed values to make sure to perform a
4088 // signed comparison.
4089 const Type *NewTy = LHSV->getType()->getSignedVersion();
4090 if (LHSV->getType() != NewTy)
4091 LHSV = InsertCastBefore(LHSV, NewTy, I);
4092 if (RHSV->getType() != NewTy)
4093 RHSV = InsertCastBefore(RHSV, NewTy, I);
4094 return new SetCondInst(Cond, LHSV, RHSV);
4098 // Only lower this if the setcc is the only user of the GEP or if we expect
4099 // the result to fold to a constant!
4100 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4101 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4102 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4103 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4104 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4105 return new SetCondInst(Cond, L, R);
4112 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
4113 bool Changed = SimplifyCommutative(I);
4114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4115 const Type *Ty = Op0->getType();
4119 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4121 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4122 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4124 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4125 // addresses never equal each other! We already know that Op0 != Op1.
4126 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4127 isa<ConstantPointerNull>(Op0)) &&
4128 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4129 isa<ConstantPointerNull>(Op1)))
4130 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4132 // setcc's with boolean values can always be turned into bitwise operations
4133 if (Ty == Type::BoolTy) {
4134 switch (I.getOpcode()) {
4135 default: assert(0 && "Invalid setcc instruction!");
4136 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
4137 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4138 InsertNewInstBefore(Xor, I);
4139 return BinaryOperator::createNot(Xor);
4141 case Instruction::SetNE:
4142 return BinaryOperator::createXor(Op0, Op1);
4144 case Instruction::SetGT:
4145 std::swap(Op0, Op1); // Change setgt -> setlt
4147 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4148 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4149 InsertNewInstBefore(Not, I);
4150 return BinaryOperator::createAnd(Not, Op1);
4152 case Instruction::SetGE:
4153 std::swap(Op0, Op1); // Change setge -> setle
4155 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4156 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4157 InsertNewInstBefore(Not, I);
4158 return BinaryOperator::createOr(Not, Op1);
4163 // See if we are doing a comparison between a constant and an instruction that
4164 // can be folded into the comparison.
4165 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4166 // Check to see if we are comparing against the minimum or maximum value...
4167 if (CI->isMinValue()) {
4168 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
4169 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4170 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
4171 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4172 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4173 return BinaryOperator::createSetEQ(Op0, Op1);
4174 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4175 return BinaryOperator::createSetNE(Op0, Op1);
4177 } else if (CI->isMaxValue()) {
4178 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
4179 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4180 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
4181 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4182 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4183 return BinaryOperator::createSetEQ(Op0, Op1);
4184 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4185 return BinaryOperator::createSetNE(Op0, Op1);
4187 // Comparing against a value really close to min or max?
4188 } else if (isMinValuePlusOne(CI)) {
4189 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4190 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4191 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4192 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4194 } else if (isMaxValueMinusOne(CI)) {
4195 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4196 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4197 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4198 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4201 // If we still have a setle or setge instruction, turn it into the
4202 // appropriate setlt or setgt instruction. Since the border cases have
4203 // already been handled above, this requires little checking.
4205 if (I.getOpcode() == Instruction::SetLE)
4206 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4207 if (I.getOpcode() == Instruction::SetGE)
4208 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4211 // See if we can fold the comparison based on bits known to be zero or one
4213 uint64_t KnownZero, KnownOne;
4214 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4215 KnownZero, KnownOne, 0))
4218 // Given the known and unknown bits, compute a range that the LHS could be
4220 if (KnownOne | KnownZero) {
4221 if (Ty->isUnsigned()) { // Unsigned comparison.
4223 uint64_t RHSVal = CI->getZExtValue();
4224 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4226 switch (I.getOpcode()) { // LE/GE have been folded already.
4227 default: assert(0 && "Unknown setcc opcode!");
4228 case Instruction::SetEQ:
4229 if (Max < RHSVal || Min > RHSVal)
4230 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4232 case Instruction::SetNE:
4233 if (Max < RHSVal || Min > RHSVal)
4234 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4236 case Instruction::SetLT:
4238 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4240 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4242 case Instruction::SetGT:
4244 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4246 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4249 } else { // Signed comparison.
4251 int64_t RHSVal = CI->getSExtValue();
4252 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4254 switch (I.getOpcode()) { // LE/GE have been folded already.
4255 default: assert(0 && "Unknown setcc opcode!");
4256 case Instruction::SetEQ:
4257 if (Max < RHSVal || Min > RHSVal)
4258 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4260 case Instruction::SetNE:
4261 if (Max < RHSVal || Min > RHSVal)
4262 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4264 case Instruction::SetLT:
4266 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4268 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4270 case Instruction::SetGT:
4272 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4274 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4280 // Since the RHS is a constantInt (CI), if the left hand side is an
4281 // instruction, see if that instruction also has constants so that the
4282 // instruction can be folded into the setcc
4283 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4284 switch (LHSI->getOpcode()) {
4285 case Instruction::And:
4286 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4287 LHSI->getOperand(0)->hasOneUse()) {
4288 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4290 // If an operand is an AND of a truncating cast, we can widen the
4291 // and/compare to be the input width without changing the value
4292 // produced, eliminating a cast.
4293 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4294 // We can do this transformation if either the AND constant does not
4295 // have its sign bit set or if it is an equality comparison.
4296 // Extending a relational comparison when we're checking the sign
4297 // bit would not work.
4298 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4300 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4301 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4302 ConstantInt *NewCST;
4304 if (Cast->getOperand(0)->getType()->isSigned()) {
4305 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4306 AndCST->getZExtValue());
4307 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4308 CI->getZExtValue());
4310 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4311 AndCST->getZExtValue());
4312 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4313 CI->getZExtValue());
4315 Instruction *NewAnd =
4316 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4318 InsertNewInstBefore(NewAnd, I);
4319 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4323 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4324 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4325 // happens a LOT in code produced by the C front-end, for bitfield
4327 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4329 // Check to see if there is a noop-cast between the shift and the and.
4331 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4332 if (CI->getOperand(0)->getType()->isIntegral() &&
4333 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4334 CI->getType()->getPrimitiveSizeInBits())
4335 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4339 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4340 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4341 const Type *AndTy = AndCST->getType(); // Type of the and.
4343 // We can fold this as long as we can't shift unknown bits
4344 // into the mask. This can only happen with signed shift
4345 // rights, as they sign-extend.
4347 bool CanFold = Shift->isLogicalShift();
4349 // To test for the bad case of the signed shr, see if any
4350 // of the bits shifted in could be tested after the mask.
4351 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4352 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4354 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
4356 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4358 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4364 if (Shift->getOpcode() == Instruction::Shl)
4365 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4367 NewCst = ConstantExpr::getShl(CI, ShAmt);
4369 // Check to see if we are shifting out any of the bits being
4371 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4372 // If we shifted bits out, the fold is not going to work out.
4373 // As a special case, check to see if this means that the
4374 // result is always true or false now.
4375 if (I.getOpcode() == Instruction::SetEQ)
4376 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4377 if (I.getOpcode() == Instruction::SetNE)
4378 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4380 I.setOperand(1, NewCst);
4381 Constant *NewAndCST;
4382 if (Shift->getOpcode() == Instruction::Shl)
4383 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4385 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4386 LHSI->setOperand(1, NewAndCST);
4388 LHSI->setOperand(0, Shift->getOperand(0));
4390 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4392 LHSI->setOperand(0, NewCast);
4394 WorkList.push_back(Shift); // Shift is dead.
4395 AddUsesToWorkList(I);
4401 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4402 // preferable because it allows the C<<Y expression to be hoisted out
4403 // of a loop if Y is invariant and X is not.
4404 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4405 I.isEquality() && !Shift->isArithmeticShift() &&
4406 isa<Instruction>(Shift->getOperand(0))) {
4409 if (Shift->getOpcode() == Instruction::LShr) {
4410 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4413 // Make sure we insert a logical shift.
4414 Constant *NewAndCST = AndCST;
4415 if (AndCST->getType()->isSigned())
4416 NewAndCST = ConstantExpr::getCast(AndCST,
4417 AndCST->getType()->getUnsignedVersion());
4418 NS = new ShiftInst(Instruction::LShr, NewAndCST,
4419 Shift->getOperand(1), "tmp");
4421 InsertNewInstBefore(cast<Instruction>(NS), I);
4423 // If C's sign doesn't agree with the and, insert a cast now.
4424 if (NS->getType() != LHSI->getType())
4425 NS = InsertCastBefore(NS, LHSI->getType(), I);
4427 Value *ShiftOp = Shift->getOperand(0);
4428 if (ShiftOp->getType() != LHSI->getType())
4429 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4431 // Compute X & (C << Y).
4432 Instruction *NewAnd =
4433 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4434 InsertNewInstBefore(NewAnd, I);
4436 I.setOperand(0, NewAnd);
4442 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
4443 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4444 if (I.isEquality()) {
4445 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4447 // Check that the shift amount is in range. If not, don't perform
4448 // undefined shifts. When the shift is visited it will be
4450 if (ShAmt->getZExtValue() >= TypeBits)
4453 // If we are comparing against bits always shifted out, the
4454 // comparison cannot succeed.
4456 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4457 if (Comp != CI) {// Comparing against a bit that we know is zero.
4458 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4459 Constant *Cst = ConstantBool::get(IsSetNE);
4460 return ReplaceInstUsesWith(I, Cst);
4463 if (LHSI->hasOneUse()) {
4464 // Otherwise strength reduce the shift into an and.
4465 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4466 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4469 if (CI->getType()->isUnsigned()) {
4470 Mask = ConstantInt::get(CI->getType(), Val);
4471 } else if (ShAmtVal != 0) {
4472 Mask = ConstantInt::get(CI->getType(), Val);
4474 Mask = ConstantInt::getAllOnesValue(CI->getType());
4478 BinaryOperator::createAnd(LHSI->getOperand(0),
4479 Mask, LHSI->getName()+".mask");
4480 Value *And = InsertNewInstBefore(AndI, I);
4481 return new SetCondInst(I.getOpcode(), And,
4482 ConstantExpr::getLShr(CI, ShAmt));
4488 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4489 case Instruction::AShr:
4490 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4491 if (I.isEquality()) {
4492 // Check that the shift amount is in range. If not, don't perform
4493 // undefined shifts. When the shift is visited it will be
4495 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4496 if (ShAmt->getZExtValue() >= TypeBits)
4499 // If we are comparing against bits always shifted out, the
4500 // comparison cannot succeed.
4502 if (CI->getType()->isUnsigned())
4503 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4506 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4509 if (Comp != CI) {// Comparing against a bit that we know is zero.
4510 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4511 Constant *Cst = ConstantBool::get(IsSetNE);
4512 return ReplaceInstUsesWith(I, Cst);
4515 if (LHSI->hasOneUse() || CI->isNullValue()) {
4516 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4518 // Otherwise strength reduce the shift into an and.
4519 uint64_t Val = ~0ULL; // All ones.
4520 Val <<= ShAmtVal; // Shift over to the right spot.
4523 if (CI->getType()->isUnsigned()) {
4524 Val &= ~0ULL >> (64-TypeBits);
4525 Mask = ConstantInt::get(CI->getType(), Val);
4527 Mask = ConstantInt::get(CI->getType(), Val);
4531 BinaryOperator::createAnd(LHSI->getOperand(0),
4532 Mask, LHSI->getName()+".mask");
4533 Value *And = InsertNewInstBefore(AndI, I);
4534 return new SetCondInst(I.getOpcode(), And,
4535 ConstantExpr::getShl(CI, ShAmt));
4541 case Instruction::SDiv:
4542 case Instruction::UDiv:
4543 // Fold: setcc ([us]div X, C1), C2 -> range test
4544 // Fold this div into the comparison, producing a range check.
4545 // Determine, based on the divide type, what the range is being
4546 // checked. If there is an overflow on the low or high side, remember
4547 // it, otherwise compute the range [low, hi) bounding the new value.
4548 // See: InsertRangeTest above for the kinds of replacements possible.
4549 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4550 // FIXME: If the operand types don't match the type of the divide
4551 // then don't attempt this transform. The code below doesn't have the
4552 // logic to deal with a signed divide and an unsigned compare (and
4553 // vice versa). This is because (x /s C1) <s C2 produces different
4554 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4555 // (x /u C1) <u C2. Simply casting the operands and result won't
4556 // work. :( The if statement below tests that condition and bails
4558 const Type *DivRHSTy = DivRHS->getType();
4559 unsigned DivOpCode = LHSI->getOpcode();
4560 if (I.isEquality() &&
4561 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4562 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4565 // Initialize the variables that will indicate the nature of the
4567 bool LoOverflow = false, HiOverflow = false;
4568 ConstantInt *LoBound = 0, *HiBound = 0;
4570 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4571 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4572 // C2 (CI). By solving for X we can turn this into a range check
4573 // instead of computing a divide.
4575 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4577 // Determine if the product overflows by seeing if the product is
4578 // not equal to the divide. Make sure we do the same kind of divide
4579 // as in the LHS instruction that we're folding.
4580 bool ProdOV = !DivRHS->isNullValue() &&
4581 (DivOpCode == Instruction::SDiv ?
4582 ConstantExpr::getSDiv(Prod, DivRHS) :
4583 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4585 // Get the SetCC opcode
4586 Instruction::BinaryOps Opcode = I.getOpcode();
4588 if (DivRHS->isNullValue()) {
4589 // Don't hack on divide by zeros!
4590 } else if (DivOpCode == Instruction::UDiv) { // udiv
4592 LoOverflow = ProdOV;
4593 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4594 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4595 if (CI->isNullValue()) { // (X / pos) op 0
4597 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4599 } else if (isPositive(CI)) { // (X / pos) op pos
4601 LoOverflow = ProdOV;
4602 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4603 } else { // (X / pos) op neg
4604 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4605 LoOverflow = AddWithOverflow(LoBound, Prod,
4606 cast<ConstantInt>(DivRHSH));
4608 HiOverflow = ProdOV;
4610 } else { // Divisor is < 0.
4611 if (CI->isNullValue()) { // (X / neg) op 0
4612 LoBound = AddOne(DivRHS);
4613 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4614 if (HiBound == DivRHS)
4615 LoBound = 0; // - INTMIN = INTMIN
4616 } else if (isPositive(CI)) { // (X / neg) op pos
4617 HiOverflow = LoOverflow = ProdOV;
4619 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4620 HiBound = AddOne(Prod);
4621 } else { // (X / neg) op neg
4623 LoOverflow = HiOverflow = ProdOV;
4624 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4627 // Dividing by a negate swaps the condition.
4628 Opcode = SetCondInst::getSwappedCondition(Opcode);
4632 Value *X = LHSI->getOperand(0);
4634 default: assert(0 && "Unhandled setcc opcode!");
4635 case Instruction::SetEQ:
4636 if (LoOverflow && HiOverflow)
4637 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4638 else if (HiOverflow)
4639 return new SetCondInst(Instruction::SetGE, X, LoBound);
4640 else if (LoOverflow)
4641 return new SetCondInst(Instruction::SetLT, X, HiBound);
4643 return InsertRangeTest(X, LoBound, HiBound, true, I);
4644 case Instruction::SetNE:
4645 if (LoOverflow && HiOverflow)
4646 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4647 else if (HiOverflow)
4648 return new SetCondInst(Instruction::SetLT, X, LoBound);
4649 else if (LoOverflow)
4650 return new SetCondInst(Instruction::SetGE, X, HiBound);
4652 return InsertRangeTest(X, LoBound, HiBound, false, I);
4653 case Instruction::SetLT:
4655 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4656 return new SetCondInst(Instruction::SetLT, X, LoBound);
4657 case Instruction::SetGT:
4659 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4660 return new SetCondInst(Instruction::SetGE, X, HiBound);
4667 // Simplify seteq and setne instructions with integer constant RHS.
4668 if (I.isEquality()) {
4669 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4671 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4672 // the second operand is a constant, simplify a bit.
4673 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4674 switch (BO->getOpcode()) {
4675 case Instruction::SRem:
4676 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4677 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4679 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4680 if (V > 1 && isPowerOf2_64(V)) {
4681 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4682 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4683 return BinaryOperator::create(I.getOpcode(), NewRem,
4684 Constant::getNullValue(BO->getType()));
4688 case Instruction::Add:
4689 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4690 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4691 if (BO->hasOneUse())
4692 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4693 ConstantExpr::getSub(CI, BOp1C));
4694 } else if (CI->isNullValue()) {
4695 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4696 // efficiently invertible, or if the add has just this one use.
4697 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4699 if (Value *NegVal = dyn_castNegVal(BOp1))
4700 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4701 else if (Value *NegVal = dyn_castNegVal(BOp0))
4702 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4703 else if (BO->hasOneUse()) {
4704 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4706 InsertNewInstBefore(Neg, I);
4707 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4711 case Instruction::Xor:
4712 // For the xor case, we can xor two constants together, eliminating
4713 // the explicit xor.
4714 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4715 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4716 ConstantExpr::getXor(CI, BOC));
4719 case Instruction::Sub:
4720 // Replace (([sub|xor] A, B) != 0) with (A != B)
4721 if (CI->isNullValue())
4722 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4726 case Instruction::Or:
4727 // If bits are being or'd in that are not present in the constant we
4728 // are comparing against, then the comparison could never succeed!
4729 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4730 Constant *NotCI = ConstantExpr::getNot(CI);
4731 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4732 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4736 case Instruction::And:
4737 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4738 // If bits are being compared against that are and'd out, then the
4739 // comparison can never succeed!
4740 if (!ConstantExpr::getAnd(CI,
4741 ConstantExpr::getNot(BOC))->isNullValue())
4742 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4744 // If we have ((X & C) == C), turn it into ((X & C) != 0).
4745 if (CI == BOC && isOneBitSet(CI))
4746 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4747 Instruction::SetNE, Op0,
4748 Constant::getNullValue(CI->getType()));
4750 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4751 // to be a signed value as appropriate.
4752 if (isSignBit(BOC)) {
4753 Value *X = BO->getOperand(0);
4754 // If 'X' is not signed, insert a cast now...
4755 if (!BOC->getType()->isSigned()) {
4756 const Type *DestTy = BOC->getType()->getSignedVersion();
4757 X = InsertCastBefore(X, DestTy, I);
4759 return new SetCondInst(isSetNE ? Instruction::SetLT :
4760 Instruction::SetGE, X,
4761 Constant::getNullValue(X->getType()));
4764 // ((X & ~7) == 0) --> X < 8
4765 if (CI->isNullValue() && isHighOnes(BOC)) {
4766 Value *X = BO->getOperand(0);
4767 Constant *NegX = ConstantExpr::getNeg(BOC);
4769 // If 'X' is signed, insert a cast now.
4770 if (NegX->getType()->isSigned()) {
4771 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4772 X = InsertCastBefore(X, DestTy, I);
4773 NegX = ConstantExpr::getCast(NegX, DestTy);
4776 return new SetCondInst(isSetNE ? Instruction::SetGE :
4777 Instruction::SetLT, X, NegX);
4783 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
4784 // Handle set{eq|ne} <intrinsic>, intcst.
4785 switch (II->getIntrinsicID()) {
4787 case Intrinsic::bswap_i16: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4788 WorkList.push_back(II); // Dead?
4789 I.setOperand(0, II->getOperand(1));
4790 I.setOperand(1, ConstantInt::get(Type::UShortTy,
4791 ByteSwap_16(CI->getZExtValue())));
4793 case Intrinsic::bswap_i32: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4794 WorkList.push_back(II); // Dead?
4795 I.setOperand(0, II->getOperand(1));
4796 I.setOperand(1, ConstantInt::get(Type::UIntTy,
4797 ByteSwap_32(CI->getZExtValue())));
4799 case Intrinsic::bswap_i64: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4800 WorkList.push_back(II); // Dead?
4801 I.setOperand(0, II->getOperand(1));
4802 I.setOperand(1, ConstantInt::get(Type::ULongTy,
4803 ByteSwap_64(CI->getZExtValue())));
4807 } else { // Not a SetEQ/SetNE
4808 // If the LHS is a cast from an integral value of the same size,
4809 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4810 Value *CastOp = Cast->getOperand(0);
4811 const Type *SrcTy = CastOp->getType();
4812 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4813 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4814 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4815 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4816 "Source and destination signednesses should differ!");
4817 if (Cast->getType()->isSigned()) {
4818 // If this is a signed comparison, check for comparisons in the
4819 // vicinity of zero.
4820 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4822 return BinaryOperator::createSetGT(CastOp,
4823 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4824 else if (I.getOpcode() == Instruction::SetGT &&
4825 cast<ConstantInt>(CI)->getSExtValue() == -1)
4826 // X > -1 => x < 128
4827 return BinaryOperator::createSetLT(CastOp,
4828 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4830 ConstantInt *CUI = cast<ConstantInt>(CI);
4831 if (I.getOpcode() == Instruction::SetLT &&
4832 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
4833 // X < 128 => X > -1
4834 return BinaryOperator::createSetGT(CastOp,
4835 ConstantInt::get(SrcTy, -1));
4836 else if (I.getOpcode() == Instruction::SetGT &&
4837 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
4839 return BinaryOperator::createSetLT(CastOp,
4840 Constant::getNullValue(SrcTy));
4847 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4848 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4849 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4850 switch (LHSI->getOpcode()) {
4851 case Instruction::GetElementPtr:
4852 if (RHSC->isNullValue()) {
4853 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4854 bool isAllZeros = true;
4855 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4856 if (!isa<Constant>(LHSI->getOperand(i)) ||
4857 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4862 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4863 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4867 case Instruction::PHI:
4868 if (Instruction *NV = FoldOpIntoPhi(I))
4871 case Instruction::Select:
4872 // If either operand of the select is a constant, we can fold the
4873 // comparison into the select arms, which will cause one to be
4874 // constant folded and the select turned into a bitwise or.
4875 Value *Op1 = 0, *Op2 = 0;
4876 if (LHSI->hasOneUse()) {
4877 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4878 // Fold the known value into the constant operand.
4879 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4880 // Insert a new SetCC of the other select operand.
4881 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4882 LHSI->getOperand(2), RHSC,
4884 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4885 // Fold the known value into the constant operand.
4886 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4887 // Insert a new SetCC of the other select operand.
4888 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4889 LHSI->getOperand(1), RHSC,
4895 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4900 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4901 if (User *GEP = dyn_castGetElementPtr(Op0))
4902 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4904 if (User *GEP = dyn_castGetElementPtr(Op1))
4905 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4906 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4909 // Test to see if the operands of the setcc are casted versions of other
4910 // values. If the cast can be stripped off both arguments, we do so now.
4911 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4912 Value *CastOp0 = CI->getOperand(0);
4913 if (CI->isLosslessCast() && I.isEquality() &&
4914 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
4915 // We keep moving the cast from the left operand over to the right
4916 // operand, where it can often be eliminated completely.
4919 // If operand #1 is a cast instruction, see if we can eliminate it as
4921 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
4922 Value *CI2Op0 = CI2->getOperand(0);
4923 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
4927 // If Op1 is a constant, we can fold the cast into the constant.
4928 if (Op1->getType() != Op0->getType())
4929 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4930 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4932 // Otherwise, cast the RHS right before the setcc
4933 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
4935 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4938 // Handle the special case of: setcc (cast bool to X), <cst>
4939 // This comes up when you have code like
4942 // For generality, we handle any zero-extension of any operand comparison
4943 // with a constant or another cast from the same type.
4944 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4945 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4949 if (I.isEquality()) {
4951 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4952 (A == Op1 || B == Op1)) {
4953 // (A^B) == A -> B == 0
4954 Value *OtherVal = A == Op1 ? B : A;
4955 return BinaryOperator::create(I.getOpcode(), OtherVal,
4956 Constant::getNullValue(A->getType()));
4957 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4958 (A == Op0 || B == Op0)) {
4959 // A == (A^B) -> B == 0
4960 Value *OtherVal = A == Op0 ? B : A;
4961 return BinaryOperator::create(I.getOpcode(), OtherVal,
4962 Constant::getNullValue(A->getType()));
4963 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4964 // (A-B) == A -> B == 0
4965 return BinaryOperator::create(I.getOpcode(), B,
4966 Constant::getNullValue(B->getType()));
4967 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4968 // A == (A-B) -> B == 0
4969 return BinaryOperator::create(I.getOpcode(), B,
4970 Constant::getNullValue(B->getType()));
4974 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4975 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4976 match(Op0, m_And(m_Value(A), m_Value(B))) &&
4977 match(Op1, m_And(m_Value(C), m_Value(D)))) {
4978 Value *X = 0, *Y = 0, *Z = 0;
4981 X = B; Y = D; Z = A;
4982 } else if (A == D) {
4983 X = B; Y = C; Z = A;
4984 } else if (B == C) {
4985 X = A; Y = D; Z = B;
4986 } else if (B == D) {
4987 X = A; Y = C; Z = B;
4990 if (X) { // Build (X^Y) & Z
4991 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
4992 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
4993 I.setOperand(0, Op1);
4994 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4999 return Changed ? &I : 0;
5002 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
5003 // We only handle extending casts so far.
5005 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
5006 const CastInst *LHSCI = cast<CastInst>(SCI.getOperand(0));
5007 Value *LHSCIOp = LHSCI->getOperand(0);
5008 const Type *SrcTy = LHSCIOp->getType();
5009 const Type *DestTy = SCI.getOperand(0)->getType();
5012 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
5015 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
5016 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
5017 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
5019 // Is this a sign or zero extension?
5020 bool isSignSrc = SrcTy->isSigned();
5021 bool isSignDest = DestTy->isSigned();
5023 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5024 // Not an extension from the same type?
5025 RHSCIOp = CI->getOperand(0);
5026 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5027 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5028 // Compute the constant that would happen if we truncated to SrcTy then
5029 // reextended to DestTy.
5030 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5031 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5034 // Make sure that src sign and dest sign match. For example,
5036 // %A = cast short %X to uint
5037 // %B = setgt uint %A, 1330
5039 // It is incorrect to transform this into
5041 // %B = setgt short %X, 1330
5043 // because %A may have negative value.
5044 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5045 // OR operation is EQ/NE.
5046 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
5051 // If the value cannot be represented in the shorter type, we cannot emit
5052 // a simple comparison.
5053 if (SCI.getOpcode() == Instruction::SetEQ)
5054 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
5055 if (SCI.getOpcode() == Instruction::SetNE)
5056 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
5058 // Evaluate the comparison for LT.
5060 if (DestTy->isSigned()) {
5061 // We're performing a signed comparison.
5063 // Signed extend and signed comparison.
5064 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
5065 Result = ConstantBool::getFalse();
5067 Result = ConstantBool::getTrue(); // X < (large) --> true
5069 // Unsigned extend and signed comparison.
5070 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5071 Result = ConstantBool::getFalse();
5073 Result = ConstantBool::getTrue();
5076 // We're performing an unsigned comparison.
5078 // Unsigned extend & compare -> always true.
5079 Result = ConstantBool::getTrue();
5081 // We're performing an unsigned comp with a sign extended value.
5082 // This is true if the input is >= 0. [aka >s -1]
5083 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5084 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5085 NegOne, SCI.getName()), SCI);
5089 // Finally, return the value computed.
5090 if (SCI.getOpcode() == Instruction::SetLT) {
5091 return ReplaceInstUsesWith(SCI, Result);
5093 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5094 if (Constant *CI = dyn_cast<Constant>(Result))
5095 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5097 return BinaryOperator::createNot(Result);
5104 // Okay, just insert a compare of the reduced operands now!
5105 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5108 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5109 assert(I.getOperand(1)->getType() == Type::UByteTy);
5110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5111 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5113 // shl X, 0 == X and shr X, 0 == X
5114 // shl 0, X == 0 and shr 0, X == 0
5115 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
5116 Op0 == Constant::getNullValue(Op0->getType()))
5117 return ReplaceInstUsesWith(I, Op0);
5119 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5120 if (!isLeftShift && I.getType()->isSigned())
5121 return ReplaceInstUsesWith(I, Op0);
5122 else // undef << X -> 0 AND undef >>u X -> 0
5123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5125 if (isa<UndefValue>(Op1)) {
5126 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
5127 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5129 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5132 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5133 if (I.getOpcode() == Instruction::AShr)
5134 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5135 if (CSI->isAllOnesValue())
5136 return ReplaceInstUsesWith(I, CSI);
5138 // Try to fold constant and into select arguments.
5139 if (isa<Constant>(Op0))
5140 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5141 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5144 // See if we can turn a signed shr into an unsigned shr.
5145 if (I.isArithmeticShift()) {
5146 if (MaskedValueIsZero(Op0,
5147 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5148 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5152 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5153 if (CUI->getType()->isUnsigned())
5154 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5159 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5161 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5162 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5163 I.getOpcode() == Instruction::AShr;
5164 bool isUnsignedShift = !isSignedShift;
5166 // See if we can simplify any instructions used by the instruction whose sole
5167 // purpose is to compute bits we don't care about.
5168 uint64_t KnownZero, KnownOne;
5169 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5170 KnownZero, KnownOne))
5173 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5174 // of a signed value.
5176 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5177 if (Op1->getZExtValue() >= TypeBits) {
5178 if (isUnsignedShift || isLeftShift)
5179 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5181 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
5186 // ((X*C1) << C2) == (X * (C1 << C2))
5187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5188 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5189 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5190 return BinaryOperator::createMul(BO->getOperand(0),
5191 ConstantExpr::getShl(BOOp, Op1));
5193 // Try to fold constant and into select arguments.
5194 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5195 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5197 if (isa<PHINode>(Op0))
5198 if (Instruction *NV = FoldOpIntoPhi(I))
5201 if (Op0->hasOneUse()) {
5202 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5203 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5206 switch (Op0BO->getOpcode()) {
5208 case Instruction::Add:
5209 case Instruction::And:
5210 case Instruction::Or:
5211 case Instruction::Xor:
5212 // These operators commute.
5213 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
5214 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5215 match(Op0BO->getOperand(1),
5216 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5217 Instruction *YS = new ShiftInst(Instruction::Shl,
5218 Op0BO->getOperand(0), Op1,
5220 InsertNewInstBefore(YS, I); // (Y << C)
5222 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5223 Op0BO->getOperand(1)->getName());
5224 InsertNewInstBefore(X, I); // (X + (Y << C))
5225 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5226 C2 = ConstantExpr::getShl(C2, Op1);
5227 return BinaryOperator::createAnd(X, C2);
5230 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5231 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5232 match(Op0BO->getOperand(1),
5233 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5234 m_ConstantInt(CC))) && V2 == Op1 &&
5235 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5236 Instruction *YS = new ShiftInst(Instruction::Shl,
5237 Op0BO->getOperand(0), Op1,
5239 InsertNewInstBefore(YS, I); // (Y << C)
5241 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5242 V1->getName()+".mask");
5243 InsertNewInstBefore(XM, I); // X & (CC << C)
5245 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5249 case Instruction::Sub:
5250 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5251 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5252 match(Op0BO->getOperand(0),
5253 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5254 Instruction *YS = new ShiftInst(Instruction::Shl,
5255 Op0BO->getOperand(1), Op1,
5257 InsertNewInstBefore(YS, I); // (Y << C)
5259 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5260 Op0BO->getOperand(0)->getName());
5261 InsertNewInstBefore(X, I); // (X + (Y << C))
5262 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5263 C2 = ConstantExpr::getShl(C2, Op1);
5264 return BinaryOperator::createAnd(X, C2);
5267 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
5268 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5269 match(Op0BO->getOperand(0),
5270 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5271 m_ConstantInt(CC))) && V2 == Op1 &&
5272 cast<BinaryOperator>(Op0BO->getOperand(0))
5273 ->getOperand(0)->hasOneUse()) {
5274 Instruction *YS = new ShiftInst(Instruction::Shl,
5275 Op0BO->getOperand(1), Op1,
5277 InsertNewInstBefore(YS, I); // (Y << C)
5279 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5280 V1->getName()+".mask");
5281 InsertNewInstBefore(XM, I); // X & (CC << C)
5283 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5290 // If the operand is an bitwise operator with a constant RHS, and the
5291 // shift is the only use, we can pull it out of the shift.
5292 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5293 bool isValid = true; // Valid only for And, Or, Xor
5294 bool highBitSet = false; // Transform if high bit of constant set?
5296 switch (Op0BO->getOpcode()) {
5297 default: isValid = false; break; // Do not perform transform!
5298 case Instruction::Add:
5299 isValid = isLeftShift;
5301 case Instruction::Or:
5302 case Instruction::Xor:
5305 case Instruction::And:
5310 // If this is a signed shift right, and the high bit is modified
5311 // by the logical operation, do not perform the transformation.
5312 // The highBitSet boolean indicates the value of the high bit of
5313 // the constant which would cause it to be modified for this
5316 if (isValid && !isLeftShift && isSignedShift) {
5317 uint64_t Val = Op0C->getZExtValue();
5318 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5322 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5324 Instruction *NewShift =
5325 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5328 InsertNewInstBefore(NewShift, I);
5330 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5337 // Find out if this is a shift of a shift by a constant.
5338 ShiftInst *ShiftOp = 0;
5339 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5341 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5342 // If this is a noop-integer cast of a shift instruction, use the shift.
5343 if (isa<ShiftInst>(CI->getOperand(0))) {
5344 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5348 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5349 // Find the operands and properties of the input shift. Note that the
5350 // signedness of the input shift may differ from the current shift if there
5351 // is a noop cast between the two.
5352 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5353 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5354 ShiftOp->getType()->isSigned() :
5355 ShiftOp->getOpcode() == Instruction::AShr;
5356 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5358 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5360 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5361 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5363 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5364 if (isLeftShift == isShiftOfLeftShift) {
5365 // Do not fold these shifts if the first one is signed and the second one
5366 // is unsigned and this is a right shift. Further, don't do any folding
5368 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5371 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5372 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5373 Amt = Op0->getType()->getPrimitiveSizeInBits();
5375 Value *Op = ShiftOp->getOperand(0);
5376 if (isShiftOfSignedShift != isSignedShift)
5377 Op = InsertNewInstBefore(
5378 CastInst::createInferredCast(Op, I.getType(), "tmp"), I);
5379 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5380 ConstantInt::get(Type::UByteTy, Amt));
5381 if (I.getType() == ShiftResult->getType())
5383 InsertNewInstBefore(ShiftResult, I);
5384 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5387 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5388 // signed types, we can only support the (A >> c1) << c2 configuration,
5389 // because it can not turn an arbitrary bit of A into a sign bit.
5390 if (isUnsignedShift || isLeftShift) {
5391 // Calculate bitmask for what gets shifted off the edge.
5392 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5394 C = ConstantExpr::getShl(C, ShiftAmt1C);
5396 C = ConstantExpr::getLShr(C, ShiftAmt1C);
5398 Value *Op = ShiftOp->getOperand(0);
5399 if (Op->getType() != C->getType())
5400 Op = InsertCastBefore(Op, I.getType(), I);
5403 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5404 InsertNewInstBefore(Mask, I);
5406 // Figure out what flavor of shift we should use...
5407 if (ShiftAmt1 == ShiftAmt2) {
5408 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
5409 } else if (ShiftAmt1 < ShiftAmt2) {
5410 return new ShiftInst(I.getOpcode(), Mask,
5411 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
5412 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5413 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5414 return new ShiftInst(Instruction::LShr, Mask,
5415 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5417 return new ShiftInst(ShiftOp->getOpcode(), Mask,
5418 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5421 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
5422 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
5423 Instruction *Shift =
5424 new ShiftInst(ShiftOp->getOpcode(), Op,
5425 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5426 InsertNewInstBefore(Shift, I);
5428 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5429 C = ConstantExpr::getShl(C, Op1);
5430 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5431 InsertNewInstBefore(Mask, I);
5432 return CastInst::create(Instruction::BitCast, Mask, I.getType());
5435 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
5436 // this case, C1 == C2 and C1 is 8, 16, or 32.
5437 if (ShiftAmt1 == ShiftAmt2) {
5438 const Type *SExtType = 0;
5439 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5440 case 8 : SExtType = Type::SByteTy; break;
5441 case 16: SExtType = Type::ShortTy; break;
5442 case 32: SExtType = Type::IntTy; break;
5446 Instruction *NewTrunc =
5447 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5448 InsertNewInstBefore(NewTrunc, I);
5449 return new SExtInst(NewTrunc, I.getType());
5458 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5459 /// expression. If so, decompose it, returning some value X, such that Val is
5462 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5464 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5465 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5466 if (CI->getType()->isUnsigned()) {
5467 Offset = CI->getZExtValue();
5469 return ConstantInt::get(Type::UIntTy, 0);
5471 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5472 if (I->getNumOperands() == 2) {
5473 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5474 if (CUI->getType()->isUnsigned()) {
5475 if (I->getOpcode() == Instruction::Shl) {
5476 // This is a value scaled by '1 << the shift amt'.
5477 Scale = 1U << CUI->getZExtValue();
5479 return I->getOperand(0);
5480 } else if (I->getOpcode() == Instruction::Mul) {
5481 // This value is scaled by 'CUI'.
5482 Scale = CUI->getZExtValue();
5484 return I->getOperand(0);
5485 } else if (I->getOpcode() == Instruction::Add) {
5486 // We have X+C. Check to see if we really have (X*C2)+C1,
5487 // where C1 is divisible by C2.
5490 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5491 Offset += CUI->getZExtValue();
5492 if (SubScale > 1 && (Offset % SubScale == 0)) {
5502 // Otherwise, we can't look past this.
5509 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5510 /// try to eliminate the cast by moving the type information into the alloc.
5511 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5512 AllocationInst &AI) {
5513 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5514 if (!PTy) return 0; // Not casting the allocation to a pointer type.
5516 // Remove any uses of AI that are dead.
5517 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5518 std::vector<Instruction*> DeadUsers;
5519 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5520 Instruction *User = cast<Instruction>(*UI++);
5521 if (isInstructionTriviallyDead(User)) {
5522 while (UI != E && *UI == User)
5523 ++UI; // If this instruction uses AI more than once, don't break UI.
5525 // Add operands to the worklist.
5526 AddUsesToWorkList(*User);
5528 DOUT << "IC: DCE: " << *User;
5530 User->eraseFromParent();
5531 removeFromWorkList(User);
5535 // Get the type really allocated and the type casted to.
5536 const Type *AllocElTy = AI.getAllocatedType();
5537 const Type *CastElTy = PTy->getElementType();
5538 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5540 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5541 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5542 if (CastElTyAlign < AllocElTyAlign) return 0;
5544 // If the allocation has multiple uses, only promote it if we are strictly
5545 // increasing the alignment of the resultant allocation. If we keep it the
5546 // same, we open the door to infinite loops of various kinds.
5547 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5549 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5550 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5551 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5553 // See if we can satisfy the modulus by pulling a scale out of the array
5555 unsigned ArraySizeScale, ArrayOffset;
5556 Value *NumElements = // See if the array size is a decomposable linear expr.
5557 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5559 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5561 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5562 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
5564 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5569 // If the allocation size is constant, form a constant mul expression
5570 Amt = ConstantInt::get(Type::UIntTy, Scale);
5571 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5572 Amt = ConstantExpr::getMul(
5573 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5574 // otherwise multiply the amount and the number of elements
5575 else if (Scale != 1) {
5576 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5577 Amt = InsertNewInstBefore(Tmp, AI);
5581 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5582 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
5583 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5584 Amt = InsertNewInstBefore(Tmp, AI);
5587 std::string Name = AI.getName(); AI.setName("");
5588 AllocationInst *New;
5589 if (isa<MallocInst>(AI))
5590 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5592 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5593 InsertNewInstBefore(New, AI);
5595 // If the allocation has multiple uses, insert a cast and change all things
5596 // that used it to use the new cast. This will also hack on CI, but it will
5598 if (!AI.hasOneUse()) {
5599 AddUsesToWorkList(AI);
5600 // New is the allocation instruction, pointer typed. AI is the original
5601 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5602 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5603 InsertNewInstBefore(NewCast, AI);
5604 AI.replaceAllUsesWith(NewCast);
5606 return ReplaceInstUsesWith(CI, New);
5609 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5610 /// and return it without inserting any new casts. This is used by code that
5611 /// tries to decide whether promoting or shrinking integer operations to wider
5612 /// or smaller types will allow us to eliminate a truncate or extend.
5613 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5614 int &NumCastsRemoved) {
5615 if (isa<Constant>(V)) return true;
5617 Instruction *I = dyn_cast<Instruction>(V);
5618 if (!I || !I->hasOneUse()) return false;
5620 switch (I->getOpcode()) {
5621 case Instruction::And:
5622 case Instruction::Or:
5623 case Instruction::Xor:
5624 // These operators can all arbitrarily be extended or truncated.
5625 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5626 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5627 case Instruction::Trunc:
5628 case Instruction::ZExt:
5629 case Instruction::SExt:
5630 case Instruction::BitCast:
5631 // If this is a cast from the destination type, we can trivially eliminate
5632 // it, and this will remove a cast overall.
5633 if (I->getOperand(0)->getType() == Ty) {
5634 // If the first operand is itself a cast, and is eliminable, do not count
5635 // this as an eliminable cast. We would prefer to eliminate those two
5637 if (isa<CastInst>(I->getOperand(0)))
5645 // TODO: Can handle more cases here.
5652 /// EvaluateInDifferentType - Given an expression that
5653 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5654 /// evaluate the expression.
5655 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5656 if (Constant *C = dyn_cast<Constant>(V))
5657 return ConstantExpr::getCast(C, Ty);
5659 // Otherwise, it must be an instruction.
5660 Instruction *I = cast<Instruction>(V);
5661 Instruction *Res = 0;
5662 switch (I->getOpcode()) {
5663 case Instruction::And:
5664 case Instruction::Or:
5665 case Instruction::Xor: {
5666 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5667 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5668 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5669 LHS, RHS, I->getName());
5672 case Instruction::Trunc:
5673 case Instruction::ZExt:
5674 case Instruction::SExt:
5675 case Instruction::BitCast:
5676 // If the source type of the cast is the type we're trying for then we can
5677 // just return the source. There's no need to insert it because its not new.
5678 if (I->getOperand(0)->getType() == Ty)
5679 return I->getOperand(0);
5681 // Some other kind of cast, which shouldn't happen, so just ..
5684 // TODO: Can handle more cases here.
5685 assert(0 && "Unreachable!");
5689 return InsertNewInstBefore(Res, *I);
5692 /// @brief Implement the transforms common to all CastInst visitors.
5693 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5694 Value *Src = CI.getOperand(0);
5696 // Casting undef to anything results in undef so might as just replace it and
5697 // get rid of the cast.
5698 if (isa<UndefValue>(Src)) // cast undef -> undef
5699 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5701 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5702 // eliminate it now.
5703 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5704 if (Instruction::CastOps opc =
5705 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5706 // The first cast (CSrc) is eliminable so we need to fix up or replace
5707 // the second cast (CI). CSrc will then have a good chance of being dead.
5708 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5712 // If casting the result of a getelementptr instruction with no offset, turn
5713 // this into a cast of the original pointer!
5715 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5716 bool AllZeroOperands = true;
5717 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5718 if (!isa<Constant>(GEP->getOperand(i)) ||
5719 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5720 AllZeroOperands = false;
5723 if (AllZeroOperands) {
5724 // Changing the cast operand is usually not a good idea but it is safe
5725 // here because the pointer operand is being replaced with another
5726 // pointer operand so the opcode doesn't need to change.
5727 CI.setOperand(0, GEP->getOperand(0));
5732 // If we are casting a malloc or alloca to a pointer to a type of the same
5733 // size, rewrite the allocation instruction to allocate the "right" type.
5734 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5735 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5738 // If we are casting a select then fold the cast into the select
5739 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5740 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5743 // If we are casting a PHI then fold the cast into the PHI
5744 if (isa<PHINode>(Src))
5745 if (Instruction *NV = FoldOpIntoPhi(CI))
5751 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5752 /// integers. This function implements the common transforms for all those
5754 /// @brief Implement the transforms common to CastInst with integer operands
5755 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5756 if (Instruction *Result = commonCastTransforms(CI))
5759 Value *Src = CI.getOperand(0);
5760 const Type *SrcTy = Src->getType();
5761 const Type *DestTy = CI.getType();
5762 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
5763 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5765 // FIXME. We currently implement cast-to-bool as a setne %X, 0. This is
5766 // because codegen cannot accurately perform a truncate to bool operation.
5767 // Something goes wrong in promotion to a larger type. When CodeGen can
5768 // handle a proper truncation to bool, this should be removed.
5769 if (DestTy == Type::BoolTy)
5770 return BinaryOperator::createSetNE(Src, Constant::getNullValue(SrcTy));
5772 // See if we can simplify any instructions used by the LHS whose sole
5773 // purpose is to compute bits we don't care about.
5774 uint64_t KnownZero = 0, KnownOne = 0;
5775 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
5776 KnownZero, KnownOne))
5779 // If the source isn't an instruction or has more than one use then we
5780 // can't do anything more.
5781 if (!isa<Instruction>(Src) || !Src->hasOneUse())
5784 // Attempt to propagate the cast into the instruction.
5785 Instruction *SrcI = cast<Instruction>(Src);
5786 int NumCastsRemoved = 0;
5787 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
5788 // If this cast is a truncate, evaluting in a different type always
5789 // eliminates the cast, so it is always a win. If this is a noop-cast
5790 // this just removes a noop cast which isn't pointful, but simplifies
5791 // the code. If this is a zero-extension, we need to do an AND to
5792 // maintain the clear top-part of the computation, so we require that
5793 // the input have eliminated at least one cast. If this is a sign
5794 // extension, we insert two new casts (to do the extension) so we
5795 // require that two casts have been eliminated.
5796 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
5798 switch (CI.getOpcode()) {
5799 case Instruction::Trunc:
5802 case Instruction::ZExt:
5803 DoXForm = NumCastsRemoved >= 1;
5805 case Instruction::SExt:
5806 DoXForm = NumCastsRemoved >= 2;
5808 case Instruction::BitCast:
5812 // All the others use floating point so we shouldn't actually
5813 // get here because of the check above.
5814 assert(!"Unknown cast type .. unreachable");
5820 Value *Res = EvaluateInDifferentType(SrcI, DestTy);
5821 assert(Res->getType() == DestTy);
5822 switch (CI.getOpcode()) {
5823 default: assert(0 && "Unknown cast type!");
5824 case Instruction::Trunc:
5825 case Instruction::BitCast:
5826 // Just replace this cast with the result.
5827 return ReplaceInstUsesWith(CI, Res);
5828 case Instruction::ZExt: {
5829 // We need to emit an AND to clear the high bits.
5830 assert(SrcBitSize < DestBitSize && "Not a zext?");
5832 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5833 if (DestBitSize < 64)
5834 C = ConstantExpr::getTrunc(C, DestTy);
5836 assert(DestBitSize == 64);
5837 C = ConstantExpr::getBitCast(C, DestTy);
5839 return BinaryOperator::createAnd(Res, C);
5841 case Instruction::SExt:
5842 // We need to emit a cast to truncate, then a cast to sext.
5843 return CastInst::create(Instruction::SExt,
5844 InsertCastBefore(Res, Src->getType(), CI), DestTy);
5849 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5850 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5852 switch (SrcI->getOpcode()) {
5853 case Instruction::Add:
5854 case Instruction::Mul:
5855 case Instruction::And:
5856 case Instruction::Or:
5857 case Instruction::Xor:
5858 // If we are discarding information, or just changing the sign,
5860 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5861 // Don't insert two casts if they cannot be eliminated. We allow
5862 // two casts to be inserted if the sizes are the same. This could
5863 // only be converting signedness, which is a noop.
5864 if (DestBitSize == SrcBitSize ||
5865 !ValueRequiresCast(Op1, DestTy,TD) ||
5866 !ValueRequiresCast(Op0, DestTy, TD)) {
5867 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5868 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5869 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5870 ->getOpcode(), Op0c, Op1c);
5874 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5875 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
5876 SrcI->getOpcode() == Instruction::Xor &&
5877 Op1 == ConstantBool::getTrue() &&
5878 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5879 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5880 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
5883 case Instruction::SDiv:
5884 case Instruction::UDiv:
5885 case Instruction::SRem:
5886 case Instruction::URem:
5887 // If we are just changing the sign, rewrite.
5888 if (DestBitSize == SrcBitSize) {
5889 // Don't insert two casts if they cannot be eliminated. We allow
5890 // two casts to be inserted if the sizes are the same. This could
5891 // only be converting signedness, which is a noop.
5892 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5893 !ValueRequiresCast(Op0, DestTy, TD)) {
5894 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5895 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5896 return BinaryOperator::create(
5897 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5902 case Instruction::Shl:
5903 // Allow changing the sign of the source operand. Do not allow
5904 // changing the size of the shift, UNLESS the shift amount is a
5905 // constant. We must not change variable sized shifts to a smaller
5906 // size, because it is undefined to shift more bits out than exist
5908 if (DestBitSize == SrcBitSize ||
5909 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5910 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5911 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5914 case Instruction::AShr:
5915 // If this is a signed shr, and if all bits shifted in are about to be
5916 // truncated off, turn it into an unsigned shr to allow greater
5918 if (DestBitSize < SrcBitSize &&
5919 isa<ConstantInt>(Op1)) {
5920 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5921 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5922 // Insert the new logical shift right.
5923 return new ShiftInst(Instruction::LShr, Op0, Op1);
5928 case Instruction::SetEQ:
5929 case Instruction::SetNE:
5930 // If we are just checking for a seteq of a single bit and casting it
5931 // to an integer. If so, shift the bit to the appropriate place then
5932 // cast to integer to avoid the comparison.
5933 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5934 uint64_t Op1CV = Op1C->getZExtValue();
5935 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5936 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5937 // cast (X == 1) to int --> X iff X has only the low bit set.
5938 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5939 // cast (X != 0) to int --> X iff X has only the low bit set.
5940 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5941 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5942 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5943 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5944 // If Op1C some other power of two, convert:
5945 uint64_t KnownZero, KnownOne;
5946 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5947 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5949 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
5950 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5951 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5952 // (X&4) == 2 --> false
5953 // (X&4) != 2 --> true
5954 Constant *Res = ConstantBool::get(isSetNE);
5955 Res = ConstantExpr::getZeroExtend(Res, CI.getType());
5956 return ReplaceInstUsesWith(CI, Res);
5959 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5962 // Perform a logical shr by shiftamt.
5963 // Insert the shift to put the result in the low bit.
5964 In = InsertNewInstBefore(
5965 new ShiftInst(Instruction::LShr, In,
5966 ConstantInt::get(Type::UByteTy, ShiftAmt),
5967 In->getName()+".lobit"), CI);
5970 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5971 Constant *One = ConstantInt::get(In->getType(), 1);
5972 In = BinaryOperator::createXor(In, One, "tmp");
5973 InsertNewInstBefore(cast<Instruction>(In), CI);
5976 if (CI.getType() == In->getType())
5977 return ReplaceInstUsesWith(CI, In);
5979 return CastInst::createInferredCast(In, CI.getType());
5988 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
5989 return commonIntCastTransforms(CI);
5992 Instruction *InstCombiner::visitZExt(CastInst &CI) {
5993 // If one of the common conversion will work ..
5994 if (Instruction *Result = commonIntCastTransforms(CI))
5997 Value *Src = CI.getOperand(0);
5999 // If this is a cast of a cast
6000 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6001 // If the operand of the ZEXT is a TRUNC then we are dealing with integral
6002 // types and we can convert this to a logical AND if the sizes are just
6003 // right. This will be much cheaper than the pair of casts.
6004 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6005 // types and if the sizes are just right we can convert this into a logical
6006 // 'and' which will be much cheaper than the pair of casts.
6007 if (isa<TruncInst>(CSrc)) {
6008 // Get the sizes of the types involved
6009 Value *A = CSrc->getOperand(0);
6010 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6011 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6012 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6013 // If we're actually extending zero bits and the trunc is a no-op
6014 if (MidSize < DstSize && SrcSize == DstSize) {
6015 // Replace both of the casts with an And of the type mask.
6016 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6017 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6019 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6020 // Unfortunately, if the type changed, we need to cast it back.
6021 if (And->getType() != CI.getType()) {
6022 And->setName(CSrc->getName()+".mask");
6023 InsertNewInstBefore(And, CI);
6024 And = CastInst::createInferredCast(And, CI.getType());
6034 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6035 return commonIntCastTransforms(CI);
6038 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6039 return commonCastTransforms(CI);
6042 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6043 return commonCastTransforms(CI);
6046 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6047 if (Instruction *I = commonCastTransforms(CI))
6050 // FIXME. We currently implement cast-to-bool as a setne %X, 0. This is
6051 // because codegen cannot accurately perform a truncate to bool operation.
6052 // Something goes wrong in promotion to a larger type. When CodeGen can
6053 // handle a proper truncation to bool, this should be removed.
6054 Value *Src = CI.getOperand(0);
6055 const Type *SrcTy = Src->getType();
6056 const Type *DestTy = CI.getType();
6057 if (DestTy == Type::BoolTy)
6058 return BinaryOperator::createSetNE(Src, Constant::getNullValue(SrcTy));
6062 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6063 if (Instruction *I = commonCastTransforms(CI))
6066 // FIXME. We currently implement cast-to-bool as a setne %X, 0. This is
6067 // because codegen cannot accurately perform a truncate to bool operation.
6068 // Something goes wrong in promotion to a larger type. When CodeGen can
6069 // handle a proper truncation to bool, this should be removed.
6070 Value *Src = CI.getOperand(0);
6071 const Type *SrcTy = Src->getType();
6072 const Type *DestTy = CI.getType();
6073 if (DestTy == Type::BoolTy)
6074 return BinaryOperator::createSetNE(Src, Constant::getNullValue(SrcTy));
6078 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6079 return commonCastTransforms(CI);
6082 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6083 return commonCastTransforms(CI);
6086 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6087 if (Instruction *I = commonCastTransforms(CI))
6090 // FIXME. We currently implement cast-to-bool as a setne %X, 0. This is
6091 // because codegen cannot accurately perform a truncate to bool operation.
6092 // Something goes wrong in promotion to a larger type. When CodeGen can
6093 // handle a proper truncation to bool, this should be removed.
6094 Value *Src = CI.getOperand(0);
6095 const Type *SrcTy = Src->getType();
6096 const Type *DestTy = CI.getType();
6097 if (DestTy == Type::BoolTy)
6098 return BinaryOperator::createSetNE(Src, Constant::getNullValue(SrcTy));
6102 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6103 return commonCastTransforms(CI);
6106 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6108 // If the operands are integer typed then apply the integer transforms,
6109 // otherwise just apply the common ones.
6110 Value *Src = CI.getOperand(0);
6111 const Type *SrcTy = Src->getType();
6112 const Type *DestTy = CI.getType();
6114 if (SrcTy->isInteger() && DestTy->isInteger()) {
6115 if (Instruction *Result = commonIntCastTransforms(CI))
6118 if (Instruction *Result = commonCastTransforms(CI))
6123 // Get rid of casts from one type to the same type. These are useless and can
6124 // be replaced by the operand.
6125 if (DestTy == Src->getType())
6126 return ReplaceInstUsesWith(CI, Src);
6128 // If the source and destination are pointers, and this cast is equivalent to
6129 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6130 // This can enhance SROA and other transforms that want type-safe pointers.
6131 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6132 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6133 const Type *DstElTy = DstPTy->getElementType();
6134 const Type *SrcElTy = SrcPTy->getElementType();
6136 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6137 unsigned NumZeros = 0;
6138 while (SrcElTy != DstElTy &&
6139 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6140 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6141 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6145 // If we found a path from the src to dest, create the getelementptr now.
6146 if (SrcElTy == DstElTy) {
6147 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6148 return new GetElementPtrInst(Src, Idxs);
6153 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6154 if (SVI->hasOneUse()) {
6155 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6156 // a bitconvert to a vector with the same # elts.
6157 if (isa<PackedType>(DestTy) &&
6158 cast<PackedType>(DestTy)->getNumElements() ==
6159 SVI->getType()->getNumElements()) {
6161 // If either of the operands is a cast from CI.getType(), then
6162 // evaluating the shuffle in the casted destination's type will allow
6163 // us to eliminate at least one cast.
6164 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6165 Tmp->getOperand(0)->getType() == DestTy) ||
6166 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6167 Tmp->getOperand(0)->getType() == DestTy)) {
6168 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0), DestTy, &CI);
6169 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1), DestTy, &CI);
6170 // Return a new shuffle vector. Use the same element ID's, as we
6171 // know the vector types match #elts.
6172 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6180 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6182 /// %D = select %cond, %C, %A
6184 /// %C = select %cond, %B, 0
6187 /// Assuming that the specified instruction is an operand to the select, return
6188 /// a bitmask indicating which operands of this instruction are foldable if they
6189 /// equal the other incoming value of the select.
6191 static unsigned GetSelectFoldableOperands(Instruction *I) {
6192 switch (I->getOpcode()) {
6193 case Instruction::Add:
6194 case Instruction::Mul:
6195 case Instruction::And:
6196 case Instruction::Or:
6197 case Instruction::Xor:
6198 return 3; // Can fold through either operand.
6199 case Instruction::Sub: // Can only fold on the amount subtracted.
6200 case Instruction::Shl: // Can only fold on the shift amount.
6201 case Instruction::LShr:
6202 case Instruction::AShr:
6205 return 0; // Cannot fold
6209 /// GetSelectFoldableConstant - For the same transformation as the previous
6210 /// function, return the identity constant that goes into the select.
6211 static Constant *GetSelectFoldableConstant(Instruction *I) {
6212 switch (I->getOpcode()) {
6213 default: assert(0 && "This cannot happen!"); abort();
6214 case Instruction::Add:
6215 case Instruction::Sub:
6216 case Instruction::Or:
6217 case Instruction::Xor:
6218 return Constant::getNullValue(I->getType());
6219 case Instruction::Shl:
6220 case Instruction::LShr:
6221 case Instruction::AShr:
6222 return Constant::getNullValue(Type::UByteTy);
6223 case Instruction::And:
6224 return ConstantInt::getAllOnesValue(I->getType());
6225 case Instruction::Mul:
6226 return ConstantInt::get(I->getType(), 1);
6230 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6231 /// have the same opcode and only one use each. Try to simplify this.
6232 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6234 if (TI->getNumOperands() == 1) {
6235 // If this is a non-volatile load or a cast from the same type,
6238 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6241 return 0; // unknown unary op.
6244 // Fold this by inserting a select from the input values.
6245 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6246 FI->getOperand(0), SI.getName()+".v");
6247 InsertNewInstBefore(NewSI, SI);
6248 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6252 // Only handle binary operators here.
6253 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6256 // Figure out if the operations have any operands in common.
6257 Value *MatchOp, *OtherOpT, *OtherOpF;
6259 if (TI->getOperand(0) == FI->getOperand(0)) {
6260 MatchOp = TI->getOperand(0);
6261 OtherOpT = TI->getOperand(1);
6262 OtherOpF = FI->getOperand(1);
6263 MatchIsOpZero = true;
6264 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6265 MatchOp = TI->getOperand(1);
6266 OtherOpT = TI->getOperand(0);
6267 OtherOpF = FI->getOperand(0);
6268 MatchIsOpZero = false;
6269 } else if (!TI->isCommutative()) {
6271 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6272 MatchOp = TI->getOperand(0);
6273 OtherOpT = TI->getOperand(1);
6274 OtherOpF = FI->getOperand(0);
6275 MatchIsOpZero = true;
6276 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6277 MatchOp = TI->getOperand(1);
6278 OtherOpT = TI->getOperand(0);
6279 OtherOpF = FI->getOperand(1);
6280 MatchIsOpZero = true;
6285 // If we reach here, they do have operations in common.
6286 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6287 OtherOpF, SI.getName()+".v");
6288 InsertNewInstBefore(NewSI, SI);
6290 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6292 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6294 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6297 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6299 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6303 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6304 Value *CondVal = SI.getCondition();
6305 Value *TrueVal = SI.getTrueValue();
6306 Value *FalseVal = SI.getFalseValue();
6308 // select true, X, Y -> X
6309 // select false, X, Y -> Y
6310 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6311 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6313 // select C, X, X -> X
6314 if (TrueVal == FalseVal)
6315 return ReplaceInstUsesWith(SI, TrueVal);
6317 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6318 return ReplaceInstUsesWith(SI, FalseVal);
6319 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6320 return ReplaceInstUsesWith(SI, TrueVal);
6321 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6322 if (isa<Constant>(TrueVal))
6323 return ReplaceInstUsesWith(SI, TrueVal);
6325 return ReplaceInstUsesWith(SI, FalseVal);
6328 if (SI.getType() == Type::BoolTy)
6329 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6330 if (C->getValue()) {
6331 // Change: A = select B, true, C --> A = or B, C
6332 return BinaryOperator::createOr(CondVal, FalseVal);
6334 // Change: A = select B, false, C --> A = and !B, C
6336 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6337 "not."+CondVal->getName()), SI);
6338 return BinaryOperator::createAnd(NotCond, FalseVal);
6340 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6341 if (C->getValue() == false) {
6342 // Change: A = select B, C, false --> A = and B, C
6343 return BinaryOperator::createAnd(CondVal, TrueVal);
6345 // Change: A = select B, C, true --> A = or !B, C
6347 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6348 "not."+CondVal->getName()), SI);
6349 return BinaryOperator::createOr(NotCond, TrueVal);
6353 // Selecting between two integer constants?
6354 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6355 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6356 // select C, 1, 0 -> cast C to int
6357 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6358 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6359 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6360 // select C, 0, 1 -> cast !C to int
6362 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6363 "not."+CondVal->getName()), SI);
6364 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6367 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6369 // (x <s 0) ? -1 : 0 -> sra x, 31
6370 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6371 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6372 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6373 bool CanXForm = false;
6374 if (CmpCst->getType()->isSigned())
6375 CanXForm = CmpCst->isNullValue() &&
6376 IC->getOpcode() == Instruction::SetLT;
6378 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6379 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6380 IC->getOpcode() == Instruction::SetGT;
6384 // The comparison constant and the result are not neccessarily the
6385 // same width. Make an all-ones value by inserting a AShr.
6386 Value *X = IC->getOperand(0);
6387 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6388 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
6389 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6391 InsertNewInstBefore(SRA, SI);
6393 // Finally, convert to the type of the select RHS. We figure out
6394 // if this requires a SExt, Trunc or BitCast based on the sizes.
6395 Instruction::CastOps opc = Instruction::BitCast;
6396 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6397 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6398 if (SRASize < SISize)
6399 opc = Instruction::SExt;
6400 else if (SRASize > SISize)
6401 opc = Instruction::Trunc;
6402 return CastInst::create(opc, SRA, SI.getType());
6407 // If one of the constants is zero (we know they can't both be) and we
6408 // have a setcc instruction with zero, and we have an 'and' with the
6409 // non-constant value, eliminate this whole mess. This corresponds to
6410 // cases like this: ((X & 27) ? 27 : 0)
6411 if (TrueValC->isNullValue() || FalseValC->isNullValue())
6412 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6413 cast<Constant>(IC->getOperand(1))->isNullValue())
6414 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6415 if (ICA->getOpcode() == Instruction::And &&
6416 isa<ConstantInt>(ICA->getOperand(1)) &&
6417 (ICA->getOperand(1) == TrueValC ||
6418 ICA->getOperand(1) == FalseValC) &&
6419 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6420 // Okay, now we know that everything is set up, we just don't
6421 // know whether we have a setne or seteq and whether the true or
6422 // false val is the zero.
6423 bool ShouldNotVal = !TrueValC->isNullValue();
6424 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6427 V = InsertNewInstBefore(BinaryOperator::create(
6428 Instruction::Xor, V, ICA->getOperand(1)), SI);
6429 return ReplaceInstUsesWith(SI, V);
6434 // See if we are selecting two values based on a comparison of the two values.
6435 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6436 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6437 // Transform (X == Y) ? X : Y -> Y
6438 if (SCI->getOpcode() == Instruction::SetEQ)
6439 return ReplaceInstUsesWith(SI, FalseVal);
6440 // Transform (X != Y) ? X : Y -> X
6441 if (SCI->getOpcode() == Instruction::SetNE)
6442 return ReplaceInstUsesWith(SI, TrueVal);
6443 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6445 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6446 // Transform (X == Y) ? Y : X -> X
6447 if (SCI->getOpcode() == Instruction::SetEQ)
6448 return ReplaceInstUsesWith(SI, FalseVal);
6449 // Transform (X != Y) ? Y : X -> Y
6450 if (SCI->getOpcode() == Instruction::SetNE)
6451 return ReplaceInstUsesWith(SI, TrueVal);
6452 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6456 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6457 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6458 if (TI->hasOneUse() && FI->hasOneUse()) {
6459 Instruction *AddOp = 0, *SubOp = 0;
6461 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6462 if (TI->getOpcode() == FI->getOpcode())
6463 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6466 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6467 // even legal for FP.
6468 if (TI->getOpcode() == Instruction::Sub &&
6469 FI->getOpcode() == Instruction::Add) {
6470 AddOp = FI; SubOp = TI;
6471 } else if (FI->getOpcode() == Instruction::Sub &&
6472 TI->getOpcode() == Instruction::Add) {
6473 AddOp = TI; SubOp = FI;
6477 Value *OtherAddOp = 0;
6478 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6479 OtherAddOp = AddOp->getOperand(1);
6480 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6481 OtherAddOp = AddOp->getOperand(0);
6485 // So at this point we know we have (Y -> OtherAddOp):
6486 // select C, (add X, Y), (sub X, Z)
6487 Value *NegVal; // Compute -Z
6488 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6489 NegVal = ConstantExpr::getNeg(C);
6491 NegVal = InsertNewInstBefore(
6492 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6495 Value *NewTrueOp = OtherAddOp;
6496 Value *NewFalseOp = NegVal;
6498 std::swap(NewTrueOp, NewFalseOp);
6499 Instruction *NewSel =
6500 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6502 NewSel = InsertNewInstBefore(NewSel, SI);
6503 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6508 // See if we can fold the select into one of our operands.
6509 if (SI.getType()->isInteger()) {
6510 // See the comment above GetSelectFoldableOperands for a description of the
6511 // transformation we are doing here.
6512 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6513 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6514 !isa<Constant>(FalseVal))
6515 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6516 unsigned OpToFold = 0;
6517 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6519 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6524 Constant *C = GetSelectFoldableConstant(TVI);
6525 std::string Name = TVI->getName(); TVI->setName("");
6526 Instruction *NewSel =
6527 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6529 InsertNewInstBefore(NewSel, SI);
6530 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6531 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6532 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6533 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6535 assert(0 && "Unknown instruction!!");
6540 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6541 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6542 !isa<Constant>(TrueVal))
6543 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6544 unsigned OpToFold = 0;
6545 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6547 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6552 Constant *C = GetSelectFoldableConstant(FVI);
6553 std::string Name = FVI->getName(); FVI->setName("");
6554 Instruction *NewSel =
6555 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6557 InsertNewInstBefore(NewSel, SI);
6558 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6559 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6560 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6561 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6563 assert(0 && "Unknown instruction!!");
6569 if (BinaryOperator::isNot(CondVal)) {
6570 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6571 SI.setOperand(1, FalseVal);
6572 SI.setOperand(2, TrueVal);
6579 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6580 /// determine, return it, otherwise return 0.
6581 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6582 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6583 unsigned Align = GV->getAlignment();
6584 if (Align == 0 && TD)
6585 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6587 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6588 unsigned Align = AI->getAlignment();
6589 if (Align == 0 && TD) {
6590 if (isa<AllocaInst>(AI))
6591 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6592 else if (isa<MallocInst>(AI)) {
6593 // Malloc returns maximally aligned memory.
6594 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6595 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6596 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6600 } else if (isa<BitCastInst>(V) ||
6601 (isa<ConstantExpr>(V) &&
6602 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6603 User *CI = cast<User>(V);
6604 if (isa<PointerType>(CI->getOperand(0)->getType()))
6605 return GetKnownAlignment(CI->getOperand(0), TD);
6607 } else if (isa<GetElementPtrInst>(V) ||
6608 (isa<ConstantExpr>(V) &&
6609 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6610 User *GEPI = cast<User>(V);
6611 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6612 if (BaseAlignment == 0) return 0;
6614 // If all indexes are zero, it is just the alignment of the base pointer.
6615 bool AllZeroOperands = true;
6616 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6617 if (!isa<Constant>(GEPI->getOperand(i)) ||
6618 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6619 AllZeroOperands = false;
6622 if (AllZeroOperands)
6623 return BaseAlignment;
6625 // Otherwise, if the base alignment is >= the alignment we expect for the
6626 // base pointer type, then we know that the resultant pointer is aligned at
6627 // least as much as its type requires.
6630 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6631 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6633 const Type *GEPTy = GEPI->getType();
6634 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6642 /// visitCallInst - CallInst simplification. This mostly only handles folding
6643 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6644 /// the heavy lifting.
6646 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6647 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6648 if (!II) return visitCallSite(&CI);
6650 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6652 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6653 bool Changed = false;
6655 // memmove/cpy/set of zero bytes is a noop.
6656 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6657 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6659 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6660 if (CI->getZExtValue() == 1) {
6661 // Replace the instruction with just byte operations. We would
6662 // transform other cases to loads/stores, but we don't know if
6663 // alignment is sufficient.
6667 // If we have a memmove and the source operation is a constant global,
6668 // then the source and dest pointers can't alias, so we can change this
6669 // into a call to memcpy.
6670 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6671 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6672 if (GVSrc->isConstant()) {
6673 Module *M = CI.getParent()->getParent()->getParent();
6675 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
6677 Name = "llvm.memcpy.i32";
6679 Name = "llvm.memcpy.i64";
6680 Function *MemCpy = M->getOrInsertFunction(Name,
6681 CI.getCalledFunction()->getFunctionType());
6682 CI.setOperand(0, MemCpy);
6687 // If we can determine a pointer alignment that is bigger than currently
6688 // set, update the alignment.
6689 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6690 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6691 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6692 unsigned Align = std::min(Alignment1, Alignment2);
6693 if (MI->getAlignment()->getZExtValue() < Align) {
6694 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
6697 } else if (isa<MemSetInst>(MI)) {
6698 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6699 if (MI->getAlignment()->getZExtValue() < Alignment) {
6700 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
6705 if (Changed) return II;
6707 switch (II->getIntrinsicID()) {
6709 case Intrinsic::ppc_altivec_lvx:
6710 case Intrinsic::ppc_altivec_lvxl:
6711 case Intrinsic::x86_sse_loadu_ps:
6712 case Intrinsic::x86_sse2_loadu_pd:
6713 case Intrinsic::x86_sse2_loadu_dq:
6714 // Turn PPC lvx -> load if the pointer is known aligned.
6715 // Turn X86 loadups -> load if the pointer is known aligned.
6716 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6717 Value *Ptr = InsertCastBefore(II->getOperand(1),
6718 PointerType::get(II->getType()), CI);
6719 return new LoadInst(Ptr);
6722 case Intrinsic::ppc_altivec_stvx:
6723 case Intrinsic::ppc_altivec_stvxl:
6724 // Turn stvx -> store if the pointer is known aligned.
6725 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
6726 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6727 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
6728 return new StoreInst(II->getOperand(1), Ptr);
6731 case Intrinsic::x86_sse_storeu_ps:
6732 case Intrinsic::x86_sse2_storeu_pd:
6733 case Intrinsic::x86_sse2_storeu_dq:
6734 case Intrinsic::x86_sse2_storel_dq:
6735 // Turn X86 storeu -> store if the pointer is known aligned.
6736 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6737 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6738 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6739 return new StoreInst(II->getOperand(2), Ptr);
6743 case Intrinsic::x86_sse_cvttss2si: {
6744 // These intrinsics only demands the 0th element of its input vector. If
6745 // we can simplify the input based on that, do so now.
6747 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6749 II->setOperand(1, V);
6755 case Intrinsic::ppc_altivec_vperm:
6756 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6757 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6758 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6760 // Check that all of the elements are integer constants or undefs.
6761 bool AllEltsOk = true;
6762 for (unsigned i = 0; i != 16; ++i) {
6763 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6764 !isa<UndefValue>(Mask->getOperand(i))) {
6771 // Cast the input vectors to byte vectors.
6772 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6773 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6774 Value *Result = UndefValue::get(Op0->getType());
6776 // Only extract each element once.
6777 Value *ExtractedElts[32];
6778 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6780 for (unsigned i = 0; i != 16; ++i) {
6781 if (isa<UndefValue>(Mask->getOperand(i)))
6783 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
6784 Idx &= 31; // Match the hardware behavior.
6786 if (ExtractedElts[Idx] == 0) {
6788 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
6789 InsertNewInstBefore(Elt, CI);
6790 ExtractedElts[Idx] = Elt;
6793 // Insert this value into the result vector.
6794 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
6795 InsertNewInstBefore(cast<Instruction>(Result), CI);
6797 return CastInst::create(Instruction::BitCast, Result, CI.getType());
6802 case Intrinsic::stackrestore: {
6803 // If the save is right next to the restore, remove the restore. This can
6804 // happen when variable allocas are DCE'd.
6805 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6806 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6807 BasicBlock::iterator BI = SS;
6809 return EraseInstFromFunction(CI);
6813 // If the stack restore is in a return/unwind block and if there are no
6814 // allocas or calls between the restore and the return, nuke the restore.
6815 TerminatorInst *TI = II->getParent()->getTerminator();
6816 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6817 BasicBlock::iterator BI = II;
6818 bool CannotRemove = false;
6819 for (++BI; &*BI != TI; ++BI) {
6820 if (isa<AllocaInst>(BI) ||
6821 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6822 CannotRemove = true;
6827 return EraseInstFromFunction(CI);
6834 return visitCallSite(II);
6837 // InvokeInst simplification
6839 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6840 return visitCallSite(&II);
6843 // visitCallSite - Improvements for call and invoke instructions.
6845 Instruction *InstCombiner::visitCallSite(CallSite CS) {
6846 bool Changed = false;
6848 // If the callee is a constexpr cast of a function, attempt to move the cast
6849 // to the arguments of the call/invoke.
6850 if (transformConstExprCastCall(CS)) return 0;
6852 Value *Callee = CS.getCalledValue();
6854 if (Function *CalleeF = dyn_cast<Function>(Callee))
6855 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6856 Instruction *OldCall = CS.getInstruction();
6857 // If the call and callee calling conventions don't match, this call must
6858 // be unreachable, as the call is undefined.
6859 new StoreInst(ConstantBool::getTrue(),
6860 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6861 if (!OldCall->use_empty())
6862 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6863 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6864 return EraseInstFromFunction(*OldCall);
6868 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6869 // This instruction is not reachable, just remove it. We insert a store to
6870 // undef so that we know that this code is not reachable, despite the fact
6871 // that we can't modify the CFG here.
6872 new StoreInst(ConstantBool::getTrue(),
6873 UndefValue::get(PointerType::get(Type::BoolTy)),
6874 CS.getInstruction());
6876 if (!CS.getInstruction()->use_empty())
6877 CS.getInstruction()->
6878 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6880 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6881 // Don't break the CFG, insert a dummy cond branch.
6882 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6883 ConstantBool::getTrue(), II);
6885 return EraseInstFromFunction(*CS.getInstruction());
6888 const PointerType *PTy = cast<PointerType>(Callee->getType());
6889 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6890 if (FTy->isVarArg()) {
6891 // See if we can optimize any arguments passed through the varargs area of
6893 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6894 E = CS.arg_end(); I != E; ++I)
6895 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6896 // If this cast does not effect the value passed through the varargs
6897 // area, we can eliminate the use of the cast.
6898 Value *Op = CI->getOperand(0);
6899 if (CI->isLosslessCast()) {
6906 return Changed ? CS.getInstruction() : 0;
6909 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6910 // attempt to move the cast to the arguments of the call/invoke.
6912 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6913 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6914 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6915 if (CE->getOpcode() != Instruction::BitCast ||
6916 !isa<Function>(CE->getOperand(0)))
6918 Function *Callee = cast<Function>(CE->getOperand(0));
6919 Instruction *Caller = CS.getInstruction();
6921 // Okay, this is a cast from a function to a different type. Unless doing so
6922 // would cause a type conversion of one of our arguments, change this call to
6923 // be a direct call with arguments casted to the appropriate types.
6925 const FunctionType *FT = Callee->getFunctionType();
6926 const Type *OldRetTy = Caller->getType();
6928 // Check to see if we are changing the return type...
6929 if (OldRetTy != FT->getReturnType()) {
6930 if (Callee->isExternal() &&
6931 !Caller->use_empty() &&
6932 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
6933 (isa<PointerType>(FT->getReturnType()) &&
6934 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
6936 return false; // Cannot transform this return value...
6938 // If the callsite is an invoke instruction, and the return value is used by
6939 // a PHI node in a successor, we cannot change the return type of the call
6940 // because there is no place to put the cast instruction (without breaking
6941 // the critical edge). Bail out in this case.
6942 if (!Caller->use_empty())
6943 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6944 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6946 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6947 if (PN->getParent() == II->getNormalDest() ||
6948 PN->getParent() == II->getUnwindDest())
6952 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6953 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6955 CallSite::arg_iterator AI = CS.arg_begin();
6956 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6957 const Type *ParamTy = FT->getParamType(i);
6958 const Type *ActTy = (*AI)->getType();
6959 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
6960 //Either we can cast directly, or we can upconvert the argument
6961 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
6962 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6963 ParamTy->isSigned() == ActTy->isSigned() &&
6964 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6965 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6966 c->getSExtValue() > 0);
6967 if (Callee->isExternal() && !isConvertible) return false;
6970 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6971 Callee->isExternal())
6972 return false; // Do not delete arguments unless we have a function body...
6974 // Okay, we decided that this is a safe thing to do: go ahead and start
6975 // inserting cast instructions as necessary...
6976 std::vector<Value*> Args;
6977 Args.reserve(NumActualArgs);
6979 AI = CS.arg_begin();
6980 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6981 const Type *ParamTy = FT->getParamType(i);
6982 if ((*AI)->getType() == ParamTy) {
6983 Args.push_back(*AI);
6985 CastInst *NewCast = CastInst::createInferredCast(*AI, ParamTy, "tmp");
6986 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
6990 // If the function takes more arguments than the call was taking, add them
6992 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6993 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6995 // If we are removing arguments to the function, emit an obnoxious warning...
6996 if (FT->getNumParams() < NumActualArgs)
6997 if (!FT->isVarArg()) {
6998 llvm_cerr << "WARNING: While resolving call to function '"
6999 << Callee->getName() << "' arguments were dropped!\n";
7001 // Add all of the arguments in their promoted form to the arg list...
7002 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7003 const Type *PTy = getPromotedType((*AI)->getType());
7004 if (PTy != (*AI)->getType()) {
7005 // Must promote to pass through va_arg area!
7006 Instruction *Cast = CastInst::createInferredCast(*AI, PTy, "tmp");
7007 InsertNewInstBefore(Cast, *Caller);
7008 Args.push_back(Cast);
7010 Args.push_back(*AI);
7015 if (FT->getReturnType() == Type::VoidTy)
7016 Caller->setName(""); // Void type should not have a name...
7019 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7020 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7021 Args, Caller->getName(), Caller);
7022 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7024 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7025 if (cast<CallInst>(Caller)->isTailCall())
7026 cast<CallInst>(NC)->setTailCall();
7027 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7030 // Insert a cast of the return type as necessary...
7032 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7033 if (NV->getType() != Type::VoidTy) {
7034 NV = NC = CastInst::createInferredCast(NC, Caller->getType(), "tmp");
7036 // If this is an invoke instruction, we should insert it after the first
7037 // non-phi, instruction in the normal successor block.
7038 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7039 BasicBlock::iterator I = II->getNormalDest()->begin();
7040 while (isa<PHINode>(I)) ++I;
7041 InsertNewInstBefore(NC, *I);
7043 // Otherwise, it's a call, just insert cast right after the call instr
7044 InsertNewInstBefore(NC, *Caller);
7046 AddUsersToWorkList(*Caller);
7048 NV = UndefValue::get(Caller->getType());
7052 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7053 Caller->replaceAllUsesWith(NV);
7054 Caller->getParent()->getInstList().erase(Caller);
7055 removeFromWorkList(Caller);
7059 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7060 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7061 /// and a single binop.
7062 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7063 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7064 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7065 isa<GetElementPtrInst>(FirstInst));
7066 unsigned Opc = FirstInst->getOpcode();
7067 Value *LHSVal = FirstInst->getOperand(0);
7068 Value *RHSVal = FirstInst->getOperand(1);
7070 const Type *LHSType = LHSVal->getType();
7071 const Type *RHSType = RHSVal->getType();
7073 // Scan to see if all operands are the same opcode, all have one use, and all
7074 // kill their operands (i.e. the operands have one use).
7075 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7076 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7077 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7078 // Verify type of the LHS matches so we don't fold setcc's of different
7079 // types or GEP's with different index types.
7080 I->getOperand(0)->getType() != LHSType ||
7081 I->getOperand(1)->getType() != RHSType)
7084 // Keep track of which operand needs a phi node.
7085 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7086 if (I->getOperand(1) != RHSVal) RHSVal = 0;
7089 // Otherwise, this is safe to transform, determine if it is profitable.
7091 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7092 // Indexes are often folded into load/store instructions, so we don't want to
7093 // hide them behind a phi.
7094 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7097 Value *InLHS = FirstInst->getOperand(0);
7098 Value *InRHS = FirstInst->getOperand(1);
7099 PHINode *NewLHS = 0, *NewRHS = 0;
7101 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7102 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7103 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7104 InsertNewInstBefore(NewLHS, PN);
7109 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7110 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7111 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7112 InsertNewInstBefore(NewRHS, PN);
7116 // Add all operands to the new PHIs.
7117 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7119 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7120 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7123 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7124 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7128 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7129 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7130 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7131 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7133 assert(isa<GetElementPtrInst>(FirstInst));
7134 return new GetElementPtrInst(LHSVal, RHSVal);
7138 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7139 /// of the block that defines it. This means that it must be obvious the value
7140 /// of the load is not changed from the point of the load to the end of the
7142 static bool isSafeToSinkLoad(LoadInst *L) {
7143 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7145 for (++BBI; BBI != E; ++BBI)
7146 if (BBI->mayWriteToMemory())
7152 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7153 // operator and they all are only used by the PHI, PHI together their
7154 // inputs, and do the operation once, to the result of the PHI.
7155 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7156 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7158 // Scan the instruction, looking for input operations that can be folded away.
7159 // If all input operands to the phi are the same instruction (e.g. a cast from
7160 // the same type or "+42") we can pull the operation through the PHI, reducing
7161 // code size and simplifying code.
7162 Constant *ConstantOp = 0;
7163 const Type *CastSrcTy = 0;
7164 bool isVolatile = false;
7165 if (isa<CastInst>(FirstInst)) {
7166 CastSrcTy = FirstInst->getOperand(0)->getType();
7167 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
7168 // Can fold binop or shift here if the RHS is a constant, otherwise call
7169 // FoldPHIArgBinOpIntoPHI.
7170 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7171 if (ConstantOp == 0)
7172 return FoldPHIArgBinOpIntoPHI(PN);
7173 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7174 isVolatile = LI->isVolatile();
7175 // We can't sink the load if the loaded value could be modified between the
7176 // load and the PHI.
7177 if (LI->getParent() != PN.getIncomingBlock(0) ||
7178 !isSafeToSinkLoad(LI))
7180 } else if (isa<GetElementPtrInst>(FirstInst)) {
7181 if (FirstInst->getNumOperands() == 2)
7182 return FoldPHIArgBinOpIntoPHI(PN);
7183 // Can't handle general GEPs yet.
7186 return 0; // Cannot fold this operation.
7189 // Check to see if all arguments are the same operation.
7190 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7191 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7192 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7193 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7196 if (I->getOperand(0)->getType() != CastSrcTy)
7197 return 0; // Cast operation must match.
7198 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7199 // We can't sink the load if the loaded value could be modified between the
7200 // load and the PHI.
7201 if (LI->isVolatile() != isVolatile ||
7202 LI->getParent() != PN.getIncomingBlock(i) ||
7203 !isSafeToSinkLoad(LI))
7205 } else if (I->getOperand(1) != ConstantOp) {
7210 // Okay, they are all the same operation. Create a new PHI node of the
7211 // correct type, and PHI together all of the LHS's of the instructions.
7212 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7213 PN.getName()+".in");
7214 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7216 Value *InVal = FirstInst->getOperand(0);
7217 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7219 // Add all operands to the new PHI.
7220 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7221 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7222 if (NewInVal != InVal)
7224 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7229 // The new PHI unions all of the same values together. This is really
7230 // common, so we handle it intelligently here for compile-time speed.
7234 InsertNewInstBefore(NewPN, PN);
7238 // Insert and return the new operation.
7239 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7240 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7241 else if (isa<LoadInst>(FirstInst))
7242 return new LoadInst(PhiVal, "", isVolatile);
7243 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7244 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7246 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7247 PhiVal, ConstantOp);
7250 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7252 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7253 if (PN->use_empty()) return true;
7254 if (!PN->hasOneUse()) return false;
7256 // Remember this node, and if we find the cycle, return.
7257 if (!PotentiallyDeadPHIs.insert(PN).second)
7260 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7261 return DeadPHICycle(PU, PotentiallyDeadPHIs);
7266 // PHINode simplification
7268 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7269 // If LCSSA is around, don't mess with Phi nodes
7270 if (mustPreserveAnalysisID(LCSSAID)) return 0;
7272 if (Value *V = PN.hasConstantValue())
7273 return ReplaceInstUsesWith(PN, V);
7275 // If all PHI operands are the same operation, pull them through the PHI,
7276 // reducing code size.
7277 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7278 PN.getIncomingValue(0)->hasOneUse())
7279 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7282 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7283 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7284 // PHI)... break the cycle.
7286 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7287 std::set<PHINode*> PotentiallyDeadPHIs;
7288 PotentiallyDeadPHIs.insert(&PN);
7289 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7290 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7296 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7297 Instruction *InsertPoint,
7299 unsigned PS = IC->getTargetData().getPointerSize();
7300 const Type *VTy = V->getType();
7301 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7302 // We must insert a cast to ensure we sign-extend.
7303 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7304 return IC->InsertCastBefore(V, DTy, *InsertPoint);
7308 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7309 Value *PtrOp = GEP.getOperand(0);
7310 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
7311 // If so, eliminate the noop.
7312 if (GEP.getNumOperands() == 1)
7313 return ReplaceInstUsesWith(GEP, PtrOp);
7315 if (isa<UndefValue>(GEP.getOperand(0)))
7316 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7318 bool HasZeroPointerIndex = false;
7319 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7320 HasZeroPointerIndex = C->isNullValue();
7322 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7323 return ReplaceInstUsesWith(GEP, PtrOp);
7325 // Eliminate unneeded casts for indices.
7326 bool MadeChange = false;
7327 gep_type_iterator GTI = gep_type_begin(GEP);
7328 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7329 if (isa<SequentialType>(*GTI)) {
7330 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7331 Value *Src = CI->getOperand(0);
7332 const Type *SrcTy = Src->getType();
7333 const Type *DestTy = CI->getType();
7334 if (Src->getType()->isInteger()) {
7335 if (SrcTy->getPrimitiveSizeInBits() ==
7336 DestTy->getPrimitiveSizeInBits()) {
7337 // We can always eliminate a cast from ulong or long to the other.
7338 // We can always eliminate a cast from uint to int or the other on
7339 // 32-bit pointer platforms.
7340 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7342 GEP.setOperand(i, Src);
7344 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7345 SrcTy->getPrimitiveSize() == 4) {
7346 // We can always eliminate a cast from int to [u]long. We can
7347 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7349 if (SrcTy->isSigned() ||
7350 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7352 GEP.setOperand(i, Src);
7357 // If we are using a wider index than needed for this platform, shrink it
7358 // to what we need. If the incoming value needs a cast instruction,
7359 // insert it. This explicit cast can make subsequent optimizations more
7361 Value *Op = GEP.getOperand(i);
7362 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7363 if (Constant *C = dyn_cast<Constant>(Op)) {
7364 GEP.setOperand(i, ConstantExpr::getCast(C,
7365 TD->getIntPtrType()->getSignedVersion()));
7368 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
7369 GEP.setOperand(i, Op);
7373 // If this is a constant idx, make sure to canonicalize it to be a signed
7374 // operand, otherwise CSE and other optimizations are pessimized.
7375 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7376 if (CUI->getType()->isUnsigned()) {
7378 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7382 if (MadeChange) return &GEP;
7384 // Combine Indices - If the source pointer to this getelementptr instruction
7385 // is a getelementptr instruction, combine the indices of the two
7386 // getelementptr instructions into a single instruction.
7388 std::vector<Value*> SrcGEPOperands;
7389 if (User *Src = dyn_castGetElementPtr(PtrOp))
7390 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7392 if (!SrcGEPOperands.empty()) {
7393 // Note that if our source is a gep chain itself that we wait for that
7394 // chain to be resolved before we perform this transformation. This
7395 // avoids us creating a TON of code in some cases.
7397 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7398 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7399 return 0; // Wait until our source is folded to completion.
7401 std::vector<Value *> Indices;
7403 // Find out whether the last index in the source GEP is a sequential idx.
7404 bool EndsWithSequential = false;
7405 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7406 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7407 EndsWithSequential = !isa<StructType>(*I);
7409 // Can we combine the two pointer arithmetics offsets?
7410 if (EndsWithSequential) {
7411 // Replace: gep (gep %P, long B), long A, ...
7412 // With: T = long A+B; gep %P, T, ...
7414 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7415 if (SO1 == Constant::getNullValue(SO1->getType())) {
7417 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7420 // If they aren't the same type, convert both to an integer of the
7421 // target's pointer size.
7422 if (SO1->getType() != GO1->getType()) {
7423 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7424 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7425 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7426 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7428 unsigned PS = TD->getPointerSize();
7429 if (SO1->getType()->getPrimitiveSize() == PS) {
7430 // Convert GO1 to SO1's type.
7431 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7433 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7434 // Convert SO1 to GO1's type.
7435 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7437 const Type *PT = TD->getIntPtrType();
7438 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7439 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7443 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7444 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7446 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7447 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7451 // Recycle the GEP we already have if possible.
7452 if (SrcGEPOperands.size() == 2) {
7453 GEP.setOperand(0, SrcGEPOperands[0]);
7454 GEP.setOperand(1, Sum);
7457 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7458 SrcGEPOperands.end()-1);
7459 Indices.push_back(Sum);
7460 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7462 } else if (isa<Constant>(*GEP.idx_begin()) &&
7463 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7464 SrcGEPOperands.size() != 1) {
7465 // Otherwise we can do the fold if the first index of the GEP is a zero
7466 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7467 SrcGEPOperands.end());
7468 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7471 if (!Indices.empty())
7472 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7474 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7475 // GEP of global variable. If all of the indices for this GEP are
7476 // constants, we can promote this to a constexpr instead of an instruction.
7478 // Scan for nonconstants...
7479 std::vector<Constant*> Indices;
7480 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7481 for (; I != E && isa<Constant>(*I); ++I)
7482 Indices.push_back(cast<Constant>(*I));
7484 if (I == E) { // If they are all constants...
7485 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7487 // Replace all uses of the GEP with the new constexpr...
7488 return ReplaceInstUsesWith(GEP, CE);
7490 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
7491 if (!isa<PointerType>(X->getType())) {
7492 // Not interesting. Source pointer must be a cast from pointer.
7493 } else if (HasZeroPointerIndex) {
7494 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7495 // into : GEP [10 x ubyte]* X, long 0, ...
7497 // This occurs when the program declares an array extern like "int X[];"
7499 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7500 const PointerType *XTy = cast<PointerType>(X->getType());
7501 if (const ArrayType *XATy =
7502 dyn_cast<ArrayType>(XTy->getElementType()))
7503 if (const ArrayType *CATy =
7504 dyn_cast<ArrayType>(CPTy->getElementType()))
7505 if (CATy->getElementType() == XATy->getElementType()) {
7506 // At this point, we know that the cast source type is a pointer
7507 // to an array of the same type as the destination pointer
7508 // array. Because the array type is never stepped over (there
7509 // is a leading zero) we can fold the cast into this GEP.
7510 GEP.setOperand(0, X);
7513 } else if (GEP.getNumOperands() == 2) {
7514 // Transform things like:
7515 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7516 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7517 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7518 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7519 if (isa<ArrayType>(SrcElTy) &&
7520 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7521 TD->getTypeSize(ResElTy)) {
7522 Value *V = InsertNewInstBefore(
7523 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7524 GEP.getOperand(1), GEP.getName()), GEP);
7525 // V and GEP are both pointer types --> BitCast
7526 return new BitCastInst(V, GEP.getType());
7529 // Transform things like:
7530 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7531 // (where tmp = 8*tmp2) into:
7532 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7534 if (isa<ArrayType>(SrcElTy) &&
7535 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7536 uint64_t ArrayEltSize =
7537 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7539 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7540 // allow either a mul, shift, or constant here.
7542 ConstantInt *Scale = 0;
7543 if (ArrayEltSize == 1) {
7544 NewIdx = GEP.getOperand(1);
7545 Scale = ConstantInt::get(NewIdx->getType(), 1);
7546 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7547 NewIdx = ConstantInt::get(CI->getType(), 1);
7549 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7550 if (Inst->getOpcode() == Instruction::Shl &&
7551 isa<ConstantInt>(Inst->getOperand(1))) {
7553 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7554 if (Inst->getType()->isSigned())
7555 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7557 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7558 NewIdx = Inst->getOperand(0);
7559 } else if (Inst->getOpcode() == Instruction::Mul &&
7560 isa<ConstantInt>(Inst->getOperand(1))) {
7561 Scale = cast<ConstantInt>(Inst->getOperand(1));
7562 NewIdx = Inst->getOperand(0);
7566 // If the index will be to exactly the right offset with the scale taken
7567 // out, perform the transformation.
7568 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7569 if (isa<ConstantInt>(Scale))
7570 Scale = ConstantInt::get(Scale->getType(),
7571 Scale->getZExtValue() / ArrayEltSize);
7572 if (Scale->getZExtValue() != 1) {
7573 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7574 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7575 NewIdx = InsertNewInstBefore(Sc, GEP);
7578 // Insert the new GEP instruction.
7579 Instruction *NewGEP =
7580 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7581 NewIdx, GEP.getName());
7582 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7583 // The NewGEP must be pointer typed, so must the old one -> BitCast
7584 return new BitCastInst(NewGEP, GEP.getType());
7593 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7594 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7595 if (AI.isArrayAllocation()) // Check C != 1
7596 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7598 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7599 AllocationInst *New = 0;
7601 // Create and insert the replacement instruction...
7602 if (isa<MallocInst>(AI))
7603 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7605 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7606 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7609 InsertNewInstBefore(New, AI);
7611 // Scan to the end of the allocation instructions, to skip over a block of
7612 // allocas if possible...
7614 BasicBlock::iterator It = New;
7615 while (isa<AllocationInst>(*It)) ++It;
7617 // Now that I is pointing to the first non-allocation-inst in the block,
7618 // insert our getelementptr instruction...
7620 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7621 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7622 New->getName()+".sub", It);
7624 // Now make everything use the getelementptr instead of the original
7626 return ReplaceInstUsesWith(AI, V);
7627 } else if (isa<UndefValue>(AI.getArraySize())) {
7628 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7631 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7632 // Note that we only do this for alloca's, because malloc should allocate and
7633 // return a unique pointer, even for a zero byte allocation.
7634 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7635 TD->getTypeSize(AI.getAllocatedType()) == 0)
7636 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7641 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7642 Value *Op = FI.getOperand(0);
7644 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7645 if (CastInst *CI = dyn_cast<CastInst>(Op))
7646 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7647 FI.setOperand(0, CI->getOperand(0));
7651 // free undef -> unreachable.
7652 if (isa<UndefValue>(Op)) {
7653 // Insert a new store to null because we cannot modify the CFG here.
7654 new StoreInst(ConstantBool::getTrue(),
7655 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7656 return EraseInstFromFunction(FI);
7659 // If we have 'free null' delete the instruction. This can happen in stl code
7660 // when lots of inlining happens.
7661 if (isa<ConstantPointerNull>(Op))
7662 return EraseInstFromFunction(FI);
7668 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7669 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7670 User *CI = cast<User>(LI.getOperand(0));
7671 Value *CastOp = CI->getOperand(0);
7673 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7674 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7675 const Type *SrcPTy = SrcTy->getElementType();
7677 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7678 isa<PackedType>(DestPTy)) {
7679 // If the source is an array, the code below will not succeed. Check to
7680 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7682 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7683 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7684 if (ASrcTy->getNumElements() != 0) {
7685 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7686 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7687 SrcTy = cast<PointerType>(CastOp->getType());
7688 SrcPTy = SrcTy->getElementType();
7691 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7692 isa<PackedType>(SrcPTy)) &&
7693 // Do not allow turning this into a load of an integer, which is then
7694 // casted to a pointer, this pessimizes pointer analysis a lot.
7695 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7696 IC.getTargetData().getTypeSize(SrcPTy) ==
7697 IC.getTargetData().getTypeSize(DestPTy)) {
7699 // Okay, we are casting from one integer or pointer type to another of
7700 // the same size. Instead of casting the pointer before the load, cast
7701 // the result of the loaded value.
7702 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7704 LI.isVolatile()),LI);
7705 // Now cast the result of the load.
7706 return CastInst::createInferredCast(NewLoad, LI.getType());
7713 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
7714 /// from this value cannot trap. If it is not obviously safe to load from the
7715 /// specified pointer, we do a quick local scan of the basic block containing
7716 /// ScanFrom, to determine if the address is already accessed.
7717 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7718 // If it is an alloca or global variable, it is always safe to load from.
7719 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7721 // Otherwise, be a little bit agressive by scanning the local block where we
7722 // want to check to see if the pointer is already being loaded or stored
7723 // from/to. If so, the previous load or store would have already trapped,
7724 // so there is no harm doing an extra load (also, CSE will later eliminate
7725 // the load entirely).
7726 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7731 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7732 if (LI->getOperand(0) == V) return true;
7733 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7734 if (SI->getOperand(1) == V) return true;
7740 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7741 Value *Op = LI.getOperand(0);
7743 // load (cast X) --> cast (load X) iff safe
7744 if (isa<CastInst>(Op))
7745 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7748 // None of the following transforms are legal for volatile loads.
7749 if (LI.isVolatile()) return 0;
7751 if (&LI.getParent()->front() != &LI) {
7752 BasicBlock::iterator BBI = &LI; --BBI;
7753 // If the instruction immediately before this is a store to the same
7754 // address, do a simple form of store->load forwarding.
7755 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7756 if (SI->getOperand(1) == LI.getOperand(0))
7757 return ReplaceInstUsesWith(LI, SI->getOperand(0));
7758 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7759 if (LIB->getOperand(0) == LI.getOperand(0))
7760 return ReplaceInstUsesWith(LI, LIB);
7763 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7764 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7765 isa<UndefValue>(GEPI->getOperand(0))) {
7766 // Insert a new store to null instruction before the load to indicate
7767 // that this code is not reachable. We do this instead of inserting
7768 // an unreachable instruction directly because we cannot modify the
7770 new StoreInst(UndefValue::get(LI.getType()),
7771 Constant::getNullValue(Op->getType()), &LI);
7772 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7775 if (Constant *C = dyn_cast<Constant>(Op)) {
7776 // load null/undef -> undef
7777 if ((C->isNullValue() || isa<UndefValue>(C))) {
7778 // Insert a new store to null instruction before the load to indicate that
7779 // this code is not reachable. We do this instead of inserting an
7780 // unreachable instruction directly because we cannot modify the CFG.
7781 new StoreInst(UndefValue::get(LI.getType()),
7782 Constant::getNullValue(Op->getType()), &LI);
7783 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7786 // Instcombine load (constant global) into the value loaded.
7787 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7788 if (GV->isConstant() && !GV->isExternal())
7789 return ReplaceInstUsesWith(LI, GV->getInitializer());
7791 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7792 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7793 if (CE->getOpcode() == Instruction::GetElementPtr) {
7794 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7795 if (GV->isConstant() && !GV->isExternal())
7797 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
7798 return ReplaceInstUsesWith(LI, V);
7799 if (CE->getOperand(0)->isNullValue()) {
7800 // Insert a new store to null instruction before the load to indicate
7801 // that this code is not reachable. We do this instead of inserting
7802 // an unreachable instruction directly because we cannot modify the
7804 new StoreInst(UndefValue::get(LI.getType()),
7805 Constant::getNullValue(Op->getType()), &LI);
7806 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7809 } else if (CE->isCast()) {
7810 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7815 if (Op->hasOneUse()) {
7816 // Change select and PHI nodes to select values instead of addresses: this
7817 // helps alias analysis out a lot, allows many others simplifications, and
7818 // exposes redundancy in the code.
7820 // Note that we cannot do the transformation unless we know that the
7821 // introduced loads cannot trap! Something like this is valid as long as
7822 // the condition is always false: load (select bool %C, int* null, int* %G),
7823 // but it would not be valid if we transformed it to load from null
7826 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7827 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
7828 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7829 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
7830 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
7831 SI->getOperand(1)->getName()+".val"), LI);
7832 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
7833 SI->getOperand(2)->getName()+".val"), LI);
7834 return new SelectInst(SI->getCondition(), V1, V2);
7837 // load (select (cond, null, P)) -> load P
7838 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7839 if (C->isNullValue()) {
7840 LI.setOperand(0, SI->getOperand(2));
7844 // load (select (cond, P, null)) -> load P
7845 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7846 if (C->isNullValue()) {
7847 LI.setOperand(0, SI->getOperand(1));
7855 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7857 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7858 User *CI = cast<User>(SI.getOperand(1));
7859 Value *CastOp = CI->getOperand(0);
7861 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7862 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7863 const Type *SrcPTy = SrcTy->getElementType();
7865 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7866 // If the source is an array, the code below will not succeed. Check to
7867 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7869 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7870 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7871 if (ASrcTy->getNumElements() != 0) {
7872 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7873 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7874 SrcTy = cast<PointerType>(CastOp->getType());
7875 SrcPTy = SrcTy->getElementType();
7878 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
7879 IC.getTargetData().getTypeSize(SrcPTy) ==
7880 IC.getTargetData().getTypeSize(DestPTy)) {
7882 // Okay, we are casting from one integer or pointer type to another of
7883 // the same size. Instead of casting the pointer before the store, cast
7884 // the value to be stored.
7886 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7887 NewCast = ConstantExpr::getCast(C, SrcPTy);
7889 NewCast = IC.InsertNewInstBefore(
7890 CastInst::createInferredCast(SI.getOperand(0), SrcPTy,
7891 SI.getOperand(0)->getName()+".c"), SI);
7893 return new StoreInst(NewCast, CastOp);
7900 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7901 Value *Val = SI.getOperand(0);
7902 Value *Ptr = SI.getOperand(1);
7904 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
7905 EraseInstFromFunction(SI);
7910 // Do really simple DSE, to catch cases where there are several consequtive
7911 // stores to the same location, separated by a few arithmetic operations. This
7912 // situation often occurs with bitfield accesses.
7913 BasicBlock::iterator BBI = &SI;
7914 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7918 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7919 // Prev store isn't volatile, and stores to the same location?
7920 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7923 EraseInstFromFunction(*PrevSI);
7929 // If this is a load, we have to stop. However, if the loaded value is from
7930 // the pointer we're loading and is producing the pointer we're storing,
7931 // then *this* store is dead (X = load P; store X -> P).
7932 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7933 if (LI == Val && LI->getOperand(0) == Ptr) {
7934 EraseInstFromFunction(SI);
7938 // Otherwise, this is a load from some other location. Stores before it
7943 // Don't skip over loads or things that can modify memory.
7944 if (BBI->mayWriteToMemory())
7949 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
7951 // store X, null -> turns into 'unreachable' in SimplifyCFG
7952 if (isa<ConstantPointerNull>(Ptr)) {
7953 if (!isa<UndefValue>(Val)) {
7954 SI.setOperand(0, UndefValue::get(Val->getType()));
7955 if (Instruction *U = dyn_cast<Instruction>(Val))
7956 WorkList.push_back(U); // Dropped a use.
7959 return 0; // Do not modify these!
7962 // store undef, Ptr -> noop
7963 if (isa<UndefValue>(Val)) {
7964 EraseInstFromFunction(SI);
7969 // If the pointer destination is a cast, see if we can fold the cast into the
7971 if (isa<CastInst>(Ptr))
7972 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7974 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7976 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7980 // If this store is the last instruction in the basic block, and if the block
7981 // ends with an unconditional branch, try to move it to the successor block.
7983 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7984 if (BI->isUnconditional()) {
7985 // Check to see if the successor block has exactly two incoming edges. If
7986 // so, see if the other predecessor contains a store to the same location.
7987 // if so, insert a PHI node (if needed) and move the stores down.
7988 BasicBlock *Dest = BI->getSuccessor(0);
7990 pred_iterator PI = pred_begin(Dest);
7991 BasicBlock *Other = 0;
7992 if (*PI != BI->getParent())
7995 if (PI != pred_end(Dest)) {
7996 if (*PI != BI->getParent())
8001 if (++PI != pred_end(Dest))
8004 if (Other) { // If only one other pred...
8005 BBI = Other->getTerminator();
8006 // Make sure this other block ends in an unconditional branch and that
8007 // there is an instruction before the branch.
8008 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8009 BBI != Other->begin()) {
8011 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8013 // If this instruction is a store to the same location.
8014 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8015 // Okay, we know we can perform this transformation. Insert a PHI
8016 // node now if we need it.
8017 Value *MergedVal = OtherStore->getOperand(0);
8018 if (MergedVal != SI.getOperand(0)) {
8019 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8020 PN->reserveOperandSpace(2);
8021 PN->addIncoming(SI.getOperand(0), SI.getParent());
8022 PN->addIncoming(OtherStore->getOperand(0), Other);
8023 MergedVal = InsertNewInstBefore(PN, Dest->front());
8026 // Advance to a place where it is safe to insert the new store and
8028 BBI = Dest->begin();
8029 while (isa<PHINode>(BBI)) ++BBI;
8030 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8031 OtherStore->isVolatile()), *BBI);
8033 // Nuke the old stores.
8034 EraseInstFromFunction(SI);
8035 EraseInstFromFunction(*OtherStore);
8047 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8048 // Change br (not X), label True, label False to: br X, label False, True
8050 BasicBlock *TrueDest;
8051 BasicBlock *FalseDest;
8052 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8053 !isa<Constant>(X)) {
8054 // Swap Destinations and condition...
8056 BI.setSuccessor(0, FalseDest);
8057 BI.setSuccessor(1, TrueDest);
8061 // Cannonicalize setne -> seteq
8062 Instruction::BinaryOps Op; Value *Y;
8063 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
8064 TrueDest, FalseDest)))
8065 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
8066 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
8067 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
8068 std::string Name = I->getName(); I->setName("");
8069 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
8070 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
8071 // Swap Destinations and condition...
8072 BI.setCondition(NewSCC);
8073 BI.setSuccessor(0, FalseDest);
8074 BI.setSuccessor(1, TrueDest);
8075 removeFromWorkList(I);
8076 I->getParent()->getInstList().erase(I);
8077 WorkList.push_back(cast<Instruction>(NewSCC));
8084 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8085 Value *Cond = SI.getCondition();
8086 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8087 if (I->getOpcode() == Instruction::Add)
8088 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8089 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8090 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8091 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8093 SI.setOperand(0, I->getOperand(0));
8094 WorkList.push_back(I);
8101 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8102 /// is to leave as a vector operation.
8103 static bool CheapToScalarize(Value *V, bool isConstant) {
8104 if (isa<ConstantAggregateZero>(V))
8106 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8107 if (isConstant) return true;
8108 // If all elts are the same, we can extract.
8109 Constant *Op0 = C->getOperand(0);
8110 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8111 if (C->getOperand(i) != Op0)
8115 Instruction *I = dyn_cast<Instruction>(V);
8116 if (!I) return false;
8118 // Insert element gets simplified to the inserted element or is deleted if
8119 // this is constant idx extract element and its a constant idx insertelt.
8120 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8121 isa<ConstantInt>(I->getOperand(2)))
8123 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8125 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8126 if (BO->hasOneUse() &&
8127 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8128 CheapToScalarize(BO->getOperand(1), isConstant)))
8134 /// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8135 /// elements into values that are larger than the #elts in the input.
8136 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8137 unsigned NElts = SVI->getType()->getNumElements();
8138 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8139 return std::vector<unsigned>(NElts, 0);
8140 if (isa<UndefValue>(SVI->getOperand(2)))
8141 return std::vector<unsigned>(NElts, 2*NElts);
8143 std::vector<unsigned> Result;
8144 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8145 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8146 if (isa<UndefValue>(CP->getOperand(i)))
8147 Result.push_back(NElts*2); // undef -> 8
8149 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8153 /// FindScalarElement - Given a vector and an element number, see if the scalar
8154 /// value is already around as a register, for example if it were inserted then
8155 /// extracted from the vector.
8156 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8157 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8158 const PackedType *PTy = cast<PackedType>(V->getType());
8159 unsigned Width = PTy->getNumElements();
8160 if (EltNo >= Width) // Out of range access.
8161 return UndefValue::get(PTy->getElementType());
8163 if (isa<UndefValue>(V))
8164 return UndefValue::get(PTy->getElementType());
8165 else if (isa<ConstantAggregateZero>(V))
8166 return Constant::getNullValue(PTy->getElementType());
8167 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8168 return CP->getOperand(EltNo);
8169 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8170 // If this is an insert to a variable element, we don't know what it is.
8171 if (!isa<ConstantInt>(III->getOperand(2)))
8173 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8175 // If this is an insert to the element we are looking for, return the
8178 return III->getOperand(1);
8180 // Otherwise, the insertelement doesn't modify the value, recurse on its
8182 return FindScalarElement(III->getOperand(0), EltNo);
8183 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8184 unsigned InEl = getShuffleMask(SVI)[EltNo];
8186 return FindScalarElement(SVI->getOperand(0), InEl);
8187 else if (InEl < Width*2)
8188 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8190 return UndefValue::get(PTy->getElementType());
8193 // Otherwise, we don't know.
8197 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8199 // If packed val is undef, replace extract with scalar undef.
8200 if (isa<UndefValue>(EI.getOperand(0)))
8201 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8203 // If packed val is constant 0, replace extract with scalar 0.
8204 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8205 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8207 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8208 // If packed val is constant with uniform operands, replace EI
8209 // with that operand
8210 Constant *op0 = C->getOperand(0);
8211 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8212 if (C->getOperand(i) != op0) {
8217 return ReplaceInstUsesWith(EI, op0);
8220 // If extracting a specified index from the vector, see if we can recursively
8221 // find a previously computed scalar that was inserted into the vector.
8222 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8223 // This instruction only demands the single element from the input vector.
8224 // If the input vector has a single use, simplify it based on this use
8226 uint64_t IndexVal = IdxC->getZExtValue();
8227 if (EI.getOperand(0)->hasOneUse()) {
8229 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8232 EI.setOperand(0, V);
8237 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8238 return ReplaceInstUsesWith(EI, Elt);
8241 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8242 if (I->hasOneUse()) {
8243 // Push extractelement into predecessor operation if legal and
8244 // profitable to do so
8245 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8246 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8247 if (CheapToScalarize(BO, isConstantElt)) {
8248 ExtractElementInst *newEI0 =
8249 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8250 EI.getName()+".lhs");
8251 ExtractElementInst *newEI1 =
8252 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8253 EI.getName()+".rhs");
8254 InsertNewInstBefore(newEI0, EI);
8255 InsertNewInstBefore(newEI1, EI);
8256 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8258 } else if (isa<LoadInst>(I)) {
8259 Value *Ptr = InsertCastBefore(I->getOperand(0),
8260 PointerType::get(EI.getType()), EI);
8261 GetElementPtrInst *GEP =
8262 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8263 InsertNewInstBefore(GEP, EI);
8264 return new LoadInst(GEP);
8267 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8268 // Extracting the inserted element?
8269 if (IE->getOperand(2) == EI.getOperand(1))
8270 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8271 // If the inserted and extracted elements are constants, they must not
8272 // be the same value, extract from the pre-inserted value instead.
8273 if (isa<Constant>(IE->getOperand(2)) &&
8274 isa<Constant>(EI.getOperand(1))) {
8275 AddUsesToWorkList(EI);
8276 EI.setOperand(0, IE->getOperand(0));
8279 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8280 // If this is extracting an element from a shufflevector, figure out where
8281 // it came from and extract from the appropriate input element instead.
8282 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8283 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8285 if (SrcIdx < SVI->getType()->getNumElements())
8286 Src = SVI->getOperand(0);
8287 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8288 SrcIdx -= SVI->getType()->getNumElements();
8289 Src = SVI->getOperand(1);
8291 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8293 return new ExtractElementInst(Src, SrcIdx);
8300 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8301 /// elements from either LHS or RHS, return the shuffle mask and true.
8302 /// Otherwise, return false.
8303 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8304 std::vector<Constant*> &Mask) {
8305 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8306 "Invalid CollectSingleShuffleElements");
8307 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8309 if (isa<UndefValue>(V)) {
8310 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8312 } else if (V == LHS) {
8313 for (unsigned i = 0; i != NumElts; ++i)
8314 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8316 } else if (V == RHS) {
8317 for (unsigned i = 0; i != NumElts; ++i)
8318 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
8320 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8321 // If this is an insert of an extract from some other vector, include it.
8322 Value *VecOp = IEI->getOperand(0);
8323 Value *ScalarOp = IEI->getOperand(1);
8324 Value *IdxOp = IEI->getOperand(2);
8326 if (!isa<ConstantInt>(IdxOp))
8328 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8330 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8331 // Okay, we can handle this if the vector we are insertinting into is
8333 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8334 // If so, update the mask to reflect the inserted undef.
8335 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8338 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8339 if (isa<ConstantInt>(EI->getOperand(1)) &&
8340 EI->getOperand(0)->getType() == V->getType()) {
8341 unsigned ExtractedIdx =
8342 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8344 // This must be extracting from either LHS or RHS.
8345 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8346 // Okay, we can handle this if the vector we are insertinting into is
8348 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8349 // If so, update the mask to reflect the inserted value.
8350 if (EI->getOperand(0) == LHS) {
8351 Mask[InsertedIdx & (NumElts-1)] =
8352 ConstantInt::get(Type::UIntTy, ExtractedIdx);
8354 assert(EI->getOperand(0) == RHS);
8355 Mask[InsertedIdx & (NumElts-1)] =
8356 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
8365 // TODO: Handle shufflevector here!
8370 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8371 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8372 /// that computes V and the LHS value of the shuffle.
8373 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8375 assert(isa<PackedType>(V->getType()) &&
8376 (RHS == 0 || V->getType() == RHS->getType()) &&
8377 "Invalid shuffle!");
8378 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8380 if (isa<UndefValue>(V)) {
8381 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8383 } else if (isa<ConstantAggregateZero>(V)) {
8384 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
8386 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8387 // If this is an insert of an extract from some other vector, include it.
8388 Value *VecOp = IEI->getOperand(0);
8389 Value *ScalarOp = IEI->getOperand(1);
8390 Value *IdxOp = IEI->getOperand(2);
8392 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8393 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8394 EI->getOperand(0)->getType() == V->getType()) {
8395 unsigned ExtractedIdx =
8396 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8397 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8399 // Either the extracted from or inserted into vector must be RHSVec,
8400 // otherwise we'd end up with a shuffle of three inputs.
8401 if (EI->getOperand(0) == RHS || RHS == 0) {
8402 RHS = EI->getOperand(0);
8403 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8404 Mask[InsertedIdx & (NumElts-1)] =
8405 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
8410 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8411 // Everything but the extracted element is replaced with the RHS.
8412 for (unsigned i = 0; i != NumElts; ++i) {
8413 if (i != InsertedIdx)
8414 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
8419 // If this insertelement is a chain that comes from exactly these two
8420 // vectors, return the vector and the effective shuffle.
8421 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8422 return EI->getOperand(0);
8427 // TODO: Handle shufflevector here!
8429 // Otherwise, can't do anything fancy. Return an identity vector.
8430 for (unsigned i = 0; i != NumElts; ++i)
8431 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8435 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8436 Value *VecOp = IE.getOperand(0);
8437 Value *ScalarOp = IE.getOperand(1);
8438 Value *IdxOp = IE.getOperand(2);
8440 // If the inserted element was extracted from some other vector, and if the
8441 // indexes are constant, try to turn this into a shufflevector operation.
8442 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8443 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8444 EI->getOperand(0)->getType() == IE.getType()) {
8445 unsigned NumVectorElts = IE.getType()->getNumElements();
8446 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8447 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8449 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8450 return ReplaceInstUsesWith(IE, VecOp);
8452 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8453 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8455 // If we are extracting a value from a vector, then inserting it right
8456 // back into the same place, just use the input vector.
8457 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8458 return ReplaceInstUsesWith(IE, VecOp);
8460 // We could theoretically do this for ANY input. However, doing so could
8461 // turn chains of insertelement instructions into a chain of shufflevector
8462 // instructions, and right now we do not merge shufflevectors. As such,
8463 // only do this in a situation where it is clear that there is benefit.
8464 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8465 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8466 // the values of VecOp, except then one read from EIOp0.
8467 // Build a new shuffle mask.
8468 std::vector<Constant*> Mask;
8469 if (isa<UndefValue>(VecOp))
8470 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8472 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8473 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
8476 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
8477 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8478 ConstantPacked::get(Mask));
8481 // If this insertelement isn't used by some other insertelement, turn it
8482 // (and any insertelements it points to), into one big shuffle.
8483 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8484 std::vector<Constant*> Mask;
8486 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8487 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8488 // We now have a shuffle of LHS, RHS, Mask.
8489 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8498 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8499 Value *LHS = SVI.getOperand(0);
8500 Value *RHS = SVI.getOperand(1);
8501 std::vector<unsigned> Mask = getShuffleMask(&SVI);
8503 bool MadeChange = false;
8505 // Undefined shuffle mask -> undefined value.
8506 if (isa<UndefValue>(SVI.getOperand(2)))
8507 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8509 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8510 // the undef, change them to undefs.
8512 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8513 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8514 if (LHS == RHS || isa<UndefValue>(LHS)) {
8515 if (isa<UndefValue>(LHS) && LHS == RHS) {
8516 // shuffle(undef,undef,mask) -> undef.
8517 return ReplaceInstUsesWith(SVI, LHS);
8520 // Remap any references to RHS to use LHS.
8521 std::vector<Constant*> Elts;
8522 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8524 Elts.push_back(UndefValue::get(Type::UIntTy));
8526 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8527 (Mask[i] < e && isa<UndefValue>(LHS)))
8528 Mask[i] = 2*e; // Turn into undef.
8530 Mask[i] &= (e-1); // Force to LHS.
8531 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
8534 SVI.setOperand(0, SVI.getOperand(1));
8535 SVI.setOperand(1, UndefValue::get(RHS->getType()));
8536 SVI.setOperand(2, ConstantPacked::get(Elts));
8537 LHS = SVI.getOperand(0);
8538 RHS = SVI.getOperand(1);
8542 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8543 bool isLHSID = true, isRHSID = true;
8545 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8546 if (Mask[i] >= e*2) continue; // Ignore undef values.
8547 // Is this an identity shuffle of the LHS value?
8548 isLHSID &= (Mask[i] == i);
8550 // Is this an identity shuffle of the RHS value?
8551 isRHSID &= (Mask[i]-e == i);
8554 // Eliminate identity shuffles.
8555 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8556 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8558 // If the LHS is a shufflevector itself, see if we can combine it with this
8559 // one without producing an unusual shuffle. Here we are really conservative:
8560 // we are absolutely afraid of producing a shuffle mask not in the input
8561 // program, because the code gen may not be smart enough to turn a merged
8562 // shuffle into two specific shuffles: it may produce worse code. As such,
8563 // we only merge two shuffles if the result is one of the two input shuffle
8564 // masks. In this case, merging the shuffles just removes one instruction,
8565 // which we know is safe. This is good for things like turning:
8566 // (splat(splat)) -> splat.
8567 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8568 if (isa<UndefValue>(RHS)) {
8569 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8571 std::vector<unsigned> NewMask;
8572 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8574 NewMask.push_back(2*e);
8576 NewMask.push_back(LHSMask[Mask[i]]);
8578 // If the result mask is equal to the src shuffle or this shuffle mask, do
8580 if (NewMask == LHSMask || NewMask == Mask) {
8581 std::vector<Constant*> Elts;
8582 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8583 if (NewMask[i] >= e*2) {
8584 Elts.push_back(UndefValue::get(Type::UIntTy));
8586 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
8589 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8590 LHSSVI->getOperand(1),
8591 ConstantPacked::get(Elts));
8596 return MadeChange ? &SVI : 0;
8601 void InstCombiner::removeFromWorkList(Instruction *I) {
8602 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8607 /// TryToSinkInstruction - Try to move the specified instruction from its
8608 /// current block into the beginning of DestBlock, which can only happen if it's
8609 /// safe to move the instruction past all of the instructions between it and the
8610 /// end of its block.
8611 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8612 assert(I->hasOneUse() && "Invariants didn't hold!");
8614 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8615 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8617 // Do not sink alloca instructions out of the entry block.
8618 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8621 // We can only sink load instructions if there is nothing between the load and
8622 // the end of block that could change the value.
8623 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8624 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8626 if (Scan->mayWriteToMemory())
8630 BasicBlock::iterator InsertPos = DestBlock->begin();
8631 while (isa<PHINode>(InsertPos)) ++InsertPos;
8633 I->moveBefore(InsertPos);
8638 /// OptimizeConstantExpr - Given a constant expression and target data layout
8639 /// information, symbolically evaluation the constant expr to something simpler
8641 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8644 Constant *Ptr = CE->getOperand(0);
8645 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8646 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8647 // If this is a constant expr gep that is effectively computing an
8648 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8649 bool isFoldableGEP = true;
8650 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8651 if (!isa<ConstantInt>(CE->getOperand(i)))
8652 isFoldableGEP = false;
8653 if (isFoldableGEP) {
8654 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8655 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8656 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
8657 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8658 return ConstantExpr::getCast(C, CE->getType());
8666 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8667 /// all reachable code to the worklist.
8669 /// This has a couple of tricks to make the code faster and more powerful. In
8670 /// particular, we constant fold and DCE instructions as we go, to avoid adding
8671 /// them to the worklist (this significantly speeds up instcombine on code where
8672 /// many instructions are dead or constant). Additionally, if we find a branch
8673 /// whose condition is a known constant, we only visit the reachable successors.
8675 static void AddReachableCodeToWorklist(BasicBlock *BB,
8676 std::set<BasicBlock*> &Visited,
8677 std::vector<Instruction*> &WorkList,
8678 const TargetData *TD) {
8679 // We have now visited this block! If we've already been here, bail out.
8680 if (!Visited.insert(BB).second) return;
8682 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8683 Instruction *Inst = BBI++;
8685 // DCE instruction if trivially dead.
8686 if (isInstructionTriviallyDead(Inst)) {
8688 DOUT << "IC: DCE: " << *Inst;
8689 Inst->eraseFromParent();
8693 // ConstantProp instruction if trivially constant.
8694 if (Constant *C = ConstantFoldInstruction(Inst)) {
8695 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8696 C = OptimizeConstantExpr(CE, TD);
8697 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
8698 Inst->replaceAllUsesWith(C);
8700 Inst->eraseFromParent();
8704 WorkList.push_back(Inst);
8707 // Recursively visit successors. If this is a branch or switch on a constant,
8708 // only visit the reachable successor.
8709 TerminatorInst *TI = BB->getTerminator();
8710 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8711 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8712 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
8713 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8717 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8718 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8719 // See if this is an explicit destination.
8720 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8721 if (SI->getCaseValue(i) == Cond) {
8722 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
8726 // Otherwise it is the default destination.
8727 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
8732 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
8733 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
8736 bool InstCombiner::runOnFunction(Function &F) {
8737 bool Changed = false;
8738 TD = &getAnalysis<TargetData>();
8741 // Do a depth-first traversal of the function, populate the worklist with
8742 // the reachable instructions. Ignore blocks that are not reachable. Keep
8743 // track of which blocks we visit.
8744 std::set<BasicBlock*> Visited;
8745 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
8747 // Do a quick scan over the function. If we find any blocks that are
8748 // unreachable, remove any instructions inside of them. This prevents
8749 // the instcombine code from having to deal with some bad special cases.
8750 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8751 if (!Visited.count(BB)) {
8752 Instruction *Term = BB->getTerminator();
8753 while (Term != BB->begin()) { // Remove instrs bottom-up
8754 BasicBlock::iterator I = Term; --I;
8756 DOUT << "IC: DCE: " << *I;
8759 if (!I->use_empty())
8760 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8761 I->eraseFromParent();
8766 while (!WorkList.empty()) {
8767 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8768 WorkList.pop_back();
8770 // Check to see if we can DCE the instruction.
8771 if (isInstructionTriviallyDead(I)) {
8772 // Add operands to the worklist.
8773 if (I->getNumOperands() < 4)
8774 AddUsesToWorkList(*I);
8777 DOUT << "IC: DCE: " << *I;
8779 I->eraseFromParent();
8780 removeFromWorkList(I);
8784 // Instruction isn't dead, see if we can constant propagate it.
8785 if (Constant *C = ConstantFoldInstruction(I)) {
8786 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8787 C = OptimizeConstantExpr(CE, TD);
8788 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
8790 // Add operands to the worklist.
8791 AddUsesToWorkList(*I);
8792 ReplaceInstUsesWith(*I, C);
8795 I->eraseFromParent();
8796 removeFromWorkList(I);
8800 // See if we can trivially sink this instruction to a successor basic block.
8801 if (I->hasOneUse()) {
8802 BasicBlock *BB = I->getParent();
8803 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8804 if (UserParent != BB) {
8805 bool UserIsSuccessor = false;
8806 // See if the user is one of our successors.
8807 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8808 if (*SI == UserParent) {
8809 UserIsSuccessor = true;
8813 // If the user is one of our immediate successors, and if that successor
8814 // only has us as a predecessors (we'd have to split the critical edge
8815 // otherwise), we can keep going.
8816 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8817 next(pred_begin(UserParent)) == pred_end(UserParent))
8818 // Okay, the CFG is simple enough, try to sink this instruction.
8819 Changed |= TryToSinkInstruction(I, UserParent);
8823 // Now that we have an instruction, try combining it to simplify it...
8824 if (Instruction *Result = visit(*I)) {
8826 // Should we replace the old instruction with a new one?
8828 DOUT << "IC: Old = " << *I
8829 << " New = " << *Result;
8831 // Everything uses the new instruction now.
8832 I->replaceAllUsesWith(Result);
8834 // Push the new instruction and any users onto the worklist.
8835 WorkList.push_back(Result);
8836 AddUsersToWorkList(*Result);
8838 // Move the name to the new instruction first...
8839 std::string OldName = I->getName(); I->setName("");
8840 Result->setName(OldName);
8842 // Insert the new instruction into the basic block...
8843 BasicBlock *InstParent = I->getParent();
8844 BasicBlock::iterator InsertPos = I;
8846 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8847 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8850 InstParent->getInstList().insert(InsertPos, Result);
8852 // Make sure that we reprocess all operands now that we reduced their
8854 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8855 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8856 WorkList.push_back(OpI);
8858 // Instructions can end up on the worklist more than once. Make sure
8859 // we do not process an instruction that has been deleted.
8860 removeFromWorkList(I);
8862 // Erase the old instruction.
8863 InstParent->getInstList().erase(I);
8865 DOUT << "IC: MOD = " << *I;
8867 // If the instruction was modified, it's possible that it is now dead.
8868 // if so, remove it.
8869 if (isInstructionTriviallyDead(I)) {
8870 // Make sure we process all operands now that we are reducing their
8872 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8873 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8874 WorkList.push_back(OpI);
8876 // Instructions may end up in the worklist more than once. Erase all
8877 // occurrences of this instruction.
8878 removeFromWorkList(I);
8879 I->eraseFromParent();
8881 WorkList.push_back(Result);
8882 AddUsersToWorkList(*Result);
8892 FunctionPass *llvm::createInstructionCombiningPass() {
8893 return new InstCombiner();