1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All SetCC instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/ADT/DepthFirstIterator.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
57 using namespace llvm::PatternMatch;
60 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
64 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
66 class InstCombiner : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(Value &I) {
77 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
79 WorkList.push_back(cast<Instruction>(*UI));
82 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
91 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
94 virtual bool runOnFunction(Function &F);
96 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97 AU.addRequired<TargetData>();
101 TargetData &getTargetData() const { return *TD; }
103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
106 // null - No change was made
107 // I - Change was made, I is still valid, I may be dead though
108 // otherwise - Change was made, replace I with returned instruction
110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
123 Instruction *visitShiftInst(ShiftInst &I);
124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
126 Instruction *visitCastInst(CastInst &CI);
127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
129 Instruction *visitSelectInst(SelectInst &CI);
130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
134 Instruction *visitAllocationInst(AllocationInst &AI);
135 Instruction *visitFreeInst(FreeInst &FI);
136 Instruction *visitLoadInst(LoadInst &LI);
137 Instruction *visitStoreInst(StoreInst &SI);
138 Instruction *visitBranchInst(BranchInst &BI);
139 Instruction *visitSwitchInst(SwitchInst &SI);
140 Instruction *visitInsertElementInst(InsertElementInst &IE);
141 Instruction *visitExtractElementInst(ExtractElementInst &EI);
142 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
144 // visitInstruction - Specify what to return for unhandled instructions...
145 Instruction *visitInstruction(Instruction &I) { return 0; }
148 Instruction *visitCallSite(CallSite CS);
149 bool transformConstExprCastCall(CallSite CS);
152 // InsertNewInstBefore - insert an instruction New before instruction Old
153 // in the program. Add the new instruction to the worklist.
155 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
156 assert(New && New->getParent() == 0 &&
157 "New instruction already inserted into a basic block!");
158 BasicBlock *BB = Old.getParent();
159 BB->getInstList().insert(&Old, New); // Insert inst
160 WorkList.push_back(New); // Add to worklist
164 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
165 /// This also adds the cast to the worklist. Finally, this returns the
167 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
168 if (V->getType() == Ty) return V;
170 if (Constant *CV = dyn_cast<Constant>(V))
171 return ConstantExpr::getCast(CV, Ty);
173 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
174 WorkList.push_back(C);
178 // ReplaceInstUsesWith - This method is to be used when an instruction is
179 // found to be dead, replacable with another preexisting expression. Here
180 // we add all uses of I to the worklist, replace all uses of I with the new
181 // value, then return I, so that the inst combiner will know that I was
184 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
185 AddUsersToWorkList(I); // Add all modified instrs to worklist
187 I.replaceAllUsesWith(V);
190 // If we are replacing the instruction with itself, this must be in a
191 // segment of unreachable code, so just clobber the instruction.
192 I.replaceAllUsesWith(UndefValue::get(I.getType()));
197 // UpdateValueUsesWith - This method is to be used when an value is
198 // found to be replacable with another preexisting expression or was
199 // updated. Here we add all uses of I to the worklist, replace all uses of
200 // I with the new value (unless the instruction was just updated), then
201 // return true, so that the inst combiner will know that I was modified.
203 bool UpdateValueUsesWith(Value *Old, Value *New) {
204 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
206 Old->replaceAllUsesWith(New);
207 if (Instruction *I = dyn_cast<Instruction>(Old))
208 WorkList.push_back(I);
209 if (Instruction *I = dyn_cast<Instruction>(New))
210 WorkList.push_back(I);
214 // EraseInstFromFunction - When dealing with an instruction that has side
215 // effects or produces a void value, we can't rely on DCE to delete the
216 // instruction. Instead, visit methods should return the value returned by
218 Instruction *EraseInstFromFunction(Instruction &I) {
219 assert(I.use_empty() && "Cannot erase instruction that is used!");
220 AddUsesToWorkList(I);
221 removeFromWorkList(&I);
223 return 0; // Don't do anything with FI
227 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
228 /// InsertBefore instruction. This is specialized a bit to avoid inserting
229 /// casts that are known to not do anything...
231 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
232 Instruction *InsertBefore);
234 // SimplifyCommutative - This performs a few simplifications for commutative
236 bool SimplifyCommutative(BinaryOperator &I);
238 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
239 uint64_t &KnownZero, uint64_t &KnownOne,
242 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
243 // PHI node as operand #0, see if we can fold the instruction into the PHI
244 // (which is only possible if all operands to the PHI are constants).
245 Instruction *FoldOpIntoPhi(Instruction &I);
247 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
248 // operator and they all are only used by the PHI, PHI together their
249 // inputs, and do the operation once, to the result of the PHI.
250 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
252 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
253 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
255 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
256 bool isSub, Instruction &I);
257 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
258 bool Inside, Instruction &IB);
259 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
262 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
265 // getComplexity: Assign a complexity or rank value to LLVM Values...
266 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
267 static unsigned getComplexity(Value *V) {
268 if (isa<Instruction>(V)) {
269 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
273 if (isa<Argument>(V)) return 3;
274 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
277 // isOnlyUse - Return true if this instruction will be deleted if we stop using
279 static bool isOnlyUse(Value *V) {
280 return V->hasOneUse() || isa<Constant>(V);
283 // getPromotedType - Return the specified type promoted as it would be to pass
284 // though a va_arg area...
285 static const Type *getPromotedType(const Type *Ty) {
286 switch (Ty->getTypeID()) {
287 case Type::SByteTyID:
288 case Type::ShortTyID: return Type::IntTy;
289 case Type::UByteTyID:
290 case Type::UShortTyID: return Type::UIntTy;
291 case Type::FloatTyID: return Type::DoubleTy;
296 /// isCast - If the specified operand is a CastInst or a constant expr cast,
297 /// return the operand value, otherwise return null.
298 static Value *isCast(Value *V) {
299 if (CastInst *I = dyn_cast<CastInst>(V))
300 return I->getOperand(0);
301 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
302 if (CE->getOpcode() == Instruction::Cast)
303 return CE->getOperand(0);
307 // SimplifyCommutative - This performs a few simplifications for commutative
310 // 1. Order operands such that they are listed from right (least complex) to
311 // left (most complex). This puts constants before unary operators before
314 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
315 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
317 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
318 bool Changed = false;
319 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
320 Changed = !I.swapOperands();
322 if (!I.isAssociative()) return Changed;
323 Instruction::BinaryOps Opcode = I.getOpcode();
324 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
325 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
326 if (isa<Constant>(I.getOperand(1))) {
327 Constant *Folded = ConstantExpr::get(I.getOpcode(),
328 cast<Constant>(I.getOperand(1)),
329 cast<Constant>(Op->getOperand(1)));
330 I.setOperand(0, Op->getOperand(0));
331 I.setOperand(1, Folded);
333 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
334 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
335 isOnlyUse(Op) && isOnlyUse(Op1)) {
336 Constant *C1 = cast<Constant>(Op->getOperand(1));
337 Constant *C2 = cast<Constant>(Op1->getOperand(1));
339 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
340 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
341 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
344 WorkList.push_back(New);
345 I.setOperand(0, New);
346 I.setOperand(1, Folded);
353 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
354 // if the LHS is a constant zero (which is the 'negate' form).
356 static inline Value *dyn_castNegVal(Value *V) {
357 if (BinaryOperator::isNeg(V))
358 return BinaryOperator::getNegArgument(V);
360 // Constants can be considered to be negated values if they can be folded.
361 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
362 return ConstantExpr::getNeg(C);
366 static inline Value *dyn_castNotVal(Value *V) {
367 if (BinaryOperator::isNot(V))
368 return BinaryOperator::getNotArgument(V);
370 // Constants can be considered to be not'ed values...
371 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
372 return ConstantExpr::getNot(C);
376 // dyn_castFoldableMul - If this value is a multiply that can be folded into
377 // other computations (because it has a constant operand), return the
378 // non-constant operand of the multiply, and set CST to point to the multiplier.
379 // Otherwise, return null.
381 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
382 if (V->hasOneUse() && V->getType()->isInteger())
383 if (Instruction *I = dyn_cast<Instruction>(V)) {
384 if (I->getOpcode() == Instruction::Mul)
385 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
386 return I->getOperand(0);
387 if (I->getOpcode() == Instruction::Shl)
388 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
389 // The multiplier is really 1 << CST.
390 Constant *One = ConstantInt::get(V->getType(), 1);
391 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
392 return I->getOperand(0);
398 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
399 /// expression, return it.
400 static User *dyn_castGetElementPtr(Value *V) {
401 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
403 if (CE->getOpcode() == Instruction::GetElementPtr)
404 return cast<User>(V);
408 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
409 static ConstantInt *AddOne(ConstantInt *C) {
410 return cast<ConstantInt>(ConstantExpr::getAdd(C,
411 ConstantInt::get(C->getType(), 1)));
413 static ConstantInt *SubOne(ConstantInt *C) {
414 return cast<ConstantInt>(ConstantExpr::getSub(C,
415 ConstantInt::get(C->getType(), 1)));
418 /// GetConstantInType - Return a ConstantInt with the specified type and value.
420 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
421 if (Ty->isUnsigned())
422 return ConstantUInt::get(Ty, Val);
423 else if (Ty->getTypeID() == Type::BoolTyID)
424 return ConstantBool::get(Val);
426 SVal <<= 64-Ty->getPrimitiveSizeInBits();
427 SVal >>= 64-Ty->getPrimitiveSizeInBits();
428 return ConstantSInt::get(Ty, SVal);
432 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
433 /// known to be either zero or one and return them in the KnownZero/KnownOne
434 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
436 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
437 uint64_t &KnownOne, unsigned Depth = 0) {
438 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
439 // we cannot optimize based on the assumption that it is zero without changing
440 // it to be an explicit zero. If we don't change it to zero, other code could
441 // optimized based on the contradictory assumption that it is non-zero.
442 // Because instcombine aggressively folds operations with undef args anyway,
443 // this won't lose us code quality.
444 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
445 // We know all of the bits for a constant!
446 KnownOne = CI->getZExtValue() & Mask;
447 KnownZero = ~KnownOne & Mask;
451 KnownZero = KnownOne = 0; // Don't know anything.
452 if (Depth == 6 || Mask == 0)
453 return; // Limit search depth.
455 uint64_t KnownZero2, KnownOne2;
456 Instruction *I = dyn_cast<Instruction>(V);
459 switch (I->getOpcode()) {
460 case Instruction::And:
461 // If either the LHS or the RHS are Zero, the result is zero.
462 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
464 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
465 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
466 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
468 // Output known-1 bits are only known if set in both the LHS & RHS.
469 KnownOne &= KnownOne2;
470 // Output known-0 are known to be clear if zero in either the LHS | RHS.
471 KnownZero |= KnownZero2;
473 case Instruction::Or:
474 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
476 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
477 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
478 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
480 // Output known-0 bits are only known if clear in both the LHS & RHS.
481 KnownZero &= KnownZero2;
482 // Output known-1 are known to be set if set in either the LHS | RHS.
483 KnownOne |= KnownOne2;
485 case Instruction::Xor: {
486 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
487 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
488 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
489 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
491 // Output known-0 bits are known if clear or set in both the LHS & RHS.
492 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
493 // Output known-1 are known to be set if set in only one of the LHS, RHS.
494 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
495 KnownZero = KnownZeroOut;
498 case Instruction::Select:
499 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
500 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
501 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
502 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
504 // Only known if known in both the LHS and RHS.
505 KnownOne &= KnownOne2;
506 KnownZero &= KnownZero2;
508 case Instruction::Cast: {
509 const Type *SrcTy = I->getOperand(0)->getType();
510 if (!SrcTy->isIntegral()) return;
512 // If this is an integer truncate or noop, just look in the input.
513 if (SrcTy->getPrimitiveSizeInBits() >=
514 I->getType()->getPrimitiveSizeInBits()) {
515 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
519 // Sign or Zero extension. Compute the bits in the result that are not
520 // present in the input.
521 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
522 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
524 // Handle zero extension.
525 if (!SrcTy->isSigned()) {
526 Mask &= SrcTy->getIntegralTypeMask();
527 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
528 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
529 // The top bits are known to be zero.
530 KnownZero |= NewBits;
533 Mask &= SrcTy->getIntegralTypeMask();
534 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
535 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
537 // If the sign bit of the input is known set or clear, then we know the
538 // top bits of the result.
539 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
540 if (KnownZero & InSignBit) { // Input sign bit known zero
541 KnownZero |= NewBits;
542 KnownOne &= ~NewBits;
543 } else if (KnownOne & InSignBit) { // Input sign bit known set
545 KnownZero &= ~NewBits;
546 } else { // Input sign bit unknown
547 KnownZero &= ~NewBits;
548 KnownOne &= ~NewBits;
553 case Instruction::Shl:
554 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
555 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
556 Mask >>= SA->getValue();
557 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
558 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
559 KnownZero <<= SA->getValue();
560 KnownOne <<= SA->getValue();
561 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
565 case Instruction::Shr:
566 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
567 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
568 // Compute the new bits that are at the top now.
569 uint64_t HighBits = (1ULL << SA->getValue())-1;
570 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
572 if (I->getType()->isUnsigned()) { // Unsigned shift right.
573 Mask <<= SA->getValue();
574 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
575 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
576 KnownZero >>= SA->getValue();
577 KnownOne >>= SA->getValue();
578 KnownZero |= HighBits; // high bits known zero.
580 Mask <<= SA->getValue();
581 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
582 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
583 KnownZero >>= SA->getValue();
584 KnownOne >>= SA->getValue();
586 // Handle the sign bits.
587 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
588 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
590 if (KnownZero & SignBit) { // New bits are known zero.
591 KnownZero |= HighBits;
592 } else if (KnownOne & SignBit) { // New bits are known one.
593 KnownOne |= HighBits;
602 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
603 /// this predicate to simplify operations downstream. Mask is known to be zero
604 /// for bits that V cannot have.
605 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
606 uint64_t KnownZero, KnownOne;
607 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
608 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
609 return (KnownZero & Mask) == Mask;
612 /// ShrinkDemandedConstant - Check to see if the specified operand of the
613 /// specified instruction is a constant integer. If so, check to see if there
614 /// are any bits set in the constant that are not demanded. If so, shrink the
615 /// constant and return true.
616 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
618 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
619 if (!OpC) return false;
621 // If there are no bits set that aren't demanded, nothing to do.
622 if ((~Demanded & OpC->getZExtValue()) == 0)
625 // This is producing any bits that are not needed, shrink the RHS.
626 uint64_t Val = Demanded & OpC->getZExtValue();
627 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
631 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
632 // set of known zero and one bits, compute the maximum and minimum values that
633 // could have the specified known zero and known one bits, returning them in
635 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
638 int64_t &Min, int64_t &Max) {
639 uint64_t TypeBits = Ty->getIntegralTypeMask();
640 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
642 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
644 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
645 // bit if it is unknown.
647 Max = KnownOne|UnknownBits;
649 if (SignBit & UnknownBits) { // Sign bit is unknown
654 // Sign extend the min/max values.
655 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
656 Min = (Min << ShAmt) >> ShAmt;
657 Max = (Max << ShAmt) >> ShAmt;
660 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
661 // a set of known zero and one bits, compute the maximum and minimum values that
662 // could have the specified known zero and known one bits, returning them in
664 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
669 uint64_t TypeBits = Ty->getIntegralTypeMask();
670 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
672 // The minimum value is when the unknown bits are all zeros.
674 // The maximum value is when the unknown bits are all ones.
675 Max = KnownOne|UnknownBits;
679 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
680 /// DemandedMask bits of the result of V are ever used downstream. If we can
681 /// use this information to simplify V, do so and return true. Otherwise,
682 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
683 /// the expression (used to simplify the caller). The KnownZero/One bits may
684 /// only be accurate for those bits in the DemandedMask.
685 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
686 uint64_t &KnownZero, uint64_t &KnownOne,
688 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
689 // We know all of the bits for a constant!
690 KnownOne = CI->getZExtValue() & DemandedMask;
691 KnownZero = ~KnownOne & DemandedMask;
695 KnownZero = KnownOne = 0;
696 if (!V->hasOneUse()) { // Other users may use these bits.
697 if (Depth != 0) { // Not at the root.
698 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
699 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
702 // If this is the root being simplified, allow it to have multiple uses,
703 // just set the DemandedMask to all bits.
704 DemandedMask = V->getType()->getIntegralTypeMask();
705 } else if (DemandedMask == 0) { // Not demanding any bits from V.
706 if (V != UndefValue::get(V->getType()))
707 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
709 } else if (Depth == 6) { // Limit search depth.
713 Instruction *I = dyn_cast<Instruction>(V);
714 if (!I) return false; // Only analyze instructions.
716 uint64_t KnownZero2, KnownOne2;
717 switch (I->getOpcode()) {
719 case Instruction::And:
720 // If either the LHS or the RHS are Zero, the result is zero.
721 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
722 KnownZero, KnownOne, Depth+1))
724 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
726 // If something is known zero on the RHS, the bits aren't demanded on the
728 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
729 KnownZero2, KnownOne2, Depth+1))
731 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
733 // If all of the demanded bits are known one on one side, return the other.
734 // These bits cannot contribute to the result of the 'and'.
735 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
736 return UpdateValueUsesWith(I, I->getOperand(0));
737 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
738 return UpdateValueUsesWith(I, I->getOperand(1));
740 // If all of the demanded bits in the inputs are known zeros, return zero.
741 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
742 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
744 // If the RHS is a constant, see if we can simplify it.
745 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
746 return UpdateValueUsesWith(I, I);
748 // Output known-1 bits are only known if set in both the LHS & RHS.
749 KnownOne &= KnownOne2;
750 // Output known-0 are known to be clear if zero in either the LHS | RHS.
751 KnownZero |= KnownZero2;
753 case Instruction::Or:
754 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
755 KnownZero, KnownOne, Depth+1))
757 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
758 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
759 KnownZero2, KnownOne2, Depth+1))
761 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
763 // If all of the demanded bits are known zero on one side, return the other.
764 // These bits cannot contribute to the result of the 'or'.
765 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
766 return UpdateValueUsesWith(I, I->getOperand(0));
767 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
768 return UpdateValueUsesWith(I, I->getOperand(1));
770 // If all of the potentially set bits on one side are known to be set on
771 // the other side, just use the 'other' side.
772 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
773 (DemandedMask & (~KnownZero)))
774 return UpdateValueUsesWith(I, I->getOperand(0));
775 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
776 (DemandedMask & (~KnownZero2)))
777 return UpdateValueUsesWith(I, I->getOperand(1));
779 // If the RHS is a constant, see if we can simplify it.
780 if (ShrinkDemandedConstant(I, 1, DemandedMask))
781 return UpdateValueUsesWith(I, I);
783 // Output known-0 bits are only known if clear in both the LHS & RHS.
784 KnownZero &= KnownZero2;
785 // Output known-1 are known to be set if set in either the LHS | RHS.
786 KnownOne |= KnownOne2;
788 case Instruction::Xor: {
789 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
790 KnownZero, KnownOne, Depth+1))
792 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
793 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
794 KnownZero2, KnownOne2, Depth+1))
796 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
798 // If all of the demanded bits are known zero on one side, return the other.
799 // These bits cannot contribute to the result of the 'xor'.
800 if ((DemandedMask & KnownZero) == DemandedMask)
801 return UpdateValueUsesWith(I, I->getOperand(0));
802 if ((DemandedMask & KnownZero2) == DemandedMask)
803 return UpdateValueUsesWith(I, I->getOperand(1));
805 // Output known-0 bits are known if clear or set in both the LHS & RHS.
806 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
807 // Output known-1 are known to be set if set in only one of the LHS, RHS.
808 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
810 // If all of the unknown bits are known to be zero on one side or the other
811 // (but not both) turn this into an *inclusive* or.
812 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
813 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
814 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
816 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
818 InsertNewInstBefore(Or, *I);
819 return UpdateValueUsesWith(I, Or);
823 // If all of the demanded bits on one side are known, and all of the set
824 // bits on that side are also known to be set on the other side, turn this
825 // into an AND, as we know the bits will be cleared.
826 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
827 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
828 if ((KnownOne & KnownOne2) == KnownOne) {
829 Constant *AndC = GetConstantInType(I->getType(),
830 ~KnownOne & DemandedMask);
832 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
833 InsertNewInstBefore(And, *I);
834 return UpdateValueUsesWith(I, And);
838 // If the RHS is a constant, see if we can simplify it.
839 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
840 if (ShrinkDemandedConstant(I, 1, DemandedMask))
841 return UpdateValueUsesWith(I, I);
843 KnownZero = KnownZeroOut;
844 KnownOne = KnownOneOut;
847 case Instruction::Select:
848 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
849 KnownZero, KnownOne, Depth+1))
851 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
852 KnownZero2, KnownOne2, Depth+1))
854 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
855 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
857 // If the operands are constants, see if we can simplify them.
858 if (ShrinkDemandedConstant(I, 1, DemandedMask))
859 return UpdateValueUsesWith(I, I);
860 if (ShrinkDemandedConstant(I, 2, DemandedMask))
861 return UpdateValueUsesWith(I, I);
863 // Only known if known in both the LHS and RHS.
864 KnownOne &= KnownOne2;
865 KnownZero &= KnownZero2;
867 case Instruction::Cast: {
868 const Type *SrcTy = I->getOperand(0)->getType();
869 if (!SrcTy->isIntegral()) return false;
871 // If this is an integer truncate or noop, just look in the input.
872 if (SrcTy->getPrimitiveSizeInBits() >=
873 I->getType()->getPrimitiveSizeInBits()) {
874 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
875 KnownZero, KnownOne, Depth+1))
877 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
881 // Sign or Zero extension. Compute the bits in the result that are not
882 // present in the input.
883 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
884 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
886 // Handle zero extension.
887 if (!SrcTy->isSigned()) {
888 DemandedMask &= SrcTy->getIntegralTypeMask();
889 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
890 KnownZero, KnownOne, Depth+1))
892 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
893 // The top bits are known to be zero.
894 KnownZero |= NewBits;
897 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
898 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
900 // If any of the sign extended bits are demanded, we know that the sign
902 if (NewBits & DemandedMask)
903 InputDemandedBits |= InSignBit;
905 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
906 KnownZero, KnownOne, Depth+1))
908 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
910 // If the sign bit of the input is known set or clear, then we know the
911 // top bits of the result.
913 // If the input sign bit is known zero, or if the NewBits are not demanded
914 // convert this into a zero extension.
915 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
916 // Convert to unsigned first.
918 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
919 I->getOperand(0)->getName());
920 InsertNewInstBefore(NewVal, *I);
921 // Then cast that to the destination type.
922 NewVal = new CastInst(NewVal, I->getType(), I->getName());
923 InsertNewInstBefore(NewVal, *I);
924 return UpdateValueUsesWith(I, NewVal);
925 } else if (KnownOne & InSignBit) { // Input sign bit known set
927 KnownZero &= ~NewBits;
928 } else { // Input sign bit unknown
929 KnownZero &= ~NewBits;
930 KnownOne &= ~NewBits;
935 case Instruction::Shl:
936 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
937 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
938 KnownZero, KnownOne, Depth+1))
940 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
941 KnownZero <<= SA->getValue();
942 KnownOne <<= SA->getValue();
943 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
946 case Instruction::Shr:
947 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
948 unsigned ShAmt = SA->getValue();
950 // Compute the new bits that are at the top now.
951 uint64_t HighBits = (1ULL << ShAmt)-1;
952 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
953 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
954 if (I->getType()->isUnsigned()) { // Unsigned shift right.
955 if (SimplifyDemandedBits(I->getOperand(0),
956 (DemandedMask << ShAmt) & TypeMask,
957 KnownZero, KnownOne, Depth+1))
959 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
960 KnownZero &= TypeMask;
961 KnownOne &= TypeMask;
964 KnownZero |= HighBits; // high bits known zero.
965 } else { // Signed shift right.
966 if (SimplifyDemandedBits(I->getOperand(0),
967 (DemandedMask << ShAmt) & TypeMask,
968 KnownZero, KnownOne, Depth+1))
970 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
971 KnownZero &= TypeMask;
972 KnownOne &= TypeMask;
973 KnownZero >>= SA->getValue();
974 KnownOne >>= SA->getValue();
976 // Handle the sign bits.
977 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
978 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
980 // If the input sign bit is known to be zero, or if none of the top bits
981 // are demanded, turn this into an unsigned shift right.
982 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
983 // Convert the input to unsigned.
985 NewVal = new CastInst(I->getOperand(0),
986 I->getType()->getUnsignedVersion(),
987 I->getOperand(0)->getName());
988 InsertNewInstBefore(NewVal, *I);
989 // Perform the unsigned shift right.
990 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
991 InsertNewInstBefore(NewVal, *I);
992 // Then cast that to the destination type.
993 NewVal = new CastInst(NewVal, I->getType(), I->getName());
994 InsertNewInstBefore(NewVal, *I);
995 return UpdateValueUsesWith(I, NewVal);
996 } else if (KnownOne & SignBit) { // New bits are known one.
997 KnownOne |= HighBits;
1004 // If the client is only demanding bits that we know, return the known
1006 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1007 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1011 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1012 // true when both operands are equal...
1014 static bool isTrueWhenEqual(Instruction &I) {
1015 return I.getOpcode() == Instruction::SetEQ ||
1016 I.getOpcode() == Instruction::SetGE ||
1017 I.getOpcode() == Instruction::SetLE;
1020 /// AssociativeOpt - Perform an optimization on an associative operator. This
1021 /// function is designed to check a chain of associative operators for a
1022 /// potential to apply a certain optimization. Since the optimization may be
1023 /// applicable if the expression was reassociated, this checks the chain, then
1024 /// reassociates the expression as necessary to expose the optimization
1025 /// opportunity. This makes use of a special Functor, which must define
1026 /// 'shouldApply' and 'apply' methods.
1028 template<typename Functor>
1029 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1030 unsigned Opcode = Root.getOpcode();
1031 Value *LHS = Root.getOperand(0);
1033 // Quick check, see if the immediate LHS matches...
1034 if (F.shouldApply(LHS))
1035 return F.apply(Root);
1037 // Otherwise, if the LHS is not of the same opcode as the root, return.
1038 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1039 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1040 // Should we apply this transform to the RHS?
1041 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1043 // If not to the RHS, check to see if we should apply to the LHS...
1044 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1045 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1049 // If the functor wants to apply the optimization to the RHS of LHSI,
1050 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1052 BasicBlock *BB = Root.getParent();
1054 // Now all of the instructions are in the current basic block, go ahead
1055 // and perform the reassociation.
1056 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1058 // First move the selected RHS to the LHS of the root...
1059 Root.setOperand(0, LHSI->getOperand(1));
1061 // Make what used to be the LHS of the root be the user of the root...
1062 Value *ExtraOperand = TmpLHSI->getOperand(1);
1063 if (&Root == TmpLHSI) {
1064 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1067 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1068 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1069 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1070 BasicBlock::iterator ARI = &Root; ++ARI;
1071 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1074 // Now propagate the ExtraOperand down the chain of instructions until we
1076 while (TmpLHSI != LHSI) {
1077 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1078 // Move the instruction to immediately before the chain we are
1079 // constructing to avoid breaking dominance properties.
1080 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1081 BB->getInstList().insert(ARI, NextLHSI);
1084 Value *NextOp = NextLHSI->getOperand(1);
1085 NextLHSI->setOperand(1, ExtraOperand);
1087 ExtraOperand = NextOp;
1090 // Now that the instructions are reassociated, have the functor perform
1091 // the transformation...
1092 return F.apply(Root);
1095 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1101 // AddRHS - Implements: X + X --> X << 1
1104 AddRHS(Value *rhs) : RHS(rhs) {}
1105 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1106 Instruction *apply(BinaryOperator &Add) const {
1107 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1108 ConstantInt::get(Type::UByteTy, 1));
1112 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1114 struct AddMaskingAnd {
1116 AddMaskingAnd(Constant *c) : C2(c) {}
1117 bool shouldApply(Value *LHS) const {
1119 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1120 ConstantExpr::getAnd(C1, C2)->isNullValue();
1122 Instruction *apply(BinaryOperator &Add) const {
1123 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1127 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1129 if (isa<CastInst>(I)) {
1130 if (Constant *SOC = dyn_cast<Constant>(SO))
1131 return ConstantExpr::getCast(SOC, I.getType());
1133 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1134 SO->getName() + ".cast"), I);
1137 // Figure out if the constant is the left or the right argument.
1138 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1139 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1141 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1143 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1144 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1147 Value *Op0 = SO, *Op1 = ConstOperand;
1149 std::swap(Op0, Op1);
1151 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1152 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1153 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1154 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1156 assert(0 && "Unknown binary instruction type!");
1159 return IC->InsertNewInstBefore(New, I);
1162 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1163 // constant as the other operand, try to fold the binary operator into the
1164 // select arguments. This also works for Cast instructions, which obviously do
1165 // not have a second operand.
1166 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1168 // Don't modify shared select instructions
1169 if (!SI->hasOneUse()) return 0;
1170 Value *TV = SI->getOperand(1);
1171 Value *FV = SI->getOperand(2);
1173 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1174 // Bool selects with constant operands can be folded to logical ops.
1175 if (SI->getType() == Type::BoolTy) return 0;
1177 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1178 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1180 return new SelectInst(SI->getCondition(), SelectTrueVal,
1187 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1188 /// node as operand #0, see if we can fold the instruction into the PHI (which
1189 /// is only possible if all operands to the PHI are constants).
1190 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1191 PHINode *PN = cast<PHINode>(I.getOperand(0));
1192 unsigned NumPHIValues = PN->getNumIncomingValues();
1193 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1194 !isa<Constant>(PN->getIncomingValue(0))) return 0;
1196 // Check to see if all of the operands of the PHI are constants. If not, we
1197 // cannot do the transformation.
1198 for (unsigned i = 1; i != NumPHIValues; ++i)
1199 if (!isa<Constant>(PN->getIncomingValue(i)))
1202 // Okay, we can do the transformation: create the new PHI node.
1203 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1205 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1206 InsertNewInstBefore(NewPN, *PN);
1208 // Next, add all of the operands to the PHI.
1209 if (I.getNumOperands() == 2) {
1210 Constant *C = cast<Constant>(I.getOperand(1));
1211 for (unsigned i = 0; i != NumPHIValues; ++i) {
1212 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1213 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1214 PN->getIncomingBlock(i));
1217 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1218 const Type *RetTy = I.getType();
1219 for (unsigned i = 0; i != NumPHIValues; ++i) {
1220 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1221 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1222 PN->getIncomingBlock(i));
1225 return ReplaceInstUsesWith(I, NewPN);
1228 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1229 bool Changed = SimplifyCommutative(I);
1230 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1232 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1233 // X + undef -> undef
1234 if (isa<UndefValue>(RHS))
1235 return ReplaceInstUsesWith(I, RHS);
1238 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1239 if (RHSC->isNullValue())
1240 return ReplaceInstUsesWith(I, LHS);
1241 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1242 if (CFP->isExactlyValue(-0.0))
1243 return ReplaceInstUsesWith(I, LHS);
1246 // X + (signbit) --> X ^ signbit
1247 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1248 uint64_t Val = CI->getZExtValue();
1249 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1250 return BinaryOperator::createXor(LHS, RHS);
1253 if (isa<PHINode>(LHS))
1254 if (Instruction *NV = FoldOpIntoPhi(I))
1257 ConstantInt *XorRHS = 0;
1259 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1260 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1261 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1262 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1264 uint64_t C0080Val = 1ULL << 31;
1265 int64_t CFF80Val = -C0080Val;
1268 if (TySizeBits > Size) {
1270 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1271 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1272 if (RHSSExt == CFF80Val) {
1273 if (XorRHS->getZExtValue() == C0080Val)
1275 } else if (RHSZExt == C0080Val) {
1276 if (XorRHS->getSExtValue() == CFF80Val)
1280 // This is a sign extend if the top bits are known zero.
1281 uint64_t Mask = ~0ULL;
1282 Mask <<= 64-(TySizeBits-Size);
1283 Mask &= XorLHS->getType()->getIntegralTypeMask();
1284 if (!MaskedValueIsZero(XorLHS, Mask))
1285 Size = 0; // Not a sign ext, but can't be any others either.
1292 } while (Size >= 8);
1295 const Type *MiddleType = 0;
1298 case 32: MiddleType = Type::IntTy; break;
1299 case 16: MiddleType = Type::ShortTy; break;
1300 case 8: MiddleType = Type::SByteTy; break;
1303 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1304 InsertNewInstBefore(NewTrunc, I);
1305 return new CastInst(NewTrunc, I.getType());
1311 if (I.getType()->isInteger()) {
1312 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1314 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1315 if (RHSI->getOpcode() == Instruction::Sub)
1316 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1317 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1319 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1320 if (LHSI->getOpcode() == Instruction::Sub)
1321 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1322 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1327 if (Value *V = dyn_castNegVal(LHS))
1328 return BinaryOperator::createSub(RHS, V);
1331 if (!isa<Constant>(RHS))
1332 if (Value *V = dyn_castNegVal(RHS))
1333 return BinaryOperator::createSub(LHS, V);
1337 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1338 if (X == RHS) // X*C + X --> X * (C+1)
1339 return BinaryOperator::createMul(RHS, AddOne(C2));
1341 // X*C1 + X*C2 --> X * (C1+C2)
1343 if (X == dyn_castFoldableMul(RHS, C1))
1344 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1347 // X + X*C --> X * (C+1)
1348 if (dyn_castFoldableMul(RHS, C2) == LHS)
1349 return BinaryOperator::createMul(LHS, AddOne(C2));
1352 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1353 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1354 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1356 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1358 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1359 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1360 return BinaryOperator::createSub(C, X);
1363 // (X & FF00) + xx00 -> (X+xx00) & FF00
1364 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1365 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1366 if (Anded == CRHS) {
1367 // See if all bits from the first bit set in the Add RHS up are included
1368 // in the mask. First, get the rightmost bit.
1369 uint64_t AddRHSV = CRHS->getRawValue();
1371 // Form a mask of all bits from the lowest bit added through the top.
1372 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1373 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1375 // See if the and mask includes all of these bits.
1376 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
1378 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1379 // Okay, the xform is safe. Insert the new add pronto.
1380 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1381 LHS->getName()), I);
1382 return BinaryOperator::createAnd(NewAdd, C2);
1387 // Try to fold constant add into select arguments.
1388 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1389 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1393 return Changed ? &I : 0;
1396 // isSignBit - Return true if the value represented by the constant only has the
1397 // highest order bit set.
1398 static bool isSignBit(ConstantInt *CI) {
1399 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1400 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1403 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1405 static Value *RemoveNoopCast(Value *V) {
1406 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1407 const Type *CTy = CI->getType();
1408 const Type *OpTy = CI->getOperand(0)->getType();
1409 if (CTy->isInteger() && OpTy->isInteger()) {
1410 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1411 return RemoveNoopCast(CI->getOperand(0));
1412 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1413 return RemoveNoopCast(CI->getOperand(0));
1418 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1419 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1421 if (Op0 == Op1) // sub X, X -> 0
1422 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1424 // If this is a 'B = x-(-A)', change to B = x+A...
1425 if (Value *V = dyn_castNegVal(Op1))
1426 return BinaryOperator::createAdd(Op0, V);
1428 if (isa<UndefValue>(Op0))
1429 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1430 if (isa<UndefValue>(Op1))
1431 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1433 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1434 // Replace (-1 - A) with (~A)...
1435 if (C->isAllOnesValue())
1436 return BinaryOperator::createNot(Op1);
1438 // C - ~X == X + (1+C)
1440 if (match(Op1, m_Not(m_Value(X))))
1441 return BinaryOperator::createAdd(X,
1442 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1443 // -((uint)X >> 31) -> ((int)X >> 31)
1444 // -((int)X >> 31) -> ((uint)X >> 31)
1445 if (C->isNullValue()) {
1446 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1447 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1448 if (SI->getOpcode() == Instruction::Shr)
1449 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1451 if (SI->getType()->isSigned())
1452 NewTy = SI->getType()->getUnsignedVersion();
1454 NewTy = SI->getType()->getSignedVersion();
1455 // Check to see if we are shifting out everything but the sign bit.
1456 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
1457 // Ok, the transformation is safe. Insert a cast of the incoming
1458 // value, then the new shift, then the new cast.
1459 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1460 SI->getOperand(0)->getName());
1461 Value *InV = InsertNewInstBefore(FirstCast, I);
1462 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1464 if (NewShift->getType() == I.getType())
1467 InV = InsertNewInstBefore(NewShift, I);
1468 return new CastInst(NewShift, I.getType());
1474 // Try to fold constant sub into select arguments.
1475 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1476 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1479 if (isa<PHINode>(Op0))
1480 if (Instruction *NV = FoldOpIntoPhi(I))
1484 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1485 if (Op1I->getOpcode() == Instruction::Add &&
1486 !Op0->getType()->isFloatingPoint()) {
1487 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1488 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1489 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1490 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1491 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1492 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1493 // C1-(X+C2) --> (C1-C2)-X
1494 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1495 Op1I->getOperand(0));
1499 if (Op1I->hasOneUse()) {
1500 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1501 // is not used by anyone else...
1503 if (Op1I->getOpcode() == Instruction::Sub &&
1504 !Op1I->getType()->isFloatingPoint()) {
1505 // Swap the two operands of the subexpr...
1506 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1507 Op1I->setOperand(0, IIOp1);
1508 Op1I->setOperand(1, IIOp0);
1510 // Create the new top level add instruction...
1511 return BinaryOperator::createAdd(Op0, Op1);
1514 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1516 if (Op1I->getOpcode() == Instruction::And &&
1517 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1518 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1521 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1522 return BinaryOperator::createAnd(Op0, NewNot);
1525 // -(X sdiv C) -> (X sdiv -C)
1526 if (Op1I->getOpcode() == Instruction::Div)
1527 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1528 if (CSI->isNullValue())
1529 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1530 return BinaryOperator::createDiv(Op1I->getOperand(0),
1531 ConstantExpr::getNeg(DivRHS));
1533 // X - X*C --> X * (1-C)
1534 ConstantInt *C2 = 0;
1535 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1537 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1538 return BinaryOperator::createMul(Op0, CP1);
1543 if (!Op0->getType()->isFloatingPoint())
1544 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1545 if (Op0I->getOpcode() == Instruction::Add) {
1546 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1547 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1548 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1549 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1550 } else if (Op0I->getOpcode() == Instruction::Sub) {
1551 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1552 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1556 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1557 if (X == Op1) { // X*C - X --> X * (C-1)
1558 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1559 return BinaryOperator::createMul(Op1, CP1);
1562 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1563 if (X == dyn_castFoldableMul(Op1, C2))
1564 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1569 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1570 /// really just returns true if the most significant (sign) bit is set.
1571 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1572 if (RHS->getType()->isSigned()) {
1573 // True if source is LHS < 0 or LHS <= -1
1574 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1575 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1577 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1578 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1579 // the size of the integer type.
1580 if (Opcode == Instruction::SetGE)
1581 return RHSC->getValue() ==
1582 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1583 if (Opcode == Instruction::SetGT)
1584 return RHSC->getValue() ==
1585 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1590 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1591 bool Changed = SimplifyCommutative(I);
1592 Value *Op0 = I.getOperand(0);
1594 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1595 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1597 // Simplify mul instructions with a constant RHS...
1598 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1599 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1601 // ((X << C1)*C2) == (X * (C2 << C1))
1602 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1603 if (SI->getOpcode() == Instruction::Shl)
1604 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1605 return BinaryOperator::createMul(SI->getOperand(0),
1606 ConstantExpr::getShl(CI, ShOp));
1608 if (CI->isNullValue())
1609 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1610 if (CI->equalsInt(1)) // X * 1 == X
1611 return ReplaceInstUsesWith(I, Op0);
1612 if (CI->isAllOnesValue()) // X * -1 == 0 - X
1613 return BinaryOperator::createNeg(Op0, I.getName());
1615 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1616 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1617 uint64_t C = Log2_64(Val);
1618 return new ShiftInst(Instruction::Shl, Op0,
1619 ConstantUInt::get(Type::UByteTy, C));
1621 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1622 if (Op1F->isNullValue())
1623 return ReplaceInstUsesWith(I, Op1);
1625 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1626 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1627 if (Op1F->getValue() == 1.0)
1628 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1631 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1632 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1633 isa<ConstantInt>(Op0I->getOperand(1))) {
1634 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1635 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1637 InsertNewInstBefore(Add, I);
1638 Value *C1C2 = ConstantExpr::getMul(Op1,
1639 cast<Constant>(Op0I->getOperand(1)));
1640 return BinaryOperator::createAdd(Add, C1C2);
1644 // Try to fold constant mul into select arguments.
1645 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1646 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1649 if (isa<PHINode>(Op0))
1650 if (Instruction *NV = FoldOpIntoPhi(I))
1654 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1655 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1656 return BinaryOperator::createMul(Op0v, Op1v);
1658 // If one of the operands of the multiply is a cast from a boolean value, then
1659 // we know the bool is either zero or one, so this is a 'masking' multiply.
1660 // See if we can simplify things based on how the boolean was originally
1662 CastInst *BoolCast = 0;
1663 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1664 if (CI->getOperand(0)->getType() == Type::BoolTy)
1667 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1668 if (CI->getOperand(0)->getType() == Type::BoolTy)
1671 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1672 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1673 const Type *SCOpTy = SCIOp0->getType();
1675 // If the setcc is true iff the sign bit of X is set, then convert this
1676 // multiply into a shift/and combination.
1677 if (isa<ConstantInt>(SCIOp1) &&
1678 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1679 // Shift the X value right to turn it into "all signbits".
1680 Constant *Amt = ConstantUInt::get(Type::UByteTy,
1681 SCOpTy->getPrimitiveSizeInBits()-1);
1682 if (SCIOp0->getType()->isUnsigned()) {
1683 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1684 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1685 SCIOp0->getName()), I);
1689 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1690 BoolCast->getOperand(0)->getName()+
1693 // If the multiply type is not the same as the source type, sign extend
1694 // or truncate to the multiply type.
1695 if (I.getType() != V->getType())
1696 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1698 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1699 return BinaryOperator::createAnd(V, OtherOp);
1704 return Changed ? &I : 0;
1707 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1708 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1710 if (isa<UndefValue>(Op0)) // undef / X -> 0
1711 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1712 if (isa<UndefValue>(Op1))
1713 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1715 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1717 if (RHS->equalsInt(1))
1718 return ReplaceInstUsesWith(I, Op0);
1721 if (RHS->isAllOnesValue())
1722 return BinaryOperator::createNeg(Op0);
1724 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1725 if (LHS->getOpcode() == Instruction::Div)
1726 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1727 // (X / C1) / C2 -> X / (C1*C2)
1728 return BinaryOperator::createDiv(LHS->getOperand(0),
1729 ConstantExpr::getMul(RHS, LHSRHS));
1732 // Check to see if this is an unsigned division with an exact power of 2,
1733 // if so, convert to a right shift.
1734 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1735 if (uint64_t Val = C->getValue()) // Don't break X / 0
1736 if (isPowerOf2_64(Val)) {
1737 uint64_t C = Log2_64(Val);
1738 return new ShiftInst(Instruction::Shr, Op0,
1739 ConstantUInt::get(Type::UByteTy, C));
1743 if (RHS->getType()->isSigned())
1744 if (Value *LHSNeg = dyn_castNegVal(Op0))
1745 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1747 if (!RHS->isNullValue()) {
1748 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1749 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1751 if (isa<PHINode>(Op0))
1752 if (Instruction *NV = FoldOpIntoPhi(I))
1757 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1758 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1759 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1760 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1761 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1762 if (STO->getValue() == 0) { // Couldn't be this argument.
1763 I.setOperand(1, SFO);
1765 } else if (SFO->getValue() == 0) {
1766 I.setOperand(1, STO);
1770 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1771 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1772 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1773 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1774 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1775 TC, SI->getName()+".t");
1776 TSI = InsertNewInstBefore(TSI, I);
1778 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1779 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1780 FC, SI->getName()+".f");
1781 FSI = InsertNewInstBefore(FSI, I);
1782 return new SelectInst(SI->getOperand(0), TSI, FSI);
1786 // 0 / X == 0, we don't need to preserve faults!
1787 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1788 if (LHS->equalsInt(0))
1789 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1791 if (I.getType()->isSigned()) {
1792 // If the sign bits of both operands are zero (i.e. we can prove they are
1793 // unsigned inputs), turn this into a udiv.
1794 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1795 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1796 const Type *NTy = Op0->getType()->getUnsignedVersion();
1797 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1798 InsertNewInstBefore(LHS, I);
1800 if (Constant *R = dyn_cast<Constant>(Op1))
1801 RHS = ConstantExpr::getCast(R, NTy);
1803 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1804 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1805 InsertNewInstBefore(Div, I);
1806 return new CastInst(Div, I.getType());
1809 // Known to be an unsigned division.
1810 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1811 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1812 if (RHSI->getOpcode() == Instruction::Shl &&
1813 isa<ConstantUInt>(RHSI->getOperand(0))) {
1814 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1815 if (isPowerOf2_64(C1)) {
1816 unsigned C2 = Log2_64(C1);
1817 Value *Add = RHSI->getOperand(1);
1819 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1820 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1823 return new ShiftInst(Instruction::Shr, Op0, Add);
1833 /// GetFactor - If we can prove that the specified value is at least a multiple
1834 /// of some factor, return that factor.
1835 static Constant *GetFactor(Value *V) {
1836 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1839 // Unless we can be tricky, we know this is a multiple of 1.
1840 Constant *Result = ConstantInt::get(V->getType(), 1);
1842 Instruction *I = dyn_cast<Instruction>(V);
1843 if (!I) return Result;
1845 if (I->getOpcode() == Instruction::Mul) {
1846 // Handle multiplies by a constant, etc.
1847 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1848 GetFactor(I->getOperand(1)));
1849 } else if (I->getOpcode() == Instruction::Shl) {
1850 // (X<<C) -> X * (1 << C)
1851 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1852 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1853 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1855 } else if (I->getOpcode() == Instruction::And) {
1856 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1857 // X & 0xFFF0 is known to be a multiple of 16.
1858 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1859 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1860 return ConstantExpr::getShl(Result,
1861 ConstantUInt::get(Type::UByteTy, Zeros));
1863 } else if (I->getOpcode() == Instruction::Cast) {
1864 Value *Op = I->getOperand(0);
1865 // Only handle int->int casts.
1866 if (!Op->getType()->isInteger()) return Result;
1867 return ConstantExpr::getCast(GetFactor(Op), V->getType());
1872 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1875 // 0 % X == 0, we don't need to preserve faults!
1876 if (Constant *LHS = dyn_cast<Constant>(Op0))
1877 if (LHS->isNullValue())
1878 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1880 if (isa<UndefValue>(Op0)) // undef % X -> 0
1881 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1882 if (isa<UndefValue>(Op1))
1883 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1885 if (I.getType()->isSigned()) {
1886 if (Value *RHSNeg = dyn_castNegVal(Op1))
1887 if (!isa<ConstantSInt>(RHSNeg) ||
1888 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1890 AddUsesToWorkList(I);
1891 I.setOperand(1, RHSNeg);
1895 // If the top bits of both operands are zero (i.e. we can prove they are
1896 // unsigned inputs), turn this into a urem.
1897 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1898 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1899 const Type *NTy = Op0->getType()->getUnsignedVersion();
1900 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1901 InsertNewInstBefore(LHS, I);
1903 if (Constant *R = dyn_cast<Constant>(Op1))
1904 RHS = ConstantExpr::getCast(R, NTy);
1906 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1907 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1908 InsertNewInstBefore(Rem, I);
1909 return new CastInst(Rem, I.getType());
1913 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1914 // X % 0 == undef, we don't need to preserve faults!
1915 if (RHS->equalsInt(0))
1916 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
1918 if (RHS->equalsInt(1)) // X % 1 == 0
1919 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1921 // Check to see if this is an unsigned remainder with an exact power of 2,
1922 // if so, convert to a bitwise and.
1923 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1924 if (isPowerOf2_64(C->getValue()))
1925 return BinaryOperator::createAnd(Op0, SubOne(C));
1927 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1928 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1929 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1931 } else if (isa<PHINode>(Op0I)) {
1932 if (Instruction *NV = FoldOpIntoPhi(I))
1936 // X*C1%C2 --> 0 iff C1%C2 == 0
1937 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
1938 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1942 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1943 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1944 if (I.getType()->isUnsigned() &&
1945 RHSI->getOpcode() == Instruction::Shl &&
1946 isa<ConstantUInt>(RHSI->getOperand(0))) {
1947 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1948 if (isPowerOf2_64(C1)) {
1949 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1950 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1952 return BinaryOperator::createAnd(Op0, Add);
1956 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1957 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1958 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1959 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1960 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1961 if (STO->getValue() == 0) { // Couldn't be this argument.
1962 I.setOperand(1, SFO);
1964 } else if (SFO->getValue() == 0) {
1965 I.setOperand(1, STO);
1969 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
1970 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1971 SubOne(STO), SI->getName()+".t"), I);
1972 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1973 SubOne(SFO), SI->getName()+".f"), I);
1974 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1982 // isMaxValueMinusOne - return true if this is Max-1
1983 static bool isMaxValueMinusOne(const ConstantInt *C) {
1984 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1985 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
1987 const ConstantSInt *CS = cast<ConstantSInt>(C);
1989 // Calculate 0111111111..11111
1990 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1991 int64_t Val = INT64_MAX; // All ones
1992 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1993 return CS->getValue() == Val-1;
1996 // isMinValuePlusOne - return true if this is Min+1
1997 static bool isMinValuePlusOne(const ConstantInt *C) {
1998 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1999 return CU->getValue() == 1;
2001 const ConstantSInt *CS = cast<ConstantSInt>(C);
2003 // Calculate 1111111111000000000000
2004 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2005 int64_t Val = -1; // All ones
2006 Val <<= TypeBits-1; // Shift over to the right spot
2007 return CS->getValue() == Val+1;
2010 // isOneBitSet - Return true if there is exactly one bit set in the specified
2012 static bool isOneBitSet(const ConstantInt *CI) {
2013 uint64_t V = CI->getRawValue();
2014 return V && (V & (V-1)) == 0;
2017 #if 0 // Currently unused
2018 // isLowOnes - Return true if the constant is of the form 0+1+.
2019 static bool isLowOnes(const ConstantInt *CI) {
2020 uint64_t V = CI->getRawValue();
2022 // There won't be bits set in parts that the type doesn't contain.
2023 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2025 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2026 return U && V && (U & V) == 0;
2030 // isHighOnes - Return true if the constant is of the form 1+0+.
2031 // This is the same as lowones(~X).
2032 static bool isHighOnes(const ConstantInt *CI) {
2033 uint64_t V = ~CI->getRawValue();
2034 if (~V == 0) return false; // 0's does not match "1+"
2036 // There won't be bits set in parts that the type doesn't contain.
2037 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2039 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2040 return U && V && (U & V) == 0;
2044 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2045 /// are carefully arranged to allow folding of expressions such as:
2047 /// (A < B) | (A > B) --> (A != B)
2049 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2050 /// represents that the comparison is true if A == B, and bit value '1' is true
2053 static unsigned getSetCondCode(const SetCondInst *SCI) {
2054 switch (SCI->getOpcode()) {
2056 case Instruction::SetGT: return 1;
2057 case Instruction::SetEQ: return 2;
2058 case Instruction::SetGE: return 3;
2059 case Instruction::SetLT: return 4;
2060 case Instruction::SetNE: return 5;
2061 case Instruction::SetLE: return 6;
2064 assert(0 && "Invalid SetCC opcode!");
2069 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2070 /// opcode and two operands into either a constant true or false, or a brand new
2071 /// SetCC instruction.
2072 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2074 case 0: return ConstantBool::False;
2075 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2076 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2077 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2078 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2079 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2080 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2081 case 7: return ConstantBool::True;
2082 default: assert(0 && "Illegal SetCCCode!"); return 0;
2086 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2087 struct FoldSetCCLogical {
2090 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2091 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2092 bool shouldApply(Value *V) const {
2093 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2094 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2095 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2098 Instruction *apply(BinaryOperator &Log) const {
2099 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2100 if (SCI->getOperand(0) != LHS) {
2101 assert(SCI->getOperand(1) == LHS);
2102 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2105 unsigned LHSCode = getSetCondCode(SCI);
2106 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2108 switch (Log.getOpcode()) {
2109 case Instruction::And: Code = LHSCode & RHSCode; break;
2110 case Instruction::Or: Code = LHSCode | RHSCode; break;
2111 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2112 default: assert(0 && "Illegal logical opcode!"); return 0;
2115 Value *RV = getSetCCValue(Code, LHS, RHS);
2116 if (Instruction *I = dyn_cast<Instruction>(RV))
2118 // Otherwise, it's a constant boolean value...
2119 return IC.ReplaceInstUsesWith(Log, RV);
2123 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2124 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2125 // guaranteed to be either a shift instruction or a binary operator.
2126 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2127 ConstantIntegral *OpRHS,
2128 ConstantIntegral *AndRHS,
2129 BinaryOperator &TheAnd) {
2130 Value *X = Op->getOperand(0);
2131 Constant *Together = 0;
2132 if (!isa<ShiftInst>(Op))
2133 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2135 switch (Op->getOpcode()) {
2136 case Instruction::Xor:
2137 if (Op->hasOneUse()) {
2138 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2139 std::string OpName = Op->getName(); Op->setName("");
2140 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2141 InsertNewInstBefore(And, TheAnd);
2142 return BinaryOperator::createXor(And, Together);
2145 case Instruction::Or:
2146 if (Together == AndRHS) // (X | C) & C --> C
2147 return ReplaceInstUsesWith(TheAnd, AndRHS);
2149 if (Op->hasOneUse() && Together != OpRHS) {
2150 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2151 std::string Op0Name = Op->getName(); Op->setName("");
2152 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2153 InsertNewInstBefore(Or, TheAnd);
2154 return BinaryOperator::createAnd(Or, AndRHS);
2157 case Instruction::Add:
2158 if (Op->hasOneUse()) {
2159 // Adding a one to a single bit bit-field should be turned into an XOR
2160 // of the bit. First thing to check is to see if this AND is with a
2161 // single bit constant.
2162 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
2164 // Clear bits that are not part of the constant.
2165 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2167 // If there is only one bit set...
2168 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2169 // Ok, at this point, we know that we are masking the result of the
2170 // ADD down to exactly one bit. If the constant we are adding has
2171 // no bits set below this bit, then we can eliminate the ADD.
2172 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
2174 // Check to see if any bits below the one bit set in AndRHSV are set.
2175 if ((AddRHS & (AndRHSV-1)) == 0) {
2176 // If not, the only thing that can effect the output of the AND is
2177 // the bit specified by AndRHSV. If that bit is set, the effect of
2178 // the XOR is to toggle the bit. If it is clear, then the ADD has
2180 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2181 TheAnd.setOperand(0, X);
2184 std::string Name = Op->getName(); Op->setName("");
2185 // Pull the XOR out of the AND.
2186 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2187 InsertNewInstBefore(NewAnd, TheAnd);
2188 return BinaryOperator::createXor(NewAnd, AndRHS);
2195 case Instruction::Shl: {
2196 // We know that the AND will not produce any of the bits shifted in, so if
2197 // the anded constant includes them, clear them now!
2199 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2200 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2201 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2203 if (CI == ShlMask) { // Masking out bits that the shift already masks
2204 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2205 } else if (CI != AndRHS) { // Reducing bits set in and.
2206 TheAnd.setOperand(1, CI);
2211 case Instruction::Shr:
2212 // We know that the AND will not produce any of the bits shifted in, so if
2213 // the anded constant includes them, clear them now! This only applies to
2214 // unsigned shifts, because a signed shr may bring in set bits!
2216 if (AndRHS->getType()->isUnsigned()) {
2217 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2218 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2219 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2221 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2222 return ReplaceInstUsesWith(TheAnd, Op);
2223 } else if (CI != AndRHS) {
2224 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2227 } else { // Signed shr.
2228 // See if this is shifting in some sign extension, then masking it out
2230 if (Op->hasOneUse()) {
2231 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2232 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2233 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2234 if (CI == AndRHS) { // Masking out bits shifted in.
2235 // Make the argument unsigned.
2236 Value *ShVal = Op->getOperand(0);
2237 ShVal = InsertCastBefore(ShVal,
2238 ShVal->getType()->getUnsignedVersion(),
2240 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2241 OpRHS, Op->getName()),
2243 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2244 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2247 return new CastInst(ShVal, Op->getType());
2257 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2258 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2259 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2260 /// insert new instructions.
2261 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2262 bool Inside, Instruction &IB) {
2263 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2264 "Lo is not <= Hi in range emission code!");
2266 if (Lo == Hi) // Trivially false.
2267 return new SetCondInst(Instruction::SetNE, V, V);
2268 if (cast<ConstantIntegral>(Lo)->isMinValue())
2269 return new SetCondInst(Instruction::SetLT, V, Hi);
2271 Constant *AddCST = ConstantExpr::getNeg(Lo);
2272 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2273 InsertNewInstBefore(Add, IB);
2274 // Convert to unsigned for the comparison.
2275 const Type *UnsType = Add->getType()->getUnsignedVersion();
2276 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2277 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2278 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2279 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2282 if (Lo == Hi) // Trivially true.
2283 return new SetCondInst(Instruction::SetEQ, V, V);
2285 Hi = SubOne(cast<ConstantInt>(Hi));
2286 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2287 return new SetCondInst(Instruction::SetGT, V, Hi);
2289 // Emit X-Lo > Hi-Lo-1
2290 Constant *AddCST = ConstantExpr::getNeg(Lo);
2291 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2292 InsertNewInstBefore(Add, IB);
2293 // Convert to unsigned for the comparison.
2294 const Type *UnsType = Add->getType()->getUnsignedVersion();
2295 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2296 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2297 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2298 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2301 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2302 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2303 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2304 // not, since all 1s are not contiguous.
2305 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2306 uint64_t V = Val->getRawValue();
2307 if (!isShiftedMask_64(V)) return false;
2309 // look for the first zero bit after the run of ones
2310 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2311 // look for the first non-zero bit
2312 ME = 64-CountLeadingZeros_64(V);
2318 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2319 /// where isSub determines whether the operator is a sub. If we can fold one of
2320 /// the following xforms:
2322 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2323 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2324 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2326 /// return (A +/- B).
2328 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2329 ConstantIntegral *Mask, bool isSub,
2331 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2332 if (!LHSI || LHSI->getNumOperands() != 2 ||
2333 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2335 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2337 switch (LHSI->getOpcode()) {
2339 case Instruction::And:
2340 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2341 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2342 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2345 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2346 // part, we don't need any explicit masks to take them out of A. If that
2347 // is all N is, ignore it.
2349 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2350 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2352 if (MaskedValueIsZero(RHS, Mask))
2357 case Instruction::Or:
2358 case Instruction::Xor:
2359 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2360 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2361 ConstantExpr::getAnd(N, Mask)->isNullValue())
2368 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2370 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2371 return InsertNewInstBefore(New, I);
2374 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2375 bool Changed = SimplifyCommutative(I);
2376 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2378 if (isa<UndefValue>(Op1)) // X & undef -> 0
2379 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2383 return ReplaceInstUsesWith(I, Op1);
2385 // See if we can simplify any instructions used by the instruction whose sole
2386 // purpose is to compute bits we don't care about.
2387 uint64_t KnownZero, KnownOne;
2388 if (!isa<PackedType>(I.getType()) &&
2389 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2390 KnownZero, KnownOne))
2393 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2394 uint64_t AndRHSMask = AndRHS->getZExtValue();
2395 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2396 uint64_t NotAndRHS = AndRHSMask^TypeMask;
2398 // Optimize a variety of ((val OP C1) & C2) combinations...
2399 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2400 Instruction *Op0I = cast<Instruction>(Op0);
2401 Value *Op0LHS = Op0I->getOperand(0);
2402 Value *Op0RHS = Op0I->getOperand(1);
2403 switch (Op0I->getOpcode()) {
2404 case Instruction::Xor:
2405 case Instruction::Or:
2406 // If the mask is only needed on one incoming arm, push it up.
2407 if (Op0I->hasOneUse()) {
2408 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2409 // Not masking anything out for the LHS, move to RHS.
2410 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2411 Op0RHS->getName()+".masked");
2412 InsertNewInstBefore(NewRHS, I);
2413 return BinaryOperator::create(
2414 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2416 if (!isa<Constant>(Op0RHS) &&
2417 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2418 // Not masking anything out for the RHS, move to LHS.
2419 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2420 Op0LHS->getName()+".masked");
2421 InsertNewInstBefore(NewLHS, I);
2422 return BinaryOperator::create(
2423 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2428 case Instruction::Add:
2429 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2430 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2431 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2432 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2433 return BinaryOperator::createAnd(V, AndRHS);
2434 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2435 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
2438 case Instruction::Sub:
2439 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2440 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2441 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2442 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2443 return BinaryOperator::createAnd(V, AndRHS);
2447 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2448 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2450 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2451 const Type *SrcTy = CI->getOperand(0)->getType();
2453 // If this is an integer truncation or change from signed-to-unsigned, and
2454 // if the source is an and/or with immediate, transform it. This
2455 // frequently occurs for bitfield accesses.
2456 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2457 if (SrcTy->getPrimitiveSizeInBits() >=
2458 I.getType()->getPrimitiveSizeInBits() &&
2459 CastOp->getNumOperands() == 2)
2460 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2461 if (CastOp->getOpcode() == Instruction::And) {
2462 // Change: and (cast (and X, C1) to T), C2
2463 // into : and (cast X to T), trunc(C1)&C2
2464 // This will folds the two ands together, which may allow other
2466 Instruction *NewCast =
2467 new CastInst(CastOp->getOperand(0), I.getType(),
2468 CastOp->getName()+".shrunk");
2469 NewCast = InsertNewInstBefore(NewCast, I);
2471 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2472 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2473 return BinaryOperator::createAnd(NewCast, C3);
2474 } else if (CastOp->getOpcode() == Instruction::Or) {
2475 // Change: and (cast (or X, C1) to T), C2
2476 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2477 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2478 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2479 return ReplaceInstUsesWith(I, AndRHS);
2484 // Try to fold constant and into select arguments.
2485 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2486 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2488 if (isa<PHINode>(Op0))
2489 if (Instruction *NV = FoldOpIntoPhi(I))
2493 Value *Op0NotVal = dyn_castNotVal(Op0);
2494 Value *Op1NotVal = dyn_castNotVal(Op1);
2496 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2497 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2499 // (~A & ~B) == (~(A | B)) - De Morgan's Law
2500 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2501 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2502 I.getName()+".demorgan");
2503 InsertNewInstBefore(Or, I);
2504 return BinaryOperator::createNot(Or);
2508 Value *A = 0, *B = 0;
2509 ConstantInt *C1 = 0, *C2 = 0;
2510 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2511 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2512 return ReplaceInstUsesWith(I, Op1);
2513 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2514 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2515 return ReplaceInstUsesWith(I, Op0);
2517 if (Op0->hasOneUse() &&
2518 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2519 if (A == Op1) { // (A^B)&A -> A&(A^B)
2520 I.swapOperands(); // Simplify below
2521 std::swap(Op0, Op1);
2522 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2523 cast<BinaryOperator>(Op0)->swapOperands();
2524 I.swapOperands(); // Simplify below
2525 std::swap(Op0, Op1);
2528 if (Op1->hasOneUse() &&
2529 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2530 if (B == Op0) { // B&(A^B) -> B&(B^A)
2531 cast<BinaryOperator>(Op1)->swapOperands();
2534 if (A == Op0) { // A&(A^B) -> A & ~B
2535 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2536 InsertNewInstBefore(NotB, I);
2537 return BinaryOperator::createAnd(A, NotB);
2543 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2544 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2545 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2548 Value *LHSVal, *RHSVal;
2549 ConstantInt *LHSCst, *RHSCst;
2550 Instruction::BinaryOps LHSCC, RHSCC;
2551 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2552 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2553 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2554 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2555 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2556 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2557 // Ensure that the larger constant is on the RHS.
2558 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2559 SetCondInst *LHS = cast<SetCondInst>(Op0);
2560 if (cast<ConstantBool>(Cmp)->getValue()) {
2561 std::swap(LHS, RHS);
2562 std::swap(LHSCst, RHSCst);
2563 std::swap(LHSCC, RHSCC);
2566 // At this point, we know we have have two setcc instructions
2567 // comparing a value against two constants and and'ing the result
2568 // together. Because of the above check, we know that we only have
2569 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2570 // FoldSetCCLogical check above), that the two constants are not
2572 assert(LHSCst != RHSCst && "Compares not folded above?");
2575 default: assert(0 && "Unknown integer condition code!");
2576 case Instruction::SetEQ:
2578 default: assert(0 && "Unknown integer condition code!");
2579 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2580 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2581 return ReplaceInstUsesWith(I, ConstantBool::False);
2582 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2583 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2584 return ReplaceInstUsesWith(I, LHS);
2586 case Instruction::SetNE:
2588 default: assert(0 && "Unknown integer condition code!");
2589 case Instruction::SetLT:
2590 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2591 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2592 break; // (X != 13 & X < 15) -> no change
2593 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2594 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2595 return ReplaceInstUsesWith(I, RHS);
2596 case Instruction::SetNE:
2597 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2598 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2599 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2600 LHSVal->getName()+".off");
2601 InsertNewInstBefore(Add, I);
2602 const Type *UnsType = Add->getType()->getUnsignedVersion();
2603 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2604 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2605 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2606 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2608 break; // (X != 13 & X != 15) -> no change
2611 case Instruction::SetLT:
2613 default: assert(0 && "Unknown integer condition code!");
2614 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2615 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2616 return ReplaceInstUsesWith(I, ConstantBool::False);
2617 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2618 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2619 return ReplaceInstUsesWith(I, LHS);
2621 case Instruction::SetGT:
2623 default: assert(0 && "Unknown integer condition code!");
2624 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2625 return ReplaceInstUsesWith(I, LHS);
2626 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2627 return ReplaceInstUsesWith(I, RHS);
2628 case Instruction::SetNE:
2629 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2630 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2631 break; // (X > 13 & X != 15) -> no change
2632 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2633 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2639 return Changed ? &I : 0;
2642 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2643 bool Changed = SimplifyCommutative(I);
2644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2646 if (isa<UndefValue>(Op1))
2647 return ReplaceInstUsesWith(I, // X | undef -> -1
2648 ConstantIntegral::getAllOnesValue(I.getType()));
2652 return ReplaceInstUsesWith(I, Op0);
2654 // See if we can simplify any instructions used by the instruction whose sole
2655 // purpose is to compute bits we don't care about.
2656 uint64_t KnownZero, KnownOne;
2657 if (!isa<PackedType>(I.getType()) &&
2658 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2659 KnownZero, KnownOne))
2663 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2664 ConstantInt *C1 = 0; Value *X = 0;
2665 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2666 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2667 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2669 InsertNewInstBefore(Or, I);
2670 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2673 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2674 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2675 std::string Op0Name = Op0->getName(); Op0->setName("");
2676 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2677 InsertNewInstBefore(Or, I);
2678 return BinaryOperator::createXor(Or,
2679 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2682 // Try to fold constant and into select arguments.
2683 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2684 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2686 if (isa<PHINode>(Op0))
2687 if (Instruction *NV = FoldOpIntoPhi(I))
2691 Value *A = 0, *B = 0;
2692 ConstantInt *C1 = 0, *C2 = 0;
2694 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2695 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2696 return ReplaceInstUsesWith(I, Op1);
2697 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2698 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2699 return ReplaceInstUsesWith(I, Op0);
2701 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2702 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2703 MaskedValueIsZero(Op1, C1->getZExtValue())) {
2704 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2706 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2709 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2710 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2711 MaskedValueIsZero(Op0, C1->getZExtValue())) {
2712 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2714 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2717 // (A & C1)|(B & C2)
2718 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2719 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2721 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2722 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2725 // If we have: ((V + N) & C1) | (V & C2)
2726 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2727 // replace with V+N.
2728 if (C1 == ConstantExpr::getNot(C2)) {
2729 Value *V1 = 0, *V2 = 0;
2730 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2731 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2732 // Add commutes, try both ways.
2733 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
2734 return ReplaceInstUsesWith(I, A);
2735 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
2736 return ReplaceInstUsesWith(I, A);
2738 // Or commutes, try both ways.
2739 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2740 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2741 // Add commutes, try both ways.
2742 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
2743 return ReplaceInstUsesWith(I, B);
2744 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
2745 return ReplaceInstUsesWith(I, B);
2750 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2751 if (A == Op1) // ~A | A == -1
2752 return ReplaceInstUsesWith(I,
2753 ConstantIntegral::getAllOnesValue(I.getType()));
2757 // Note, A is still live here!
2758 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2760 return ReplaceInstUsesWith(I,
2761 ConstantIntegral::getAllOnesValue(I.getType()));
2763 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2764 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2765 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2766 I.getName()+".demorgan"), I);
2767 return BinaryOperator::createNot(And);
2771 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2772 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2773 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2776 Value *LHSVal, *RHSVal;
2777 ConstantInt *LHSCst, *RHSCst;
2778 Instruction::BinaryOps LHSCC, RHSCC;
2779 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2780 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2781 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2782 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2783 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2784 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2785 // Ensure that the larger constant is on the RHS.
2786 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2787 SetCondInst *LHS = cast<SetCondInst>(Op0);
2788 if (cast<ConstantBool>(Cmp)->getValue()) {
2789 std::swap(LHS, RHS);
2790 std::swap(LHSCst, RHSCst);
2791 std::swap(LHSCC, RHSCC);
2794 // At this point, we know we have have two setcc instructions
2795 // comparing a value against two constants and or'ing the result
2796 // together. Because of the above check, we know that we only have
2797 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2798 // FoldSetCCLogical check above), that the two constants are not
2800 assert(LHSCst != RHSCst && "Compares not folded above?");
2803 default: assert(0 && "Unknown integer condition code!");
2804 case Instruction::SetEQ:
2806 default: assert(0 && "Unknown integer condition code!");
2807 case Instruction::SetEQ:
2808 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2809 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2810 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2811 LHSVal->getName()+".off");
2812 InsertNewInstBefore(Add, I);
2813 const Type *UnsType = Add->getType()->getUnsignedVersion();
2814 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2815 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2816 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2817 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2819 break; // (X == 13 | X == 15) -> no change
2821 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2823 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2824 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2825 return ReplaceInstUsesWith(I, RHS);
2828 case Instruction::SetNE:
2830 default: assert(0 && "Unknown integer condition code!");
2831 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2832 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2833 return ReplaceInstUsesWith(I, LHS);
2834 case Instruction::SetNE: // (X != 13 | X != 15) -> true
2835 case Instruction::SetLT: // (X != 13 | X < 15) -> true
2836 return ReplaceInstUsesWith(I, ConstantBool::True);
2839 case Instruction::SetLT:
2841 default: assert(0 && "Unknown integer condition code!");
2842 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2844 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2845 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2846 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2847 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2848 return ReplaceInstUsesWith(I, RHS);
2851 case Instruction::SetGT:
2853 default: assert(0 && "Unknown integer condition code!");
2854 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2855 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2856 return ReplaceInstUsesWith(I, LHS);
2857 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2858 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2859 return ReplaceInstUsesWith(I, ConstantBool::True);
2865 return Changed ? &I : 0;
2868 // XorSelf - Implements: X ^ X --> 0
2871 XorSelf(Value *rhs) : RHS(rhs) {}
2872 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2873 Instruction *apply(BinaryOperator &Xor) const {
2879 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2880 bool Changed = SimplifyCommutative(I);
2881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2883 if (isa<UndefValue>(Op1))
2884 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2886 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2887 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2888 assert(Result == &I && "AssociativeOpt didn't work?");
2889 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2892 // See if we can simplify any instructions used by the instruction whose sole
2893 // purpose is to compute bits we don't care about.
2894 uint64_t KnownZero, KnownOne;
2895 if (!isa<PackedType>(I.getType()) &&
2896 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2897 KnownZero, KnownOne))
2900 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2901 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2902 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2903 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2904 if (RHS == ConstantBool::True && SCI->hasOneUse())
2905 return new SetCondInst(SCI->getInverseCondition(),
2906 SCI->getOperand(0), SCI->getOperand(1));
2908 // ~(c-X) == X-c-1 == X+(-c-1)
2909 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2910 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2911 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2912 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2913 ConstantInt::get(I.getType(), 1));
2914 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2917 // ~(~X & Y) --> (X | ~Y)
2918 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2919 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2920 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2922 BinaryOperator::createNot(Op0I->getOperand(1),
2923 Op0I->getOperand(1)->getName()+".not");
2924 InsertNewInstBefore(NotY, I);
2925 return BinaryOperator::createOr(Op0NotVal, NotY);
2929 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2930 if (Op0I->getOpcode() == Instruction::Add) {
2931 // ~(X-c) --> (-c-1)-X
2932 if (RHS->isAllOnesValue()) {
2933 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2934 return BinaryOperator::createSub(
2935 ConstantExpr::getSub(NegOp0CI,
2936 ConstantInt::get(I.getType(), 1)),
2937 Op0I->getOperand(0));
2939 } else if (Op0I->getOpcode() == Instruction::Or) {
2940 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2941 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2942 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2943 // Anything in both C1 and C2 is known to be zero, remove it from
2945 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2946 NewRHS = ConstantExpr::getAnd(NewRHS,
2947 ConstantExpr::getNot(CommonBits));
2948 WorkList.push_back(Op0I);
2949 I.setOperand(0, Op0I->getOperand(0));
2950 I.setOperand(1, NewRHS);
2956 // Try to fold constant and into select arguments.
2957 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2958 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2960 if (isa<PHINode>(Op0))
2961 if (Instruction *NV = FoldOpIntoPhi(I))
2965 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
2967 return ReplaceInstUsesWith(I,
2968 ConstantIntegral::getAllOnesValue(I.getType()));
2970 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
2972 return ReplaceInstUsesWith(I,
2973 ConstantIntegral::getAllOnesValue(I.getType()));
2975 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
2976 if (Op1I->getOpcode() == Instruction::Or) {
2977 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2978 Op1I->swapOperands();
2980 std::swap(Op0, Op1);
2981 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2982 I.swapOperands(); // Simplified below.
2983 std::swap(Op0, Op1);
2985 } else if (Op1I->getOpcode() == Instruction::Xor) {
2986 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2987 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2988 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2989 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2990 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
2991 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
2992 Op1I->swapOperands();
2993 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
2994 I.swapOperands(); // Simplified below.
2995 std::swap(Op0, Op1);
2999 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3000 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3001 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3002 Op0I->swapOperands();
3003 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3004 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3005 InsertNewInstBefore(NotB, I);
3006 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3008 } else if (Op0I->getOpcode() == Instruction::Xor) {
3009 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3010 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3011 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3012 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3013 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3014 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3015 Op0I->swapOperands();
3016 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3017 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3018 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3019 InsertNewInstBefore(N, I);
3020 return BinaryOperator::createAnd(N, Op1);
3024 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3025 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3026 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3029 return Changed ? &I : 0;
3032 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3033 /// overflowed for this type.
3034 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3036 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3037 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3040 static bool isPositive(ConstantInt *C) {
3041 return cast<ConstantSInt>(C)->getValue() >= 0;
3044 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3045 /// overflowed for this type.
3046 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3048 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3050 if (In1->getType()->isUnsigned())
3051 return cast<ConstantUInt>(Result)->getValue() <
3052 cast<ConstantUInt>(In1)->getValue();
3053 if (isPositive(In1) != isPositive(In2))
3055 if (isPositive(In1))
3056 return cast<ConstantSInt>(Result)->getValue() <
3057 cast<ConstantSInt>(In1)->getValue();
3058 return cast<ConstantSInt>(Result)->getValue() >
3059 cast<ConstantSInt>(In1)->getValue();
3062 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3063 /// code necessary to compute the offset from the base pointer (without adding
3064 /// in the base pointer). Return the result as a signed integer of intptr size.
3065 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3066 TargetData &TD = IC.getTargetData();
3067 gep_type_iterator GTI = gep_type_begin(GEP);
3068 const Type *UIntPtrTy = TD.getIntPtrType();
3069 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3070 Value *Result = Constant::getNullValue(SIntPtrTy);
3072 // Build a mask for high order bits.
3073 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3075 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3076 Value *Op = GEP->getOperand(i);
3077 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3078 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3080 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3081 if (!OpC->isNullValue()) {
3082 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3083 Scale = ConstantExpr::getMul(OpC, Scale);
3084 if (Constant *RC = dyn_cast<Constant>(Result))
3085 Result = ConstantExpr::getAdd(RC, Scale);
3087 // Emit an add instruction.
3088 Result = IC.InsertNewInstBefore(
3089 BinaryOperator::createAdd(Result, Scale,
3090 GEP->getName()+".offs"), I);
3094 // Convert to correct type.
3095 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3096 Op->getName()+".c"), I);
3098 // We'll let instcombine(mul) convert this to a shl if possible.
3099 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3100 GEP->getName()+".idx"), I);
3102 // Emit an add instruction.
3103 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3104 GEP->getName()+".offs"), I);
3110 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3111 /// else. At this point we know that the GEP is on the LHS of the comparison.
3112 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3113 Instruction::BinaryOps Cond,
3115 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3117 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3118 if (isa<PointerType>(CI->getOperand(0)->getType()))
3119 RHS = CI->getOperand(0);
3121 Value *PtrBase = GEPLHS->getOperand(0);
3122 if (PtrBase == RHS) {
3123 // As an optimization, we don't actually have to compute the actual value of
3124 // OFFSET if this is a seteq or setne comparison, just return whether each
3125 // index is zero or not.
3126 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3127 Instruction *InVal = 0;
3128 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3129 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3131 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3132 if (isa<UndefValue>(C)) // undef index -> undef.
3133 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3134 if (C->isNullValue())
3136 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3137 EmitIt = false; // This is indexing into a zero sized array?
3138 } else if (isa<ConstantInt>(C))
3139 return ReplaceInstUsesWith(I, // No comparison is needed here.
3140 ConstantBool::get(Cond == Instruction::SetNE));
3145 new SetCondInst(Cond, GEPLHS->getOperand(i),
3146 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3150 InVal = InsertNewInstBefore(InVal, I);
3151 InsertNewInstBefore(Comp, I);
3152 if (Cond == Instruction::SetNE) // True if any are unequal
3153 InVal = BinaryOperator::createOr(InVal, Comp);
3154 else // True if all are equal
3155 InVal = BinaryOperator::createAnd(InVal, Comp);
3163 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3164 ConstantBool::get(Cond == Instruction::SetEQ));
3167 // Only lower this if the setcc is the only user of the GEP or if we expect
3168 // the result to fold to a constant!
3169 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3170 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3171 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3172 return new SetCondInst(Cond, Offset,
3173 Constant::getNullValue(Offset->getType()));
3175 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3176 // If the base pointers are different, but the indices are the same, just
3177 // compare the base pointer.
3178 if (PtrBase != GEPRHS->getOperand(0)) {
3179 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3180 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3181 GEPRHS->getOperand(0)->getType();
3183 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3184 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3185 IndicesTheSame = false;
3189 // If all indices are the same, just compare the base pointers.
3191 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3192 GEPRHS->getOperand(0));
3194 // Otherwise, the base pointers are different and the indices are
3195 // different, bail out.
3199 // If one of the GEPs has all zero indices, recurse.
3200 bool AllZeros = true;
3201 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3202 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3203 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3208 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3209 SetCondInst::getSwappedCondition(Cond), I);
3211 // If the other GEP has all zero indices, recurse.
3213 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3214 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3215 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3220 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3222 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3223 // If the GEPs only differ by one index, compare it.
3224 unsigned NumDifferences = 0; // Keep track of # differences.
3225 unsigned DiffOperand = 0; // The operand that differs.
3226 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3227 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3228 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3229 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3230 // Irreconcilable differences.
3234 if (NumDifferences++) break;
3239 if (NumDifferences == 0) // SAME GEP?
3240 return ReplaceInstUsesWith(I, // No comparison is needed here.
3241 ConstantBool::get(Cond == Instruction::SetEQ));
3242 else if (NumDifferences == 1) {
3243 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3244 Value *RHSV = GEPRHS->getOperand(DiffOperand);
3246 // Convert the operands to signed values to make sure to perform a
3247 // signed comparison.
3248 const Type *NewTy = LHSV->getType()->getSignedVersion();
3249 if (LHSV->getType() != NewTy)
3250 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3251 LHSV->getName()), I);
3252 if (RHSV->getType() != NewTy)
3253 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3254 RHSV->getName()), I);
3255 return new SetCondInst(Cond, LHSV, RHSV);
3259 // Only lower this if the setcc is the only user of the GEP or if we expect
3260 // the result to fold to a constant!
3261 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3262 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3263 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3264 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3265 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3266 return new SetCondInst(Cond, L, R);
3273 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3274 bool Changed = SimplifyCommutative(I);
3275 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3276 const Type *Ty = Op0->getType();
3280 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3282 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3283 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3285 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3286 // addresses never equal each other! We already know that Op0 != Op1.
3287 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3288 isa<ConstantPointerNull>(Op0)) &&
3289 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3290 isa<ConstantPointerNull>(Op1)))
3291 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3293 // setcc's with boolean values can always be turned into bitwise operations
3294 if (Ty == Type::BoolTy) {
3295 switch (I.getOpcode()) {
3296 default: assert(0 && "Invalid setcc instruction!");
3297 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
3298 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3299 InsertNewInstBefore(Xor, I);
3300 return BinaryOperator::createNot(Xor);
3302 case Instruction::SetNE:
3303 return BinaryOperator::createXor(Op0, Op1);
3305 case Instruction::SetGT:
3306 std::swap(Op0, Op1); // Change setgt -> setlt
3308 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3309 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3310 InsertNewInstBefore(Not, I);
3311 return BinaryOperator::createAnd(Not, Op1);
3313 case Instruction::SetGE:
3314 std::swap(Op0, Op1); // Change setge -> setle
3316 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3317 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3318 InsertNewInstBefore(Not, I);
3319 return BinaryOperator::createOr(Not, Op1);
3324 // See if we are doing a comparison between a constant and an instruction that
3325 // can be folded into the comparison.
3326 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3327 // Check to see if we are comparing against the minimum or maximum value...
3328 if (CI->isMinValue()) {
3329 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3330 return ReplaceInstUsesWith(I, ConstantBool::False);
3331 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3332 return ReplaceInstUsesWith(I, ConstantBool::True);
3333 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3334 return BinaryOperator::createSetEQ(Op0, Op1);
3335 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3336 return BinaryOperator::createSetNE(Op0, Op1);
3338 } else if (CI->isMaxValue()) {
3339 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3340 return ReplaceInstUsesWith(I, ConstantBool::False);
3341 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3342 return ReplaceInstUsesWith(I, ConstantBool::True);
3343 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3344 return BinaryOperator::createSetEQ(Op0, Op1);
3345 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3346 return BinaryOperator::createSetNE(Op0, Op1);
3348 // Comparing against a value really close to min or max?
3349 } else if (isMinValuePlusOne(CI)) {
3350 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3351 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3352 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3353 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3355 } else if (isMaxValueMinusOne(CI)) {
3356 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3357 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3358 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3359 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3362 // If we still have a setle or setge instruction, turn it into the
3363 // appropriate setlt or setgt instruction. Since the border cases have
3364 // already been handled above, this requires little checking.
3366 if (I.getOpcode() == Instruction::SetLE)
3367 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3368 if (I.getOpcode() == Instruction::SetGE)
3369 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3372 // See if we can fold the comparison based on bits known to be zero or one
3374 uint64_t KnownZero, KnownOne;
3375 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3376 KnownZero, KnownOne, 0))
3379 // Given the known and unknown bits, compute a range that the LHS could be
3381 if (KnownOne | KnownZero) {
3382 if (Ty->isUnsigned()) { // Unsigned comparison.
3384 uint64_t RHSVal = CI->getZExtValue();
3385 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3387 switch (I.getOpcode()) { // LE/GE have been folded already.
3388 default: assert(0 && "Unknown setcc opcode!");
3389 case Instruction::SetEQ:
3390 if (Max < RHSVal || Min > RHSVal)
3391 return ReplaceInstUsesWith(I, ConstantBool::False);
3393 case Instruction::SetNE:
3394 if (Max < RHSVal || Min > RHSVal)
3395 return ReplaceInstUsesWith(I, ConstantBool::True);
3397 case Instruction::SetLT:
3398 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3399 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3401 case Instruction::SetGT:
3402 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3403 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3406 } else { // Signed comparison.
3408 int64_t RHSVal = CI->getSExtValue();
3409 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3411 switch (I.getOpcode()) { // LE/GE have been folded already.
3412 default: assert(0 && "Unknown setcc opcode!");
3413 case Instruction::SetEQ:
3414 if (Max < RHSVal || Min > RHSVal)
3415 return ReplaceInstUsesWith(I, ConstantBool::False);
3417 case Instruction::SetNE:
3418 if (Max < RHSVal || Min > RHSVal)
3419 return ReplaceInstUsesWith(I, ConstantBool::True);
3421 case Instruction::SetLT:
3422 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3423 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3425 case Instruction::SetGT:
3426 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3427 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3434 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3435 switch (LHSI->getOpcode()) {
3436 case Instruction::And:
3437 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3438 LHSI->getOperand(0)->hasOneUse()) {
3439 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3440 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3441 // happens a LOT in code produced by the C front-end, for bitfield
3443 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
3444 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3446 // Check to see if there is a noop-cast between the shift and the and.
3448 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3449 if (CI->getOperand(0)->getType()->isIntegral() &&
3450 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3451 CI->getType()->getPrimitiveSizeInBits())
3452 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3455 ConstantUInt *ShAmt;
3456 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
3457 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3458 const Type *AndTy = AndCST->getType(); // Type of the and.
3460 // We can fold this as long as we can't shift unknown bits
3461 // into the mask. This can only happen with signed shift
3462 // rights, as they sign-extend.
3464 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
3467 // To test for the bad case of the signed shr, see if any
3468 // of the bits shifted in could be tested after the mask.
3469 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3470 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3472 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
3474 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3476 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3482 if (Shift->getOpcode() == Instruction::Shl)
3483 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3485 NewCst = ConstantExpr::getShl(CI, ShAmt);
3487 // Check to see if we are shifting out any of the bits being
3489 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3490 // If we shifted bits out, the fold is not going to work out.
3491 // As a special case, check to see if this means that the
3492 // result is always true or false now.
3493 if (I.getOpcode() == Instruction::SetEQ)
3494 return ReplaceInstUsesWith(I, ConstantBool::False);
3495 if (I.getOpcode() == Instruction::SetNE)
3496 return ReplaceInstUsesWith(I, ConstantBool::True);
3498 I.setOperand(1, NewCst);
3499 Constant *NewAndCST;
3500 if (Shift->getOpcode() == Instruction::Shl)
3501 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3503 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3504 LHSI->setOperand(1, NewAndCST);
3506 LHSI->setOperand(0, Shift->getOperand(0));
3508 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3510 LHSI->setOperand(0, NewCast);
3512 WorkList.push_back(Shift); // Shift is dead.
3513 AddUsesToWorkList(I);
3521 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3522 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3523 switch (I.getOpcode()) {
3525 case Instruction::SetEQ:
3526 case Instruction::SetNE: {
3527 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3529 // Check that the shift amount is in range. If not, don't perform
3530 // undefined shifts. When the shift is visited it will be
3532 if (ShAmt->getValue() >= TypeBits)
3535 // If we are comparing against bits always shifted out, the
3536 // comparison cannot succeed.
3538 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3539 if (Comp != CI) {// Comparing against a bit that we know is zero.
3540 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3541 Constant *Cst = ConstantBool::get(IsSetNE);
3542 return ReplaceInstUsesWith(I, Cst);
3545 if (LHSI->hasOneUse()) {
3546 // Otherwise strength reduce the shift into an and.
3547 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3548 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3551 if (CI->getType()->isUnsigned()) {
3552 Mask = ConstantUInt::get(CI->getType(), Val);
3553 } else if (ShAmtVal != 0) {
3554 Mask = ConstantSInt::get(CI->getType(), Val);
3556 Mask = ConstantInt::getAllOnesValue(CI->getType());
3560 BinaryOperator::createAnd(LHSI->getOperand(0),
3561 Mask, LHSI->getName()+".mask");
3562 Value *And = InsertNewInstBefore(AndI, I);
3563 return new SetCondInst(I.getOpcode(), And,
3564 ConstantExpr::getUShr(CI, ShAmt));
3571 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
3572 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3573 switch (I.getOpcode()) {
3575 case Instruction::SetEQ:
3576 case Instruction::SetNE: {
3578 // Check that the shift amount is in range. If not, don't perform
3579 // undefined shifts. When the shift is visited it will be
3581 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3582 if (ShAmt->getValue() >= TypeBits)
3585 // If we are comparing against bits always shifted out, the
3586 // comparison cannot succeed.
3588 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
3590 if (Comp != CI) {// Comparing against a bit that we know is zero.
3591 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3592 Constant *Cst = ConstantBool::get(IsSetNE);
3593 return ReplaceInstUsesWith(I, Cst);
3596 if (LHSI->hasOneUse() || CI->isNullValue()) {
3597 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3599 // Otherwise strength reduce the shift into an and.
3600 uint64_t Val = ~0ULL; // All ones.
3601 Val <<= ShAmtVal; // Shift over to the right spot.
3604 if (CI->getType()->isUnsigned()) {
3605 Val &= ~0ULL >> (64-TypeBits);
3606 Mask = ConstantUInt::get(CI->getType(), Val);
3608 Mask = ConstantSInt::get(CI->getType(), Val);
3612 BinaryOperator::createAnd(LHSI->getOperand(0),
3613 Mask, LHSI->getName()+".mask");
3614 Value *And = InsertNewInstBefore(AndI, I);
3615 return new SetCondInst(I.getOpcode(), And,
3616 ConstantExpr::getShl(CI, ShAmt));
3624 case Instruction::Div:
3625 // Fold: (div X, C1) op C2 -> range check
3626 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3627 // Fold this div into the comparison, producing a range check.
3628 // Determine, based on the divide type, what the range is being
3629 // checked. If there is an overflow on the low or high side, remember
3630 // it, otherwise compute the range [low, hi) bounding the new value.
3631 bool LoOverflow = false, HiOverflow = 0;
3632 ConstantInt *LoBound = 0, *HiBound = 0;
3635 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3637 Instruction::BinaryOps Opcode = I.getOpcode();
3639 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3640 } else if (LHSI->getType()->isUnsigned()) { // udiv
3642 LoOverflow = ProdOV;
3643 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3644 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3645 if (CI->isNullValue()) { // (X / pos) op 0
3647 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3649 } else if (isPositive(CI)) { // (X / pos) op pos
3651 LoOverflow = ProdOV;
3652 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3653 } else { // (X / pos) op neg
3654 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3655 LoOverflow = AddWithOverflow(LoBound, Prod,
3656 cast<ConstantInt>(DivRHSH));
3658 HiOverflow = ProdOV;
3660 } else { // Divisor is < 0.
3661 if (CI->isNullValue()) { // (X / neg) op 0
3662 LoBound = AddOne(DivRHS);
3663 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
3664 if (HiBound == DivRHS)
3665 LoBound = 0; // - INTMIN = INTMIN
3666 } else if (isPositive(CI)) { // (X / neg) op pos
3667 HiOverflow = LoOverflow = ProdOV;
3669 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3670 HiBound = AddOne(Prod);
3671 } else { // (X / neg) op neg
3673 LoOverflow = HiOverflow = ProdOV;
3674 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3677 // Dividing by a negate swaps the condition.
3678 Opcode = SetCondInst::getSwappedCondition(Opcode);
3682 Value *X = LHSI->getOperand(0);
3684 default: assert(0 && "Unhandled setcc opcode!");
3685 case Instruction::SetEQ:
3686 if (LoOverflow && HiOverflow)
3687 return ReplaceInstUsesWith(I, ConstantBool::False);
3688 else if (HiOverflow)
3689 return new SetCondInst(Instruction::SetGE, X, LoBound);
3690 else if (LoOverflow)
3691 return new SetCondInst(Instruction::SetLT, X, HiBound);
3693 return InsertRangeTest(X, LoBound, HiBound, true, I);
3694 case Instruction::SetNE:
3695 if (LoOverflow && HiOverflow)
3696 return ReplaceInstUsesWith(I, ConstantBool::True);
3697 else if (HiOverflow)
3698 return new SetCondInst(Instruction::SetLT, X, LoBound);
3699 else if (LoOverflow)
3700 return new SetCondInst(Instruction::SetGE, X, HiBound);
3702 return InsertRangeTest(X, LoBound, HiBound, false, I);
3703 case Instruction::SetLT:
3705 return ReplaceInstUsesWith(I, ConstantBool::False);
3706 return new SetCondInst(Instruction::SetLT, X, LoBound);
3707 case Instruction::SetGT:
3709 return ReplaceInstUsesWith(I, ConstantBool::False);
3710 return new SetCondInst(Instruction::SetGE, X, HiBound);
3717 // Simplify seteq and setne instructions...
3718 if (I.getOpcode() == Instruction::SetEQ ||
3719 I.getOpcode() == Instruction::SetNE) {
3720 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3722 // If the first operand is (and|or|xor) with a constant, and the second
3723 // operand is a constant, simplify a bit.
3724 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3725 switch (BO->getOpcode()) {
3726 case Instruction::Rem:
3727 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3728 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3730 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3731 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3732 if (isPowerOf2_64(V)) {
3733 unsigned L2 = Log2_64(V);
3734 const Type *UTy = BO->getType()->getUnsignedVersion();
3735 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3737 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3738 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3739 RHSCst, BO->getName()), I);
3740 return BinaryOperator::create(I.getOpcode(), NewRem,
3741 Constant::getNullValue(UTy));
3746 case Instruction::Add:
3747 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3748 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3749 if (BO->hasOneUse())
3750 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3751 ConstantExpr::getSub(CI, BOp1C));
3752 } else if (CI->isNullValue()) {
3753 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3754 // efficiently invertible, or if the add has just this one use.
3755 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3757 if (Value *NegVal = dyn_castNegVal(BOp1))
3758 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3759 else if (Value *NegVal = dyn_castNegVal(BOp0))
3760 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3761 else if (BO->hasOneUse()) {
3762 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3764 InsertNewInstBefore(Neg, I);
3765 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3769 case Instruction::Xor:
3770 // For the xor case, we can xor two constants together, eliminating
3771 // the explicit xor.
3772 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3773 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3774 ConstantExpr::getXor(CI, BOC));
3777 case Instruction::Sub:
3778 // Replace (([sub|xor] A, B) != 0) with (A != B)
3779 if (CI->isNullValue())
3780 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3784 case Instruction::Or:
3785 // If bits are being or'd in that are not present in the constant we
3786 // are comparing against, then the comparison could never succeed!
3787 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3788 Constant *NotCI = ConstantExpr::getNot(CI);
3789 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3790 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3794 case Instruction::And:
3795 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3796 // If bits are being compared against that are and'd out, then the
3797 // comparison can never succeed!
3798 if (!ConstantExpr::getAnd(CI,
3799 ConstantExpr::getNot(BOC))->isNullValue())
3800 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3802 // If we have ((X & C) == C), turn it into ((X & C) != 0).
3803 if (CI == BOC && isOneBitSet(CI))
3804 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3805 Instruction::SetNE, Op0,
3806 Constant::getNullValue(CI->getType()));
3808 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3809 // to be a signed value as appropriate.
3810 if (isSignBit(BOC)) {
3811 Value *X = BO->getOperand(0);
3812 // If 'X' is not signed, insert a cast now...
3813 if (!BOC->getType()->isSigned()) {
3814 const Type *DestTy = BOC->getType()->getSignedVersion();
3815 X = InsertCastBefore(X, DestTy, I);
3817 return new SetCondInst(isSetNE ? Instruction::SetLT :
3818 Instruction::SetGE, X,
3819 Constant::getNullValue(X->getType()));
3822 // ((X & ~7) == 0) --> X < 8
3823 if (CI->isNullValue() && isHighOnes(BOC)) {
3824 Value *X = BO->getOperand(0);
3825 Constant *NegX = ConstantExpr::getNeg(BOC);
3827 // If 'X' is signed, insert a cast now.
3828 if (NegX->getType()->isSigned()) {
3829 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3830 X = InsertCastBefore(X, DestTy, I);
3831 NegX = ConstantExpr::getCast(NegX, DestTy);
3834 return new SetCondInst(isSetNE ? Instruction::SetGE :
3835 Instruction::SetLT, X, NegX);
3842 } else { // Not a SetEQ/SetNE
3843 // If the LHS is a cast from an integral value of the same size,
3844 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3845 Value *CastOp = Cast->getOperand(0);
3846 const Type *SrcTy = CastOp->getType();
3847 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3848 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3849 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3850 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3851 "Source and destination signednesses should differ!");
3852 if (Cast->getType()->isSigned()) {
3853 // If this is a signed comparison, check for comparisons in the
3854 // vicinity of zero.
3855 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3857 return BinaryOperator::createSetGT(CastOp,
3858 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3859 else if (I.getOpcode() == Instruction::SetGT &&
3860 cast<ConstantSInt>(CI)->getValue() == -1)
3861 // X > -1 => x < 128
3862 return BinaryOperator::createSetLT(CastOp,
3863 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3865 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3866 if (I.getOpcode() == Instruction::SetLT &&
3867 CUI->getValue() == 1ULL << (SrcTySize-1))
3868 // X < 128 => X > -1
3869 return BinaryOperator::createSetGT(CastOp,
3870 ConstantSInt::get(SrcTy, -1));
3871 else if (I.getOpcode() == Instruction::SetGT &&
3872 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3874 return BinaryOperator::createSetLT(CastOp,
3875 Constant::getNullValue(SrcTy));
3882 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3883 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3884 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3885 switch (LHSI->getOpcode()) {
3886 case Instruction::GetElementPtr:
3887 if (RHSC->isNullValue()) {
3888 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3889 bool isAllZeros = true;
3890 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3891 if (!isa<Constant>(LHSI->getOperand(i)) ||
3892 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3897 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3898 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3902 case Instruction::PHI:
3903 if (Instruction *NV = FoldOpIntoPhi(I))
3906 case Instruction::Select:
3907 // If either operand of the select is a constant, we can fold the
3908 // comparison into the select arms, which will cause one to be
3909 // constant folded and the select turned into a bitwise or.
3910 Value *Op1 = 0, *Op2 = 0;
3911 if (LHSI->hasOneUse()) {
3912 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3913 // Fold the known value into the constant operand.
3914 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3915 // Insert a new SetCC of the other select operand.
3916 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3917 LHSI->getOperand(2), RHSC,
3919 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3920 // Fold the known value into the constant operand.
3921 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3922 // Insert a new SetCC of the other select operand.
3923 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3924 LHSI->getOperand(1), RHSC,
3930 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3935 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3936 if (User *GEP = dyn_castGetElementPtr(Op0))
3937 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3939 if (User *GEP = dyn_castGetElementPtr(Op1))
3940 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3941 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3944 // Test to see if the operands of the setcc are casted versions of other
3945 // values. If the cast can be stripped off both arguments, we do so now.
3946 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3947 Value *CastOp0 = CI->getOperand(0);
3948 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3949 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3950 (I.getOpcode() == Instruction::SetEQ ||
3951 I.getOpcode() == Instruction::SetNE)) {
3952 // We keep moving the cast from the left operand over to the right
3953 // operand, where it can often be eliminated completely.
3956 // If operand #1 is a cast instruction, see if we can eliminate it as
3958 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3959 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3961 Op1 = CI2->getOperand(0);
3963 // If Op1 is a constant, we can fold the cast into the constant.
3964 if (Op1->getType() != Op0->getType())
3965 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3966 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3968 // Otherwise, cast the RHS right before the setcc
3969 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3970 InsertNewInstBefore(cast<Instruction>(Op1), I);
3972 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3975 // Handle the special case of: setcc (cast bool to X), <cst>
3976 // This comes up when you have code like
3979 // For generality, we handle any zero-extension of any operand comparison
3980 // with a constant or another cast from the same type.
3981 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3982 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3986 if (I.getOpcode() == Instruction::SetNE ||
3987 I.getOpcode() == Instruction::SetEQ) {
3989 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3990 (A == Op1 || B == Op1)) {
3991 // (A^B) == A -> B == 0
3992 Value *OtherVal = A == Op1 ? B : A;
3993 return BinaryOperator::create(I.getOpcode(), OtherVal,
3994 Constant::getNullValue(A->getType()));
3995 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3996 (A == Op0 || B == Op0)) {
3997 // A == (A^B) -> B == 0
3998 Value *OtherVal = A == Op0 ? B : A;
3999 return BinaryOperator::create(I.getOpcode(), OtherVal,
4000 Constant::getNullValue(A->getType()));
4001 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4002 // (A-B) == A -> B == 0
4003 return BinaryOperator::create(I.getOpcode(), B,
4004 Constant::getNullValue(B->getType()));
4005 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4006 // A == (A-B) -> B == 0
4007 return BinaryOperator::create(I.getOpcode(), B,
4008 Constant::getNullValue(B->getType()));
4011 return Changed ? &I : 0;
4014 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4015 // We only handle extending casts so far.
4017 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4018 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4019 const Type *SrcTy = LHSCIOp->getType();
4020 const Type *DestTy = SCI.getOperand(0)->getType();
4023 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
4026 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4027 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4028 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4030 // Is this a sign or zero extension?
4031 bool isSignSrc = SrcTy->isSigned();
4032 bool isSignDest = DestTy->isSigned();
4034 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4035 // Not an extension from the same type?
4036 RHSCIOp = CI->getOperand(0);
4037 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4038 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4039 // Compute the constant that would happen if we truncated to SrcTy then
4040 // reextended to DestTy.
4041 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4043 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4046 // If the value cannot be represented in the shorter type, we cannot emit
4047 // a simple comparison.
4048 if (SCI.getOpcode() == Instruction::SetEQ)
4049 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4050 if (SCI.getOpcode() == Instruction::SetNE)
4051 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4053 // Evaluate the comparison for LT.
4055 if (DestTy->isSigned()) {
4056 // We're performing a signed comparison.
4058 // Signed extend and signed comparison.
4059 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4060 Result = ConstantBool::False;
4062 Result = ConstantBool::True; // X < (large) --> true
4064 // Unsigned extend and signed comparison.
4065 if (cast<ConstantSInt>(CI)->getValue() < 0)
4066 Result = ConstantBool::False;
4068 Result = ConstantBool::True;
4071 // We're performing an unsigned comparison.
4073 // Unsigned extend & compare -> always true.
4074 Result = ConstantBool::True;
4076 // We're performing an unsigned comp with a sign extended value.
4077 // This is true if the input is >= 0. [aka >s -1]
4078 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4079 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4080 NegOne, SCI.getName()), SCI);
4084 // Finally, return the value computed.
4085 if (SCI.getOpcode() == Instruction::SetLT) {
4086 return ReplaceInstUsesWith(SCI, Result);
4088 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4089 if (Constant *CI = dyn_cast<Constant>(Result))
4090 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4092 return BinaryOperator::createNot(Result);
4099 // Okay, just insert a compare of the reduced operands now!
4100 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4103 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4104 assert(I.getOperand(1)->getType() == Type::UByteTy);
4105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4106 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4108 // shl X, 0 == X and shr X, 0 == X
4109 // shl 0, X == 0 and shr 0, X == 0
4110 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4111 Op0 == Constant::getNullValue(Op0->getType()))
4112 return ReplaceInstUsesWith(I, Op0);
4114 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4115 if (!isLeftShift && I.getType()->isSigned())
4116 return ReplaceInstUsesWith(I, Op0);
4117 else // undef << X -> 0 AND undef >>u X -> 0
4118 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4120 if (isa<UndefValue>(Op1)) {
4121 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4122 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4124 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4127 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4129 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4130 if (CSI->isAllOnesValue())
4131 return ReplaceInstUsesWith(I, CSI);
4133 // Try to fold constant and into select arguments.
4134 if (isa<Constant>(Op0))
4135 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4136 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4139 // See if we can turn a signed shr into an unsigned shr.
4140 if (!isLeftShift && I.getType()->isSigned()) {
4141 if (MaskedValueIsZero(Op0,
4142 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4143 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4144 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4146 return new CastInst(V, I.getType());
4150 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4151 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4156 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4158 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4159 bool isSignedShift = Op0->getType()->isSigned();
4160 bool isUnsignedShift = !isSignedShift;
4162 // See if we can simplify any instructions used by the instruction whose sole
4163 // purpose is to compute bits we don't care about.
4164 uint64_t KnownZero, KnownOne;
4165 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4166 KnownZero, KnownOne))
4169 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4170 // of a signed value.
4172 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4173 if (Op1->getValue() >= TypeBits) {
4174 if (isUnsignedShift || isLeftShift)
4175 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4177 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4182 // ((X*C1) << C2) == (X * (C1 << C2))
4183 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4184 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4185 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4186 return BinaryOperator::createMul(BO->getOperand(0),
4187 ConstantExpr::getShl(BOOp, Op1));
4189 // Try to fold constant and into select arguments.
4190 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4191 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4193 if (isa<PHINode>(Op0))
4194 if (Instruction *NV = FoldOpIntoPhi(I))
4197 if (Op0->hasOneUse()) {
4198 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4199 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4202 switch (Op0BO->getOpcode()) {
4204 case Instruction::Add:
4205 case Instruction::And:
4206 case Instruction::Or:
4207 case Instruction::Xor:
4208 // These operators commute.
4209 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
4210 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4211 match(Op0BO->getOperand(1),
4212 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4213 Instruction *YS = new ShiftInst(Instruction::Shl,
4214 Op0BO->getOperand(0), Op1,
4216 InsertNewInstBefore(YS, I); // (Y << C)
4218 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4219 Op0BO->getOperand(1)->getName());
4220 InsertNewInstBefore(X, I); // (X + (Y << C))
4221 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4222 C2 = ConstantExpr::getShl(C2, Op1);
4223 return BinaryOperator::createAnd(X, C2);
4226 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4227 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4228 match(Op0BO->getOperand(1),
4229 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4230 m_ConstantInt(CC))) && V2 == Op1 &&
4231 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
4232 Instruction *YS = new ShiftInst(Instruction::Shl,
4233 Op0BO->getOperand(0), Op1,
4235 InsertNewInstBefore(YS, I); // (Y << C)
4237 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4238 V1->getName()+".mask");
4239 InsertNewInstBefore(XM, I); // X & (CC << C)
4241 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4245 case Instruction::Sub:
4246 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4247 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4248 match(Op0BO->getOperand(0),
4249 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4250 Instruction *YS = new ShiftInst(Instruction::Shl,
4251 Op0BO->getOperand(1), Op1,
4253 InsertNewInstBefore(YS, I); // (Y << C)
4255 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4256 Op0BO->getOperand(0)->getName());
4257 InsertNewInstBefore(X, I); // (X + (Y << C))
4258 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4259 C2 = ConstantExpr::getShl(C2, Op1);
4260 return BinaryOperator::createAnd(X, C2);
4263 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4264 match(Op0BO->getOperand(0),
4265 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4266 m_ConstantInt(CC))) && V2 == Op1 &&
4267 cast<BinaryOperator>(Op0BO->getOperand(0))
4268 ->getOperand(0)->hasOneUse()) {
4269 Instruction *YS = new ShiftInst(Instruction::Shl,
4270 Op0BO->getOperand(1), Op1,
4272 InsertNewInstBefore(YS, I); // (Y << C)
4274 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4275 V1->getName()+".mask");
4276 InsertNewInstBefore(XM, I); // X & (CC << C)
4278 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4285 // If the operand is an bitwise operator with a constant RHS, and the
4286 // shift is the only use, we can pull it out of the shift.
4287 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4288 bool isValid = true; // Valid only for And, Or, Xor
4289 bool highBitSet = false; // Transform if high bit of constant set?
4291 switch (Op0BO->getOpcode()) {
4292 default: isValid = false; break; // Do not perform transform!
4293 case Instruction::Add:
4294 isValid = isLeftShift;
4296 case Instruction::Or:
4297 case Instruction::Xor:
4300 case Instruction::And:
4305 // If this is a signed shift right, and the high bit is modified
4306 // by the logical operation, do not perform the transformation.
4307 // The highBitSet boolean indicates the value of the high bit of
4308 // the constant which would cause it to be modified for this
4311 if (isValid && !isLeftShift && isSignedShift) {
4312 uint64_t Val = Op0C->getRawValue();
4313 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4317 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4319 Instruction *NewShift =
4320 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4323 InsertNewInstBefore(NewShift, I);
4325 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4332 // Find out if this is a shift of a shift by a constant.
4333 ShiftInst *ShiftOp = 0;
4334 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
4336 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4337 // If this is a noop-integer case of a shift instruction, use the shift.
4338 if (CI->getOperand(0)->getType()->isInteger() &&
4339 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4340 CI->getType()->getPrimitiveSizeInBits() &&
4341 isa<ShiftInst>(CI->getOperand(0))) {
4342 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4346 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4347 // Find the operands and properties of the input shift. Note that the
4348 // signedness of the input shift may differ from the current shift if there
4349 // is a noop cast between the two.
4350 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4351 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
4352 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
4354 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4356 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4357 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4359 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4360 if (isLeftShift == isShiftOfLeftShift) {
4361 // Do not fold these shifts if the first one is signed and the second one
4362 // is unsigned and this is a right shift. Further, don't do any folding
4364 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4367 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4368 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4369 Amt = Op0->getType()->getPrimitiveSizeInBits();
4371 Value *Op = ShiftOp->getOperand(0);
4372 if (isShiftOfSignedShift != isSignedShift)
4373 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4374 return new ShiftInst(I.getOpcode(), Op,
4375 ConstantUInt::get(Type::UByteTy, Amt));
4378 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4379 // signed types, we can only support the (A >> c1) << c2 configuration,
4380 // because it can not turn an arbitrary bit of A into a sign bit.
4381 if (isUnsignedShift || isLeftShift) {
4382 // Calculate bitmask for what gets shifted off the edge.
4383 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4385 C = ConstantExpr::getShl(C, ShiftAmt1C);
4387 C = ConstantExpr::getUShr(C, ShiftAmt1C);
4389 Value *Op = ShiftOp->getOperand(0);
4390 if (isShiftOfSignedShift != isSignedShift)
4391 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4394 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4395 InsertNewInstBefore(Mask, I);
4397 // Figure out what flavor of shift we should use...
4398 if (ShiftAmt1 == ShiftAmt2) {
4399 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
4400 } else if (ShiftAmt1 < ShiftAmt2) {
4401 return new ShiftInst(I.getOpcode(), Mask,
4402 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
4403 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4404 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4405 // Make sure to emit an unsigned shift right, not a signed one.
4406 Mask = InsertNewInstBefore(new CastInst(Mask,
4407 Mask->getType()->getUnsignedVersion(),
4409 Mask = new ShiftInst(Instruction::Shr, Mask,
4410 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4411 InsertNewInstBefore(Mask, I);
4412 return new CastInst(Mask, I.getType());
4414 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4415 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4418 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4419 Op = InsertNewInstBefore(new CastInst(Mask,
4420 I.getType()->getSignedVersion(),
4421 Mask->getName()), I);
4422 Instruction *Shift =
4423 new ShiftInst(ShiftOp->getOpcode(), Op,
4424 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4425 InsertNewInstBefore(Shift, I);
4427 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4428 C = ConstantExpr::getShl(C, Op1);
4429 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4430 InsertNewInstBefore(Mask, I);
4431 return new CastInst(Mask, I.getType());
4434 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
4435 // this case, C1 == C2 and C1 is 8, 16, or 32.
4436 if (ShiftAmt1 == ShiftAmt2) {
4437 const Type *SExtType = 0;
4438 switch (ShiftAmt1) {
4439 case 8 : SExtType = Type::SByteTy; break;
4440 case 16: SExtType = Type::ShortTy; break;
4441 case 32: SExtType = Type::IntTy; break;
4445 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4447 InsertNewInstBefore(NewTrunc, I);
4448 return new CastInst(NewTrunc, I.getType());
4463 /// getCastType - In the future, we will split the cast instruction into these
4464 /// various types. Until then, we have to do the analysis here.
4465 static CastType getCastType(const Type *Src, const Type *Dest) {
4466 assert(Src->isIntegral() && Dest->isIntegral() &&
4467 "Only works on integral types!");
4468 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4469 unsigned DestSize = Dest->getPrimitiveSizeInBits();
4471 if (SrcSize == DestSize) return Noop;
4472 if (SrcSize > DestSize) return Truncate;
4473 if (Src->isSigned()) return Signext;
4478 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4481 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4482 const Type *DstTy, TargetData *TD) {
4484 // It is legal to eliminate the instruction if casting A->B->A if the sizes
4485 // are identical and the bits don't get reinterpreted (for example
4486 // int->float->int would not be allowed).
4487 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
4490 // If we are casting between pointer and integer types, treat pointers as
4491 // integers of the appropriate size for the code below.
4492 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4493 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4494 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
4496 // Allow free casting and conversion of sizes as long as the sign doesn't
4498 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
4499 CastType FirstCast = getCastType(SrcTy, MidTy);
4500 CastType SecondCast = getCastType(MidTy, DstTy);
4502 // Capture the effect of these two casts. If the result is a legal cast,
4503 // the CastType is stored here, otherwise a special code is used.
4504 static const unsigned CastResult[] = {
4505 // First cast is noop
4507 // First cast is a truncate
4508 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4509 // First cast is a sign ext
4510 2, 5, 2, 4, // signext->zeroext never ok
4511 // First cast is a zero ext
4515 unsigned Result = CastResult[FirstCast*4+SecondCast];
4517 default: assert(0 && "Illegal table value!");
4522 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4523 // truncates, we could eliminate more casts.
4524 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4526 return false; // Not possible to eliminate this here.
4528 // Sign or zero extend followed by truncate is always ok if the result
4529 // is a truncate or noop.
4530 CastType ResultCast = getCastType(SrcTy, DstTy);
4531 if (ResultCast == Noop || ResultCast == Truncate)
4533 // Otherwise we are still growing the value, we are only safe if the
4534 // result will match the sign/zeroextendness of the result.
4535 return ResultCast == FirstCast;
4539 // If this is a cast from 'float -> double -> integer', cast from
4540 // 'float -> integer' directly, as the value isn't changed by the
4541 // float->double conversion.
4542 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4543 DstTy->isIntegral() &&
4544 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4547 // Packed type conversions don't modify bits.
4548 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
4554 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
4555 if (V->getType() == Ty || isa<Constant>(V)) return false;
4556 if (const CastInst *CI = dyn_cast<CastInst>(V))
4557 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4563 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4564 /// InsertBefore instruction. This is specialized a bit to avoid inserting
4565 /// casts that are known to not do anything...
4567 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4568 Instruction *InsertBefore) {
4569 if (V->getType() == DestTy) return V;
4570 if (Constant *C = dyn_cast<Constant>(V))
4571 return ConstantExpr::getCast(C, DestTy);
4573 CastInst *CI = new CastInst(V, DestTy, V->getName());
4574 InsertNewInstBefore(CI, *InsertBefore);
4578 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4579 /// expression. If so, decompose it, returning some value X, such that Val is
4582 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4584 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4585 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4586 Offset = CI->getValue();
4588 return ConstantUInt::get(Type::UIntTy, 0);
4589 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4590 if (I->getNumOperands() == 2) {
4591 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4592 if (I->getOpcode() == Instruction::Shl) {
4593 // This is a value scaled by '1 << the shift amt'.
4594 Scale = 1U << CUI->getValue();
4596 return I->getOperand(0);
4597 } else if (I->getOpcode() == Instruction::Mul) {
4598 // This value is scaled by 'CUI'.
4599 Scale = CUI->getValue();
4601 return I->getOperand(0);
4602 } else if (I->getOpcode() == Instruction::Add) {
4603 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4606 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4608 Offset += CUI->getValue();
4609 if (SubScale > 1 && (Offset % SubScale == 0)) {
4618 // Otherwise, we can't look past this.
4625 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4626 /// try to eliminate the cast by moving the type information into the alloc.
4627 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4628 AllocationInst &AI) {
4629 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
4630 if (!PTy) return 0; // Not casting the allocation to a pointer type.
4632 // Remove any uses of AI that are dead.
4633 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4634 std::vector<Instruction*> DeadUsers;
4635 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4636 Instruction *User = cast<Instruction>(*UI++);
4637 if (isInstructionTriviallyDead(User)) {
4638 while (UI != E && *UI == User)
4639 ++UI; // If this instruction uses AI more than once, don't break UI.
4641 // Add operands to the worklist.
4642 AddUsesToWorkList(*User);
4644 DEBUG(std::cerr << "IC: DCE: " << *User);
4646 User->eraseFromParent();
4647 removeFromWorkList(User);
4651 // Get the type really allocated and the type casted to.
4652 const Type *AllocElTy = AI.getAllocatedType();
4653 const Type *CastElTy = PTy->getElementType();
4654 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4656 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4657 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4658 if (CastElTyAlign < AllocElTyAlign) return 0;
4660 // If the allocation has multiple uses, only promote it if we are strictly
4661 // increasing the alignment of the resultant allocation. If we keep it the
4662 // same, we open the door to infinite loops of various kinds.
4663 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4665 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4666 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4667 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4669 // See if we can satisfy the modulus by pulling a scale out of the array
4671 unsigned ArraySizeScale, ArrayOffset;
4672 Value *NumElements = // See if the array size is a decomposable linear expr.
4673 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4675 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4677 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4678 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
4680 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4685 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4686 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4687 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4688 else if (Scale != 1) {
4689 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4690 Amt = InsertNewInstBefore(Tmp, AI);
4694 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4695 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4696 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4697 Amt = InsertNewInstBefore(Tmp, AI);
4700 std::string Name = AI.getName(); AI.setName("");
4701 AllocationInst *New;
4702 if (isa<MallocInst>(AI))
4703 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4705 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4706 InsertNewInstBefore(New, AI);
4708 // If the allocation has multiple uses, insert a cast and change all things
4709 // that used it to use the new cast. This will also hack on CI, but it will
4711 if (!AI.hasOneUse()) {
4712 AddUsesToWorkList(AI);
4713 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4714 InsertNewInstBefore(NewCast, AI);
4715 AI.replaceAllUsesWith(NewCast);
4717 return ReplaceInstUsesWith(CI, New);
4721 // CastInst simplification
4723 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4724 Value *Src = CI.getOperand(0);
4726 // If the user is casting a value to the same type, eliminate this cast
4728 if (CI.getType() == Src->getType())
4729 return ReplaceInstUsesWith(CI, Src);
4731 if (isa<UndefValue>(Src)) // cast undef -> undef
4732 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4734 // If casting the result of another cast instruction, try to eliminate this
4737 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4738 Value *A = CSrc->getOperand(0);
4739 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4740 CI.getType(), TD)) {
4741 // This instruction now refers directly to the cast's src operand. This
4742 // has a good chance of making CSrc dead.
4743 CI.setOperand(0, CSrc->getOperand(0));
4747 // If this is an A->B->A cast, and we are dealing with integral types, try
4748 // to convert this into a logical 'and' instruction.
4750 if (A->getType()->isInteger() &&
4751 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
4752 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
4753 CSrc->getType()->getPrimitiveSizeInBits() <
4754 CI.getType()->getPrimitiveSizeInBits()&&
4755 A->getType()->getPrimitiveSizeInBits() ==
4756 CI.getType()->getPrimitiveSizeInBits()) {
4757 assert(CSrc->getType() != Type::ULongTy &&
4758 "Cannot have type bigger than ulong!");
4759 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
4760 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4762 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4763 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4764 if (And->getType() != CI.getType()) {
4765 And->setName(CSrc->getName()+".mask");
4766 InsertNewInstBefore(And, CI);
4767 And = new CastInst(And, CI.getType());
4773 // If this is a cast to bool, turn it into the appropriate setne instruction.
4774 if (CI.getType() == Type::BoolTy)
4775 return BinaryOperator::createSetNE(CI.getOperand(0),
4776 Constant::getNullValue(CI.getOperand(0)->getType()));
4778 // See if we can simplify any instructions used by the LHS whose sole
4779 // purpose is to compute bits we don't care about.
4780 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4781 uint64_t KnownZero, KnownOne;
4782 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4783 KnownZero, KnownOne))
4787 // If casting the result of a getelementptr instruction with no offset, turn
4788 // this into a cast of the original pointer!
4790 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4791 bool AllZeroOperands = true;
4792 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4793 if (!isa<Constant>(GEP->getOperand(i)) ||
4794 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4795 AllZeroOperands = false;
4798 if (AllZeroOperands) {
4799 CI.setOperand(0, GEP->getOperand(0));
4804 // If we are casting a malloc or alloca to a pointer to a type of the same
4805 // size, rewrite the allocation instruction to allocate the "right" type.
4807 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
4808 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4811 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4812 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4814 if (isa<PHINode>(Src))
4815 if (Instruction *NV = FoldOpIntoPhi(CI))
4818 // If the source and destination are pointers, and this cast is equivalent to
4819 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
4820 // This can enhance SROA and other transforms that want type-safe pointers.
4821 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
4822 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
4823 const Type *DstTy = DstPTy->getElementType();
4824 const Type *SrcTy = SrcPTy->getElementType();
4826 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
4827 unsigned NumZeros = 0;
4828 while (SrcTy != DstTy &&
4829 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
4830 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
4834 // If we found a path from the src to dest, create the getelementptr now.
4835 if (SrcTy == DstTy) {
4836 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
4837 return new GetElementPtrInst(Src, Idxs);
4841 // If the source value is an instruction with only this use, we can attempt to
4842 // propagate the cast into the instruction. Also, only handle integral types
4844 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4845 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4846 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4847 const Type *DestTy = CI.getType();
4848 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4849 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
4851 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4852 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4854 switch (SrcI->getOpcode()) {
4855 case Instruction::Add:
4856 case Instruction::Mul:
4857 case Instruction::And:
4858 case Instruction::Or:
4859 case Instruction::Xor:
4860 // If we are discarding information, or just changing the sign, rewrite.
4861 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4862 // Don't insert two casts if they cannot be eliminated. We allow two
4863 // casts to be inserted if the sizes are the same. This could only be
4864 // converting signedness, which is a noop.
4865 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4866 !ValueRequiresCast(Op0, DestTy, TD)) {
4867 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4868 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4869 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4870 ->getOpcode(), Op0c, Op1c);
4874 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4875 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4876 Op1 == ConstantBool::True &&
4877 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4878 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4879 return BinaryOperator::createXor(New,
4880 ConstantInt::get(CI.getType(), 1));
4883 case Instruction::Shl:
4884 // Allow changing the sign of the source operand. Do not allow changing
4885 // the size of the shift, UNLESS the shift amount is a constant. We
4886 // mush not change variable sized shifts to a smaller size, because it
4887 // is undefined to shift more bits out than exist in the value.
4888 if (DestBitSize == SrcBitSize ||
4889 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4890 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4891 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4894 case Instruction::Shr:
4895 // If this is a signed shr, and if all bits shifted in are about to be
4896 // truncated off, turn it into an unsigned shr to allow greater
4898 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4899 isa<ConstantInt>(Op1)) {
4900 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4901 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4902 // Convert to unsigned.
4903 Value *N1 = InsertOperandCastBefore(Op0,
4904 Op0->getType()->getUnsignedVersion(), &CI);
4905 // Insert the new shift, which is now unsigned.
4906 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4907 Op1, Src->getName()), CI);
4908 return new CastInst(N1, CI.getType());
4913 case Instruction::SetEQ:
4914 case Instruction::SetNE:
4915 // We if we are just checking for a seteq of a single bit and casting it
4916 // to an integer. If so, shift the bit to the appropriate place then
4917 // cast to integer to avoid the comparison.
4918 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4919 uint64_t Op1CV = Op1C->getZExtValue();
4920 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
4921 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4922 // cast (X == 1) to int --> X iff X has only the low bit set.
4923 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
4924 // cast (X != 0) to int --> X iff X has only the low bit set.
4925 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
4926 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
4927 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4928 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4929 // If Op1C some other power of two, convert:
4930 uint64_t KnownZero, KnownOne;
4931 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4932 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4934 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4935 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4936 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4937 // (X&4) == 2 --> false
4938 // (X&4) != 2 --> true
4939 Constant *Res = ConstantBool::get(isSetNE);
4940 Res = ConstantExpr::getCast(Res, CI.getType());
4941 return ReplaceInstUsesWith(CI, Res);
4944 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4947 // Perform an unsigned shr by shiftamt. Convert input to
4948 // unsigned if it is signed.
4949 if (In->getType()->isSigned())
4950 In = InsertNewInstBefore(new CastInst(In,
4951 In->getType()->getUnsignedVersion(), In->getName()),CI);
4952 // Insert the shift to put the result in the low bit.
4953 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4954 ConstantInt::get(Type::UByteTy, ShiftAmt),
4955 In->getName()+".lobit"), CI);
4958 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
4959 Constant *One = ConstantInt::get(In->getType(), 1);
4960 In = BinaryOperator::createXor(In, One, "tmp");
4961 InsertNewInstBefore(cast<Instruction>(In), CI);
4964 if (CI.getType() == In->getType())
4965 return ReplaceInstUsesWith(CI, In);
4967 return new CastInst(In, CI.getType());
4978 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4980 /// %D = select %cond, %C, %A
4982 /// %C = select %cond, %B, 0
4985 /// Assuming that the specified instruction is an operand to the select, return
4986 /// a bitmask indicating which operands of this instruction are foldable if they
4987 /// equal the other incoming value of the select.
4989 static unsigned GetSelectFoldableOperands(Instruction *I) {
4990 switch (I->getOpcode()) {
4991 case Instruction::Add:
4992 case Instruction::Mul:
4993 case Instruction::And:
4994 case Instruction::Or:
4995 case Instruction::Xor:
4996 return 3; // Can fold through either operand.
4997 case Instruction::Sub: // Can only fold on the amount subtracted.
4998 case Instruction::Shl: // Can only fold on the shift amount.
4999 case Instruction::Shr:
5002 return 0; // Cannot fold
5006 /// GetSelectFoldableConstant - For the same transformation as the previous
5007 /// function, return the identity constant that goes into the select.
5008 static Constant *GetSelectFoldableConstant(Instruction *I) {
5009 switch (I->getOpcode()) {
5010 default: assert(0 && "This cannot happen!"); abort();
5011 case Instruction::Add:
5012 case Instruction::Sub:
5013 case Instruction::Or:
5014 case Instruction::Xor:
5015 return Constant::getNullValue(I->getType());
5016 case Instruction::Shl:
5017 case Instruction::Shr:
5018 return Constant::getNullValue(Type::UByteTy);
5019 case Instruction::And:
5020 return ConstantInt::getAllOnesValue(I->getType());
5021 case Instruction::Mul:
5022 return ConstantInt::get(I->getType(), 1);
5026 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5027 /// have the same opcode and only one use each. Try to simplify this.
5028 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5030 if (TI->getNumOperands() == 1) {
5031 // If this is a non-volatile load or a cast from the same type,
5033 if (TI->getOpcode() == Instruction::Cast) {
5034 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5037 return 0; // unknown unary op.
5040 // Fold this by inserting a select from the input values.
5041 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5042 FI->getOperand(0), SI.getName()+".v");
5043 InsertNewInstBefore(NewSI, SI);
5044 return new CastInst(NewSI, TI->getType());
5047 // Only handle binary operators here.
5048 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5051 // Figure out if the operations have any operands in common.
5052 Value *MatchOp, *OtherOpT, *OtherOpF;
5054 if (TI->getOperand(0) == FI->getOperand(0)) {
5055 MatchOp = TI->getOperand(0);
5056 OtherOpT = TI->getOperand(1);
5057 OtherOpF = FI->getOperand(1);
5058 MatchIsOpZero = true;
5059 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5060 MatchOp = TI->getOperand(1);
5061 OtherOpT = TI->getOperand(0);
5062 OtherOpF = FI->getOperand(0);
5063 MatchIsOpZero = false;
5064 } else if (!TI->isCommutative()) {
5066 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5067 MatchOp = TI->getOperand(0);
5068 OtherOpT = TI->getOperand(1);
5069 OtherOpF = FI->getOperand(0);
5070 MatchIsOpZero = true;
5071 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5072 MatchOp = TI->getOperand(1);
5073 OtherOpT = TI->getOperand(0);
5074 OtherOpF = FI->getOperand(1);
5075 MatchIsOpZero = true;
5080 // If we reach here, they do have operations in common.
5081 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5082 OtherOpF, SI.getName()+".v");
5083 InsertNewInstBefore(NewSI, SI);
5085 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5087 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5089 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5092 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5094 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5098 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
5099 Value *CondVal = SI.getCondition();
5100 Value *TrueVal = SI.getTrueValue();
5101 Value *FalseVal = SI.getFalseValue();
5103 // select true, X, Y -> X
5104 // select false, X, Y -> Y
5105 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
5106 if (C == ConstantBool::True)
5107 return ReplaceInstUsesWith(SI, TrueVal);
5109 assert(C == ConstantBool::False);
5110 return ReplaceInstUsesWith(SI, FalseVal);
5113 // select C, X, X -> X
5114 if (TrueVal == FalseVal)
5115 return ReplaceInstUsesWith(SI, TrueVal);
5117 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5118 return ReplaceInstUsesWith(SI, FalseVal);
5119 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5120 return ReplaceInstUsesWith(SI, TrueVal);
5121 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5122 if (isa<Constant>(TrueVal))
5123 return ReplaceInstUsesWith(SI, TrueVal);
5125 return ReplaceInstUsesWith(SI, FalseVal);
5128 if (SI.getType() == Type::BoolTy)
5129 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5130 if (C == ConstantBool::True) {
5131 // Change: A = select B, true, C --> A = or B, C
5132 return BinaryOperator::createOr(CondVal, FalseVal);
5134 // Change: A = select B, false, C --> A = and !B, C
5136 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5137 "not."+CondVal->getName()), SI);
5138 return BinaryOperator::createAnd(NotCond, FalseVal);
5140 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5141 if (C == ConstantBool::False) {
5142 // Change: A = select B, C, false --> A = and B, C
5143 return BinaryOperator::createAnd(CondVal, TrueVal);
5145 // Change: A = select B, C, true --> A = or !B, C
5147 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5148 "not."+CondVal->getName()), SI);
5149 return BinaryOperator::createOr(NotCond, TrueVal);
5153 // Selecting between two integer constants?
5154 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5155 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5156 // select C, 1, 0 -> cast C to int
5157 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5158 return new CastInst(CondVal, SI.getType());
5159 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5160 // select C, 0, 1 -> cast !C to int
5162 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5163 "not."+CondVal->getName()), SI);
5164 return new CastInst(NotCond, SI.getType());
5167 // If one of the constants is zero (we know they can't both be) and we
5168 // have a setcc instruction with zero, and we have an 'and' with the
5169 // non-constant value, eliminate this whole mess. This corresponds to
5170 // cases like this: ((X & 27) ? 27 : 0)
5171 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5172 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5173 if ((IC->getOpcode() == Instruction::SetEQ ||
5174 IC->getOpcode() == Instruction::SetNE) &&
5175 isa<ConstantInt>(IC->getOperand(1)) &&
5176 cast<Constant>(IC->getOperand(1))->isNullValue())
5177 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5178 if (ICA->getOpcode() == Instruction::And &&
5179 isa<ConstantInt>(ICA->getOperand(1)) &&
5180 (ICA->getOperand(1) == TrueValC ||
5181 ICA->getOperand(1) == FalseValC) &&
5182 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5183 // Okay, now we know that everything is set up, we just don't
5184 // know whether we have a setne or seteq and whether the true or
5185 // false val is the zero.
5186 bool ShouldNotVal = !TrueValC->isNullValue();
5187 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5190 V = InsertNewInstBefore(BinaryOperator::create(
5191 Instruction::Xor, V, ICA->getOperand(1)), SI);
5192 return ReplaceInstUsesWith(SI, V);
5196 // See if we are selecting two values based on a comparison of the two values.
5197 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5198 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5199 // Transform (X == Y) ? X : Y -> Y
5200 if (SCI->getOpcode() == Instruction::SetEQ)
5201 return ReplaceInstUsesWith(SI, FalseVal);
5202 // Transform (X != Y) ? X : Y -> X
5203 if (SCI->getOpcode() == Instruction::SetNE)
5204 return ReplaceInstUsesWith(SI, TrueVal);
5205 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5207 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5208 // Transform (X == Y) ? Y : X -> X
5209 if (SCI->getOpcode() == Instruction::SetEQ)
5210 return ReplaceInstUsesWith(SI, FalseVal);
5211 // Transform (X != Y) ? Y : X -> Y
5212 if (SCI->getOpcode() == Instruction::SetNE)
5213 return ReplaceInstUsesWith(SI, TrueVal);
5214 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5218 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5219 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5220 if (TI->hasOneUse() && FI->hasOneUse()) {
5221 bool isInverse = false;
5222 Instruction *AddOp = 0, *SubOp = 0;
5224 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5225 if (TI->getOpcode() == FI->getOpcode())
5226 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5229 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5230 // even legal for FP.
5231 if (TI->getOpcode() == Instruction::Sub &&
5232 FI->getOpcode() == Instruction::Add) {
5233 AddOp = FI; SubOp = TI;
5234 } else if (FI->getOpcode() == Instruction::Sub &&
5235 TI->getOpcode() == Instruction::Add) {
5236 AddOp = TI; SubOp = FI;
5240 Value *OtherAddOp = 0;
5241 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5242 OtherAddOp = AddOp->getOperand(1);
5243 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5244 OtherAddOp = AddOp->getOperand(0);
5248 // So at this point we know we have (Y -> OtherAddOp):
5249 // select C, (add X, Y), (sub X, Z)
5250 Value *NegVal; // Compute -Z
5251 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5252 NegVal = ConstantExpr::getNeg(C);
5254 NegVal = InsertNewInstBefore(
5255 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
5258 Value *NewTrueOp = OtherAddOp;
5259 Value *NewFalseOp = NegVal;
5261 std::swap(NewTrueOp, NewFalseOp);
5262 Instruction *NewSel =
5263 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5265 NewSel = InsertNewInstBefore(NewSel, SI);
5266 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
5271 // See if we can fold the select into one of our operands.
5272 if (SI.getType()->isInteger()) {
5273 // See the comment above GetSelectFoldableOperands for a description of the
5274 // transformation we are doing here.
5275 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5276 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5277 !isa<Constant>(FalseVal))
5278 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5279 unsigned OpToFold = 0;
5280 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5282 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5287 Constant *C = GetSelectFoldableConstant(TVI);
5288 std::string Name = TVI->getName(); TVI->setName("");
5289 Instruction *NewSel =
5290 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5292 InsertNewInstBefore(NewSel, SI);
5293 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5294 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5295 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5296 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5298 assert(0 && "Unknown instruction!!");
5303 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5304 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5305 !isa<Constant>(TrueVal))
5306 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5307 unsigned OpToFold = 0;
5308 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5310 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5315 Constant *C = GetSelectFoldableConstant(FVI);
5316 std::string Name = FVI->getName(); FVI->setName("");
5317 Instruction *NewSel =
5318 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5320 InsertNewInstBefore(NewSel, SI);
5321 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5322 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5323 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5324 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5326 assert(0 && "Unknown instruction!!");
5332 if (BinaryOperator::isNot(CondVal)) {
5333 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5334 SI.setOperand(1, FalseVal);
5335 SI.setOperand(2, TrueVal);
5342 /// GetKnownAlignment - If the specified pointer has an alignment that we can
5343 /// determine, return it, otherwise return 0.
5344 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5345 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5346 unsigned Align = GV->getAlignment();
5347 if (Align == 0 && TD)
5348 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5350 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5351 unsigned Align = AI->getAlignment();
5352 if (Align == 0 && TD) {
5353 if (isa<AllocaInst>(AI))
5354 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5355 else if (isa<MallocInst>(AI)) {
5356 // Malloc returns maximally aligned memory.
5357 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5358 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5359 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5363 } else if (isa<CastInst>(V) ||
5364 (isa<ConstantExpr>(V) &&
5365 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5366 User *CI = cast<User>(V);
5367 if (isa<PointerType>(CI->getOperand(0)->getType()))
5368 return GetKnownAlignment(CI->getOperand(0), TD);
5370 } else if (isa<GetElementPtrInst>(V) ||
5371 (isa<ConstantExpr>(V) &&
5372 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5373 User *GEPI = cast<User>(V);
5374 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5375 if (BaseAlignment == 0) return 0;
5377 // If all indexes are zero, it is just the alignment of the base pointer.
5378 bool AllZeroOperands = true;
5379 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5380 if (!isa<Constant>(GEPI->getOperand(i)) ||
5381 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5382 AllZeroOperands = false;
5385 if (AllZeroOperands)
5386 return BaseAlignment;
5388 // Otherwise, if the base alignment is >= the alignment we expect for the
5389 // base pointer type, then we know that the resultant pointer is aligned at
5390 // least as much as its type requires.
5393 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5394 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
5396 const Type *GEPTy = GEPI->getType();
5397 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5405 /// visitCallInst - CallInst simplification. This mostly only handles folding
5406 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5407 /// the heavy lifting.
5409 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
5410 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5411 if (!II) return visitCallSite(&CI);
5413 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5415 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
5416 bool Changed = false;
5418 // memmove/cpy/set of zero bytes is a noop.
5419 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5420 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5422 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5423 if (CI->getRawValue() == 1) {
5424 // Replace the instruction with just byte operations. We would
5425 // transform other cases to loads/stores, but we don't know if
5426 // alignment is sufficient.
5430 // If we have a memmove and the source operation is a constant global,
5431 // then the source and dest pointers can't alias, so we can change this
5432 // into a call to memcpy.
5433 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
5434 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5435 if (GVSrc->isConstant()) {
5436 Module *M = CI.getParent()->getParent()->getParent();
5438 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5440 Name = "llvm.memcpy.i32";
5442 Name = "llvm.memcpy.i64";
5443 Function *MemCpy = M->getOrInsertFunction(Name,
5444 CI.getCalledFunction()->getFunctionType());
5445 CI.setOperand(0, MemCpy);
5450 // If we can determine a pointer alignment that is bigger than currently
5451 // set, update the alignment.
5452 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5453 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5454 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5455 unsigned Align = std::min(Alignment1, Alignment2);
5456 if (MI->getAlignment()->getRawValue() < Align) {
5457 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5460 } else if (isa<MemSetInst>(MI)) {
5461 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5462 if (MI->getAlignment()->getRawValue() < Alignment) {
5463 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5468 if (Changed) return II;
5470 switch (II->getIntrinsicID()) {
5472 case Intrinsic::ppc_altivec_lvx:
5473 case Intrinsic::ppc_altivec_lvxl:
5474 case Intrinsic::x86_sse_loadu_ps:
5475 case Intrinsic::x86_sse2_loadu_pd:
5476 case Intrinsic::x86_sse2_loadu_dq:
5477 // Turn PPC lvx -> load if the pointer is known aligned.
5478 // Turn X86 loadups -> load if the pointer is known aligned.
5479 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5480 Value *Ptr = InsertCastBefore(II->getOperand(1),
5481 PointerType::get(II->getType()), CI);
5482 return new LoadInst(Ptr);
5485 case Intrinsic::ppc_altivec_stvx:
5486 case Intrinsic::ppc_altivec_stvxl:
5487 // Turn stvx -> store if the pointer is known aligned.
5488 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
5489 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5490 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
5491 return new StoreInst(II->getOperand(1), Ptr);
5494 case Intrinsic::x86_sse_storeu_ps:
5495 case Intrinsic::x86_sse2_storeu_pd:
5496 case Intrinsic::x86_sse2_storeu_dq:
5497 case Intrinsic::x86_sse2_storel_dq:
5498 // Turn X86 storeu -> store if the pointer is known aligned.
5499 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5500 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5501 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5502 return new StoreInst(II->getOperand(2), Ptr);
5505 case Intrinsic::ppc_altivec_vperm:
5506 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5507 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5508 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5510 // Check that all of the elements are integer constants or undefs.
5511 bool AllEltsOk = true;
5512 for (unsigned i = 0; i != 16; ++i) {
5513 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5514 !isa<UndefValue>(Mask->getOperand(i))) {
5521 // Cast the input vectors to byte vectors.
5522 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5523 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5524 Value *Result = UndefValue::get(Op0->getType());
5526 // Only extract each element once.
5527 Value *ExtractedElts[32];
5528 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5530 for (unsigned i = 0; i != 16; ++i) {
5531 if (isa<UndefValue>(Mask->getOperand(i)))
5533 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5534 Idx &= 31; // Match the hardware behavior.
5536 if (ExtractedElts[Idx] == 0) {
5538 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5539 ConstantUInt::get(Type::UIntTy, Idx&15),
5541 InsertNewInstBefore(Elt, CI);
5542 ExtractedElts[Idx] = Elt;
5545 // Insert this value into the result vector.
5546 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5547 ConstantUInt::get(Type::UIntTy, i),
5549 InsertNewInstBefore(cast<Instruction>(Result), CI);
5551 return new CastInst(Result, CI.getType());
5556 case Intrinsic::stackrestore: {
5557 // If the save is right next to the restore, remove the restore. This can
5558 // happen when variable allocas are DCE'd.
5559 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5560 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5561 BasicBlock::iterator BI = SS;
5563 return EraseInstFromFunction(CI);
5567 // If the stack restore is in a return/unwind block and if there are no
5568 // allocas or calls between the restore and the return, nuke the restore.
5569 TerminatorInst *TI = II->getParent()->getTerminator();
5570 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5571 BasicBlock::iterator BI = II;
5572 bool CannotRemove = false;
5573 for (++BI; &*BI != TI; ++BI) {
5574 if (isa<AllocaInst>(BI) ||
5575 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5576 CannotRemove = true;
5581 return EraseInstFromFunction(CI);
5588 return visitCallSite(II);
5591 // InvokeInst simplification
5593 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
5594 return visitCallSite(&II);
5597 // visitCallSite - Improvements for call and invoke instructions.
5599 Instruction *InstCombiner::visitCallSite(CallSite CS) {
5600 bool Changed = false;
5602 // If the callee is a constexpr cast of a function, attempt to move the cast
5603 // to the arguments of the call/invoke.
5604 if (transformConstExprCastCall(CS)) return 0;
5606 Value *Callee = CS.getCalledValue();
5608 if (Function *CalleeF = dyn_cast<Function>(Callee))
5609 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5610 Instruction *OldCall = CS.getInstruction();
5611 // If the call and callee calling conventions don't match, this call must
5612 // be unreachable, as the call is undefined.
5613 new StoreInst(ConstantBool::True,
5614 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5615 if (!OldCall->use_empty())
5616 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5617 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5618 return EraseInstFromFunction(*OldCall);
5622 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5623 // This instruction is not reachable, just remove it. We insert a store to
5624 // undef so that we know that this code is not reachable, despite the fact
5625 // that we can't modify the CFG here.
5626 new StoreInst(ConstantBool::True,
5627 UndefValue::get(PointerType::get(Type::BoolTy)),
5628 CS.getInstruction());
5630 if (!CS.getInstruction()->use_empty())
5631 CS.getInstruction()->
5632 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5634 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5635 // Don't break the CFG, insert a dummy cond branch.
5636 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5637 ConstantBool::True, II);
5639 return EraseInstFromFunction(*CS.getInstruction());
5642 const PointerType *PTy = cast<PointerType>(Callee->getType());
5643 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5644 if (FTy->isVarArg()) {
5645 // See if we can optimize any arguments passed through the varargs area of
5647 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5648 E = CS.arg_end(); I != E; ++I)
5649 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5650 // If this cast does not effect the value passed through the varargs
5651 // area, we can eliminate the use of the cast.
5652 Value *Op = CI->getOperand(0);
5653 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5660 return Changed ? CS.getInstruction() : 0;
5663 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
5664 // attempt to move the cast to the arguments of the call/invoke.
5666 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5667 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5668 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
5669 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
5671 Function *Callee = cast<Function>(CE->getOperand(0));
5672 Instruction *Caller = CS.getInstruction();
5674 // Okay, this is a cast from a function to a different type. Unless doing so
5675 // would cause a type conversion of one of our arguments, change this call to
5676 // be a direct call with arguments casted to the appropriate types.
5678 const FunctionType *FT = Callee->getFunctionType();
5679 const Type *OldRetTy = Caller->getType();
5681 // Check to see if we are changing the return type...
5682 if (OldRetTy != FT->getReturnType()) {
5683 if (Callee->isExternal() &&
5684 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
5685 (isa<PointerType>(FT->getReturnType()) &&
5686 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
5687 && !Caller->use_empty())
5688 return false; // Cannot transform this return value...
5690 // If the callsite is an invoke instruction, and the return value is used by
5691 // a PHI node in a successor, we cannot change the return type of the call
5692 // because there is no place to put the cast instruction (without breaking
5693 // the critical edge). Bail out in this case.
5694 if (!Caller->use_empty())
5695 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5696 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5698 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5699 if (PN->getParent() == II->getNormalDest() ||
5700 PN->getParent() == II->getUnwindDest())
5704 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5705 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
5707 CallSite::arg_iterator AI = CS.arg_begin();
5708 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5709 const Type *ParamTy = FT->getParamType(i);
5710 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
5711 if (Callee->isExternal() && !isConvertible) return false;
5714 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5715 Callee->isExternal())
5716 return false; // Do not delete arguments unless we have a function body...
5718 // Okay, we decided that this is a safe thing to do: go ahead and start
5719 // inserting cast instructions as necessary...
5720 std::vector<Value*> Args;
5721 Args.reserve(NumActualArgs);
5723 AI = CS.arg_begin();
5724 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5725 const Type *ParamTy = FT->getParamType(i);
5726 if ((*AI)->getType() == ParamTy) {
5727 Args.push_back(*AI);
5729 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5734 // If the function takes more arguments than the call was taking, add them
5736 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5737 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5739 // If we are removing arguments to the function, emit an obnoxious warning...
5740 if (FT->getNumParams() < NumActualArgs)
5741 if (!FT->isVarArg()) {
5742 std::cerr << "WARNING: While resolving call to function '"
5743 << Callee->getName() << "' arguments were dropped!\n";
5745 // Add all of the arguments in their promoted form to the arg list...
5746 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5747 const Type *PTy = getPromotedType((*AI)->getType());
5748 if (PTy != (*AI)->getType()) {
5749 // Must promote to pass through va_arg area!
5750 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5751 InsertNewInstBefore(Cast, *Caller);
5752 Args.push_back(Cast);
5754 Args.push_back(*AI);
5759 if (FT->getReturnType() == Type::VoidTy)
5760 Caller->setName(""); // Void type should not have a name...
5763 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5764 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
5765 Args, Caller->getName(), Caller);
5766 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
5768 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
5769 if (cast<CallInst>(Caller)->isTailCall())
5770 cast<CallInst>(NC)->setTailCall();
5771 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
5774 // Insert a cast of the return type as necessary...
5776 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5777 if (NV->getType() != Type::VoidTy) {
5778 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
5780 // If this is an invoke instruction, we should insert it after the first
5781 // non-phi, instruction in the normal successor block.
5782 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5783 BasicBlock::iterator I = II->getNormalDest()->begin();
5784 while (isa<PHINode>(I)) ++I;
5785 InsertNewInstBefore(NC, *I);
5787 // Otherwise, it's a call, just insert cast right after the call instr
5788 InsertNewInstBefore(NC, *Caller);
5790 AddUsersToWorkList(*Caller);
5792 NV = UndefValue::get(Caller->getType());
5796 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5797 Caller->replaceAllUsesWith(NV);
5798 Caller->getParent()->getInstList().erase(Caller);
5799 removeFromWorkList(Caller);
5804 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5805 // operator and they all are only used by the PHI, PHI together their
5806 // inputs, and do the operation once, to the result of the PHI.
5807 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5808 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5810 // Scan the instruction, looking for input operations that can be folded away.
5811 // If all input operands to the phi are the same instruction (e.g. a cast from
5812 // the same type or "+42") we can pull the operation through the PHI, reducing
5813 // code size and simplifying code.
5814 Constant *ConstantOp = 0;
5815 const Type *CastSrcTy = 0;
5816 if (isa<CastInst>(FirstInst)) {
5817 CastSrcTy = FirstInst->getOperand(0)->getType();
5818 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5819 // Can fold binop or shift if the RHS is a constant.
5820 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5821 if (ConstantOp == 0) return 0;
5823 return 0; // Cannot fold this operation.
5826 // Check to see if all arguments are the same operation.
5827 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5828 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5829 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5830 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5833 if (I->getOperand(0)->getType() != CastSrcTy)
5834 return 0; // Cast operation must match.
5835 } else if (I->getOperand(1) != ConstantOp) {
5840 // Okay, they are all the same operation. Create a new PHI node of the
5841 // correct type, and PHI together all of the LHS's of the instructions.
5842 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5843 PN.getName()+".in");
5844 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
5846 Value *InVal = FirstInst->getOperand(0);
5847 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
5849 // Add all operands to the new PHI.
5850 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5851 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5852 if (NewInVal != InVal)
5854 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5859 // The new PHI unions all of the same values together. This is really
5860 // common, so we handle it intelligently here for compile-time speed.
5864 InsertNewInstBefore(NewPN, PN);
5868 // Insert and return the new operation.
5869 if (isa<CastInst>(FirstInst))
5870 return new CastInst(PhiVal, PN.getType());
5871 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
5872 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
5874 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
5875 PhiVal, ConstantOp);
5878 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5880 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5881 if (PN->use_empty()) return true;
5882 if (!PN->hasOneUse()) return false;
5884 // Remember this node, and if we find the cycle, return.
5885 if (!PotentiallyDeadPHIs.insert(PN).second)
5888 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5889 return DeadPHICycle(PU, PotentiallyDeadPHIs);
5894 // PHINode simplification
5896 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
5897 if (Value *V = PN.hasConstantValue())
5898 return ReplaceInstUsesWith(PN, V);
5900 // If the only user of this instruction is a cast instruction, and all of the
5901 // incoming values are constants, change this PHI to merge together the casted
5904 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5905 if (CI->getType() != PN.getType()) { // noop casts will be folded
5906 bool AllConstant = true;
5907 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5908 if (!isa<Constant>(PN.getIncomingValue(i))) {
5909 AllConstant = false;
5913 // Make a new PHI with all casted values.
5914 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5915 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5916 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5917 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5918 PN.getIncomingBlock(i));
5921 // Update the cast instruction.
5922 CI->setOperand(0, New);
5923 WorkList.push_back(CI); // revisit the cast instruction to fold.
5924 WorkList.push_back(New); // Make sure to revisit the new Phi
5925 return &PN; // PN is now dead!
5929 // If all PHI operands are the same operation, pull them through the PHI,
5930 // reducing code size.
5931 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5932 PN.getIncomingValue(0)->hasOneUse())
5933 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5936 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5937 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5938 // PHI)... break the cycle.
5940 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5941 std::set<PHINode*> PotentiallyDeadPHIs;
5942 PotentiallyDeadPHIs.insert(&PN);
5943 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5944 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5950 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5951 Instruction *InsertPoint,
5953 unsigned PS = IC->getTargetData().getPointerSize();
5954 const Type *VTy = V->getType();
5955 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5956 // We must insert a cast to ensure we sign-extend.
5957 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5958 V->getName()), *InsertPoint);
5959 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5964 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
5965 Value *PtrOp = GEP.getOperand(0);
5966 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
5967 // If so, eliminate the noop.
5968 if (GEP.getNumOperands() == 1)
5969 return ReplaceInstUsesWith(GEP, PtrOp);
5971 if (isa<UndefValue>(GEP.getOperand(0)))
5972 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5974 bool HasZeroPointerIndex = false;
5975 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5976 HasZeroPointerIndex = C->isNullValue();
5978 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
5979 return ReplaceInstUsesWith(GEP, PtrOp);
5981 // Eliminate unneeded casts for indices.
5982 bool MadeChange = false;
5983 gep_type_iterator GTI = gep_type_begin(GEP);
5984 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5985 if (isa<SequentialType>(*GTI)) {
5986 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5987 Value *Src = CI->getOperand(0);
5988 const Type *SrcTy = Src->getType();
5989 const Type *DestTy = CI->getType();
5990 if (Src->getType()->isInteger()) {
5991 if (SrcTy->getPrimitiveSizeInBits() ==
5992 DestTy->getPrimitiveSizeInBits()) {
5993 // We can always eliminate a cast from ulong or long to the other.
5994 // We can always eliminate a cast from uint to int or the other on
5995 // 32-bit pointer platforms.
5996 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
5998 GEP.setOperand(i, Src);
6000 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6001 SrcTy->getPrimitiveSize() == 4) {
6002 // We can always eliminate a cast from int to [u]long. We can
6003 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6005 if (SrcTy->isSigned() ||
6006 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
6008 GEP.setOperand(i, Src);
6013 // If we are using a wider index than needed for this platform, shrink it
6014 // to what we need. If the incoming value needs a cast instruction,
6015 // insert it. This explicit cast can make subsequent optimizations more
6017 Value *Op = GEP.getOperand(i);
6018 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
6019 if (Constant *C = dyn_cast<Constant>(Op)) {
6020 GEP.setOperand(i, ConstantExpr::getCast(C,
6021 TD->getIntPtrType()->getSignedVersion()));
6024 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6025 Op->getName()), GEP);
6026 GEP.setOperand(i, Op);
6030 // If this is a constant idx, make sure to canonicalize it to be a signed
6031 // operand, otherwise CSE and other optimizations are pessimized.
6032 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6033 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6034 CUI->getType()->getSignedVersion()));
6038 if (MadeChange) return &GEP;
6040 // Combine Indices - If the source pointer to this getelementptr instruction
6041 // is a getelementptr instruction, combine the indices of the two
6042 // getelementptr instructions into a single instruction.
6044 std::vector<Value*> SrcGEPOperands;
6045 if (User *Src = dyn_castGetElementPtr(PtrOp))
6046 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
6048 if (!SrcGEPOperands.empty()) {
6049 // Note that if our source is a gep chain itself that we wait for that
6050 // chain to be resolved before we perform this transformation. This
6051 // avoids us creating a TON of code in some cases.
6053 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6054 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6055 return 0; // Wait until our source is folded to completion.
6057 std::vector<Value *> Indices;
6059 // Find out whether the last index in the source GEP is a sequential idx.
6060 bool EndsWithSequential = false;
6061 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6062 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
6063 EndsWithSequential = !isa<StructType>(*I);
6065 // Can we combine the two pointer arithmetics offsets?
6066 if (EndsWithSequential) {
6067 // Replace: gep (gep %P, long B), long A, ...
6068 // With: T = long A+B; gep %P, T, ...
6070 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
6071 if (SO1 == Constant::getNullValue(SO1->getType())) {
6073 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6076 // If they aren't the same type, convert both to an integer of the
6077 // target's pointer size.
6078 if (SO1->getType() != GO1->getType()) {
6079 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6080 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6081 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6082 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6084 unsigned PS = TD->getPointerSize();
6085 if (SO1->getType()->getPrimitiveSize() == PS) {
6086 // Convert GO1 to SO1's type.
6087 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6089 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6090 // Convert SO1 to GO1's type.
6091 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6093 const Type *PT = TD->getIntPtrType();
6094 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6095 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6099 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6100 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6102 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6103 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
6107 // Recycle the GEP we already have if possible.
6108 if (SrcGEPOperands.size() == 2) {
6109 GEP.setOperand(0, SrcGEPOperands[0]);
6110 GEP.setOperand(1, Sum);
6113 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6114 SrcGEPOperands.end()-1);
6115 Indices.push_back(Sum);
6116 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6118 } else if (isa<Constant>(*GEP.idx_begin()) &&
6119 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
6120 SrcGEPOperands.size() != 1) {
6121 // Otherwise we can do the fold if the first index of the GEP is a zero
6122 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6123 SrcGEPOperands.end());
6124 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6127 if (!Indices.empty())
6128 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
6130 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
6131 // GEP of global variable. If all of the indices for this GEP are
6132 // constants, we can promote this to a constexpr instead of an instruction.
6134 // Scan for nonconstants...
6135 std::vector<Constant*> Indices;
6136 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6137 for (; I != E && isa<Constant>(*I); ++I)
6138 Indices.push_back(cast<Constant>(*I));
6140 if (I == E) { // If they are all constants...
6141 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
6143 // Replace all uses of the GEP with the new constexpr...
6144 return ReplaceInstUsesWith(GEP, CE);
6146 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6147 if (!isa<PointerType>(X->getType())) {
6148 // Not interesting. Source pointer must be a cast from pointer.
6149 } else if (HasZeroPointerIndex) {
6150 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6151 // into : GEP [10 x ubyte]* X, long 0, ...
6153 // This occurs when the program declares an array extern like "int X[];"
6155 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6156 const PointerType *XTy = cast<PointerType>(X->getType());
6157 if (const ArrayType *XATy =
6158 dyn_cast<ArrayType>(XTy->getElementType()))
6159 if (const ArrayType *CATy =
6160 dyn_cast<ArrayType>(CPTy->getElementType()))
6161 if (CATy->getElementType() == XATy->getElementType()) {
6162 // At this point, we know that the cast source type is a pointer
6163 // to an array of the same type as the destination pointer
6164 // array. Because the array type is never stepped over (there
6165 // is a leading zero) we can fold the cast into this GEP.
6166 GEP.setOperand(0, X);
6169 } else if (GEP.getNumOperands() == 2) {
6170 // Transform things like:
6171 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6172 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
6173 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6174 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6175 if (isa<ArrayType>(SrcElTy) &&
6176 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6177 TD->getTypeSize(ResElTy)) {
6178 Value *V = InsertNewInstBefore(
6179 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6180 GEP.getOperand(1), GEP.getName()), GEP);
6181 return new CastInst(V, GEP.getType());
6184 // Transform things like:
6185 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6186 // (where tmp = 8*tmp2) into:
6187 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6189 if (isa<ArrayType>(SrcElTy) &&
6190 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6191 uint64_t ArrayEltSize =
6192 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6194 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6195 // allow either a mul, shift, or constant here.
6197 ConstantInt *Scale = 0;
6198 if (ArrayEltSize == 1) {
6199 NewIdx = GEP.getOperand(1);
6200 Scale = ConstantInt::get(NewIdx->getType(), 1);
6201 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
6202 NewIdx = ConstantInt::get(CI->getType(), 1);
6204 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6205 if (Inst->getOpcode() == Instruction::Shl &&
6206 isa<ConstantInt>(Inst->getOperand(1))) {
6207 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6208 if (Inst->getType()->isSigned())
6209 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6211 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6212 NewIdx = Inst->getOperand(0);
6213 } else if (Inst->getOpcode() == Instruction::Mul &&
6214 isa<ConstantInt>(Inst->getOperand(1))) {
6215 Scale = cast<ConstantInt>(Inst->getOperand(1));
6216 NewIdx = Inst->getOperand(0);
6220 // If the index will be to exactly the right offset with the scale taken
6221 // out, perform the transformation.
6222 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6223 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6224 Scale = ConstantSInt::get(C->getType(),
6225 (int64_t)C->getRawValue() /
6226 (int64_t)ArrayEltSize);
6228 Scale = ConstantUInt::get(Scale->getType(),
6229 Scale->getRawValue() / ArrayEltSize);
6230 if (Scale->getRawValue() != 1) {
6231 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6232 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6233 NewIdx = InsertNewInstBefore(Sc, GEP);
6236 // Insert the new GEP instruction.
6238 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6239 NewIdx, GEP.getName());
6240 Idx = InsertNewInstBefore(Idx, GEP);
6241 return new CastInst(Idx, GEP.getType());
6250 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6251 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6252 if (AI.isArrayAllocation()) // Check C != 1
6253 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6254 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
6255 AllocationInst *New = 0;
6257 // Create and insert the replacement instruction...
6258 if (isa<MallocInst>(AI))
6259 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
6261 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
6262 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
6265 InsertNewInstBefore(New, AI);
6267 // Scan to the end of the allocation instructions, to skip over a block of
6268 // allocas if possible...
6270 BasicBlock::iterator It = New;
6271 while (isa<AllocationInst>(*It)) ++It;
6273 // Now that I is pointing to the first non-allocation-inst in the block,
6274 // insert our getelementptr instruction...
6276 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6277 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6278 New->getName()+".sub", It);
6280 // Now make everything use the getelementptr instead of the original
6282 return ReplaceInstUsesWith(AI, V);
6283 } else if (isa<UndefValue>(AI.getArraySize())) {
6284 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6287 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6288 // Note that we only do this for alloca's, because malloc should allocate and
6289 // return a unique pointer, even for a zero byte allocation.
6290 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
6291 TD->getTypeSize(AI.getAllocatedType()) == 0)
6292 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6297 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6298 Value *Op = FI.getOperand(0);
6300 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6301 if (CastInst *CI = dyn_cast<CastInst>(Op))
6302 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6303 FI.setOperand(0, CI->getOperand(0));
6307 // free undef -> unreachable.
6308 if (isa<UndefValue>(Op)) {
6309 // Insert a new store to null because we cannot modify the CFG here.
6310 new StoreInst(ConstantBool::True,
6311 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6312 return EraseInstFromFunction(FI);
6315 // If we have 'free null' delete the instruction. This can happen in stl code
6316 // when lots of inlining happens.
6317 if (isa<ConstantPointerNull>(Op))
6318 return EraseInstFromFunction(FI);
6324 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
6325 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6326 User *CI = cast<User>(LI.getOperand(0));
6327 Value *CastOp = CI->getOperand(0);
6329 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6330 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6331 const Type *SrcPTy = SrcTy->getElementType();
6333 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6334 isa<PackedType>(DestPTy)) {
6335 // If the source is an array, the code below will not succeed. Check to
6336 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6338 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6339 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6340 if (ASrcTy->getNumElements() != 0) {
6341 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6342 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6343 SrcTy = cast<PointerType>(CastOp->getType());
6344 SrcPTy = SrcTy->getElementType();
6347 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6348 isa<PackedType>(SrcPTy)) &&
6349 // Do not allow turning this into a load of an integer, which is then
6350 // casted to a pointer, this pessimizes pointer analysis a lot.
6351 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
6352 IC.getTargetData().getTypeSize(SrcPTy) ==
6353 IC.getTargetData().getTypeSize(DestPTy)) {
6355 // Okay, we are casting from one integer or pointer type to another of
6356 // the same size. Instead of casting the pointer before the load, cast
6357 // the result of the loaded value.
6358 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6360 LI.isVolatile()),LI);
6361 // Now cast the result of the load.
6362 return new CastInst(NewLoad, LI.getType());
6369 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
6370 /// from this value cannot trap. If it is not obviously safe to load from the
6371 /// specified pointer, we do a quick local scan of the basic block containing
6372 /// ScanFrom, to determine if the address is already accessed.
6373 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6374 // If it is an alloca or global variable, it is always safe to load from.
6375 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6377 // Otherwise, be a little bit agressive by scanning the local block where we
6378 // want to check to see if the pointer is already being loaded or stored
6379 // from/to. If so, the previous load or store would have already trapped,
6380 // so there is no harm doing an extra load (also, CSE will later eliminate
6381 // the load entirely).
6382 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6387 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6388 if (LI->getOperand(0) == V) return true;
6389 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6390 if (SI->getOperand(1) == V) return true;
6396 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6397 Value *Op = LI.getOperand(0);
6399 // load (cast X) --> cast (load X) iff safe
6400 if (CastInst *CI = dyn_cast<CastInst>(Op))
6401 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6404 // None of the following transforms are legal for volatile loads.
6405 if (LI.isVolatile()) return 0;
6407 if (&LI.getParent()->front() != &LI) {
6408 BasicBlock::iterator BBI = &LI; --BBI;
6409 // If the instruction immediately before this is a store to the same
6410 // address, do a simple form of store->load forwarding.
6411 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6412 if (SI->getOperand(1) == LI.getOperand(0))
6413 return ReplaceInstUsesWith(LI, SI->getOperand(0));
6414 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6415 if (LIB->getOperand(0) == LI.getOperand(0))
6416 return ReplaceInstUsesWith(LI, LIB);
6419 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6420 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6421 isa<UndefValue>(GEPI->getOperand(0))) {
6422 // Insert a new store to null instruction before the load to indicate
6423 // that this code is not reachable. We do this instead of inserting
6424 // an unreachable instruction directly because we cannot modify the
6426 new StoreInst(UndefValue::get(LI.getType()),
6427 Constant::getNullValue(Op->getType()), &LI);
6428 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6431 if (Constant *C = dyn_cast<Constant>(Op)) {
6432 // load null/undef -> undef
6433 if ((C->isNullValue() || isa<UndefValue>(C))) {
6434 // Insert a new store to null instruction before the load to indicate that
6435 // this code is not reachable. We do this instead of inserting an
6436 // unreachable instruction directly because we cannot modify the CFG.
6437 new StoreInst(UndefValue::get(LI.getType()),
6438 Constant::getNullValue(Op->getType()), &LI);
6439 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6442 // Instcombine load (constant global) into the value loaded.
6443 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6444 if (GV->isConstant() && !GV->isExternal())
6445 return ReplaceInstUsesWith(LI, GV->getInitializer());
6447 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6448 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6449 if (CE->getOpcode() == Instruction::GetElementPtr) {
6450 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6451 if (GV->isConstant() && !GV->isExternal())
6453 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
6454 return ReplaceInstUsesWith(LI, V);
6455 if (CE->getOperand(0)->isNullValue()) {
6456 // Insert a new store to null instruction before the load to indicate
6457 // that this code is not reachable. We do this instead of inserting
6458 // an unreachable instruction directly because we cannot modify the
6460 new StoreInst(UndefValue::get(LI.getType()),
6461 Constant::getNullValue(Op->getType()), &LI);
6462 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6465 } else if (CE->getOpcode() == Instruction::Cast) {
6466 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6471 if (Op->hasOneUse()) {
6472 // Change select and PHI nodes to select values instead of addresses: this
6473 // helps alias analysis out a lot, allows many others simplifications, and
6474 // exposes redundancy in the code.
6476 // Note that we cannot do the transformation unless we know that the
6477 // introduced loads cannot trap! Something like this is valid as long as
6478 // the condition is always false: load (select bool %C, int* null, int* %G),
6479 // but it would not be valid if we transformed it to load from null
6482 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6483 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
6484 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6485 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
6486 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
6487 SI->getOperand(1)->getName()+".val"), LI);
6488 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
6489 SI->getOperand(2)->getName()+".val"), LI);
6490 return new SelectInst(SI->getCondition(), V1, V2);
6493 // load (select (cond, null, P)) -> load P
6494 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6495 if (C->isNullValue()) {
6496 LI.setOperand(0, SI->getOperand(2));
6500 // load (select (cond, P, null)) -> load P
6501 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6502 if (C->isNullValue()) {
6503 LI.setOperand(0, SI->getOperand(1));
6507 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6508 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
6509 bool Safe = PN->getParent() == LI.getParent();
6511 // Scan all of the instructions between the PHI and the load to make
6512 // sure there are no instructions that might possibly alter the value
6513 // loaded from the PHI.
6515 BasicBlock::iterator I = &LI;
6516 for (--I; !isa<PHINode>(I); --I)
6517 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6523 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
6524 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
6525 PN->getIncomingBlock(i)->getTerminator()))
6530 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6531 InsertNewInstBefore(NewPN, *PN);
6532 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6534 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6535 BasicBlock *BB = PN->getIncomingBlock(i);
6536 Value *&TheLoad = LoadMap[BB];
6538 Value *InVal = PN->getIncomingValue(i);
6539 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6540 InVal->getName()+".val"),
6541 *BB->getTerminator());
6543 NewPN->addIncoming(TheLoad, BB);
6545 return ReplaceInstUsesWith(LI, NewPN);
6552 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6554 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6555 User *CI = cast<User>(SI.getOperand(1));
6556 Value *CastOp = CI->getOperand(0);
6558 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6559 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6560 const Type *SrcPTy = SrcTy->getElementType();
6562 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6563 // If the source is an array, the code below will not succeed. Check to
6564 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6566 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6567 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6568 if (ASrcTy->getNumElements() != 0) {
6569 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6570 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6571 SrcTy = cast<PointerType>(CastOp->getType());
6572 SrcPTy = SrcTy->getElementType();
6575 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
6576 IC.getTargetData().getTypeSize(SrcPTy) ==
6577 IC.getTargetData().getTypeSize(DestPTy)) {
6579 // Okay, we are casting from one integer or pointer type to another of
6580 // the same size. Instead of casting the pointer before the store, cast
6581 // the value to be stored.
6583 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6584 NewCast = ConstantExpr::getCast(C, SrcPTy);
6586 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6588 SI.getOperand(0)->getName()+".c"), SI);
6590 return new StoreInst(NewCast, CastOp);
6597 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6598 Value *Val = SI.getOperand(0);
6599 Value *Ptr = SI.getOperand(1);
6601 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
6602 EraseInstFromFunction(SI);
6607 // Do really simple DSE, to catch cases where there are several consequtive
6608 // stores to the same location, separated by a few arithmetic operations. This
6609 // situation often occurs with bitfield accesses.
6610 BasicBlock::iterator BBI = &SI;
6611 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6615 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6616 // Prev store isn't volatile, and stores to the same location?
6617 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6620 EraseInstFromFunction(*PrevSI);
6626 // Don't skip over loads or things that can modify memory.
6627 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6632 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
6634 // store X, null -> turns into 'unreachable' in SimplifyCFG
6635 if (isa<ConstantPointerNull>(Ptr)) {
6636 if (!isa<UndefValue>(Val)) {
6637 SI.setOperand(0, UndefValue::get(Val->getType()));
6638 if (Instruction *U = dyn_cast<Instruction>(Val))
6639 WorkList.push_back(U); // Dropped a use.
6642 return 0; // Do not modify these!
6645 // store undef, Ptr -> noop
6646 if (isa<UndefValue>(Val)) {
6647 EraseInstFromFunction(SI);
6652 // If the pointer destination is a cast, see if we can fold the cast into the
6654 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6655 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6657 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6658 if (CE->getOpcode() == Instruction::Cast)
6659 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6663 // If this store is the last instruction in the basic block, and if the block
6664 // ends with an unconditional branch, try to move it to the successor block.
6666 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6667 if (BI->isUnconditional()) {
6668 // Check to see if the successor block has exactly two incoming edges. If
6669 // so, see if the other predecessor contains a store to the same location.
6670 // if so, insert a PHI node (if needed) and move the stores down.
6671 BasicBlock *Dest = BI->getSuccessor(0);
6673 pred_iterator PI = pred_begin(Dest);
6674 BasicBlock *Other = 0;
6675 if (*PI != BI->getParent())
6678 if (PI != pred_end(Dest)) {
6679 if (*PI != BI->getParent())
6684 if (++PI != pred_end(Dest))
6687 if (Other) { // If only one other pred...
6688 BBI = Other->getTerminator();
6689 // Make sure this other block ends in an unconditional branch and that
6690 // there is an instruction before the branch.
6691 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6692 BBI != Other->begin()) {
6694 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6696 // If this instruction is a store to the same location.
6697 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6698 // Okay, we know we can perform this transformation. Insert a PHI
6699 // node now if we need it.
6700 Value *MergedVal = OtherStore->getOperand(0);
6701 if (MergedVal != SI.getOperand(0)) {
6702 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6703 PN->reserveOperandSpace(2);
6704 PN->addIncoming(SI.getOperand(0), SI.getParent());
6705 PN->addIncoming(OtherStore->getOperand(0), Other);
6706 MergedVal = InsertNewInstBefore(PN, Dest->front());
6709 // Advance to a place where it is safe to insert the new store and
6711 BBI = Dest->begin();
6712 while (isa<PHINode>(BBI)) ++BBI;
6713 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6714 OtherStore->isVolatile()), *BBI);
6716 // Nuke the old stores.
6717 EraseInstFromFunction(SI);
6718 EraseInstFromFunction(*OtherStore);
6730 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6731 // Change br (not X), label True, label False to: br X, label False, True
6733 BasicBlock *TrueDest;
6734 BasicBlock *FalseDest;
6735 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6736 !isa<Constant>(X)) {
6737 // Swap Destinations and condition...
6739 BI.setSuccessor(0, FalseDest);
6740 BI.setSuccessor(1, TrueDest);
6744 // Cannonicalize setne -> seteq
6745 Instruction::BinaryOps Op; Value *Y;
6746 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6747 TrueDest, FalseDest)))
6748 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6749 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6750 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6751 std::string Name = I->getName(); I->setName("");
6752 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6753 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
6754 // Swap Destinations and condition...
6755 BI.setCondition(NewSCC);
6756 BI.setSuccessor(0, FalseDest);
6757 BI.setSuccessor(1, TrueDest);
6758 removeFromWorkList(I);
6759 I->getParent()->getInstList().erase(I);
6760 WorkList.push_back(cast<Instruction>(NewSCC));
6767 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6768 Value *Cond = SI.getCondition();
6769 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6770 if (I->getOpcode() == Instruction::Add)
6771 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6772 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6773 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
6774 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
6776 SI.setOperand(0, I->getOperand(0));
6777 WorkList.push_back(I);
6784 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6785 /// is to leave as a vector operation.
6786 static bool CheapToScalarize(Value *V, bool isConstant) {
6787 if (isa<ConstantAggregateZero>(V))
6789 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6790 if (isConstant) return true;
6791 // If all elts are the same, we can extract.
6792 Constant *Op0 = C->getOperand(0);
6793 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6794 if (C->getOperand(i) != Op0)
6798 Instruction *I = dyn_cast<Instruction>(V);
6799 if (!I) return false;
6801 // Insert element gets simplified to the inserted element or is deleted if
6802 // this is constant idx extract element and its a constant idx insertelt.
6803 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6804 isa<ConstantInt>(I->getOperand(2)))
6806 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6808 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6809 if (BO->hasOneUse() &&
6810 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6811 CheapToScalarize(BO->getOperand(1), isConstant)))
6817 /// FindScalarElement - Given a vector and an element number, see if the scalar
6818 /// value is already around as a register, for example if it were inserted then
6819 /// extracted from the vector.
6820 static Value *FindScalarElement(Value *V, unsigned EltNo) {
6821 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
6822 const PackedType *PTy = cast<PackedType>(V->getType());
6823 unsigned Width = PTy->getNumElements();
6824 if (EltNo >= Width) // Out of range access.
6825 return UndefValue::get(PTy->getElementType());
6827 if (isa<UndefValue>(V))
6828 return UndefValue::get(PTy->getElementType());
6829 else if (isa<ConstantAggregateZero>(V))
6830 return Constant::getNullValue(PTy->getElementType());
6831 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
6832 return CP->getOperand(EltNo);
6833 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
6834 // If this is an insert to a variable element, we don't know what it is.
6835 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
6836 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
6838 // If this is an insert to the element we are looking for, return the
6840 if (EltNo == IIElt) return III->getOperand(1);
6842 // Otherwise, the insertelement doesn't modify the value, recurse on its
6844 return FindScalarElement(III->getOperand(0), EltNo);
6845 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
6846 if (isa<ConstantAggregateZero>(SVI->getOperand(2))) {
6847 return FindScalarElement(SVI->getOperand(0), 0);
6848 } else if (ConstantPacked *CP =
6849 dyn_cast<ConstantPacked>(SVI->getOperand(2))) {
6850 if (isa<UndefValue>(CP->getOperand(EltNo)))
6851 return UndefValue::get(PTy->getElementType());
6852 unsigned InEl = cast<ConstantUInt>(CP->getOperand(EltNo))->getValue();
6854 return FindScalarElement(SVI->getOperand(0), InEl);
6856 return FindScalarElement(SVI->getOperand(1), InEl - Width);
6860 // Otherwise, we don't know.
6864 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6866 // If packed val is undef, replace extract with scalar undef.
6867 if (isa<UndefValue>(EI.getOperand(0)))
6868 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
6870 // If packed val is constant 0, replace extract with scalar 0.
6871 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
6872 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
6874 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6875 // If packed val is constant with uniform operands, replace EI
6876 // with that operand
6877 Constant *op0 = C->getOperand(0);
6878 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6879 if (C->getOperand(i) != op0) {
6884 return ReplaceInstUsesWith(EI, op0);
6887 // If extracting a specified index from the vector, see if we can recursively
6888 // find a previously computed scalar that was inserted into the vector.
6889 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
6890 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
6891 return ReplaceInstUsesWith(EI, Elt);
6894 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6895 if (I->hasOneUse()) {
6896 // Push extractelement into predecessor operation if legal and
6897 // profitable to do so
6898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6899 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
6900 if (CheapToScalarize(BO, isConstantElt)) {
6901 ExtractElementInst *newEI0 =
6902 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6903 EI.getName()+".lhs");
6904 ExtractElementInst *newEI1 =
6905 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6906 EI.getName()+".rhs");
6907 InsertNewInstBefore(newEI0, EI);
6908 InsertNewInstBefore(newEI1, EI);
6909 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6911 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6912 Value *Ptr = InsertCastBefore(I->getOperand(0),
6913 PointerType::get(EI.getType()), EI);
6914 GetElementPtrInst *GEP =
6915 new GetElementPtrInst(Ptr, EI.getOperand(1),
6916 I->getName() + ".gep");
6917 InsertNewInstBefore(GEP, EI);
6918 return new LoadInst(GEP);
6919 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
6920 // Extracting the inserted element?
6921 if (IE->getOperand(2) == EI.getOperand(1))
6922 return ReplaceInstUsesWith(EI, IE->getOperand(1));
6923 // If the inserted and extracted elements are constants, they must not
6924 // be the same value, extract from the pre-inserted value instead.
6925 if (isa<Constant>(IE->getOperand(2)) &&
6926 isa<Constant>(EI.getOperand(1))) {
6927 AddUsesToWorkList(EI);
6928 EI.setOperand(0, IE->getOperand(0));
6936 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
6937 /// elements from either LHS or RHS, return the shuffle mask and true.
6938 /// Otherwise, return false.
6939 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
6940 std::vector<Constant*> &Mask) {
6941 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
6942 "Invalid CollectSingleShuffleElements");
6943 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
6945 if (isa<UndefValue>(V)) {
6946 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
6948 } else if (V == LHS) {
6949 for (unsigned i = 0; i != NumElts; ++i)
6950 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
6952 } else if (V == RHS) {
6953 for (unsigned i = 0; i != NumElts; ++i)
6954 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
6956 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
6957 // If this is an insert of an extract from some other vector, include it.
6958 Value *VecOp = IEI->getOperand(0);
6959 Value *ScalarOp = IEI->getOperand(1);
6960 Value *IdxOp = IEI->getOperand(2);
6962 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
6963 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
6964 EI->getOperand(0)->getType() == V->getType()) {
6965 unsigned ExtractedIdx =
6966 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
6967 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
6969 // This must be extracting from either LHS or RHS.
6970 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
6971 // Okay, we can handle this if the vector we are insertinting into is
6973 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
6974 // If so, update the mask to reflect the inserted value.
6975 if (EI->getOperand(0) == LHS) {
6976 Mask[InsertedIdx & (NumElts-1)] =
6977 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
6979 assert(EI->getOperand(0) == RHS);
6980 Mask[InsertedIdx & (NumElts-1)] =
6981 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
6990 // TODO: Handle shufflevector here!
6995 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
6996 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
6997 /// that computes V and the LHS value of the shuffle.
6998 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
7000 assert(isa<PackedType>(V->getType()) &&
7001 (RHS == 0 || V->getType() == RHS->getType()) &&
7002 "Invalid shuffle!");
7003 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7005 if (isa<UndefValue>(V)) {
7006 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7008 } else if (isa<ConstantAggregateZero>(V)) {
7009 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7011 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7012 // If this is an insert of an extract from some other vector, include it.
7013 Value *VecOp = IEI->getOperand(0);
7014 Value *ScalarOp = IEI->getOperand(1);
7015 Value *IdxOp = IEI->getOperand(2);
7017 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7018 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7019 EI->getOperand(0)->getType() == V->getType()) {
7020 unsigned ExtractedIdx =
7021 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7022 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7024 // Either the extracted from or inserted into vector must be RHSVec,
7025 // otherwise we'd end up with a shuffle of three inputs.
7026 if (EI->getOperand(0) == RHS || RHS == 0) {
7027 RHS = EI->getOperand(0);
7028 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
7029 Mask[InsertedIdx & (NumElts-1)] =
7030 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7035 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
7036 // Everything but the extracted element is replaced with the RHS.
7037 for (unsigned i = 0; i != NumElts; ++i) {
7038 if (i != InsertedIdx)
7039 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7044 // If this insertelement is a chain that comes from exactly these two
7045 // vectors, return the vector and the effective shuffle.
7046 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7047 return EI->getOperand(0);
7052 // TODO: Handle shufflevector here!
7054 // Otherwise, can't do anything fancy. Return an identity vector.
7055 for (unsigned i = 0; i != NumElts; ++i)
7056 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7060 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7061 Value *VecOp = IE.getOperand(0);
7062 Value *ScalarOp = IE.getOperand(1);
7063 Value *IdxOp = IE.getOperand(2);
7065 // If the inserted element was extracted from some other vector, and if the
7066 // indexes are constant, try to turn this into a shufflevector operation.
7067 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7068 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7069 EI->getOperand(0)->getType() == IE.getType()) {
7070 unsigned NumVectorElts = IE.getType()->getNumElements();
7071 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7072 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7074 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7075 return ReplaceInstUsesWith(IE, VecOp);
7077 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7078 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7080 // If we are extracting a value from a vector, then inserting it right
7081 // back into the same place, just use the input vector.
7082 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7083 return ReplaceInstUsesWith(IE, VecOp);
7085 // We could theoretically do this for ANY input. However, doing so could
7086 // turn chains of insertelement instructions into a chain of shufflevector
7087 // instructions, and right now we do not merge shufflevectors. As such,
7088 // only do this in a situation where it is clear that there is benefit.
7089 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7090 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7091 // the values of VecOp, except then one read from EIOp0.
7092 // Build a new shuffle mask.
7093 std::vector<Constant*> Mask;
7094 if (isa<UndefValue>(VecOp))
7095 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7097 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7098 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7101 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7102 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7103 ConstantPacked::get(Mask));
7106 // If this insertelement isn't used by some other insertelement, turn it
7107 // (and any insertelements it points to), into one big shuffle.
7108 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7109 std::vector<Constant*> Mask;
7111 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7112 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7113 // We now have a shuffle of LHS, RHS, Mask.
7114 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
7123 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7124 Value *LHS = SVI.getOperand(0);
7125 Value *RHS = SVI.getOperand(1);
7126 Constant *Mask = cast<Constant>(SVI.getOperand(2));
7128 bool MadeChange = false;
7130 if (isa<UndefValue>(Mask))
7131 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7133 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7134 // the undef, change them to undefs.
7136 // Canonicalize shuffle(x,x) -> shuffle(x,undef)
7138 if (isa<UndefValue>(LHS)) {
7139 // shuffle(undef,undef,mask) -> undef.
7140 return ReplaceInstUsesWith(SVI, LHS);
7143 if (!isa<ConstantAggregateZero>(Mask)) {
7144 // Remap any references to RHS to use LHS.
7145 ConstantPacked *CP = cast<ConstantPacked>(Mask);
7146 std::vector<Constant*> Elts;
7147 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7148 Elts.push_back(CP->getOperand(i));
7149 if (isa<UndefValue>(CP->getOperand(i)))
7151 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7153 Elts.back() = ConstantUInt::get(Type::UIntTy, MV & (e-1));
7155 Mask = ConstantPacked::get(Elts);
7157 SVI.setOperand(1, UndefValue::get(RHS->getType()));
7158 SVI.setOperand(2, Mask);
7162 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7163 if (isa<UndefValue>(LHS)) {
7164 // shuffle(undef,x,<0,0,0,0>) -> undef.
7165 if (isa<ConstantAggregateZero>(Mask))
7166 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7168 ConstantPacked *CPM = cast<ConstantPacked>(Mask);
7169 std::vector<Constant*> Elts;
7170 for (unsigned i = 0, e = CPM->getNumOperands(); i != e; ++i) {
7171 if (isa<UndefValue>(CPM->getOperand(i)))
7172 Elts.push_back(CPM->getOperand(i));
7174 unsigned EltNo = cast<ConstantUInt>(CPM->getOperand(i))->getRawValue();
7176 Elts.push_back(ConstantUInt::get(Type::UIntTy, EltNo-e));
7177 else // Referring to the undef.
7178 Elts.push_back(UndefValue::get(Type::UIntTy));
7181 return new ShuffleVectorInst(RHS, LHS, ConstantPacked::get(Elts));
7184 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Mask)) {
7185 bool isLHSID = true, isRHSID = true;
7187 // Analyze the shuffle.
7188 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7189 if (isa<UndefValue>(CP->getOperand(i)))
7191 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7193 // Is this an identity shuffle of the LHS value?
7194 isLHSID &= (MV == i);
7196 // Is this an identity shuffle of the RHS value?
7197 isRHSID &= (MV-e == i);
7200 // Eliminate identity shuffles.
7201 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7202 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
7205 return MadeChange ? &SVI : 0;
7210 void InstCombiner::removeFromWorkList(Instruction *I) {
7211 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7216 /// TryToSinkInstruction - Try to move the specified instruction from its
7217 /// current block into the beginning of DestBlock, which can only happen if it's
7218 /// safe to move the instruction past all of the instructions between it and the
7219 /// end of its block.
7220 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7221 assert(I->hasOneUse() && "Invariants didn't hold!");
7223 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7224 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
7226 // Do not sink alloca instructions out of the entry block.
7227 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7230 // We can only sink load instructions if there is nothing between the load and
7231 // the end of block that could change the value.
7232 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7233 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7235 if (Scan->mayWriteToMemory())
7239 BasicBlock::iterator InsertPos = DestBlock->begin();
7240 while (isa<PHINode>(InsertPos)) ++InsertPos;
7242 I->moveBefore(InsertPos);
7247 bool InstCombiner::runOnFunction(Function &F) {
7248 bool Changed = false;
7249 TD = &getAnalysis<TargetData>();
7252 // Populate the worklist with the reachable instructions.
7253 std::set<BasicBlock*> Visited;
7254 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
7255 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
7256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
7257 WorkList.push_back(I);
7259 // Do a quick scan over the function. If we find any blocks that are
7260 // unreachable, remove any instructions inside of them. This prevents
7261 // the instcombine code from having to deal with some bad special cases.
7262 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7263 if (!Visited.count(BB)) {
7264 Instruction *Term = BB->getTerminator();
7265 while (Term != BB->begin()) { // Remove instrs bottom-up
7266 BasicBlock::iterator I = Term; --I;
7268 DEBUG(std::cerr << "IC: DCE: " << *I);
7271 if (!I->use_empty())
7272 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7273 I->eraseFromParent();
7278 while (!WorkList.empty()) {
7279 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7280 WorkList.pop_back();
7282 // Check to see if we can DCE or ConstantPropagate the instruction...
7283 // Check to see if we can DIE the instruction...
7284 if (isInstructionTriviallyDead(I)) {
7285 // Add operands to the worklist...
7286 if (I->getNumOperands() < 4)
7287 AddUsesToWorkList(*I);
7290 DEBUG(std::cerr << "IC: DCE: " << *I);
7292 I->eraseFromParent();
7293 removeFromWorkList(I);
7297 // Instruction isn't dead, see if we can constant propagate it...
7298 if (Constant *C = ConstantFoldInstruction(I)) {
7299 Value* Ptr = I->getOperand(0);
7300 if (isa<GetElementPtrInst>(I) &&
7301 cast<Constant>(Ptr)->isNullValue() &&
7302 !isa<ConstantPointerNull>(C) &&
7303 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7304 // If this is a constant expr gep that is effectively computing an
7305 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
7306 bool isFoldableGEP = true;
7307 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
7308 if (!isa<ConstantInt>(I->getOperand(i)))
7309 isFoldableGEP = false;
7310 if (isFoldableGEP) {
7311 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
7312 std::vector<Value*>(I->op_begin()+1, I->op_end()));
7313 C = ConstantUInt::get(Type::ULongTy, Offset);
7314 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7315 C = ConstantExpr::getCast(C, I->getType());
7319 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7321 // Add operands to the worklist...
7322 AddUsesToWorkList(*I);
7323 ReplaceInstUsesWith(*I, C);
7326 I->getParent()->getInstList().erase(I);
7327 removeFromWorkList(I);
7331 // See if we can trivially sink this instruction to a successor basic block.
7332 if (I->hasOneUse()) {
7333 BasicBlock *BB = I->getParent();
7334 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7335 if (UserParent != BB) {
7336 bool UserIsSuccessor = false;
7337 // See if the user is one of our successors.
7338 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7339 if (*SI == UserParent) {
7340 UserIsSuccessor = true;
7344 // If the user is one of our immediate successors, and if that successor
7345 // only has us as a predecessors (we'd have to split the critical edge
7346 // otherwise), we can keep going.
7347 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7348 next(pred_begin(UserParent)) == pred_end(UserParent))
7349 // Okay, the CFG is simple enough, try to sink this instruction.
7350 Changed |= TryToSinkInstruction(I, UserParent);
7354 // Now that we have an instruction, try combining it to simplify it...
7355 if (Instruction *Result = visit(*I)) {
7357 // Should we replace the old instruction with a new one?
7359 DEBUG(std::cerr << "IC: Old = " << *I
7360 << " New = " << *Result);
7362 // Everything uses the new instruction now.
7363 I->replaceAllUsesWith(Result);
7365 // Push the new instruction and any users onto the worklist.
7366 WorkList.push_back(Result);
7367 AddUsersToWorkList(*Result);
7369 // Move the name to the new instruction first...
7370 std::string OldName = I->getName(); I->setName("");
7371 Result->setName(OldName);
7373 // Insert the new instruction into the basic block...
7374 BasicBlock *InstParent = I->getParent();
7375 BasicBlock::iterator InsertPos = I;
7377 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7378 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7381 InstParent->getInstList().insert(InsertPos, Result);
7383 // Make sure that we reprocess all operands now that we reduced their
7385 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7386 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7387 WorkList.push_back(OpI);
7389 // Instructions can end up on the worklist more than once. Make sure
7390 // we do not process an instruction that has been deleted.
7391 removeFromWorkList(I);
7393 // Erase the old instruction.
7394 InstParent->getInstList().erase(I);
7396 DEBUG(std::cerr << "IC: MOD = " << *I);
7398 // If the instruction was modified, it's possible that it is now dead.
7399 // if so, remove it.
7400 if (isInstructionTriviallyDead(I)) {
7401 // Make sure we process all operands now that we are reducing their
7403 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7404 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7405 WorkList.push_back(OpI);
7407 // Instructions may end up in the worklist more than once. Erase all
7408 // occurrences of this instruction.
7409 removeFromWorkList(I);
7410 I->eraseFromParent();
7412 WorkList.push_back(Result);
7413 AddUsersToWorkList(*Result);
7423 FunctionPass *llvm::createInstructionCombiningPass() {
7424 return new InstCombiner();