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/Statistic.h"
52 #include "llvm/ADT/STLExtras.h"
56 using namespace llvm::PatternMatch;
59 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
63 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
65 class InstCombiner : public FunctionPass,
66 public InstVisitor<InstCombiner, Instruction*> {
67 // Worklist of all of the instructions that need to be simplified.
68 std::vector<Instruction*> WorkList;
71 /// AddUsersToWorkList - When an instruction is simplified, add all users of
72 /// the instruction to the work lists because they might get more simplified
75 void AddUsersToWorkList(Value &I) {
76 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
78 WorkList.push_back(cast<Instruction>(*UI));
81 /// AddUsesToWorkList - When an instruction is simplified, add operands to
82 /// the work lists because they might get more simplified now.
84 void AddUsesToWorkList(Instruction &I) {
85 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
86 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
87 WorkList.push_back(Op);
90 // removeFromWorkList - remove all instances of I from the worklist.
91 void removeFromWorkList(Instruction *I);
93 virtual bool runOnFunction(Function &F);
95 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96 AU.addRequired<TargetData>();
100 TargetData &getTargetData() const { return *TD; }
102 // Visitation implementation - Implement instruction combining for different
103 // instruction types. The semantics are as follows:
105 // null - No change was made
106 // I - Change was made, I is still valid, I may be dead though
107 // otherwise - Change was made, replace I with returned instruction
109 Instruction *visitAdd(BinaryOperator &I);
110 Instruction *visitSub(BinaryOperator &I);
111 Instruction *visitMul(BinaryOperator &I);
112 Instruction *visitDiv(BinaryOperator &I);
113 Instruction *visitRem(BinaryOperator &I);
114 Instruction *visitAnd(BinaryOperator &I);
115 Instruction *visitOr (BinaryOperator &I);
116 Instruction *visitXor(BinaryOperator &I);
117 Instruction *visitSetCondInst(SetCondInst &I);
118 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
121 Instruction::BinaryOps Cond, Instruction &I);
122 Instruction *visitShiftInst(ShiftInst &I);
123 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125 Instruction *visitCastInst(CastInst &CI);
126 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 Instruction *visitSelectInst(SelectInst &CI);
129 Instruction *visitCallInst(CallInst &CI);
130 Instruction *visitInvokeInst(InvokeInst &II);
131 Instruction *visitPHINode(PHINode &PN);
132 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
133 Instruction *visitAllocationInst(AllocationInst &AI);
134 Instruction *visitFreeInst(FreeInst &FI);
135 Instruction *visitLoadInst(LoadInst &LI);
136 Instruction *visitStoreInst(StoreInst &SI);
137 Instruction *visitBranchInst(BranchInst &BI);
138 Instruction *visitSwitchInst(SwitchInst &SI);
139 Instruction *visitInsertElementInst(InsertElementInst &IE);
140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
141 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
143 // visitInstruction - Specify what to return for unhandled instructions...
144 Instruction *visitInstruction(Instruction &I) { return 0; }
147 Instruction *visitCallSite(CallSite CS);
148 bool transformConstExprCastCall(CallSite CS);
151 // InsertNewInstBefore - insert an instruction New before instruction Old
152 // in the program. Add the new instruction to the worklist.
154 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
155 assert(New && New->getParent() == 0 &&
156 "New instruction already inserted into a basic block!");
157 BasicBlock *BB = Old.getParent();
158 BB->getInstList().insert(&Old, New); // Insert inst
159 WorkList.push_back(New); // Add to worklist
163 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
164 /// This also adds the cast to the worklist. Finally, this returns the
166 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
167 if (V->getType() == Ty) return V;
169 if (Constant *CV = dyn_cast<Constant>(V))
170 return ConstantExpr::getCast(CV, Ty);
172 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
173 WorkList.push_back(C);
177 // ReplaceInstUsesWith - This method is to be used when an instruction is
178 // found to be dead, replacable with another preexisting expression. Here
179 // we add all uses of I to the worklist, replace all uses of I with the new
180 // value, then return I, so that the inst combiner will know that I was
183 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
184 AddUsersToWorkList(I); // Add all modified instrs to worklist
186 I.replaceAllUsesWith(V);
189 // If we are replacing the instruction with itself, this must be in a
190 // segment of unreachable code, so just clobber the instruction.
191 I.replaceAllUsesWith(UndefValue::get(I.getType()));
196 // UpdateValueUsesWith - This method is to be used when an value is
197 // found to be replacable with another preexisting expression or was
198 // updated. Here we add all uses of I to the worklist, replace all uses of
199 // I with the new value (unless the instruction was just updated), then
200 // return true, so that the inst combiner will know that I was modified.
202 bool UpdateValueUsesWith(Value *Old, Value *New) {
203 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
205 Old->replaceAllUsesWith(New);
206 if (Instruction *I = dyn_cast<Instruction>(Old))
207 WorkList.push_back(I);
208 if (Instruction *I = dyn_cast<Instruction>(New))
209 WorkList.push_back(I);
213 // EraseInstFromFunction - When dealing with an instruction that has side
214 // effects or produces a void value, we can't rely on DCE to delete the
215 // instruction. Instead, visit methods should return the value returned by
217 Instruction *EraseInstFromFunction(Instruction &I) {
218 assert(I.use_empty() && "Cannot erase instruction that is used!");
219 AddUsesToWorkList(I);
220 removeFromWorkList(&I);
222 return 0; // Don't do anything with FI
226 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
227 /// InsertBefore instruction. This is specialized a bit to avoid inserting
228 /// casts that are known to not do anything...
230 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
231 Instruction *InsertBefore);
233 // SimplifyCommutative - This performs a few simplifications for commutative
235 bool SimplifyCommutative(BinaryOperator &I);
237 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
238 uint64_t &KnownZero, uint64_t &KnownOne,
241 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
242 // PHI node as operand #0, see if we can fold the instruction into the PHI
243 // (which is only possible if all operands to the PHI are constants).
244 Instruction *FoldOpIntoPhi(Instruction &I);
246 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
247 // operator and they all are only used by the PHI, PHI together their
248 // inputs, and do the operation once, to the result of the PHI.
249 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
251 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
252 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
254 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
255 bool isSub, Instruction &I);
256 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
257 bool Inside, Instruction &IB);
258 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
260 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
263 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
266 // getComplexity: Assign a complexity or rank value to LLVM Values...
267 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
268 static unsigned getComplexity(Value *V) {
269 if (isa<Instruction>(V)) {
270 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
274 if (isa<Argument>(V)) return 3;
275 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
278 // isOnlyUse - Return true if this instruction will be deleted if we stop using
280 static bool isOnlyUse(Value *V) {
281 return V->hasOneUse() || isa<Constant>(V);
284 // getPromotedType - Return the specified type promoted as it would be to pass
285 // though a va_arg area...
286 static const Type *getPromotedType(const Type *Ty) {
287 switch (Ty->getTypeID()) {
288 case Type::SByteTyID:
289 case Type::ShortTyID: return Type::IntTy;
290 case Type::UByteTyID:
291 case Type::UShortTyID: return Type::UIntTy;
292 case Type::FloatTyID: return Type::DoubleTy;
297 /// isCast - If the specified operand is a CastInst or a constant expr cast,
298 /// return the operand value, otherwise return null.
299 static Value *isCast(Value *V) {
300 if (CastInst *I = dyn_cast<CastInst>(V))
301 return I->getOperand(0);
302 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
303 if (CE->getOpcode() == Instruction::Cast)
304 return CE->getOperand(0);
315 /// getCastType - In the future, we will split the cast instruction into these
316 /// various types. Until then, we have to do the analysis here.
317 static CastType getCastType(const Type *Src, const Type *Dest) {
318 assert(Src->isIntegral() && Dest->isIntegral() &&
319 "Only works on integral types!");
320 unsigned SrcSize = Src->getPrimitiveSizeInBits();
321 unsigned DestSize = Dest->getPrimitiveSizeInBits();
323 if (SrcSize == DestSize) return Noop;
324 if (SrcSize > DestSize) return Truncate;
325 if (Src->isSigned()) return Signext;
330 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
333 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
334 const Type *DstTy, TargetData *TD) {
336 // It is legal to eliminate the instruction if casting A->B->A if the sizes
337 // are identical and the bits don't get reinterpreted (for example
338 // int->float->int would not be allowed).
339 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
342 // If we are casting between pointer and integer types, treat pointers as
343 // integers of the appropriate size for the code below.
344 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
345 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
346 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
348 // Allow free casting and conversion of sizes as long as the sign doesn't
350 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
351 CastType FirstCast = getCastType(SrcTy, MidTy);
352 CastType SecondCast = getCastType(MidTy, DstTy);
354 // Capture the effect of these two casts. If the result is a legal cast,
355 // the CastType is stored here, otherwise a special code is used.
356 static const unsigned CastResult[] = {
357 // First cast is noop
359 // First cast is a truncate
360 1, 1, 4, 4, // trunc->extend is not safe to eliminate
361 // First cast is a sign ext
362 2, 5, 2, 4, // signext->zeroext never ok
363 // First cast is a zero ext
367 unsigned Result = CastResult[FirstCast*4+SecondCast];
369 default: assert(0 && "Illegal table value!");
374 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
375 // truncates, we could eliminate more casts.
376 return (unsigned)getCastType(SrcTy, DstTy) == Result;
378 return false; // Not possible to eliminate this here.
380 // Sign or zero extend followed by truncate is always ok if the result
381 // is a truncate or noop.
382 CastType ResultCast = getCastType(SrcTy, DstTy);
383 if (ResultCast == Noop || ResultCast == Truncate)
385 // Otherwise we are still growing the value, we are only safe if the
386 // result will match the sign/zeroextendness of the result.
387 return ResultCast == FirstCast;
391 // If this is a cast from 'float -> double -> integer', cast from
392 // 'float -> integer' directly, as the value isn't changed by the
393 // float->double conversion.
394 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
395 DstTy->isIntegral() &&
396 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
399 // Packed type conversions don't modify bits.
400 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
406 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
407 /// in any code being generated. It does not require codegen if V is simple
408 /// enough or if the cast can be folded into other casts.
409 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
410 if (V->getType() == Ty || isa<Constant>(V)) return false;
412 // If this is a noop cast, it isn't real codegen.
413 if (V->getType()->isLosslesslyConvertibleTo(Ty))
416 // If this is another cast that can be elimianted, it isn't codegen either.
417 if (const CastInst *CI = dyn_cast<CastInst>(V))
418 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
424 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
425 /// InsertBefore instruction. This is specialized a bit to avoid inserting
426 /// casts that are known to not do anything...
428 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
429 Instruction *InsertBefore) {
430 if (V->getType() == DestTy) return V;
431 if (Constant *C = dyn_cast<Constant>(V))
432 return ConstantExpr::getCast(C, DestTy);
434 CastInst *CI = new CastInst(V, DestTy, V->getName());
435 InsertNewInstBefore(CI, *InsertBefore);
439 // SimplifyCommutative - This performs a few simplifications for commutative
442 // 1. Order operands such that they are listed from right (least complex) to
443 // left (most complex). This puts constants before unary operators before
446 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
447 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
449 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
450 bool Changed = false;
451 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
452 Changed = !I.swapOperands();
454 if (!I.isAssociative()) return Changed;
455 Instruction::BinaryOps Opcode = I.getOpcode();
456 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
457 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
458 if (isa<Constant>(I.getOperand(1))) {
459 Constant *Folded = ConstantExpr::get(I.getOpcode(),
460 cast<Constant>(I.getOperand(1)),
461 cast<Constant>(Op->getOperand(1)));
462 I.setOperand(0, Op->getOperand(0));
463 I.setOperand(1, Folded);
465 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
466 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
467 isOnlyUse(Op) && isOnlyUse(Op1)) {
468 Constant *C1 = cast<Constant>(Op->getOperand(1));
469 Constant *C2 = cast<Constant>(Op1->getOperand(1));
471 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
472 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
473 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
476 WorkList.push_back(New);
477 I.setOperand(0, New);
478 I.setOperand(1, Folded);
485 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
486 // if the LHS is a constant zero (which is the 'negate' form).
488 static inline Value *dyn_castNegVal(Value *V) {
489 if (BinaryOperator::isNeg(V))
490 return BinaryOperator::getNegArgument(V);
492 // Constants can be considered to be negated values if they can be folded.
493 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
494 return ConstantExpr::getNeg(C);
498 static inline Value *dyn_castNotVal(Value *V) {
499 if (BinaryOperator::isNot(V))
500 return BinaryOperator::getNotArgument(V);
502 // Constants can be considered to be not'ed values...
503 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
504 return ConstantExpr::getNot(C);
508 // dyn_castFoldableMul - If this value is a multiply that can be folded into
509 // other computations (because it has a constant operand), return the
510 // non-constant operand of the multiply, and set CST to point to the multiplier.
511 // Otherwise, return null.
513 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
514 if (V->hasOneUse() && V->getType()->isInteger())
515 if (Instruction *I = dyn_cast<Instruction>(V)) {
516 if (I->getOpcode() == Instruction::Mul)
517 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
518 return I->getOperand(0);
519 if (I->getOpcode() == Instruction::Shl)
520 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
521 // The multiplier is really 1 << CST.
522 Constant *One = ConstantInt::get(V->getType(), 1);
523 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
524 return I->getOperand(0);
530 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
531 /// expression, return it.
532 static User *dyn_castGetElementPtr(Value *V) {
533 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
534 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
535 if (CE->getOpcode() == Instruction::GetElementPtr)
536 return cast<User>(V);
540 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
541 static ConstantInt *AddOne(ConstantInt *C) {
542 return cast<ConstantInt>(ConstantExpr::getAdd(C,
543 ConstantInt::get(C->getType(), 1)));
545 static ConstantInt *SubOne(ConstantInt *C) {
546 return cast<ConstantInt>(ConstantExpr::getSub(C,
547 ConstantInt::get(C->getType(), 1)));
550 /// GetConstantInType - Return a ConstantInt with the specified type and value.
552 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
553 if (Ty->isUnsigned())
554 return ConstantUInt::get(Ty, Val);
555 else if (Ty->getTypeID() == Type::BoolTyID)
556 return ConstantBool::get(Val);
558 SVal <<= 64-Ty->getPrimitiveSizeInBits();
559 SVal >>= 64-Ty->getPrimitiveSizeInBits();
560 return ConstantSInt::get(Ty, SVal);
564 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
565 /// known to be either zero or one and return them in the KnownZero/KnownOne
566 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
568 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
569 uint64_t &KnownOne, unsigned Depth = 0) {
570 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
571 // we cannot optimize based on the assumption that it is zero without changing
572 // it to be an explicit zero. If we don't change it to zero, other code could
573 // optimized based on the contradictory assumption that it is non-zero.
574 // Because instcombine aggressively folds operations with undef args anyway,
575 // this won't lose us code quality.
576 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
577 // We know all of the bits for a constant!
578 KnownOne = CI->getZExtValue() & Mask;
579 KnownZero = ~KnownOne & Mask;
583 KnownZero = KnownOne = 0; // Don't know anything.
584 if (Depth == 6 || Mask == 0)
585 return; // Limit search depth.
587 uint64_t KnownZero2, KnownOne2;
588 Instruction *I = dyn_cast<Instruction>(V);
591 Mask &= V->getType()->getIntegralTypeMask();
593 switch (I->getOpcode()) {
594 case Instruction::And:
595 // If either the LHS or the RHS are Zero, the result is zero.
596 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
598 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
599 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
600 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
602 // Output known-1 bits are only known if set in both the LHS & RHS.
603 KnownOne &= KnownOne2;
604 // Output known-0 are known to be clear if zero in either the LHS | RHS.
605 KnownZero |= KnownZero2;
607 case Instruction::Or:
608 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
610 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
611 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
612 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
614 // Output known-0 bits are only known if clear in both the LHS & RHS.
615 KnownZero &= KnownZero2;
616 // Output known-1 are known to be set if set in either the LHS | RHS.
617 KnownOne |= KnownOne2;
619 case Instruction::Xor: {
620 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
621 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
622 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
623 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
625 // Output known-0 bits are known if clear or set in both the LHS & RHS.
626 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
627 // Output known-1 are known to be set if set in only one of the LHS, RHS.
628 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
629 KnownZero = KnownZeroOut;
632 case Instruction::Select:
633 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
634 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
635 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
636 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
638 // Only known if known in both the LHS and RHS.
639 KnownOne &= KnownOne2;
640 KnownZero &= KnownZero2;
642 case Instruction::Cast: {
643 const Type *SrcTy = I->getOperand(0)->getType();
644 if (!SrcTy->isIntegral()) return;
646 // If this is an integer truncate or noop, just look in the input.
647 if (SrcTy->getPrimitiveSizeInBits() >=
648 I->getType()->getPrimitiveSizeInBits()) {
649 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
653 // Sign or Zero extension. Compute the bits in the result that are not
654 // present in the input.
655 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
656 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
658 // Handle zero extension.
659 if (!SrcTy->isSigned()) {
660 Mask &= SrcTy->getIntegralTypeMask();
661 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
662 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
663 // The top bits are known to be zero.
664 KnownZero |= NewBits;
667 Mask &= SrcTy->getIntegralTypeMask();
668 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
671 // If the sign bit of the input is known set or clear, then we know the
672 // top bits of the result.
673 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
674 if (KnownZero & InSignBit) { // Input sign bit known zero
675 KnownZero |= NewBits;
676 KnownOne &= ~NewBits;
677 } else if (KnownOne & InSignBit) { // Input sign bit known set
679 KnownZero &= ~NewBits;
680 } else { // Input sign bit unknown
681 KnownZero &= ~NewBits;
682 KnownOne &= ~NewBits;
687 case Instruction::Shl:
688 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
689 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
690 Mask >>= SA->getValue();
691 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
692 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
693 KnownZero <<= SA->getValue();
694 KnownOne <<= SA->getValue();
695 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
699 case Instruction::Shr:
700 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
701 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
702 // Compute the new bits that are at the top now.
703 uint64_t HighBits = (1ULL << SA->getValue())-1;
704 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
706 if (I->getType()->isUnsigned()) { // Unsigned shift right.
707 Mask <<= SA->getValue();
708 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
709 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
710 KnownZero >>= SA->getValue();
711 KnownOne >>= SA->getValue();
712 KnownZero |= HighBits; // high bits known zero.
714 Mask <<= SA->getValue();
715 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
716 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
717 KnownZero >>= SA->getValue();
718 KnownOne >>= SA->getValue();
720 // Handle the sign bits.
721 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
722 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
724 if (KnownZero & SignBit) { // New bits are known zero.
725 KnownZero |= HighBits;
726 } else if (KnownOne & SignBit) { // New bits are known one.
727 KnownOne |= HighBits;
736 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
737 /// this predicate to simplify operations downstream. Mask is known to be zero
738 /// for bits that V cannot have.
739 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
740 uint64_t KnownZero, KnownOne;
741 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
742 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
743 return (KnownZero & Mask) == Mask;
746 /// ShrinkDemandedConstant - Check to see if the specified operand of the
747 /// specified instruction is a constant integer. If so, check to see if there
748 /// are any bits set in the constant that are not demanded. If so, shrink the
749 /// constant and return true.
750 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
752 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
753 if (!OpC) return false;
755 // If there are no bits set that aren't demanded, nothing to do.
756 if ((~Demanded & OpC->getZExtValue()) == 0)
759 // This is producing any bits that are not needed, shrink the RHS.
760 uint64_t Val = Demanded & OpC->getZExtValue();
761 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
765 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
766 // set of known zero and one bits, compute the maximum and minimum values that
767 // could have the specified known zero and known one bits, returning them in
769 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
772 int64_t &Min, int64_t &Max) {
773 uint64_t TypeBits = Ty->getIntegralTypeMask();
774 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
776 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
778 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
779 // bit if it is unknown.
781 Max = KnownOne|UnknownBits;
783 if (SignBit & UnknownBits) { // Sign bit is unknown
788 // Sign extend the min/max values.
789 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
790 Min = (Min << ShAmt) >> ShAmt;
791 Max = (Max << ShAmt) >> ShAmt;
794 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
795 // a set of known zero and one bits, compute the maximum and minimum values that
796 // could have the specified known zero and known one bits, returning them in
798 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
803 uint64_t TypeBits = Ty->getIntegralTypeMask();
804 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
806 // The minimum value is when the unknown bits are all zeros.
808 // The maximum value is when the unknown bits are all ones.
809 Max = KnownOne|UnknownBits;
813 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
814 /// DemandedMask bits of the result of V are ever used downstream. If we can
815 /// use this information to simplify V, do so and return true. Otherwise,
816 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
817 /// the expression (used to simplify the caller). The KnownZero/One bits may
818 /// only be accurate for those bits in the DemandedMask.
819 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
820 uint64_t &KnownZero, uint64_t &KnownOne,
822 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
823 // We know all of the bits for a constant!
824 KnownOne = CI->getZExtValue() & DemandedMask;
825 KnownZero = ~KnownOne & DemandedMask;
829 KnownZero = KnownOne = 0;
830 if (!V->hasOneUse()) { // Other users may use these bits.
831 if (Depth != 0) { // Not at the root.
832 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
833 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
836 // If this is the root being simplified, allow it to have multiple uses,
837 // just set the DemandedMask to all bits.
838 DemandedMask = V->getType()->getIntegralTypeMask();
839 } else if (DemandedMask == 0) { // Not demanding any bits from V.
840 if (V != UndefValue::get(V->getType()))
841 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
843 } else if (Depth == 6) { // Limit search depth.
847 Instruction *I = dyn_cast<Instruction>(V);
848 if (!I) return false; // Only analyze instructions.
850 DemandedMask &= V->getType()->getIntegralTypeMask();
852 uint64_t KnownZero2, KnownOne2;
853 switch (I->getOpcode()) {
855 case Instruction::And:
856 // If either the LHS or the RHS are Zero, the result is zero.
857 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
858 KnownZero, KnownOne, Depth+1))
860 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
862 // If something is known zero on the RHS, the bits aren't demanded on the
864 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
865 KnownZero2, KnownOne2, Depth+1))
867 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
869 // If all of the demanded bits are known one on one side, return the other.
870 // These bits cannot contribute to the result of the 'and'.
871 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
872 return UpdateValueUsesWith(I, I->getOperand(0));
873 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
874 return UpdateValueUsesWith(I, I->getOperand(1));
876 // If all of the demanded bits in the inputs are known zeros, return zero.
877 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
878 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
880 // If the RHS is a constant, see if we can simplify it.
881 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
882 return UpdateValueUsesWith(I, I);
884 // Output known-1 bits are only known if set in both the LHS & RHS.
885 KnownOne &= KnownOne2;
886 // Output known-0 are known to be clear if zero in either the LHS | RHS.
887 KnownZero |= KnownZero2;
889 case Instruction::Or:
890 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
891 KnownZero, KnownOne, Depth+1))
893 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
894 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
895 KnownZero2, KnownOne2, Depth+1))
897 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
899 // If all of the demanded bits are known zero on one side, return the other.
900 // These bits cannot contribute to the result of the 'or'.
901 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
902 return UpdateValueUsesWith(I, I->getOperand(0));
903 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
904 return UpdateValueUsesWith(I, I->getOperand(1));
906 // If all of the potentially set bits on one side are known to be set on
907 // the other side, just use the 'other' side.
908 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
909 (DemandedMask & (~KnownZero)))
910 return UpdateValueUsesWith(I, I->getOperand(0));
911 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
912 (DemandedMask & (~KnownZero2)))
913 return UpdateValueUsesWith(I, I->getOperand(1));
915 // If the RHS is a constant, see if we can simplify it.
916 if (ShrinkDemandedConstant(I, 1, DemandedMask))
917 return UpdateValueUsesWith(I, I);
919 // Output known-0 bits are only known if clear in both the LHS & RHS.
920 KnownZero &= KnownZero2;
921 // Output known-1 are known to be set if set in either the LHS | RHS.
922 KnownOne |= KnownOne2;
924 case Instruction::Xor: {
925 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
926 KnownZero, KnownOne, Depth+1))
928 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
929 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
930 KnownZero2, KnownOne2, Depth+1))
932 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
934 // If all of the demanded bits are known zero on one side, return the other.
935 // These bits cannot contribute to the result of the 'xor'.
936 if ((DemandedMask & KnownZero) == DemandedMask)
937 return UpdateValueUsesWith(I, I->getOperand(0));
938 if ((DemandedMask & KnownZero2) == DemandedMask)
939 return UpdateValueUsesWith(I, I->getOperand(1));
941 // Output known-0 bits are known if clear or set in both the LHS & RHS.
942 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
943 // Output known-1 are known to be set if set in only one of the LHS, RHS.
944 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
946 // If all of the unknown bits are known to be zero on one side or the other
947 // (but not both) turn this into an *inclusive* or.
948 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
949 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
950 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
952 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
954 InsertNewInstBefore(Or, *I);
955 return UpdateValueUsesWith(I, Or);
959 // If all of the demanded bits on one side are known, and all of the set
960 // bits on that side are also known to be set on the other side, turn this
961 // into an AND, as we know the bits will be cleared.
962 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
963 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
964 if ((KnownOne & KnownOne2) == KnownOne) {
965 Constant *AndC = GetConstantInType(I->getType(),
966 ~KnownOne & DemandedMask);
968 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
969 InsertNewInstBefore(And, *I);
970 return UpdateValueUsesWith(I, And);
974 // If the RHS is a constant, see if we can simplify it.
975 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
976 if (ShrinkDemandedConstant(I, 1, DemandedMask))
977 return UpdateValueUsesWith(I, I);
979 KnownZero = KnownZeroOut;
980 KnownOne = KnownOneOut;
983 case Instruction::Select:
984 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
985 KnownZero, KnownOne, Depth+1))
987 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
988 KnownZero2, KnownOne2, Depth+1))
990 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
991 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
993 // If the operands are constants, see if we can simplify them.
994 if (ShrinkDemandedConstant(I, 1, DemandedMask))
995 return UpdateValueUsesWith(I, I);
996 if (ShrinkDemandedConstant(I, 2, DemandedMask))
997 return UpdateValueUsesWith(I, I);
999 // Only known if known in both the LHS and RHS.
1000 KnownOne &= KnownOne2;
1001 KnownZero &= KnownZero2;
1003 case Instruction::Cast: {
1004 const Type *SrcTy = I->getOperand(0)->getType();
1005 if (!SrcTy->isIntegral()) return false;
1007 // If this is an integer truncate or noop, just look in the input.
1008 if (SrcTy->getPrimitiveSizeInBits() >=
1009 I->getType()->getPrimitiveSizeInBits()) {
1010 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1011 KnownZero, KnownOne, Depth+1))
1013 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1017 // Sign or Zero extension. Compute the bits in the result that are not
1018 // present in the input.
1019 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1020 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1022 // Handle zero extension.
1023 if (!SrcTy->isSigned()) {
1024 DemandedMask &= SrcTy->getIntegralTypeMask();
1025 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1026 KnownZero, KnownOne, Depth+1))
1028 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1029 // The top bits are known to be zero.
1030 KnownZero |= NewBits;
1033 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1034 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1036 // If any of the sign extended bits are demanded, we know that the sign
1038 if (NewBits & DemandedMask)
1039 InputDemandedBits |= InSignBit;
1041 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1042 KnownZero, KnownOne, Depth+1))
1044 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1046 // If the sign bit of the input is known set or clear, then we know the
1047 // top bits of the result.
1049 // If the input sign bit is known zero, or if the NewBits are not demanded
1050 // convert this into a zero extension.
1051 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1052 // Convert to unsigned first.
1053 Instruction *NewVal;
1054 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
1055 I->getOperand(0)->getName());
1056 InsertNewInstBefore(NewVal, *I);
1057 // Then cast that to the destination type.
1058 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1059 InsertNewInstBefore(NewVal, *I);
1060 return UpdateValueUsesWith(I, NewVal);
1061 } else if (KnownOne & InSignBit) { // Input sign bit known set
1062 KnownOne |= NewBits;
1063 KnownZero &= ~NewBits;
1064 } else { // Input sign bit unknown
1065 KnownZero &= ~NewBits;
1066 KnownOne &= ~NewBits;
1071 case Instruction::Shl:
1072 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1073 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1074 KnownZero, KnownOne, Depth+1))
1076 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1077 KnownZero <<= SA->getValue();
1078 KnownOne <<= SA->getValue();
1079 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1082 case Instruction::Shr:
1083 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1084 unsigned ShAmt = SA->getValue();
1086 // Compute the new bits that are at the top now.
1087 uint64_t HighBits = (1ULL << ShAmt)-1;
1088 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
1089 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1090 if (I->getType()->isUnsigned()) { // Unsigned shift right.
1091 if (SimplifyDemandedBits(I->getOperand(0),
1092 (DemandedMask << ShAmt) & TypeMask,
1093 KnownZero, KnownOne, Depth+1))
1095 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1096 KnownZero &= TypeMask;
1097 KnownOne &= TypeMask;
1098 KnownZero >>= ShAmt;
1100 KnownZero |= HighBits; // high bits known zero.
1101 } else { // Signed shift right.
1102 if (SimplifyDemandedBits(I->getOperand(0),
1103 (DemandedMask << ShAmt) & TypeMask,
1104 KnownZero, KnownOne, Depth+1))
1106 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1107 KnownZero &= TypeMask;
1108 KnownOne &= TypeMask;
1109 KnownZero >>= SA->getValue();
1110 KnownOne >>= SA->getValue();
1112 // Handle the sign bits.
1113 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1114 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1116 // If the input sign bit is known to be zero, or if none of the top bits
1117 // are demanded, turn this into an unsigned shift right.
1118 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1119 // Convert the input to unsigned.
1120 Instruction *NewVal;
1121 NewVal = new CastInst(I->getOperand(0),
1122 I->getType()->getUnsignedVersion(),
1123 I->getOperand(0)->getName());
1124 InsertNewInstBefore(NewVal, *I);
1125 // Perform the unsigned shift right.
1126 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1127 InsertNewInstBefore(NewVal, *I);
1128 // Then cast that to the destination type.
1129 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1130 InsertNewInstBefore(NewVal, *I);
1131 return UpdateValueUsesWith(I, NewVal);
1132 } else if (KnownOne & SignBit) { // New bits are known one.
1133 KnownOne |= HighBits;
1140 // If the client is only demanding bits that we know, return the known
1142 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1143 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1147 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1148 // true when both operands are equal...
1150 static bool isTrueWhenEqual(Instruction &I) {
1151 return I.getOpcode() == Instruction::SetEQ ||
1152 I.getOpcode() == Instruction::SetGE ||
1153 I.getOpcode() == Instruction::SetLE;
1156 /// AssociativeOpt - Perform an optimization on an associative operator. This
1157 /// function is designed to check a chain of associative operators for a
1158 /// potential to apply a certain optimization. Since the optimization may be
1159 /// applicable if the expression was reassociated, this checks the chain, then
1160 /// reassociates the expression as necessary to expose the optimization
1161 /// opportunity. This makes use of a special Functor, which must define
1162 /// 'shouldApply' and 'apply' methods.
1164 template<typename Functor>
1165 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1166 unsigned Opcode = Root.getOpcode();
1167 Value *LHS = Root.getOperand(0);
1169 // Quick check, see if the immediate LHS matches...
1170 if (F.shouldApply(LHS))
1171 return F.apply(Root);
1173 // Otherwise, if the LHS is not of the same opcode as the root, return.
1174 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1175 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1176 // Should we apply this transform to the RHS?
1177 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1179 // If not to the RHS, check to see if we should apply to the LHS...
1180 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1181 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1185 // If the functor wants to apply the optimization to the RHS of LHSI,
1186 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1188 BasicBlock *BB = Root.getParent();
1190 // Now all of the instructions are in the current basic block, go ahead
1191 // and perform the reassociation.
1192 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1194 // First move the selected RHS to the LHS of the root...
1195 Root.setOperand(0, LHSI->getOperand(1));
1197 // Make what used to be the LHS of the root be the user of the root...
1198 Value *ExtraOperand = TmpLHSI->getOperand(1);
1199 if (&Root == TmpLHSI) {
1200 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1203 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1204 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1205 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1206 BasicBlock::iterator ARI = &Root; ++ARI;
1207 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1210 // Now propagate the ExtraOperand down the chain of instructions until we
1212 while (TmpLHSI != LHSI) {
1213 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1214 // Move the instruction to immediately before the chain we are
1215 // constructing to avoid breaking dominance properties.
1216 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1217 BB->getInstList().insert(ARI, NextLHSI);
1220 Value *NextOp = NextLHSI->getOperand(1);
1221 NextLHSI->setOperand(1, ExtraOperand);
1223 ExtraOperand = NextOp;
1226 // Now that the instructions are reassociated, have the functor perform
1227 // the transformation...
1228 return F.apply(Root);
1231 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1237 // AddRHS - Implements: X + X --> X << 1
1240 AddRHS(Value *rhs) : RHS(rhs) {}
1241 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1242 Instruction *apply(BinaryOperator &Add) const {
1243 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1244 ConstantInt::get(Type::UByteTy, 1));
1248 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1250 struct AddMaskingAnd {
1252 AddMaskingAnd(Constant *c) : C2(c) {}
1253 bool shouldApply(Value *LHS) const {
1255 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1256 ConstantExpr::getAnd(C1, C2)->isNullValue();
1258 Instruction *apply(BinaryOperator &Add) const {
1259 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1263 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1265 if (isa<CastInst>(I)) {
1266 if (Constant *SOC = dyn_cast<Constant>(SO))
1267 return ConstantExpr::getCast(SOC, I.getType());
1269 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1270 SO->getName() + ".cast"), I);
1273 // Figure out if the constant is the left or the right argument.
1274 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1275 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1277 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1279 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1280 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1283 Value *Op0 = SO, *Op1 = ConstOperand;
1285 std::swap(Op0, Op1);
1287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1288 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1289 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1290 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1292 assert(0 && "Unknown binary instruction type!");
1295 return IC->InsertNewInstBefore(New, I);
1298 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1299 // constant as the other operand, try to fold the binary operator into the
1300 // select arguments. This also works for Cast instructions, which obviously do
1301 // not have a second operand.
1302 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1304 // Don't modify shared select instructions
1305 if (!SI->hasOneUse()) return 0;
1306 Value *TV = SI->getOperand(1);
1307 Value *FV = SI->getOperand(2);
1309 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1310 // Bool selects with constant operands can be folded to logical ops.
1311 if (SI->getType() == Type::BoolTy) return 0;
1313 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1314 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1316 return new SelectInst(SI->getCondition(), SelectTrueVal,
1323 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1324 /// node as operand #0, see if we can fold the instruction into the PHI (which
1325 /// is only possible if all operands to the PHI are constants).
1326 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1327 PHINode *PN = cast<PHINode>(I.getOperand(0));
1328 unsigned NumPHIValues = PN->getNumIncomingValues();
1329 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1330 !isa<Constant>(PN->getIncomingValue(0))) return 0;
1332 // Check to see if all of the operands of the PHI are constants. If not, we
1333 // cannot do the transformation.
1334 for (unsigned i = 1; i != NumPHIValues; ++i)
1335 if (!isa<Constant>(PN->getIncomingValue(i)))
1338 // Okay, we can do the transformation: create the new PHI node.
1339 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1341 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1342 InsertNewInstBefore(NewPN, *PN);
1344 // Next, add all of the operands to the PHI.
1345 if (I.getNumOperands() == 2) {
1346 Constant *C = cast<Constant>(I.getOperand(1));
1347 for (unsigned i = 0; i != NumPHIValues; ++i) {
1348 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1349 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1350 PN->getIncomingBlock(i));
1353 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1354 const Type *RetTy = I.getType();
1355 for (unsigned i = 0; i != NumPHIValues; ++i) {
1356 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1357 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1358 PN->getIncomingBlock(i));
1361 return ReplaceInstUsesWith(I, NewPN);
1364 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1365 bool Changed = SimplifyCommutative(I);
1366 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1368 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1369 // X + undef -> undef
1370 if (isa<UndefValue>(RHS))
1371 return ReplaceInstUsesWith(I, RHS);
1374 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1375 if (RHSC->isNullValue())
1376 return ReplaceInstUsesWith(I, LHS);
1377 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1378 if (CFP->isExactlyValue(-0.0))
1379 return ReplaceInstUsesWith(I, LHS);
1382 // X + (signbit) --> X ^ signbit
1383 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1384 uint64_t Val = CI->getZExtValue();
1385 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1386 return BinaryOperator::createXor(LHS, RHS);
1389 if (isa<PHINode>(LHS))
1390 if (Instruction *NV = FoldOpIntoPhi(I))
1393 ConstantInt *XorRHS = 0;
1395 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1396 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1397 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1398 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1400 uint64_t C0080Val = 1ULL << 31;
1401 int64_t CFF80Val = -C0080Val;
1404 if (TySizeBits > Size) {
1406 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1407 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1408 if (RHSSExt == CFF80Val) {
1409 if (XorRHS->getZExtValue() == C0080Val)
1411 } else if (RHSZExt == C0080Val) {
1412 if (XorRHS->getSExtValue() == CFF80Val)
1416 // This is a sign extend if the top bits are known zero.
1417 uint64_t Mask = ~0ULL;
1418 Mask <<= 64-(TySizeBits-Size);
1419 Mask &= XorLHS->getType()->getIntegralTypeMask();
1420 if (!MaskedValueIsZero(XorLHS, Mask))
1421 Size = 0; // Not a sign ext, but can't be any others either.
1428 } while (Size >= 8);
1431 const Type *MiddleType = 0;
1434 case 32: MiddleType = Type::IntTy; break;
1435 case 16: MiddleType = Type::ShortTy; break;
1436 case 8: MiddleType = Type::SByteTy; break;
1439 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1440 InsertNewInstBefore(NewTrunc, I);
1441 return new CastInst(NewTrunc, I.getType());
1447 if (I.getType()->isInteger()) {
1448 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1450 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1451 if (RHSI->getOpcode() == Instruction::Sub)
1452 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1453 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1455 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1456 if (LHSI->getOpcode() == Instruction::Sub)
1457 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1458 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1463 if (Value *V = dyn_castNegVal(LHS))
1464 return BinaryOperator::createSub(RHS, V);
1467 if (!isa<Constant>(RHS))
1468 if (Value *V = dyn_castNegVal(RHS))
1469 return BinaryOperator::createSub(LHS, V);
1473 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1474 if (X == RHS) // X*C + X --> X * (C+1)
1475 return BinaryOperator::createMul(RHS, AddOne(C2));
1477 // X*C1 + X*C2 --> X * (C1+C2)
1479 if (X == dyn_castFoldableMul(RHS, C1))
1480 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1483 // X + X*C --> X * (C+1)
1484 if (dyn_castFoldableMul(RHS, C2) == LHS)
1485 return BinaryOperator::createMul(LHS, AddOne(C2));
1488 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1489 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1490 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1492 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1494 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1495 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1496 return BinaryOperator::createSub(C, X);
1499 // (X & FF00) + xx00 -> (X+xx00) & FF00
1500 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1501 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1502 if (Anded == CRHS) {
1503 // See if all bits from the first bit set in the Add RHS up are included
1504 // in the mask. First, get the rightmost bit.
1505 uint64_t AddRHSV = CRHS->getRawValue();
1507 // Form a mask of all bits from the lowest bit added through the top.
1508 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1509 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1511 // See if the and mask includes all of these bits.
1512 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
1514 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1515 // Okay, the xform is safe. Insert the new add pronto.
1516 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1517 LHS->getName()), I);
1518 return BinaryOperator::createAnd(NewAdd, C2);
1523 // Try to fold constant add into select arguments.
1524 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1525 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1529 return Changed ? &I : 0;
1532 // isSignBit - Return true if the value represented by the constant only has the
1533 // highest order bit set.
1534 static bool isSignBit(ConstantInt *CI) {
1535 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1536 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1539 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1541 static Value *RemoveNoopCast(Value *V) {
1542 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1543 const Type *CTy = CI->getType();
1544 const Type *OpTy = CI->getOperand(0)->getType();
1545 if (CTy->isInteger() && OpTy->isInteger()) {
1546 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1547 return RemoveNoopCast(CI->getOperand(0));
1548 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1549 return RemoveNoopCast(CI->getOperand(0));
1554 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1555 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1557 if (Op0 == Op1) // sub X, X -> 0
1558 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1560 // If this is a 'B = x-(-A)', change to B = x+A...
1561 if (Value *V = dyn_castNegVal(Op1))
1562 return BinaryOperator::createAdd(Op0, V);
1564 if (isa<UndefValue>(Op0))
1565 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1566 if (isa<UndefValue>(Op1))
1567 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1569 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1570 // Replace (-1 - A) with (~A)...
1571 if (C->isAllOnesValue())
1572 return BinaryOperator::createNot(Op1);
1574 // C - ~X == X + (1+C)
1576 if (match(Op1, m_Not(m_Value(X))))
1577 return BinaryOperator::createAdd(X,
1578 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1579 // -((uint)X >> 31) -> ((int)X >> 31)
1580 // -((int)X >> 31) -> ((uint)X >> 31)
1581 if (C->isNullValue()) {
1582 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1583 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1584 if (SI->getOpcode() == Instruction::Shr)
1585 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1587 if (SI->getType()->isSigned())
1588 NewTy = SI->getType()->getUnsignedVersion();
1590 NewTy = SI->getType()->getSignedVersion();
1591 // Check to see if we are shifting out everything but the sign bit.
1592 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
1593 // Ok, the transformation is safe. Insert a cast of the incoming
1594 // value, then the new shift, then the new cast.
1595 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1596 SI->getOperand(0)->getName());
1597 Value *InV = InsertNewInstBefore(FirstCast, I);
1598 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1600 if (NewShift->getType() == I.getType())
1603 InV = InsertNewInstBefore(NewShift, I);
1604 return new CastInst(NewShift, I.getType());
1610 // Try to fold constant sub into select arguments.
1611 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1612 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1615 if (isa<PHINode>(Op0))
1616 if (Instruction *NV = FoldOpIntoPhi(I))
1620 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1621 if (Op1I->getOpcode() == Instruction::Add &&
1622 !Op0->getType()->isFloatingPoint()) {
1623 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1624 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1625 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1626 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1627 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1628 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1629 // C1-(X+C2) --> (C1-C2)-X
1630 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1631 Op1I->getOperand(0));
1635 if (Op1I->hasOneUse()) {
1636 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1637 // is not used by anyone else...
1639 if (Op1I->getOpcode() == Instruction::Sub &&
1640 !Op1I->getType()->isFloatingPoint()) {
1641 // Swap the two operands of the subexpr...
1642 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1643 Op1I->setOperand(0, IIOp1);
1644 Op1I->setOperand(1, IIOp0);
1646 // Create the new top level add instruction...
1647 return BinaryOperator::createAdd(Op0, Op1);
1650 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1652 if (Op1I->getOpcode() == Instruction::And &&
1653 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1654 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1657 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1658 return BinaryOperator::createAnd(Op0, NewNot);
1661 // -(X sdiv C) -> (X sdiv -C)
1662 if (Op1I->getOpcode() == Instruction::Div)
1663 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1664 if (CSI->isNullValue())
1665 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1666 return BinaryOperator::createDiv(Op1I->getOperand(0),
1667 ConstantExpr::getNeg(DivRHS));
1669 // X - X*C --> X * (1-C)
1670 ConstantInt *C2 = 0;
1671 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1673 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1674 return BinaryOperator::createMul(Op0, CP1);
1679 if (!Op0->getType()->isFloatingPoint())
1680 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1681 if (Op0I->getOpcode() == Instruction::Add) {
1682 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1683 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1684 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1685 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1686 } else if (Op0I->getOpcode() == Instruction::Sub) {
1687 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1688 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1692 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1693 if (X == Op1) { // X*C - X --> X * (C-1)
1694 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1695 return BinaryOperator::createMul(Op1, CP1);
1698 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1699 if (X == dyn_castFoldableMul(Op1, C2))
1700 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1705 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1706 /// really just returns true if the most significant (sign) bit is set.
1707 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1708 if (RHS->getType()->isSigned()) {
1709 // True if source is LHS < 0 or LHS <= -1
1710 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1711 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1713 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1714 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1715 // the size of the integer type.
1716 if (Opcode == Instruction::SetGE)
1717 return RHSC->getValue() ==
1718 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1719 if (Opcode == Instruction::SetGT)
1720 return RHSC->getValue() ==
1721 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1726 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1727 bool Changed = SimplifyCommutative(I);
1728 Value *Op0 = I.getOperand(0);
1730 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1731 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1733 // Simplify mul instructions with a constant RHS...
1734 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1735 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1737 // ((X << C1)*C2) == (X * (C2 << C1))
1738 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1739 if (SI->getOpcode() == Instruction::Shl)
1740 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1741 return BinaryOperator::createMul(SI->getOperand(0),
1742 ConstantExpr::getShl(CI, ShOp));
1744 if (CI->isNullValue())
1745 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1746 if (CI->equalsInt(1)) // X * 1 == X
1747 return ReplaceInstUsesWith(I, Op0);
1748 if (CI->isAllOnesValue()) // X * -1 == 0 - X
1749 return BinaryOperator::createNeg(Op0, I.getName());
1751 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1752 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1753 uint64_t C = Log2_64(Val);
1754 return new ShiftInst(Instruction::Shl, Op0,
1755 ConstantUInt::get(Type::UByteTy, C));
1757 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1758 if (Op1F->isNullValue())
1759 return ReplaceInstUsesWith(I, Op1);
1761 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1762 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1763 if (Op1F->getValue() == 1.0)
1764 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1767 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1768 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1769 isa<ConstantInt>(Op0I->getOperand(1))) {
1770 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1771 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1773 InsertNewInstBefore(Add, I);
1774 Value *C1C2 = ConstantExpr::getMul(Op1,
1775 cast<Constant>(Op0I->getOperand(1)));
1776 return BinaryOperator::createAdd(Add, C1C2);
1780 // Try to fold constant mul into select arguments.
1781 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1782 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1785 if (isa<PHINode>(Op0))
1786 if (Instruction *NV = FoldOpIntoPhi(I))
1790 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1791 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1792 return BinaryOperator::createMul(Op0v, Op1v);
1794 // If one of the operands of the multiply is a cast from a boolean value, then
1795 // we know the bool is either zero or one, so this is a 'masking' multiply.
1796 // See if we can simplify things based on how the boolean was originally
1798 CastInst *BoolCast = 0;
1799 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1800 if (CI->getOperand(0)->getType() == Type::BoolTy)
1803 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1804 if (CI->getOperand(0)->getType() == Type::BoolTy)
1807 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1808 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1809 const Type *SCOpTy = SCIOp0->getType();
1811 // If the setcc is true iff the sign bit of X is set, then convert this
1812 // multiply into a shift/and combination.
1813 if (isa<ConstantInt>(SCIOp1) &&
1814 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1815 // Shift the X value right to turn it into "all signbits".
1816 Constant *Amt = ConstantUInt::get(Type::UByteTy,
1817 SCOpTy->getPrimitiveSizeInBits()-1);
1818 if (SCIOp0->getType()->isUnsigned()) {
1819 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1820 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1821 SCIOp0->getName()), I);
1825 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1826 BoolCast->getOperand(0)->getName()+
1829 // If the multiply type is not the same as the source type, sign extend
1830 // or truncate to the multiply type.
1831 if (I.getType() != V->getType())
1832 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1834 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1835 return BinaryOperator::createAnd(V, OtherOp);
1840 return Changed ? &I : 0;
1843 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1844 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1846 if (isa<UndefValue>(Op0)) // undef / X -> 0
1847 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1848 if (isa<UndefValue>(Op1))
1849 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1851 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1853 if (RHS->equalsInt(1))
1854 return ReplaceInstUsesWith(I, Op0);
1857 if (RHS->isAllOnesValue())
1858 return BinaryOperator::createNeg(Op0);
1860 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1861 if (LHS->getOpcode() == Instruction::Div)
1862 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1863 // (X / C1) / C2 -> X / (C1*C2)
1864 return BinaryOperator::createDiv(LHS->getOperand(0),
1865 ConstantExpr::getMul(RHS, LHSRHS));
1868 // Check to see if this is an unsigned division with an exact power of 2,
1869 // if so, convert to a right shift.
1870 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1871 if (uint64_t Val = C->getValue()) // Don't break X / 0
1872 if (isPowerOf2_64(Val)) {
1873 uint64_t C = Log2_64(Val);
1874 return new ShiftInst(Instruction::Shr, Op0,
1875 ConstantUInt::get(Type::UByteTy, C));
1879 if (RHS->getType()->isSigned())
1880 if (Value *LHSNeg = dyn_castNegVal(Op0))
1881 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1883 if (!RHS->isNullValue()) {
1884 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1885 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1887 if (isa<PHINode>(Op0))
1888 if (Instruction *NV = FoldOpIntoPhi(I))
1893 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1894 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1895 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1896 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1897 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1898 if (STO->getValue() == 0) { // Couldn't be this argument.
1899 I.setOperand(1, SFO);
1901 } else if (SFO->getValue() == 0) {
1902 I.setOperand(1, STO);
1906 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1907 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1908 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1909 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1910 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1911 TC, SI->getName()+".t");
1912 TSI = InsertNewInstBefore(TSI, I);
1914 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1915 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1916 FC, SI->getName()+".f");
1917 FSI = InsertNewInstBefore(FSI, I);
1918 return new SelectInst(SI->getOperand(0), TSI, FSI);
1922 // 0 / X == 0, we don't need to preserve faults!
1923 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1924 if (LHS->equalsInt(0))
1925 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1927 if (I.getType()->isSigned()) {
1928 // If the sign bits of both operands are zero (i.e. we can prove they are
1929 // unsigned inputs), turn this into a udiv.
1930 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1931 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1932 const Type *NTy = Op0->getType()->getUnsignedVersion();
1933 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1934 InsertNewInstBefore(LHS, I);
1936 if (Constant *R = dyn_cast<Constant>(Op1))
1937 RHS = ConstantExpr::getCast(R, NTy);
1939 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1940 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1941 InsertNewInstBefore(Div, I);
1942 return new CastInst(Div, I.getType());
1945 // Known to be an unsigned division.
1946 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1947 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1948 if (RHSI->getOpcode() == Instruction::Shl &&
1949 isa<ConstantUInt>(RHSI->getOperand(0))) {
1950 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1951 if (isPowerOf2_64(C1)) {
1952 unsigned C2 = Log2_64(C1);
1953 Value *Add = RHSI->getOperand(1);
1955 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1956 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1959 return new ShiftInst(Instruction::Shr, Op0, Add);
1969 /// GetFactor - If we can prove that the specified value is at least a multiple
1970 /// of some factor, return that factor.
1971 static Constant *GetFactor(Value *V) {
1972 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1975 // Unless we can be tricky, we know this is a multiple of 1.
1976 Constant *Result = ConstantInt::get(V->getType(), 1);
1978 Instruction *I = dyn_cast<Instruction>(V);
1979 if (!I) return Result;
1981 if (I->getOpcode() == Instruction::Mul) {
1982 // Handle multiplies by a constant, etc.
1983 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1984 GetFactor(I->getOperand(1)));
1985 } else if (I->getOpcode() == Instruction::Shl) {
1986 // (X<<C) -> X * (1 << C)
1987 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1988 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1989 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1991 } else if (I->getOpcode() == Instruction::And) {
1992 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1993 // X & 0xFFF0 is known to be a multiple of 16.
1994 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1995 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1996 return ConstantExpr::getShl(Result,
1997 ConstantUInt::get(Type::UByteTy, Zeros));
1999 } else if (I->getOpcode() == Instruction::Cast) {
2000 Value *Op = I->getOperand(0);
2001 // Only handle int->int casts.
2002 if (!Op->getType()->isInteger()) return Result;
2003 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2008 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
2009 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2011 // 0 % X == 0, we don't need to preserve faults!
2012 if (Constant *LHS = dyn_cast<Constant>(Op0))
2013 if (LHS->isNullValue())
2014 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2016 if (isa<UndefValue>(Op0)) // undef % X -> 0
2017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2018 if (isa<UndefValue>(Op1))
2019 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2021 if (I.getType()->isSigned()) {
2022 if (Value *RHSNeg = dyn_castNegVal(Op1))
2023 if (!isa<ConstantSInt>(RHSNeg) ||
2024 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
2026 AddUsesToWorkList(I);
2027 I.setOperand(1, RHSNeg);
2031 // If the top bits of both operands are zero (i.e. we can prove they are
2032 // unsigned inputs), turn this into a urem.
2033 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2034 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2035 const Type *NTy = Op0->getType()->getUnsignedVersion();
2036 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2037 InsertNewInstBefore(LHS, I);
2039 if (Constant *R = dyn_cast<Constant>(Op1))
2040 RHS = ConstantExpr::getCast(R, NTy);
2042 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2043 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2044 InsertNewInstBefore(Rem, I);
2045 return new CastInst(Rem, I.getType());
2049 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2050 // X % 0 == undef, we don't need to preserve faults!
2051 if (RHS->equalsInt(0))
2052 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2054 if (RHS->equalsInt(1)) // X % 1 == 0
2055 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2057 // Check to see if this is an unsigned remainder with an exact power of 2,
2058 // if so, convert to a bitwise and.
2059 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
2060 if (isPowerOf2_64(C->getValue()))
2061 return BinaryOperator::createAnd(Op0, SubOne(C));
2063 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2064 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2065 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2067 } else if (isa<PHINode>(Op0I)) {
2068 if (Instruction *NV = FoldOpIntoPhi(I))
2072 // X*C1%C2 --> 0 iff C1%C2 == 0
2073 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2074 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2078 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2079 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2080 if (I.getType()->isUnsigned() &&
2081 RHSI->getOpcode() == Instruction::Shl &&
2082 isa<ConstantUInt>(RHSI->getOperand(0))) {
2083 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2084 if (isPowerOf2_64(C1)) {
2085 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2086 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2088 return BinaryOperator::createAnd(Op0, Add);
2092 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2093 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2094 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2095 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2096 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
2097 if (STO->getValue() == 0) { // Couldn't be this argument.
2098 I.setOperand(1, SFO);
2100 } else if (SFO->getValue() == 0) {
2101 I.setOperand(1, STO);
2105 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2106 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2107 SubOne(STO), SI->getName()+".t"), I);
2108 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2109 SubOne(SFO), SI->getName()+".f"), I);
2110 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2118 // isMaxValueMinusOne - return true if this is Max-1
2119 static bool isMaxValueMinusOne(const ConstantInt *C) {
2120 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2121 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
2123 const ConstantSInt *CS = cast<ConstantSInt>(C);
2125 // Calculate 0111111111..11111
2126 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2127 int64_t Val = INT64_MAX; // All ones
2128 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2129 return CS->getValue() == Val-1;
2132 // isMinValuePlusOne - return true if this is Min+1
2133 static bool isMinValuePlusOne(const ConstantInt *C) {
2134 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2135 return CU->getValue() == 1;
2137 const ConstantSInt *CS = cast<ConstantSInt>(C);
2139 // Calculate 1111111111000000000000
2140 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2141 int64_t Val = -1; // All ones
2142 Val <<= TypeBits-1; // Shift over to the right spot
2143 return CS->getValue() == Val+1;
2146 // isOneBitSet - Return true if there is exactly one bit set in the specified
2148 static bool isOneBitSet(const ConstantInt *CI) {
2149 uint64_t V = CI->getRawValue();
2150 return V && (V & (V-1)) == 0;
2153 #if 0 // Currently unused
2154 // isLowOnes - Return true if the constant is of the form 0+1+.
2155 static bool isLowOnes(const ConstantInt *CI) {
2156 uint64_t V = CI->getRawValue();
2158 // There won't be bits set in parts that the type doesn't contain.
2159 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2161 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2162 return U && V && (U & V) == 0;
2166 // isHighOnes - Return true if the constant is of the form 1+0+.
2167 // This is the same as lowones(~X).
2168 static bool isHighOnes(const ConstantInt *CI) {
2169 uint64_t V = ~CI->getRawValue();
2170 if (~V == 0) return false; // 0's does not match "1+"
2172 // There won't be bits set in parts that the type doesn't contain.
2173 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2175 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2176 return U && V && (U & V) == 0;
2180 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2181 /// are carefully arranged to allow folding of expressions such as:
2183 /// (A < B) | (A > B) --> (A != B)
2185 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2186 /// represents that the comparison is true if A == B, and bit value '1' is true
2189 static unsigned getSetCondCode(const SetCondInst *SCI) {
2190 switch (SCI->getOpcode()) {
2192 case Instruction::SetGT: return 1;
2193 case Instruction::SetEQ: return 2;
2194 case Instruction::SetGE: return 3;
2195 case Instruction::SetLT: return 4;
2196 case Instruction::SetNE: return 5;
2197 case Instruction::SetLE: return 6;
2200 assert(0 && "Invalid SetCC opcode!");
2205 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2206 /// opcode and two operands into either a constant true or false, or a brand new
2207 /// SetCC instruction.
2208 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2210 case 0: return ConstantBool::False;
2211 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2212 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2213 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2214 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2215 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2216 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2217 case 7: return ConstantBool::True;
2218 default: assert(0 && "Illegal SetCCCode!"); return 0;
2222 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2223 struct FoldSetCCLogical {
2226 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2227 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2228 bool shouldApply(Value *V) const {
2229 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2230 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2231 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2234 Instruction *apply(BinaryOperator &Log) const {
2235 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2236 if (SCI->getOperand(0) != LHS) {
2237 assert(SCI->getOperand(1) == LHS);
2238 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2241 unsigned LHSCode = getSetCondCode(SCI);
2242 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2244 switch (Log.getOpcode()) {
2245 case Instruction::And: Code = LHSCode & RHSCode; break;
2246 case Instruction::Or: Code = LHSCode | RHSCode; break;
2247 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2248 default: assert(0 && "Illegal logical opcode!"); return 0;
2251 Value *RV = getSetCCValue(Code, LHS, RHS);
2252 if (Instruction *I = dyn_cast<Instruction>(RV))
2254 // Otherwise, it's a constant boolean value...
2255 return IC.ReplaceInstUsesWith(Log, RV);
2259 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2260 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2261 // guaranteed to be either a shift instruction or a binary operator.
2262 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2263 ConstantIntegral *OpRHS,
2264 ConstantIntegral *AndRHS,
2265 BinaryOperator &TheAnd) {
2266 Value *X = Op->getOperand(0);
2267 Constant *Together = 0;
2268 if (!isa<ShiftInst>(Op))
2269 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2271 switch (Op->getOpcode()) {
2272 case Instruction::Xor:
2273 if (Op->hasOneUse()) {
2274 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2275 std::string OpName = Op->getName(); Op->setName("");
2276 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2277 InsertNewInstBefore(And, TheAnd);
2278 return BinaryOperator::createXor(And, Together);
2281 case Instruction::Or:
2282 if (Together == AndRHS) // (X | C) & C --> C
2283 return ReplaceInstUsesWith(TheAnd, AndRHS);
2285 if (Op->hasOneUse() && Together != OpRHS) {
2286 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2287 std::string Op0Name = Op->getName(); Op->setName("");
2288 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2289 InsertNewInstBefore(Or, TheAnd);
2290 return BinaryOperator::createAnd(Or, AndRHS);
2293 case Instruction::Add:
2294 if (Op->hasOneUse()) {
2295 // Adding a one to a single bit bit-field should be turned into an XOR
2296 // of the bit. First thing to check is to see if this AND is with a
2297 // single bit constant.
2298 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
2300 // Clear bits that are not part of the constant.
2301 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2303 // If there is only one bit set...
2304 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2305 // Ok, at this point, we know that we are masking the result of the
2306 // ADD down to exactly one bit. If the constant we are adding has
2307 // no bits set below this bit, then we can eliminate the ADD.
2308 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
2310 // Check to see if any bits below the one bit set in AndRHSV are set.
2311 if ((AddRHS & (AndRHSV-1)) == 0) {
2312 // If not, the only thing that can effect the output of the AND is
2313 // the bit specified by AndRHSV. If that bit is set, the effect of
2314 // the XOR is to toggle the bit. If it is clear, then the ADD has
2316 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2317 TheAnd.setOperand(0, X);
2320 std::string Name = Op->getName(); Op->setName("");
2321 // Pull the XOR out of the AND.
2322 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2323 InsertNewInstBefore(NewAnd, TheAnd);
2324 return BinaryOperator::createXor(NewAnd, AndRHS);
2331 case Instruction::Shl: {
2332 // We know that the AND will not produce any of the bits shifted in, so if
2333 // the anded constant includes them, clear them now!
2335 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2336 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2337 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2339 if (CI == ShlMask) { // Masking out bits that the shift already masks
2340 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2341 } else if (CI != AndRHS) { // Reducing bits set in and.
2342 TheAnd.setOperand(1, CI);
2347 case Instruction::Shr:
2348 // We know that the AND will not produce any of the bits shifted in, so if
2349 // the anded constant includes them, clear them now! This only applies to
2350 // unsigned shifts, because a signed shr may bring in set bits!
2352 if (AndRHS->getType()->isUnsigned()) {
2353 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2354 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2355 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2357 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2358 return ReplaceInstUsesWith(TheAnd, Op);
2359 } else if (CI != AndRHS) {
2360 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2363 } else { // Signed shr.
2364 // See if this is shifting in some sign extension, then masking it out
2366 if (Op->hasOneUse()) {
2367 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2368 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2369 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2370 if (CI == AndRHS) { // Masking out bits shifted in.
2371 // Make the argument unsigned.
2372 Value *ShVal = Op->getOperand(0);
2373 ShVal = InsertCastBefore(ShVal,
2374 ShVal->getType()->getUnsignedVersion(),
2376 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2377 OpRHS, Op->getName()),
2379 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2380 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2383 return new CastInst(ShVal, Op->getType());
2393 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2394 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2395 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2396 /// insert new instructions.
2397 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2398 bool Inside, Instruction &IB) {
2399 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2400 "Lo is not <= Hi in range emission code!");
2402 if (Lo == Hi) // Trivially false.
2403 return new SetCondInst(Instruction::SetNE, V, V);
2404 if (cast<ConstantIntegral>(Lo)->isMinValue())
2405 return new SetCondInst(Instruction::SetLT, V, Hi);
2407 Constant *AddCST = ConstantExpr::getNeg(Lo);
2408 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2409 InsertNewInstBefore(Add, IB);
2410 // Convert to unsigned for the comparison.
2411 const Type *UnsType = Add->getType()->getUnsignedVersion();
2412 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2413 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2414 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2415 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2418 if (Lo == Hi) // Trivially true.
2419 return new SetCondInst(Instruction::SetEQ, V, V);
2421 Hi = SubOne(cast<ConstantInt>(Hi));
2422 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2423 return new SetCondInst(Instruction::SetGT, V, Hi);
2425 // Emit X-Lo > Hi-Lo-1
2426 Constant *AddCST = ConstantExpr::getNeg(Lo);
2427 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2428 InsertNewInstBefore(Add, IB);
2429 // Convert to unsigned for the comparison.
2430 const Type *UnsType = Add->getType()->getUnsignedVersion();
2431 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2432 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2433 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2434 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2437 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2438 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2439 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2440 // not, since all 1s are not contiguous.
2441 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2442 uint64_t V = Val->getRawValue();
2443 if (!isShiftedMask_64(V)) return false;
2445 // look for the first zero bit after the run of ones
2446 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2447 // look for the first non-zero bit
2448 ME = 64-CountLeadingZeros_64(V);
2454 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2455 /// where isSub determines whether the operator is a sub. If we can fold one of
2456 /// the following xforms:
2458 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2459 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2460 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2462 /// return (A +/- B).
2464 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2465 ConstantIntegral *Mask, bool isSub,
2467 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2468 if (!LHSI || LHSI->getNumOperands() != 2 ||
2469 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2471 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2473 switch (LHSI->getOpcode()) {
2475 case Instruction::And:
2476 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2477 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2478 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2481 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2482 // part, we don't need any explicit masks to take them out of A. If that
2483 // is all N is, ignore it.
2485 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2486 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2488 if (MaskedValueIsZero(RHS, Mask))
2493 case Instruction::Or:
2494 case Instruction::Xor:
2495 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2496 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2497 ConstantExpr::getAnd(N, Mask)->isNullValue())
2504 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2506 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2507 return InsertNewInstBefore(New, I);
2510 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2511 bool Changed = SimplifyCommutative(I);
2512 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2514 if (isa<UndefValue>(Op1)) // X & undef -> 0
2515 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2519 return ReplaceInstUsesWith(I, Op1);
2521 // See if we can simplify any instructions used by the instruction whose sole
2522 // purpose is to compute bits we don't care about.
2523 uint64_t KnownZero, KnownOne;
2524 if (!isa<PackedType>(I.getType()) &&
2525 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2526 KnownZero, KnownOne))
2529 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2530 uint64_t AndRHSMask = AndRHS->getZExtValue();
2531 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2532 uint64_t NotAndRHS = AndRHSMask^TypeMask;
2534 // Optimize a variety of ((val OP C1) & C2) combinations...
2535 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2536 Instruction *Op0I = cast<Instruction>(Op0);
2537 Value *Op0LHS = Op0I->getOperand(0);
2538 Value *Op0RHS = Op0I->getOperand(1);
2539 switch (Op0I->getOpcode()) {
2540 case Instruction::Xor:
2541 case Instruction::Or:
2542 // If the mask is only needed on one incoming arm, push it up.
2543 if (Op0I->hasOneUse()) {
2544 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2545 // Not masking anything out for the LHS, move to RHS.
2546 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2547 Op0RHS->getName()+".masked");
2548 InsertNewInstBefore(NewRHS, I);
2549 return BinaryOperator::create(
2550 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2552 if (!isa<Constant>(Op0RHS) &&
2553 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2554 // Not masking anything out for the RHS, move to LHS.
2555 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2556 Op0LHS->getName()+".masked");
2557 InsertNewInstBefore(NewLHS, I);
2558 return BinaryOperator::create(
2559 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2564 case Instruction::Add:
2565 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2566 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2567 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2568 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2569 return BinaryOperator::createAnd(V, AndRHS);
2570 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2571 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
2574 case Instruction::Sub:
2575 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2576 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2577 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2578 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2579 return BinaryOperator::createAnd(V, AndRHS);
2583 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2584 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2586 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2587 const Type *SrcTy = CI->getOperand(0)->getType();
2589 // If this is an integer truncation or change from signed-to-unsigned, and
2590 // if the source is an and/or with immediate, transform it. This
2591 // frequently occurs for bitfield accesses.
2592 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2593 if (SrcTy->getPrimitiveSizeInBits() >=
2594 I.getType()->getPrimitiveSizeInBits() &&
2595 CastOp->getNumOperands() == 2)
2596 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2597 if (CastOp->getOpcode() == Instruction::And) {
2598 // Change: and (cast (and X, C1) to T), C2
2599 // into : and (cast X to T), trunc(C1)&C2
2600 // This will folds the two ands together, which may allow other
2602 Instruction *NewCast =
2603 new CastInst(CastOp->getOperand(0), I.getType(),
2604 CastOp->getName()+".shrunk");
2605 NewCast = InsertNewInstBefore(NewCast, I);
2607 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2608 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2609 return BinaryOperator::createAnd(NewCast, C3);
2610 } else if (CastOp->getOpcode() == Instruction::Or) {
2611 // Change: and (cast (or X, C1) to T), C2
2612 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2613 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2614 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2615 return ReplaceInstUsesWith(I, AndRHS);
2620 // Try to fold constant and into select arguments.
2621 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2622 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2624 if (isa<PHINode>(Op0))
2625 if (Instruction *NV = FoldOpIntoPhi(I))
2629 Value *Op0NotVal = dyn_castNotVal(Op0);
2630 Value *Op1NotVal = dyn_castNotVal(Op1);
2632 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2633 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2635 // (~A & ~B) == (~(A | B)) - De Morgan's Law
2636 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2637 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2638 I.getName()+".demorgan");
2639 InsertNewInstBefore(Or, I);
2640 return BinaryOperator::createNot(Or);
2644 Value *A = 0, *B = 0;
2645 ConstantInt *C1 = 0, *C2 = 0;
2646 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2647 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2648 return ReplaceInstUsesWith(I, Op1);
2649 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2650 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2651 return ReplaceInstUsesWith(I, Op0);
2653 if (Op0->hasOneUse() &&
2654 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2655 if (A == Op1) { // (A^B)&A -> A&(A^B)
2656 I.swapOperands(); // Simplify below
2657 std::swap(Op0, Op1);
2658 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2659 cast<BinaryOperator>(Op0)->swapOperands();
2660 I.swapOperands(); // Simplify below
2661 std::swap(Op0, Op1);
2664 if (Op1->hasOneUse() &&
2665 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2666 if (B == Op0) { // B&(A^B) -> B&(B^A)
2667 cast<BinaryOperator>(Op1)->swapOperands();
2670 if (A == Op0) { // A&(A^B) -> A & ~B
2671 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2672 InsertNewInstBefore(NotB, I);
2673 return BinaryOperator::createAnd(A, NotB);
2679 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2680 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2681 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2684 Value *LHSVal, *RHSVal;
2685 ConstantInt *LHSCst, *RHSCst;
2686 Instruction::BinaryOps LHSCC, RHSCC;
2687 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2688 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2689 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2690 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2691 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2692 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2693 // Ensure that the larger constant is on the RHS.
2694 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2695 SetCondInst *LHS = cast<SetCondInst>(Op0);
2696 if (cast<ConstantBool>(Cmp)->getValue()) {
2697 std::swap(LHS, RHS);
2698 std::swap(LHSCst, RHSCst);
2699 std::swap(LHSCC, RHSCC);
2702 // At this point, we know we have have two setcc instructions
2703 // comparing a value against two constants and and'ing the result
2704 // together. Because of the above check, we know that we only have
2705 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2706 // FoldSetCCLogical check above), that the two constants are not
2708 assert(LHSCst != RHSCst && "Compares not folded above?");
2711 default: assert(0 && "Unknown integer condition code!");
2712 case Instruction::SetEQ:
2714 default: assert(0 && "Unknown integer condition code!");
2715 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2716 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2717 return ReplaceInstUsesWith(I, ConstantBool::False);
2718 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2719 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2720 return ReplaceInstUsesWith(I, LHS);
2722 case Instruction::SetNE:
2724 default: assert(0 && "Unknown integer condition code!");
2725 case Instruction::SetLT:
2726 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2727 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2728 break; // (X != 13 & X < 15) -> no change
2729 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2730 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2731 return ReplaceInstUsesWith(I, RHS);
2732 case Instruction::SetNE:
2733 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2734 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2735 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2736 LHSVal->getName()+".off");
2737 InsertNewInstBefore(Add, I);
2738 const Type *UnsType = Add->getType()->getUnsignedVersion();
2739 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2740 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2741 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2742 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2744 break; // (X != 13 & X != 15) -> no change
2747 case Instruction::SetLT:
2749 default: assert(0 && "Unknown integer condition code!");
2750 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2751 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2752 return ReplaceInstUsesWith(I, ConstantBool::False);
2753 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2754 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2755 return ReplaceInstUsesWith(I, LHS);
2757 case Instruction::SetGT:
2759 default: assert(0 && "Unknown integer condition code!");
2760 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2761 return ReplaceInstUsesWith(I, LHS);
2762 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2763 return ReplaceInstUsesWith(I, RHS);
2764 case Instruction::SetNE:
2765 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2766 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2767 break; // (X > 13 & X != 15) -> no change
2768 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2769 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2775 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2776 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2777 const Type *SrcTy = Op0C->getOperand(0)->getType();
2778 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2779 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
2780 // Only do this if the casts both really cause code to be generated.
2781 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2782 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
2783 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2784 Op1C->getOperand(0),
2786 InsertNewInstBefore(NewOp, I);
2787 return new CastInst(NewOp, I.getType());
2791 return Changed ? &I : 0;
2794 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2795 bool Changed = SimplifyCommutative(I);
2796 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2798 if (isa<UndefValue>(Op1))
2799 return ReplaceInstUsesWith(I, // X | undef -> -1
2800 ConstantIntegral::getAllOnesValue(I.getType()));
2804 return ReplaceInstUsesWith(I, Op0);
2806 // See if we can simplify any instructions used by the instruction whose sole
2807 // purpose is to compute bits we don't care about.
2808 uint64_t KnownZero, KnownOne;
2809 if (!isa<PackedType>(I.getType()) &&
2810 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2811 KnownZero, KnownOne))
2815 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2816 ConstantInt *C1 = 0; Value *X = 0;
2817 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2818 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2819 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2821 InsertNewInstBefore(Or, I);
2822 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2825 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2826 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2827 std::string Op0Name = Op0->getName(); Op0->setName("");
2828 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2829 InsertNewInstBefore(Or, I);
2830 return BinaryOperator::createXor(Or,
2831 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2834 // Try to fold constant and into select arguments.
2835 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2836 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2838 if (isa<PHINode>(Op0))
2839 if (Instruction *NV = FoldOpIntoPhi(I))
2843 Value *A = 0, *B = 0;
2844 ConstantInt *C1 = 0, *C2 = 0;
2846 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2847 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2848 return ReplaceInstUsesWith(I, Op1);
2849 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2850 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2851 return ReplaceInstUsesWith(I, Op0);
2853 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2854 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2855 MaskedValueIsZero(Op1, C1->getZExtValue())) {
2856 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2858 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2861 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2862 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2863 MaskedValueIsZero(Op0, C1->getZExtValue())) {
2864 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2866 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2869 // (A & C1)|(B & C2)
2870 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2871 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2873 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2874 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2877 // If we have: ((V + N) & C1) | (V & C2)
2878 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2879 // replace with V+N.
2880 if (C1 == ConstantExpr::getNot(C2)) {
2881 Value *V1 = 0, *V2 = 0;
2882 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2883 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2884 // Add commutes, try both ways.
2885 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
2886 return ReplaceInstUsesWith(I, A);
2887 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
2888 return ReplaceInstUsesWith(I, A);
2890 // Or commutes, try both ways.
2891 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2892 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2893 // Add commutes, try both ways.
2894 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
2895 return ReplaceInstUsesWith(I, B);
2896 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
2897 return ReplaceInstUsesWith(I, B);
2902 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2903 if (A == Op1) // ~A | A == -1
2904 return ReplaceInstUsesWith(I,
2905 ConstantIntegral::getAllOnesValue(I.getType()));
2909 // Note, A is still live here!
2910 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2912 return ReplaceInstUsesWith(I,
2913 ConstantIntegral::getAllOnesValue(I.getType()));
2915 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2916 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2917 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2918 I.getName()+".demorgan"), I);
2919 return BinaryOperator::createNot(And);
2923 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2924 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2925 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2928 Value *LHSVal, *RHSVal;
2929 ConstantInt *LHSCst, *RHSCst;
2930 Instruction::BinaryOps LHSCC, RHSCC;
2931 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2932 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2933 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2934 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2935 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2936 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2937 // Ensure that the larger constant is on the RHS.
2938 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2939 SetCondInst *LHS = cast<SetCondInst>(Op0);
2940 if (cast<ConstantBool>(Cmp)->getValue()) {
2941 std::swap(LHS, RHS);
2942 std::swap(LHSCst, RHSCst);
2943 std::swap(LHSCC, RHSCC);
2946 // At this point, we know we have have two setcc instructions
2947 // comparing a value against two constants and or'ing the result
2948 // together. Because of the above check, we know that we only have
2949 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2950 // FoldSetCCLogical check above), that the two constants are not
2952 assert(LHSCst != RHSCst && "Compares not folded above?");
2955 default: assert(0 && "Unknown integer condition code!");
2956 case Instruction::SetEQ:
2958 default: assert(0 && "Unknown integer condition code!");
2959 case Instruction::SetEQ:
2960 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2961 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2962 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2963 LHSVal->getName()+".off");
2964 InsertNewInstBefore(Add, I);
2965 const Type *UnsType = Add->getType()->getUnsignedVersion();
2966 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2967 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2968 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2969 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2971 break; // (X == 13 | X == 15) -> no change
2973 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2975 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2976 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2977 return ReplaceInstUsesWith(I, RHS);
2980 case Instruction::SetNE:
2982 default: assert(0 && "Unknown integer condition code!");
2983 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2984 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2985 return ReplaceInstUsesWith(I, LHS);
2986 case Instruction::SetNE: // (X != 13 | X != 15) -> true
2987 case Instruction::SetLT: // (X != 13 | X < 15) -> true
2988 return ReplaceInstUsesWith(I, ConstantBool::True);
2991 case Instruction::SetLT:
2993 default: assert(0 && "Unknown integer condition code!");
2994 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2996 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2997 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2998 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2999 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3000 return ReplaceInstUsesWith(I, RHS);
3003 case Instruction::SetGT:
3005 default: assert(0 && "Unknown integer condition code!");
3006 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3007 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3008 return ReplaceInstUsesWith(I, LHS);
3009 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3010 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3011 return ReplaceInstUsesWith(I, ConstantBool::True);
3017 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3018 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3019 const Type *SrcTy = Op0C->getOperand(0)->getType();
3020 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3021 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3022 // Only do this if the casts both really cause code to be generated.
3023 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3024 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3025 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3026 Op1C->getOperand(0),
3028 InsertNewInstBefore(NewOp, I);
3029 return new CastInst(NewOp, I.getType());
3034 return Changed ? &I : 0;
3037 // XorSelf - Implements: X ^ X --> 0
3040 XorSelf(Value *rhs) : RHS(rhs) {}
3041 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3042 Instruction *apply(BinaryOperator &Xor) const {
3048 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3049 bool Changed = SimplifyCommutative(I);
3050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3052 if (isa<UndefValue>(Op1))
3053 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3055 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3056 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3057 assert(Result == &I && "AssociativeOpt didn't work?");
3058 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3061 // See if we can simplify any instructions used by the instruction whose sole
3062 // purpose is to compute bits we don't care about.
3063 uint64_t KnownZero, KnownOne;
3064 if (!isa<PackedType>(I.getType()) &&
3065 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3066 KnownZero, KnownOne))
3069 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3070 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3071 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3072 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3073 if (RHS == ConstantBool::True && SCI->hasOneUse())
3074 return new SetCondInst(SCI->getInverseCondition(),
3075 SCI->getOperand(0), SCI->getOperand(1));
3077 // ~(c-X) == X-c-1 == X+(-c-1)
3078 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3079 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3080 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3081 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3082 ConstantInt::get(I.getType(), 1));
3083 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3086 // ~(~X & Y) --> (X | ~Y)
3087 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3088 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3089 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3091 BinaryOperator::createNot(Op0I->getOperand(1),
3092 Op0I->getOperand(1)->getName()+".not");
3093 InsertNewInstBefore(NotY, I);
3094 return BinaryOperator::createOr(Op0NotVal, NotY);
3098 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3099 if (Op0I->getOpcode() == Instruction::Add) {
3100 // ~(X-c) --> (-c-1)-X
3101 if (RHS->isAllOnesValue()) {
3102 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3103 return BinaryOperator::createSub(
3104 ConstantExpr::getSub(NegOp0CI,
3105 ConstantInt::get(I.getType(), 1)),
3106 Op0I->getOperand(0));
3108 } else if (Op0I->getOpcode() == Instruction::Or) {
3109 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3110 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3111 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3112 // Anything in both C1 and C2 is known to be zero, remove it from
3114 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3115 NewRHS = ConstantExpr::getAnd(NewRHS,
3116 ConstantExpr::getNot(CommonBits));
3117 WorkList.push_back(Op0I);
3118 I.setOperand(0, Op0I->getOperand(0));
3119 I.setOperand(1, NewRHS);
3125 // Try to fold constant and into select arguments.
3126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3127 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3129 if (isa<PHINode>(Op0))
3130 if (Instruction *NV = FoldOpIntoPhi(I))
3134 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
3136 return ReplaceInstUsesWith(I,
3137 ConstantIntegral::getAllOnesValue(I.getType()));
3139 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
3141 return ReplaceInstUsesWith(I,
3142 ConstantIntegral::getAllOnesValue(I.getType()));
3144 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3145 if (Op1I->getOpcode() == Instruction::Or) {
3146 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
3147 Op1I->swapOperands();
3149 std::swap(Op0, Op1);
3150 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
3151 I.swapOperands(); // Simplified below.
3152 std::swap(Op0, Op1);
3154 } else if (Op1I->getOpcode() == Instruction::Xor) {
3155 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3156 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3157 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3158 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3159 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3160 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3161 Op1I->swapOperands();
3162 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3163 I.swapOperands(); // Simplified below.
3164 std::swap(Op0, Op1);
3168 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3169 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3170 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3171 Op0I->swapOperands();
3172 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3173 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3174 InsertNewInstBefore(NotB, I);
3175 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3177 } else if (Op0I->getOpcode() == Instruction::Xor) {
3178 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3179 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3180 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3181 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3182 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3183 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3184 Op0I->swapOperands();
3185 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3186 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3187 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3188 InsertNewInstBefore(N, I);
3189 return BinaryOperator::createAnd(N, Op1);
3193 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3194 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3195 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3198 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3199 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3200 const Type *SrcTy = Op0C->getOperand(0)->getType();
3201 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3202 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3203 // Only do this if the casts both really cause code to be generated.
3204 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3205 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3206 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3207 Op1C->getOperand(0),
3209 InsertNewInstBefore(NewOp, I);
3210 return new CastInst(NewOp, I.getType());
3214 return Changed ? &I : 0;
3217 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3218 /// overflowed for this type.
3219 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3221 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3222 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3225 static bool isPositive(ConstantInt *C) {
3226 return cast<ConstantSInt>(C)->getValue() >= 0;
3229 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3230 /// overflowed for this type.
3231 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3233 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3235 if (In1->getType()->isUnsigned())
3236 return cast<ConstantUInt>(Result)->getValue() <
3237 cast<ConstantUInt>(In1)->getValue();
3238 if (isPositive(In1) != isPositive(In2))
3240 if (isPositive(In1))
3241 return cast<ConstantSInt>(Result)->getValue() <
3242 cast<ConstantSInt>(In1)->getValue();
3243 return cast<ConstantSInt>(Result)->getValue() >
3244 cast<ConstantSInt>(In1)->getValue();
3247 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3248 /// code necessary to compute the offset from the base pointer (without adding
3249 /// in the base pointer). Return the result as a signed integer of intptr size.
3250 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3251 TargetData &TD = IC.getTargetData();
3252 gep_type_iterator GTI = gep_type_begin(GEP);
3253 const Type *UIntPtrTy = TD.getIntPtrType();
3254 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3255 Value *Result = Constant::getNullValue(SIntPtrTy);
3257 // Build a mask for high order bits.
3258 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3260 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3261 Value *Op = GEP->getOperand(i);
3262 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3263 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3265 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3266 if (!OpC->isNullValue()) {
3267 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3268 Scale = ConstantExpr::getMul(OpC, Scale);
3269 if (Constant *RC = dyn_cast<Constant>(Result))
3270 Result = ConstantExpr::getAdd(RC, Scale);
3272 // Emit an add instruction.
3273 Result = IC.InsertNewInstBefore(
3274 BinaryOperator::createAdd(Result, Scale,
3275 GEP->getName()+".offs"), I);
3279 // Convert to correct type.
3280 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3281 Op->getName()+".c"), I);
3283 // We'll let instcombine(mul) convert this to a shl if possible.
3284 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3285 GEP->getName()+".idx"), I);
3287 // Emit an add instruction.
3288 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3289 GEP->getName()+".offs"), I);
3295 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3296 /// else. At this point we know that the GEP is on the LHS of the comparison.
3297 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3298 Instruction::BinaryOps Cond,
3300 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3302 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3303 if (isa<PointerType>(CI->getOperand(0)->getType()))
3304 RHS = CI->getOperand(0);
3306 Value *PtrBase = GEPLHS->getOperand(0);
3307 if (PtrBase == RHS) {
3308 // As an optimization, we don't actually have to compute the actual value of
3309 // OFFSET if this is a seteq or setne comparison, just return whether each
3310 // index is zero or not.
3311 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3312 Instruction *InVal = 0;
3313 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3314 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3316 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3317 if (isa<UndefValue>(C)) // undef index -> undef.
3318 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3319 if (C->isNullValue())
3321 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3322 EmitIt = false; // This is indexing into a zero sized array?
3323 } else if (isa<ConstantInt>(C))
3324 return ReplaceInstUsesWith(I, // No comparison is needed here.
3325 ConstantBool::get(Cond == Instruction::SetNE));
3330 new SetCondInst(Cond, GEPLHS->getOperand(i),
3331 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3335 InVal = InsertNewInstBefore(InVal, I);
3336 InsertNewInstBefore(Comp, I);
3337 if (Cond == Instruction::SetNE) // True if any are unequal
3338 InVal = BinaryOperator::createOr(InVal, Comp);
3339 else // True if all are equal
3340 InVal = BinaryOperator::createAnd(InVal, Comp);
3348 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3349 ConstantBool::get(Cond == Instruction::SetEQ));
3352 // Only lower this if the setcc is the only user of the GEP or if we expect
3353 // the result to fold to a constant!
3354 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3355 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3356 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3357 return new SetCondInst(Cond, Offset,
3358 Constant::getNullValue(Offset->getType()));
3360 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3361 // If the base pointers are different, but the indices are the same, just
3362 // compare the base pointer.
3363 if (PtrBase != GEPRHS->getOperand(0)) {
3364 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3365 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3366 GEPRHS->getOperand(0)->getType();
3368 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3369 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3370 IndicesTheSame = false;
3374 // If all indices are the same, just compare the base pointers.
3376 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3377 GEPRHS->getOperand(0));
3379 // Otherwise, the base pointers are different and the indices are
3380 // different, bail out.
3384 // If one of the GEPs has all zero indices, recurse.
3385 bool AllZeros = true;
3386 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3387 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3388 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3393 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3394 SetCondInst::getSwappedCondition(Cond), I);
3396 // If the other GEP has all zero indices, recurse.
3398 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3399 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3400 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3405 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3407 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3408 // If the GEPs only differ by one index, compare it.
3409 unsigned NumDifferences = 0; // Keep track of # differences.
3410 unsigned DiffOperand = 0; // The operand that differs.
3411 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3412 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3413 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3414 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3415 // Irreconcilable differences.
3419 if (NumDifferences++) break;
3424 if (NumDifferences == 0) // SAME GEP?
3425 return ReplaceInstUsesWith(I, // No comparison is needed here.
3426 ConstantBool::get(Cond == Instruction::SetEQ));
3427 else if (NumDifferences == 1) {
3428 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3429 Value *RHSV = GEPRHS->getOperand(DiffOperand);
3431 // Convert the operands to signed values to make sure to perform a
3432 // signed comparison.
3433 const Type *NewTy = LHSV->getType()->getSignedVersion();
3434 if (LHSV->getType() != NewTy)
3435 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3436 LHSV->getName()), I);
3437 if (RHSV->getType() != NewTy)
3438 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3439 RHSV->getName()), I);
3440 return new SetCondInst(Cond, LHSV, RHSV);
3444 // Only lower this if the setcc is the only user of the GEP or if we expect
3445 // the result to fold to a constant!
3446 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3447 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3448 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3449 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3450 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3451 return new SetCondInst(Cond, L, R);
3458 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3459 bool Changed = SimplifyCommutative(I);
3460 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3461 const Type *Ty = Op0->getType();
3465 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3467 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3468 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3470 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3471 // addresses never equal each other! We already know that Op0 != Op1.
3472 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3473 isa<ConstantPointerNull>(Op0)) &&
3474 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3475 isa<ConstantPointerNull>(Op1)))
3476 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3478 // setcc's with boolean values can always be turned into bitwise operations
3479 if (Ty == Type::BoolTy) {
3480 switch (I.getOpcode()) {
3481 default: assert(0 && "Invalid setcc instruction!");
3482 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
3483 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3484 InsertNewInstBefore(Xor, I);
3485 return BinaryOperator::createNot(Xor);
3487 case Instruction::SetNE:
3488 return BinaryOperator::createXor(Op0, Op1);
3490 case Instruction::SetGT:
3491 std::swap(Op0, Op1); // Change setgt -> setlt
3493 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3494 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3495 InsertNewInstBefore(Not, I);
3496 return BinaryOperator::createAnd(Not, Op1);
3498 case Instruction::SetGE:
3499 std::swap(Op0, Op1); // Change setge -> setle
3501 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3502 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3503 InsertNewInstBefore(Not, I);
3504 return BinaryOperator::createOr(Not, Op1);
3509 // See if we are doing a comparison between a constant and an instruction that
3510 // can be folded into the comparison.
3511 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3512 // Check to see if we are comparing against the minimum or maximum value...
3513 if (CI->isMinValue()) {
3514 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3515 return ReplaceInstUsesWith(I, ConstantBool::False);
3516 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3517 return ReplaceInstUsesWith(I, ConstantBool::True);
3518 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3519 return BinaryOperator::createSetEQ(Op0, Op1);
3520 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3521 return BinaryOperator::createSetNE(Op0, Op1);
3523 } else if (CI->isMaxValue()) {
3524 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3525 return ReplaceInstUsesWith(I, ConstantBool::False);
3526 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3527 return ReplaceInstUsesWith(I, ConstantBool::True);
3528 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3529 return BinaryOperator::createSetEQ(Op0, Op1);
3530 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3531 return BinaryOperator::createSetNE(Op0, Op1);
3533 // Comparing against a value really close to min or max?
3534 } else if (isMinValuePlusOne(CI)) {
3535 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3536 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3537 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3538 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3540 } else if (isMaxValueMinusOne(CI)) {
3541 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3542 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3543 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3544 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3547 // If we still have a setle or setge instruction, turn it into the
3548 // appropriate setlt or setgt instruction. Since the border cases have
3549 // already been handled above, this requires little checking.
3551 if (I.getOpcode() == Instruction::SetLE)
3552 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3553 if (I.getOpcode() == Instruction::SetGE)
3554 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3557 // See if we can fold the comparison based on bits known to be zero or one
3559 uint64_t KnownZero, KnownOne;
3560 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3561 KnownZero, KnownOne, 0))
3564 // Given the known and unknown bits, compute a range that the LHS could be
3566 if (KnownOne | KnownZero) {
3567 if (Ty->isUnsigned()) { // Unsigned comparison.
3569 uint64_t RHSVal = CI->getZExtValue();
3570 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3572 switch (I.getOpcode()) { // LE/GE have been folded already.
3573 default: assert(0 && "Unknown setcc opcode!");
3574 case Instruction::SetEQ:
3575 if (Max < RHSVal || Min > RHSVal)
3576 return ReplaceInstUsesWith(I, ConstantBool::False);
3578 case Instruction::SetNE:
3579 if (Max < RHSVal || Min > RHSVal)
3580 return ReplaceInstUsesWith(I, ConstantBool::True);
3582 case Instruction::SetLT:
3583 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3584 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3586 case Instruction::SetGT:
3587 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3588 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3591 } else { // Signed comparison.
3593 int64_t RHSVal = CI->getSExtValue();
3594 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3596 switch (I.getOpcode()) { // LE/GE have been folded already.
3597 default: assert(0 && "Unknown setcc opcode!");
3598 case Instruction::SetEQ:
3599 if (Max < RHSVal || Min > RHSVal)
3600 return ReplaceInstUsesWith(I, ConstantBool::False);
3602 case Instruction::SetNE:
3603 if (Max < RHSVal || Min > RHSVal)
3604 return ReplaceInstUsesWith(I, ConstantBool::True);
3606 case Instruction::SetLT:
3607 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3608 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3610 case Instruction::SetGT:
3611 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3612 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3619 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3620 switch (LHSI->getOpcode()) {
3621 case Instruction::And:
3622 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3623 LHSI->getOperand(0)->hasOneUse()) {
3624 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3625 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3626 // happens a LOT in code produced by the C front-end, for bitfield
3628 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
3629 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3631 // Check to see if there is a noop-cast between the shift and the and.
3633 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3634 if (CI->getOperand(0)->getType()->isIntegral() &&
3635 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3636 CI->getType()->getPrimitiveSizeInBits())
3637 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3640 ConstantUInt *ShAmt;
3641 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
3642 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3643 const Type *AndTy = AndCST->getType(); // Type of the and.
3645 // We can fold this as long as we can't shift unknown bits
3646 // into the mask. This can only happen with signed shift
3647 // rights, as they sign-extend.
3649 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
3652 // To test for the bad case of the signed shr, see if any
3653 // of the bits shifted in could be tested after the mask.
3654 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3655 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3657 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
3659 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3661 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3667 if (Shift->getOpcode() == Instruction::Shl)
3668 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3670 NewCst = ConstantExpr::getShl(CI, ShAmt);
3672 // Check to see if we are shifting out any of the bits being
3674 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3675 // If we shifted bits out, the fold is not going to work out.
3676 // As a special case, check to see if this means that the
3677 // result is always true or false now.
3678 if (I.getOpcode() == Instruction::SetEQ)
3679 return ReplaceInstUsesWith(I, ConstantBool::False);
3680 if (I.getOpcode() == Instruction::SetNE)
3681 return ReplaceInstUsesWith(I, ConstantBool::True);
3683 I.setOperand(1, NewCst);
3684 Constant *NewAndCST;
3685 if (Shift->getOpcode() == Instruction::Shl)
3686 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3688 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3689 LHSI->setOperand(1, NewAndCST);
3691 LHSI->setOperand(0, Shift->getOperand(0));
3693 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3695 LHSI->setOperand(0, NewCast);
3697 WorkList.push_back(Shift); // Shift is dead.
3698 AddUsesToWorkList(I);
3706 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3707 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3708 switch (I.getOpcode()) {
3710 case Instruction::SetEQ:
3711 case Instruction::SetNE: {
3712 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3714 // Check that the shift amount is in range. If not, don't perform
3715 // undefined shifts. When the shift is visited it will be
3717 if (ShAmt->getValue() >= TypeBits)
3720 // If we are comparing against bits always shifted out, the
3721 // comparison cannot succeed.
3723 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3724 if (Comp != CI) {// Comparing against a bit that we know is zero.
3725 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3726 Constant *Cst = ConstantBool::get(IsSetNE);
3727 return ReplaceInstUsesWith(I, Cst);
3730 if (LHSI->hasOneUse()) {
3731 // Otherwise strength reduce the shift into an and.
3732 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3733 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3736 if (CI->getType()->isUnsigned()) {
3737 Mask = ConstantUInt::get(CI->getType(), Val);
3738 } else if (ShAmtVal != 0) {
3739 Mask = ConstantSInt::get(CI->getType(), Val);
3741 Mask = ConstantInt::getAllOnesValue(CI->getType());
3745 BinaryOperator::createAnd(LHSI->getOperand(0),
3746 Mask, LHSI->getName()+".mask");
3747 Value *And = InsertNewInstBefore(AndI, I);
3748 return new SetCondInst(I.getOpcode(), And,
3749 ConstantExpr::getUShr(CI, ShAmt));
3756 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
3757 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3758 switch (I.getOpcode()) {
3760 case Instruction::SetEQ:
3761 case Instruction::SetNE: {
3763 // Check that the shift amount is in range. If not, don't perform
3764 // undefined shifts. When the shift is visited it will be
3766 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3767 if (ShAmt->getValue() >= TypeBits)
3770 // If we are comparing against bits always shifted out, the
3771 // comparison cannot succeed.
3773 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
3775 if (Comp != CI) {// Comparing against a bit that we know is zero.
3776 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3777 Constant *Cst = ConstantBool::get(IsSetNE);
3778 return ReplaceInstUsesWith(I, Cst);
3781 if (LHSI->hasOneUse() || CI->isNullValue()) {
3782 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3784 // Otherwise strength reduce the shift into an and.
3785 uint64_t Val = ~0ULL; // All ones.
3786 Val <<= ShAmtVal; // Shift over to the right spot.
3789 if (CI->getType()->isUnsigned()) {
3790 Val &= ~0ULL >> (64-TypeBits);
3791 Mask = ConstantUInt::get(CI->getType(), Val);
3793 Mask = ConstantSInt::get(CI->getType(), Val);
3797 BinaryOperator::createAnd(LHSI->getOperand(0),
3798 Mask, LHSI->getName()+".mask");
3799 Value *And = InsertNewInstBefore(AndI, I);
3800 return new SetCondInst(I.getOpcode(), And,
3801 ConstantExpr::getShl(CI, ShAmt));
3809 case Instruction::Div:
3810 // Fold: (div X, C1) op C2 -> range check
3811 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3812 // Fold this div into the comparison, producing a range check.
3813 // Determine, based on the divide type, what the range is being
3814 // checked. If there is an overflow on the low or high side, remember
3815 // it, otherwise compute the range [low, hi) bounding the new value.
3816 bool LoOverflow = false, HiOverflow = 0;
3817 ConstantInt *LoBound = 0, *HiBound = 0;
3820 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3822 Instruction::BinaryOps Opcode = I.getOpcode();
3824 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3825 } else if (LHSI->getType()->isUnsigned()) { // udiv
3827 LoOverflow = ProdOV;
3828 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3829 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3830 if (CI->isNullValue()) { // (X / pos) op 0
3832 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3834 } else if (isPositive(CI)) { // (X / pos) op pos
3836 LoOverflow = ProdOV;
3837 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3838 } else { // (X / pos) op neg
3839 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3840 LoOverflow = AddWithOverflow(LoBound, Prod,
3841 cast<ConstantInt>(DivRHSH));
3843 HiOverflow = ProdOV;
3845 } else { // Divisor is < 0.
3846 if (CI->isNullValue()) { // (X / neg) op 0
3847 LoBound = AddOne(DivRHS);
3848 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
3849 if (HiBound == DivRHS)
3850 LoBound = 0; // - INTMIN = INTMIN
3851 } else if (isPositive(CI)) { // (X / neg) op pos
3852 HiOverflow = LoOverflow = ProdOV;
3854 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3855 HiBound = AddOne(Prod);
3856 } else { // (X / neg) op neg
3858 LoOverflow = HiOverflow = ProdOV;
3859 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3862 // Dividing by a negate swaps the condition.
3863 Opcode = SetCondInst::getSwappedCondition(Opcode);
3867 Value *X = LHSI->getOperand(0);
3869 default: assert(0 && "Unhandled setcc opcode!");
3870 case Instruction::SetEQ:
3871 if (LoOverflow && HiOverflow)
3872 return ReplaceInstUsesWith(I, ConstantBool::False);
3873 else if (HiOverflow)
3874 return new SetCondInst(Instruction::SetGE, X, LoBound);
3875 else if (LoOverflow)
3876 return new SetCondInst(Instruction::SetLT, X, HiBound);
3878 return InsertRangeTest(X, LoBound, HiBound, true, I);
3879 case Instruction::SetNE:
3880 if (LoOverflow && HiOverflow)
3881 return ReplaceInstUsesWith(I, ConstantBool::True);
3882 else if (HiOverflow)
3883 return new SetCondInst(Instruction::SetLT, X, LoBound);
3884 else if (LoOverflow)
3885 return new SetCondInst(Instruction::SetGE, X, HiBound);
3887 return InsertRangeTest(X, LoBound, HiBound, false, I);
3888 case Instruction::SetLT:
3890 return ReplaceInstUsesWith(I, ConstantBool::False);
3891 return new SetCondInst(Instruction::SetLT, X, LoBound);
3892 case Instruction::SetGT:
3894 return ReplaceInstUsesWith(I, ConstantBool::False);
3895 return new SetCondInst(Instruction::SetGE, X, HiBound);
3902 // Simplify seteq and setne instructions...
3903 if (I.getOpcode() == Instruction::SetEQ ||
3904 I.getOpcode() == Instruction::SetNE) {
3905 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3907 // If the first operand is (and|or|xor) with a constant, and the second
3908 // operand is a constant, simplify a bit.
3909 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3910 switch (BO->getOpcode()) {
3911 case Instruction::Rem:
3912 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3913 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3915 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3916 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3917 if (isPowerOf2_64(V)) {
3918 unsigned L2 = Log2_64(V);
3919 const Type *UTy = BO->getType()->getUnsignedVersion();
3920 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3922 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3923 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3924 RHSCst, BO->getName()), I);
3925 return BinaryOperator::create(I.getOpcode(), NewRem,
3926 Constant::getNullValue(UTy));
3931 case Instruction::Add:
3932 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3933 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3934 if (BO->hasOneUse())
3935 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3936 ConstantExpr::getSub(CI, BOp1C));
3937 } else if (CI->isNullValue()) {
3938 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3939 // efficiently invertible, or if the add has just this one use.
3940 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3942 if (Value *NegVal = dyn_castNegVal(BOp1))
3943 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3944 else if (Value *NegVal = dyn_castNegVal(BOp0))
3945 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3946 else if (BO->hasOneUse()) {
3947 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3949 InsertNewInstBefore(Neg, I);
3950 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3954 case Instruction::Xor:
3955 // For the xor case, we can xor two constants together, eliminating
3956 // the explicit xor.
3957 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3958 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3959 ConstantExpr::getXor(CI, BOC));
3962 case Instruction::Sub:
3963 // Replace (([sub|xor] A, B) != 0) with (A != B)
3964 if (CI->isNullValue())
3965 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3969 case Instruction::Or:
3970 // If bits are being or'd in that are not present in the constant we
3971 // are comparing against, then the comparison could never succeed!
3972 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3973 Constant *NotCI = ConstantExpr::getNot(CI);
3974 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3975 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3979 case Instruction::And:
3980 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3981 // If bits are being compared against that are and'd out, then the
3982 // comparison can never succeed!
3983 if (!ConstantExpr::getAnd(CI,
3984 ConstantExpr::getNot(BOC))->isNullValue())
3985 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3987 // If we have ((X & C) == C), turn it into ((X & C) != 0).
3988 if (CI == BOC && isOneBitSet(CI))
3989 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3990 Instruction::SetNE, Op0,
3991 Constant::getNullValue(CI->getType()));
3993 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3994 // to be a signed value as appropriate.
3995 if (isSignBit(BOC)) {
3996 Value *X = BO->getOperand(0);
3997 // If 'X' is not signed, insert a cast now...
3998 if (!BOC->getType()->isSigned()) {
3999 const Type *DestTy = BOC->getType()->getSignedVersion();
4000 X = InsertCastBefore(X, DestTy, I);
4002 return new SetCondInst(isSetNE ? Instruction::SetLT :
4003 Instruction::SetGE, X,
4004 Constant::getNullValue(X->getType()));
4007 // ((X & ~7) == 0) --> X < 8
4008 if (CI->isNullValue() && isHighOnes(BOC)) {
4009 Value *X = BO->getOperand(0);
4010 Constant *NegX = ConstantExpr::getNeg(BOC);
4012 // If 'X' is signed, insert a cast now.
4013 if (NegX->getType()->isSigned()) {
4014 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4015 X = InsertCastBefore(X, DestTy, I);
4016 NegX = ConstantExpr::getCast(NegX, DestTy);
4019 return new SetCondInst(isSetNE ? Instruction::SetGE :
4020 Instruction::SetLT, X, NegX);
4027 } else { // Not a SetEQ/SetNE
4028 // If the LHS is a cast from an integral value of the same size,
4029 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4030 Value *CastOp = Cast->getOperand(0);
4031 const Type *SrcTy = CastOp->getType();
4032 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4033 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4034 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4035 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4036 "Source and destination signednesses should differ!");
4037 if (Cast->getType()->isSigned()) {
4038 // If this is a signed comparison, check for comparisons in the
4039 // vicinity of zero.
4040 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4042 return BinaryOperator::createSetGT(CastOp,
4043 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4044 else if (I.getOpcode() == Instruction::SetGT &&
4045 cast<ConstantSInt>(CI)->getValue() == -1)
4046 // X > -1 => x < 128
4047 return BinaryOperator::createSetLT(CastOp,
4048 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4050 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4051 if (I.getOpcode() == Instruction::SetLT &&
4052 CUI->getValue() == 1ULL << (SrcTySize-1))
4053 // X < 128 => X > -1
4054 return BinaryOperator::createSetGT(CastOp,
4055 ConstantSInt::get(SrcTy, -1));
4056 else if (I.getOpcode() == Instruction::SetGT &&
4057 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
4059 return BinaryOperator::createSetLT(CastOp,
4060 Constant::getNullValue(SrcTy));
4067 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4068 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4069 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4070 switch (LHSI->getOpcode()) {
4071 case Instruction::GetElementPtr:
4072 if (RHSC->isNullValue()) {
4073 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4074 bool isAllZeros = true;
4075 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4076 if (!isa<Constant>(LHSI->getOperand(i)) ||
4077 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4082 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4083 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4087 case Instruction::PHI:
4088 if (Instruction *NV = FoldOpIntoPhi(I))
4091 case Instruction::Select:
4092 // If either operand of the select is a constant, we can fold the
4093 // comparison into the select arms, which will cause one to be
4094 // constant folded and the select turned into a bitwise or.
4095 Value *Op1 = 0, *Op2 = 0;
4096 if (LHSI->hasOneUse()) {
4097 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4098 // Fold the known value into the constant operand.
4099 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4100 // Insert a new SetCC of the other select operand.
4101 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4102 LHSI->getOperand(2), RHSC,
4104 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4105 // Fold the known value into the constant operand.
4106 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4107 // Insert a new SetCC of the other select operand.
4108 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4109 LHSI->getOperand(1), RHSC,
4115 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4120 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4121 if (User *GEP = dyn_castGetElementPtr(Op0))
4122 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4124 if (User *GEP = dyn_castGetElementPtr(Op1))
4125 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4126 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4129 // Test to see if the operands of the setcc are casted versions of other
4130 // values. If the cast can be stripped off both arguments, we do so now.
4131 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4132 Value *CastOp0 = CI->getOperand(0);
4133 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
4134 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
4135 (I.getOpcode() == Instruction::SetEQ ||
4136 I.getOpcode() == Instruction::SetNE)) {
4137 // We keep moving the cast from the left operand over to the right
4138 // operand, where it can often be eliminated completely.
4141 // If operand #1 is a cast instruction, see if we can eliminate it as
4143 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4144 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
4146 Op1 = CI2->getOperand(0);
4148 // If Op1 is a constant, we can fold the cast into the constant.
4149 if (Op1->getType() != Op0->getType())
4150 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4151 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4153 // Otherwise, cast the RHS right before the setcc
4154 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4155 InsertNewInstBefore(cast<Instruction>(Op1), I);
4157 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4160 // Handle the special case of: setcc (cast bool to X), <cst>
4161 // This comes up when you have code like
4164 // For generality, we handle any zero-extension of any operand comparison
4165 // with a constant or another cast from the same type.
4166 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4167 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4171 if (I.getOpcode() == Instruction::SetNE ||
4172 I.getOpcode() == Instruction::SetEQ) {
4174 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4175 (A == Op1 || B == Op1)) {
4176 // (A^B) == A -> B == 0
4177 Value *OtherVal = A == Op1 ? B : A;
4178 return BinaryOperator::create(I.getOpcode(), OtherVal,
4179 Constant::getNullValue(A->getType()));
4180 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4181 (A == Op0 || B == Op0)) {
4182 // A == (A^B) -> B == 0
4183 Value *OtherVal = A == Op0 ? B : A;
4184 return BinaryOperator::create(I.getOpcode(), OtherVal,
4185 Constant::getNullValue(A->getType()));
4186 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4187 // (A-B) == A -> B == 0
4188 return BinaryOperator::create(I.getOpcode(), B,
4189 Constant::getNullValue(B->getType()));
4190 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4191 // A == (A-B) -> B == 0
4192 return BinaryOperator::create(I.getOpcode(), B,
4193 Constant::getNullValue(B->getType()));
4196 return Changed ? &I : 0;
4199 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4200 // We only handle extending casts so far.
4202 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4203 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4204 const Type *SrcTy = LHSCIOp->getType();
4205 const Type *DestTy = SCI.getOperand(0)->getType();
4208 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
4211 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4212 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4213 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4215 // Is this a sign or zero extension?
4216 bool isSignSrc = SrcTy->isSigned();
4217 bool isSignDest = DestTy->isSigned();
4219 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4220 // Not an extension from the same type?
4221 RHSCIOp = CI->getOperand(0);
4222 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4223 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4224 // Compute the constant that would happen if we truncated to SrcTy then
4225 // reextended to DestTy.
4226 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4228 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4231 // If the value cannot be represented in the shorter type, we cannot emit
4232 // a simple comparison.
4233 if (SCI.getOpcode() == Instruction::SetEQ)
4234 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4235 if (SCI.getOpcode() == Instruction::SetNE)
4236 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4238 // Evaluate the comparison for LT.
4240 if (DestTy->isSigned()) {
4241 // We're performing a signed comparison.
4243 // Signed extend and signed comparison.
4244 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4245 Result = ConstantBool::False;
4247 Result = ConstantBool::True; // X < (large) --> true
4249 // Unsigned extend and signed comparison.
4250 if (cast<ConstantSInt>(CI)->getValue() < 0)
4251 Result = ConstantBool::False;
4253 Result = ConstantBool::True;
4256 // We're performing an unsigned comparison.
4258 // Unsigned extend & compare -> always true.
4259 Result = ConstantBool::True;
4261 // We're performing an unsigned comp with a sign extended value.
4262 // This is true if the input is >= 0. [aka >s -1]
4263 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4264 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4265 NegOne, SCI.getName()), SCI);
4269 // Finally, return the value computed.
4270 if (SCI.getOpcode() == Instruction::SetLT) {
4271 return ReplaceInstUsesWith(SCI, Result);
4273 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4274 if (Constant *CI = dyn_cast<Constant>(Result))
4275 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4277 return BinaryOperator::createNot(Result);
4284 // Okay, just insert a compare of the reduced operands now!
4285 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4288 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4289 assert(I.getOperand(1)->getType() == Type::UByteTy);
4290 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4291 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4293 // shl X, 0 == X and shr X, 0 == X
4294 // shl 0, X == 0 and shr 0, X == 0
4295 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4296 Op0 == Constant::getNullValue(Op0->getType()))
4297 return ReplaceInstUsesWith(I, Op0);
4299 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4300 if (!isLeftShift && I.getType()->isSigned())
4301 return ReplaceInstUsesWith(I, Op0);
4302 else // undef << X -> 0 AND undef >>u X -> 0
4303 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4305 if (isa<UndefValue>(Op1)) {
4306 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4307 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4309 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4312 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4314 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4315 if (CSI->isAllOnesValue())
4316 return ReplaceInstUsesWith(I, CSI);
4318 // Try to fold constant and into select arguments.
4319 if (isa<Constant>(Op0))
4320 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4321 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4324 // See if we can turn a signed shr into an unsigned shr.
4325 if (!isLeftShift && I.getType()->isSigned()) {
4326 if (MaskedValueIsZero(Op0,
4327 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4328 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4329 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4331 return new CastInst(V, I.getType());
4335 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4336 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4341 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4343 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4344 bool isSignedShift = Op0->getType()->isSigned();
4345 bool isUnsignedShift = !isSignedShift;
4347 // See if we can simplify any instructions used by the instruction whose sole
4348 // purpose is to compute bits we don't care about.
4349 uint64_t KnownZero, KnownOne;
4350 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4351 KnownZero, KnownOne))
4354 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4355 // of a signed value.
4357 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4358 if (Op1->getValue() >= TypeBits) {
4359 if (isUnsignedShift || isLeftShift)
4360 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4362 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4367 // ((X*C1) << C2) == (X * (C1 << C2))
4368 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4369 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4370 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4371 return BinaryOperator::createMul(BO->getOperand(0),
4372 ConstantExpr::getShl(BOOp, Op1));
4374 // Try to fold constant and into select arguments.
4375 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4376 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4378 if (isa<PHINode>(Op0))
4379 if (Instruction *NV = FoldOpIntoPhi(I))
4382 if (Op0->hasOneUse()) {
4383 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4384 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4387 switch (Op0BO->getOpcode()) {
4389 case Instruction::Add:
4390 case Instruction::And:
4391 case Instruction::Or:
4392 case Instruction::Xor:
4393 // These operators commute.
4394 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
4395 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4396 match(Op0BO->getOperand(1),
4397 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4398 Instruction *YS = new ShiftInst(Instruction::Shl,
4399 Op0BO->getOperand(0), Op1,
4401 InsertNewInstBefore(YS, I); // (Y << C)
4403 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4404 Op0BO->getOperand(1)->getName());
4405 InsertNewInstBefore(X, I); // (X + (Y << C))
4406 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4407 C2 = ConstantExpr::getShl(C2, Op1);
4408 return BinaryOperator::createAnd(X, C2);
4411 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4412 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4413 match(Op0BO->getOperand(1),
4414 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4415 m_ConstantInt(CC))) && V2 == Op1 &&
4416 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
4417 Instruction *YS = new ShiftInst(Instruction::Shl,
4418 Op0BO->getOperand(0), Op1,
4420 InsertNewInstBefore(YS, I); // (Y << C)
4422 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4423 V1->getName()+".mask");
4424 InsertNewInstBefore(XM, I); // X & (CC << C)
4426 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4430 case Instruction::Sub:
4431 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4432 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4433 match(Op0BO->getOperand(0),
4434 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4435 Instruction *YS = new ShiftInst(Instruction::Shl,
4436 Op0BO->getOperand(1), Op1,
4438 InsertNewInstBefore(YS, I); // (Y << C)
4440 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4441 Op0BO->getOperand(0)->getName());
4442 InsertNewInstBefore(X, I); // (X + (Y << C))
4443 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4444 C2 = ConstantExpr::getShl(C2, Op1);
4445 return BinaryOperator::createAnd(X, C2);
4448 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4449 match(Op0BO->getOperand(0),
4450 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4451 m_ConstantInt(CC))) && V2 == Op1 &&
4452 cast<BinaryOperator>(Op0BO->getOperand(0))
4453 ->getOperand(0)->hasOneUse()) {
4454 Instruction *YS = new ShiftInst(Instruction::Shl,
4455 Op0BO->getOperand(1), Op1,
4457 InsertNewInstBefore(YS, I); // (Y << C)
4459 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4460 V1->getName()+".mask");
4461 InsertNewInstBefore(XM, I); // X & (CC << C)
4463 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4470 // If the operand is an bitwise operator with a constant RHS, and the
4471 // shift is the only use, we can pull it out of the shift.
4472 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4473 bool isValid = true; // Valid only for And, Or, Xor
4474 bool highBitSet = false; // Transform if high bit of constant set?
4476 switch (Op0BO->getOpcode()) {
4477 default: isValid = false; break; // Do not perform transform!
4478 case Instruction::Add:
4479 isValid = isLeftShift;
4481 case Instruction::Or:
4482 case Instruction::Xor:
4485 case Instruction::And:
4490 // If this is a signed shift right, and the high bit is modified
4491 // by the logical operation, do not perform the transformation.
4492 // The highBitSet boolean indicates the value of the high bit of
4493 // the constant which would cause it to be modified for this
4496 if (isValid && !isLeftShift && isSignedShift) {
4497 uint64_t Val = Op0C->getRawValue();
4498 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4502 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4504 Instruction *NewShift =
4505 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4508 InsertNewInstBefore(NewShift, I);
4510 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4517 // Find out if this is a shift of a shift by a constant.
4518 ShiftInst *ShiftOp = 0;
4519 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
4521 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4522 // If this is a noop-integer case of a shift instruction, use the shift.
4523 if (CI->getOperand(0)->getType()->isInteger() &&
4524 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4525 CI->getType()->getPrimitiveSizeInBits() &&
4526 isa<ShiftInst>(CI->getOperand(0))) {
4527 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4531 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4532 // Find the operands and properties of the input shift. Note that the
4533 // signedness of the input shift may differ from the current shift if there
4534 // is a noop cast between the two.
4535 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4536 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
4537 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
4539 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4541 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4542 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4544 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4545 if (isLeftShift == isShiftOfLeftShift) {
4546 // Do not fold these shifts if the first one is signed and the second one
4547 // is unsigned and this is a right shift. Further, don't do any folding
4549 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4552 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4553 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4554 Amt = Op0->getType()->getPrimitiveSizeInBits();
4556 Value *Op = ShiftOp->getOperand(0);
4557 if (isShiftOfSignedShift != isSignedShift)
4558 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4559 return new ShiftInst(I.getOpcode(), Op,
4560 ConstantUInt::get(Type::UByteTy, Amt));
4563 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4564 // signed types, we can only support the (A >> c1) << c2 configuration,
4565 // because it can not turn an arbitrary bit of A into a sign bit.
4566 if (isUnsignedShift || isLeftShift) {
4567 // Calculate bitmask for what gets shifted off the edge.
4568 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4570 C = ConstantExpr::getShl(C, ShiftAmt1C);
4572 C = ConstantExpr::getUShr(C, ShiftAmt1C);
4574 Value *Op = ShiftOp->getOperand(0);
4575 if (isShiftOfSignedShift != isSignedShift)
4576 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4579 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4580 InsertNewInstBefore(Mask, I);
4582 // Figure out what flavor of shift we should use...
4583 if (ShiftAmt1 == ShiftAmt2) {
4584 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
4585 } else if (ShiftAmt1 < ShiftAmt2) {
4586 return new ShiftInst(I.getOpcode(), Mask,
4587 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
4588 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4589 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4590 // Make sure to emit an unsigned shift right, not a signed one.
4591 Mask = InsertNewInstBefore(new CastInst(Mask,
4592 Mask->getType()->getUnsignedVersion(),
4594 Mask = new ShiftInst(Instruction::Shr, Mask,
4595 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4596 InsertNewInstBefore(Mask, I);
4597 return new CastInst(Mask, I.getType());
4599 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4600 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4603 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4604 Op = InsertNewInstBefore(new CastInst(Mask,
4605 I.getType()->getSignedVersion(),
4606 Mask->getName()), I);
4607 Instruction *Shift =
4608 new ShiftInst(ShiftOp->getOpcode(), Op,
4609 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4610 InsertNewInstBefore(Shift, I);
4612 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4613 C = ConstantExpr::getShl(C, Op1);
4614 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4615 InsertNewInstBefore(Mask, I);
4616 return new CastInst(Mask, I.getType());
4619 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
4620 // this case, C1 == C2 and C1 is 8, 16, or 32.
4621 if (ShiftAmt1 == ShiftAmt2) {
4622 const Type *SExtType = 0;
4623 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
4624 case 8 : SExtType = Type::SByteTy; break;
4625 case 16: SExtType = Type::ShortTy; break;
4626 case 32: SExtType = Type::IntTy; break;
4630 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4632 InsertNewInstBefore(NewTrunc, I);
4633 return new CastInst(NewTrunc, I.getType());
4642 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4643 /// expression. If so, decompose it, returning some value X, such that Val is
4646 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4648 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4649 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4650 Offset = CI->getValue();
4652 return ConstantUInt::get(Type::UIntTy, 0);
4653 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4654 if (I->getNumOperands() == 2) {
4655 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4656 if (I->getOpcode() == Instruction::Shl) {
4657 // This is a value scaled by '1 << the shift amt'.
4658 Scale = 1U << CUI->getValue();
4660 return I->getOperand(0);
4661 } else if (I->getOpcode() == Instruction::Mul) {
4662 // This value is scaled by 'CUI'.
4663 Scale = CUI->getValue();
4665 return I->getOperand(0);
4666 } else if (I->getOpcode() == Instruction::Add) {
4667 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4670 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4672 Offset += CUI->getValue();
4673 if (SubScale > 1 && (Offset % SubScale == 0)) {
4682 // Otherwise, we can't look past this.
4689 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4690 /// try to eliminate the cast by moving the type information into the alloc.
4691 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4692 AllocationInst &AI) {
4693 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
4694 if (!PTy) return 0; // Not casting the allocation to a pointer type.
4696 // Remove any uses of AI that are dead.
4697 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4698 std::vector<Instruction*> DeadUsers;
4699 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4700 Instruction *User = cast<Instruction>(*UI++);
4701 if (isInstructionTriviallyDead(User)) {
4702 while (UI != E && *UI == User)
4703 ++UI; // If this instruction uses AI more than once, don't break UI.
4705 // Add operands to the worklist.
4706 AddUsesToWorkList(*User);
4708 DEBUG(std::cerr << "IC: DCE: " << *User);
4710 User->eraseFromParent();
4711 removeFromWorkList(User);
4715 // Get the type really allocated and the type casted to.
4716 const Type *AllocElTy = AI.getAllocatedType();
4717 const Type *CastElTy = PTy->getElementType();
4718 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4720 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4721 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4722 if (CastElTyAlign < AllocElTyAlign) return 0;
4724 // If the allocation has multiple uses, only promote it if we are strictly
4725 // increasing the alignment of the resultant allocation. If we keep it the
4726 // same, we open the door to infinite loops of various kinds.
4727 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4729 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4730 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4731 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4733 // See if we can satisfy the modulus by pulling a scale out of the array
4735 unsigned ArraySizeScale, ArrayOffset;
4736 Value *NumElements = // See if the array size is a decomposable linear expr.
4737 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4739 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4741 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4742 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
4744 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4749 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4750 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4751 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4752 else if (Scale != 1) {
4753 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4754 Amt = InsertNewInstBefore(Tmp, AI);
4758 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4759 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4760 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4761 Amt = InsertNewInstBefore(Tmp, AI);
4764 std::string Name = AI.getName(); AI.setName("");
4765 AllocationInst *New;
4766 if (isa<MallocInst>(AI))
4767 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4769 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4770 InsertNewInstBefore(New, AI);
4772 // If the allocation has multiple uses, insert a cast and change all things
4773 // that used it to use the new cast. This will also hack on CI, but it will
4775 if (!AI.hasOneUse()) {
4776 AddUsesToWorkList(AI);
4777 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4778 InsertNewInstBefore(NewCast, AI);
4779 AI.replaceAllUsesWith(NewCast);
4781 return ReplaceInstUsesWith(CI, New);
4784 /// CanEvaluateInDifferentType - Return true if we can take the specified value
4785 /// and return it without inserting any new casts. This is used by code that
4786 /// tries to decide whether promoting or shrinking integer operations to wider
4787 /// or smaller types will allow us to eliminate a truncate or extend.
4788 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
4789 int &NumCastsRemoved) {
4790 if (isa<Constant>(V)) return true;
4792 Instruction *I = dyn_cast<Instruction>(V);
4793 if (!I || !I->hasOneUse()) return false;
4795 switch (I->getOpcode()) {
4796 case Instruction::And:
4797 case Instruction::Or:
4798 case Instruction::Xor:
4799 // These operators can all arbitrarily be extended or truncated.
4800 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
4801 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
4802 case Instruction::Cast:
4803 // If this is a cast from the destination type, we can trivially eliminate
4804 // it, and this will remove a cast overall.
4805 if (I->getOperand(0)->getType() == Ty) {
4809 // TODO: Can handle more cases here.
4816 /// EvaluateInDifferentType - Given an expression that
4817 /// CanEvaluateInDifferentType returns true for, actually insert the code to
4818 /// evaluate the expression.
4819 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
4820 if (Constant *C = dyn_cast<Constant>(V))
4821 return ConstantExpr::getCast(C, Ty);
4823 // Otherwise, it must be an instruction.
4824 Instruction *I = cast<Instruction>(V);
4826 switch (I->getOpcode()) {
4827 case Instruction::And:
4828 case Instruction::Or:
4829 case Instruction::Xor: {
4830 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
4831 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
4832 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
4833 LHS, RHS, I->getName());
4836 case Instruction::Cast:
4837 // If this is a cast from the destination type, return the input.
4838 if (I->getOperand(0)->getType() == Ty)
4839 return I->getOperand(0);
4841 // TODO: Can handle more cases here.
4842 assert(0 && "Unreachable!");
4846 return InsertNewInstBefore(Res, *I);
4850 // CastInst simplification
4852 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4853 Value *Src = CI.getOperand(0);
4855 // If the user is casting a value to the same type, eliminate this cast
4857 if (CI.getType() == Src->getType())
4858 return ReplaceInstUsesWith(CI, Src);
4860 if (isa<UndefValue>(Src)) // cast undef -> undef
4861 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4863 // If casting the result of another cast instruction, try to eliminate this
4866 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4867 Value *A = CSrc->getOperand(0);
4868 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4869 CI.getType(), TD)) {
4870 // This instruction now refers directly to the cast's src operand. This
4871 // has a good chance of making CSrc dead.
4872 CI.setOperand(0, CSrc->getOperand(0));
4876 // If this is an A->B->A cast, and we are dealing with integral types, try
4877 // to convert this into a logical 'and' instruction.
4879 if (A->getType()->isInteger() &&
4880 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
4881 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
4882 CSrc->getType()->getPrimitiveSizeInBits() <
4883 CI.getType()->getPrimitiveSizeInBits()&&
4884 A->getType()->getPrimitiveSizeInBits() ==
4885 CI.getType()->getPrimitiveSizeInBits()) {
4886 assert(CSrc->getType() != Type::ULongTy &&
4887 "Cannot have type bigger than ulong!");
4888 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
4889 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4891 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4892 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4893 if (And->getType() != CI.getType()) {
4894 And->setName(CSrc->getName()+".mask");
4895 InsertNewInstBefore(And, CI);
4896 And = new CastInst(And, CI.getType());
4902 // If this is a cast to bool, turn it into the appropriate setne instruction.
4903 if (CI.getType() == Type::BoolTy)
4904 return BinaryOperator::createSetNE(CI.getOperand(0),
4905 Constant::getNullValue(CI.getOperand(0)->getType()));
4907 // See if we can simplify any instructions used by the LHS whose sole
4908 // purpose is to compute bits we don't care about.
4909 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4910 uint64_t KnownZero, KnownOne;
4911 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4912 KnownZero, KnownOne))
4916 // If casting the result of a getelementptr instruction with no offset, turn
4917 // this into a cast of the original pointer!
4919 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4920 bool AllZeroOperands = true;
4921 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4922 if (!isa<Constant>(GEP->getOperand(i)) ||
4923 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4924 AllZeroOperands = false;
4927 if (AllZeroOperands) {
4928 CI.setOperand(0, GEP->getOperand(0));
4933 // If we are casting a malloc or alloca to a pointer to a type of the same
4934 // size, rewrite the allocation instruction to allocate the "right" type.
4936 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
4937 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4940 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4941 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4943 if (isa<PHINode>(Src))
4944 if (Instruction *NV = FoldOpIntoPhi(CI))
4947 // If the source and destination are pointers, and this cast is equivalent to
4948 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
4949 // This can enhance SROA and other transforms that want type-safe pointers.
4950 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
4951 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
4952 const Type *DstTy = DstPTy->getElementType();
4953 const Type *SrcTy = SrcPTy->getElementType();
4955 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
4956 unsigned NumZeros = 0;
4957 while (SrcTy != DstTy &&
4958 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
4959 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
4963 // If we found a path from the src to dest, create the getelementptr now.
4964 if (SrcTy == DstTy) {
4965 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
4966 return new GetElementPtrInst(Src, Idxs);
4970 // If the source value is an instruction with only this use, we can attempt to
4971 // propagate the cast into the instruction. Also, only handle integral types
4973 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4974 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4975 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4977 int NumCastsRemoved = 0;
4978 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
4979 // If this cast is a truncate, evaluting in a different type always
4980 // eliminates the cast, so it is always a win. If this is a noop-cast
4981 // this just removes a noop cast which isn't pointful, but simplifies
4982 // the code. If this is a zero-extension, we need to do an AND to
4983 // maintain the clear top-part of the computation, so we require that
4984 // the input have eliminated at least one cast. If this is a sign
4985 // extension, we insert two new casts (to do the extension) so we
4986 // require that two casts have been eliminated.
4988 switch (getCastType(Src->getType(), CI.getType())) {
4989 default: assert(0 && "Unknown cast type!");
4995 DoXForm = NumCastsRemoved >= 1;
4998 DoXForm = NumCastsRemoved >= 2;
5003 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5004 assert(Res->getType() == CI.getType());
5005 switch (getCastType(Src->getType(), CI.getType())) {
5006 default: assert(0 && "Unknown cast type!");
5009 // Just replace this cast with the result.
5010 return ReplaceInstUsesWith(CI, Res);
5012 // We need to emit an AND to clear the high bits.
5013 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5014 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5015 assert(SrcBitSize < DestBitSize && "Not a zext?");
5016 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5017 C = ConstantExpr::getCast(C, CI.getType());
5018 return BinaryOperator::createAnd(Res, C);
5021 // We need to emit a cast to truncate, then a cast to sext.
5022 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5028 const Type *DestTy = CI.getType();
5029 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5030 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5032 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5033 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5035 switch (SrcI->getOpcode()) {
5036 case Instruction::Add:
5037 case Instruction::Mul:
5038 case Instruction::And:
5039 case Instruction::Or:
5040 case Instruction::Xor:
5041 // If we are discarding information, or just changing the sign, rewrite.
5042 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5043 // Don't insert two casts if they cannot be eliminated. We allow two
5044 // casts to be inserted if the sizes are the same. This could only be
5045 // converting signedness, which is a noop.
5046 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5047 !ValueRequiresCast(Op0, DestTy, TD)) {
5048 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5049 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5050 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5051 ->getOpcode(), Op0c, Op1c);
5055 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5056 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5057 Op1 == ConstantBool::True &&
5058 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5059 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5060 return BinaryOperator::createXor(New,
5061 ConstantInt::get(CI.getType(), 1));
5064 case Instruction::Shl:
5065 // Allow changing the sign of the source operand. Do not allow changing
5066 // the size of the shift, UNLESS the shift amount is a constant. We
5067 // mush not change variable sized shifts to a smaller size, because it
5068 // is undefined to shift more bits out than exist in the value.
5069 if (DestBitSize == SrcBitSize ||
5070 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5071 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5072 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5075 case Instruction::Shr:
5076 // If this is a signed shr, and if all bits shifted in are about to be
5077 // truncated off, turn it into an unsigned shr to allow greater
5079 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5080 isa<ConstantInt>(Op1)) {
5081 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5082 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5083 // Convert to unsigned.
5084 Value *N1 = InsertOperandCastBefore(Op0,
5085 Op0->getType()->getUnsignedVersion(), &CI);
5086 // Insert the new shift, which is now unsigned.
5087 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5088 Op1, Src->getName()), CI);
5089 return new CastInst(N1, CI.getType());
5094 case Instruction::SetEQ:
5095 case Instruction::SetNE:
5096 // We if we are just checking for a seteq of a single bit and casting it
5097 // to an integer. If so, shift the bit to the appropriate place then
5098 // cast to integer to avoid the comparison.
5099 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5100 uint64_t Op1CV = Op1C->getZExtValue();
5101 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5102 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5103 // cast (X == 1) to int --> X iff X has only the low bit set.
5104 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5105 // cast (X != 0) to int --> X iff X has only the low bit set.
5106 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5107 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5108 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5109 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5110 // If Op1C some other power of two, convert:
5111 uint64_t KnownZero, KnownOne;
5112 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5113 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5115 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5116 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5117 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5118 // (X&4) == 2 --> false
5119 // (X&4) != 2 --> true
5120 Constant *Res = ConstantBool::get(isSetNE);
5121 Res = ConstantExpr::getCast(Res, CI.getType());
5122 return ReplaceInstUsesWith(CI, Res);
5125 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5128 // Perform an unsigned shr by shiftamt. Convert input to
5129 // unsigned if it is signed.
5130 if (In->getType()->isSigned())
5131 In = InsertNewInstBefore(new CastInst(In,
5132 In->getType()->getUnsignedVersion(), In->getName()),CI);
5133 // Insert the shift to put the result in the low bit.
5134 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
5135 ConstantInt::get(Type::UByteTy, ShiftAmt),
5136 In->getName()+".lobit"), CI);
5139 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5140 Constant *One = ConstantInt::get(In->getType(), 1);
5141 In = BinaryOperator::createXor(In, One, "tmp");
5142 InsertNewInstBefore(cast<Instruction>(In), CI);
5145 if (CI.getType() == In->getType())
5146 return ReplaceInstUsesWith(CI, In);
5148 return new CastInst(In, CI.getType());
5159 /// GetSelectFoldableOperands - We want to turn code that looks like this:
5161 /// %D = select %cond, %C, %A
5163 /// %C = select %cond, %B, 0
5166 /// Assuming that the specified instruction is an operand to the select, return
5167 /// a bitmask indicating which operands of this instruction are foldable if they
5168 /// equal the other incoming value of the select.
5170 static unsigned GetSelectFoldableOperands(Instruction *I) {
5171 switch (I->getOpcode()) {
5172 case Instruction::Add:
5173 case Instruction::Mul:
5174 case Instruction::And:
5175 case Instruction::Or:
5176 case Instruction::Xor:
5177 return 3; // Can fold through either operand.
5178 case Instruction::Sub: // Can only fold on the amount subtracted.
5179 case Instruction::Shl: // Can only fold on the shift amount.
5180 case Instruction::Shr:
5183 return 0; // Cannot fold
5187 /// GetSelectFoldableConstant - For the same transformation as the previous
5188 /// function, return the identity constant that goes into the select.
5189 static Constant *GetSelectFoldableConstant(Instruction *I) {
5190 switch (I->getOpcode()) {
5191 default: assert(0 && "This cannot happen!"); abort();
5192 case Instruction::Add:
5193 case Instruction::Sub:
5194 case Instruction::Or:
5195 case Instruction::Xor:
5196 return Constant::getNullValue(I->getType());
5197 case Instruction::Shl:
5198 case Instruction::Shr:
5199 return Constant::getNullValue(Type::UByteTy);
5200 case Instruction::And:
5201 return ConstantInt::getAllOnesValue(I->getType());
5202 case Instruction::Mul:
5203 return ConstantInt::get(I->getType(), 1);
5207 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5208 /// have the same opcode and only one use each. Try to simplify this.
5209 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5211 if (TI->getNumOperands() == 1) {
5212 // If this is a non-volatile load or a cast from the same type,
5214 if (TI->getOpcode() == Instruction::Cast) {
5215 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5218 return 0; // unknown unary op.
5221 // Fold this by inserting a select from the input values.
5222 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5223 FI->getOperand(0), SI.getName()+".v");
5224 InsertNewInstBefore(NewSI, SI);
5225 return new CastInst(NewSI, TI->getType());
5228 // Only handle binary operators here.
5229 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5232 // Figure out if the operations have any operands in common.
5233 Value *MatchOp, *OtherOpT, *OtherOpF;
5235 if (TI->getOperand(0) == FI->getOperand(0)) {
5236 MatchOp = TI->getOperand(0);
5237 OtherOpT = TI->getOperand(1);
5238 OtherOpF = FI->getOperand(1);
5239 MatchIsOpZero = true;
5240 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5241 MatchOp = TI->getOperand(1);
5242 OtherOpT = TI->getOperand(0);
5243 OtherOpF = FI->getOperand(0);
5244 MatchIsOpZero = false;
5245 } else if (!TI->isCommutative()) {
5247 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5248 MatchOp = TI->getOperand(0);
5249 OtherOpT = TI->getOperand(1);
5250 OtherOpF = FI->getOperand(0);
5251 MatchIsOpZero = true;
5252 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5253 MatchOp = TI->getOperand(1);
5254 OtherOpT = TI->getOperand(0);
5255 OtherOpF = FI->getOperand(1);
5256 MatchIsOpZero = true;
5261 // If we reach here, they do have operations in common.
5262 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5263 OtherOpF, SI.getName()+".v");
5264 InsertNewInstBefore(NewSI, SI);
5266 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5268 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5270 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5273 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5275 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5279 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
5280 Value *CondVal = SI.getCondition();
5281 Value *TrueVal = SI.getTrueValue();
5282 Value *FalseVal = SI.getFalseValue();
5284 // select true, X, Y -> X
5285 // select false, X, Y -> Y
5286 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
5287 if (C == ConstantBool::True)
5288 return ReplaceInstUsesWith(SI, TrueVal);
5290 assert(C == ConstantBool::False);
5291 return ReplaceInstUsesWith(SI, FalseVal);
5294 // select C, X, X -> X
5295 if (TrueVal == FalseVal)
5296 return ReplaceInstUsesWith(SI, TrueVal);
5298 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5299 return ReplaceInstUsesWith(SI, FalseVal);
5300 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5301 return ReplaceInstUsesWith(SI, TrueVal);
5302 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5303 if (isa<Constant>(TrueVal))
5304 return ReplaceInstUsesWith(SI, TrueVal);
5306 return ReplaceInstUsesWith(SI, FalseVal);
5309 if (SI.getType() == Type::BoolTy)
5310 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5311 if (C == ConstantBool::True) {
5312 // Change: A = select B, true, C --> A = or B, C
5313 return BinaryOperator::createOr(CondVal, FalseVal);
5315 // Change: A = select B, false, C --> A = and !B, C
5317 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5318 "not."+CondVal->getName()), SI);
5319 return BinaryOperator::createAnd(NotCond, FalseVal);
5321 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5322 if (C == ConstantBool::False) {
5323 // Change: A = select B, C, false --> A = and B, C
5324 return BinaryOperator::createAnd(CondVal, TrueVal);
5326 // Change: A = select B, C, true --> A = or !B, C
5328 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5329 "not."+CondVal->getName()), SI);
5330 return BinaryOperator::createOr(NotCond, TrueVal);
5334 // Selecting between two integer constants?
5335 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5336 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5337 // select C, 1, 0 -> cast C to int
5338 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5339 return new CastInst(CondVal, SI.getType());
5340 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5341 // select C, 0, 1 -> cast !C to int
5343 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5344 "not."+CondVal->getName()), SI);
5345 return new CastInst(NotCond, SI.getType());
5348 // If one of the constants is zero (we know they can't both be) and we
5349 // have a setcc instruction with zero, and we have an 'and' with the
5350 // non-constant value, eliminate this whole mess. This corresponds to
5351 // cases like this: ((X & 27) ? 27 : 0)
5352 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5353 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5354 if ((IC->getOpcode() == Instruction::SetEQ ||
5355 IC->getOpcode() == Instruction::SetNE) &&
5356 isa<ConstantInt>(IC->getOperand(1)) &&
5357 cast<Constant>(IC->getOperand(1))->isNullValue())
5358 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5359 if (ICA->getOpcode() == Instruction::And &&
5360 isa<ConstantInt>(ICA->getOperand(1)) &&
5361 (ICA->getOperand(1) == TrueValC ||
5362 ICA->getOperand(1) == FalseValC) &&
5363 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5364 // Okay, now we know that everything is set up, we just don't
5365 // know whether we have a setne or seteq and whether the true or
5366 // false val is the zero.
5367 bool ShouldNotVal = !TrueValC->isNullValue();
5368 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5371 V = InsertNewInstBefore(BinaryOperator::create(
5372 Instruction::Xor, V, ICA->getOperand(1)), SI);
5373 return ReplaceInstUsesWith(SI, V);
5377 // See if we are selecting two values based on a comparison of the two values.
5378 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5379 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5380 // Transform (X == Y) ? X : Y -> Y
5381 if (SCI->getOpcode() == Instruction::SetEQ)
5382 return ReplaceInstUsesWith(SI, FalseVal);
5383 // Transform (X != Y) ? X : Y -> X
5384 if (SCI->getOpcode() == Instruction::SetNE)
5385 return ReplaceInstUsesWith(SI, TrueVal);
5386 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5388 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5389 // Transform (X == Y) ? Y : X -> X
5390 if (SCI->getOpcode() == Instruction::SetEQ)
5391 return ReplaceInstUsesWith(SI, FalseVal);
5392 // Transform (X != Y) ? Y : X -> Y
5393 if (SCI->getOpcode() == Instruction::SetNE)
5394 return ReplaceInstUsesWith(SI, TrueVal);
5395 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5399 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5400 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5401 if (TI->hasOneUse() && FI->hasOneUse()) {
5402 bool isInverse = false;
5403 Instruction *AddOp = 0, *SubOp = 0;
5405 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5406 if (TI->getOpcode() == FI->getOpcode())
5407 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5410 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5411 // even legal for FP.
5412 if (TI->getOpcode() == Instruction::Sub &&
5413 FI->getOpcode() == Instruction::Add) {
5414 AddOp = FI; SubOp = TI;
5415 } else if (FI->getOpcode() == Instruction::Sub &&
5416 TI->getOpcode() == Instruction::Add) {
5417 AddOp = TI; SubOp = FI;
5421 Value *OtherAddOp = 0;
5422 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5423 OtherAddOp = AddOp->getOperand(1);
5424 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5425 OtherAddOp = AddOp->getOperand(0);
5429 // So at this point we know we have (Y -> OtherAddOp):
5430 // select C, (add X, Y), (sub X, Z)
5431 Value *NegVal; // Compute -Z
5432 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5433 NegVal = ConstantExpr::getNeg(C);
5435 NegVal = InsertNewInstBefore(
5436 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
5439 Value *NewTrueOp = OtherAddOp;
5440 Value *NewFalseOp = NegVal;
5442 std::swap(NewTrueOp, NewFalseOp);
5443 Instruction *NewSel =
5444 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5446 NewSel = InsertNewInstBefore(NewSel, SI);
5447 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
5452 // See if we can fold the select into one of our operands.
5453 if (SI.getType()->isInteger()) {
5454 // See the comment above GetSelectFoldableOperands for a description of the
5455 // transformation we are doing here.
5456 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5457 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5458 !isa<Constant>(FalseVal))
5459 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5460 unsigned OpToFold = 0;
5461 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5463 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5468 Constant *C = GetSelectFoldableConstant(TVI);
5469 std::string Name = TVI->getName(); TVI->setName("");
5470 Instruction *NewSel =
5471 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5473 InsertNewInstBefore(NewSel, SI);
5474 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5475 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5476 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5477 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5479 assert(0 && "Unknown instruction!!");
5484 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5485 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5486 !isa<Constant>(TrueVal))
5487 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5488 unsigned OpToFold = 0;
5489 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5491 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5496 Constant *C = GetSelectFoldableConstant(FVI);
5497 std::string Name = FVI->getName(); FVI->setName("");
5498 Instruction *NewSel =
5499 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5501 InsertNewInstBefore(NewSel, SI);
5502 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5503 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5504 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5505 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5507 assert(0 && "Unknown instruction!!");
5513 if (BinaryOperator::isNot(CondVal)) {
5514 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5515 SI.setOperand(1, FalseVal);
5516 SI.setOperand(2, TrueVal);
5523 /// GetKnownAlignment - If the specified pointer has an alignment that we can
5524 /// determine, return it, otherwise return 0.
5525 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5526 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5527 unsigned Align = GV->getAlignment();
5528 if (Align == 0 && TD)
5529 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5531 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5532 unsigned Align = AI->getAlignment();
5533 if (Align == 0 && TD) {
5534 if (isa<AllocaInst>(AI))
5535 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5536 else if (isa<MallocInst>(AI)) {
5537 // Malloc returns maximally aligned memory.
5538 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5539 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5540 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5544 } else if (isa<CastInst>(V) ||
5545 (isa<ConstantExpr>(V) &&
5546 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5547 User *CI = cast<User>(V);
5548 if (isa<PointerType>(CI->getOperand(0)->getType()))
5549 return GetKnownAlignment(CI->getOperand(0), TD);
5551 } else if (isa<GetElementPtrInst>(V) ||
5552 (isa<ConstantExpr>(V) &&
5553 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5554 User *GEPI = cast<User>(V);
5555 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5556 if (BaseAlignment == 0) return 0;
5558 // If all indexes are zero, it is just the alignment of the base pointer.
5559 bool AllZeroOperands = true;
5560 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5561 if (!isa<Constant>(GEPI->getOperand(i)) ||
5562 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5563 AllZeroOperands = false;
5566 if (AllZeroOperands)
5567 return BaseAlignment;
5569 // Otherwise, if the base alignment is >= the alignment we expect for the
5570 // base pointer type, then we know that the resultant pointer is aligned at
5571 // least as much as its type requires.
5574 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5575 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
5577 const Type *GEPTy = GEPI->getType();
5578 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5586 /// visitCallInst - CallInst simplification. This mostly only handles folding
5587 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5588 /// the heavy lifting.
5590 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
5591 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5592 if (!II) return visitCallSite(&CI);
5594 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5596 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
5597 bool Changed = false;
5599 // memmove/cpy/set of zero bytes is a noop.
5600 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5601 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5603 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5604 if (CI->getRawValue() == 1) {
5605 // Replace the instruction with just byte operations. We would
5606 // transform other cases to loads/stores, but we don't know if
5607 // alignment is sufficient.
5611 // If we have a memmove and the source operation is a constant global,
5612 // then the source and dest pointers can't alias, so we can change this
5613 // into a call to memcpy.
5614 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
5615 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5616 if (GVSrc->isConstant()) {
5617 Module *M = CI.getParent()->getParent()->getParent();
5619 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5621 Name = "llvm.memcpy.i32";
5623 Name = "llvm.memcpy.i64";
5624 Function *MemCpy = M->getOrInsertFunction(Name,
5625 CI.getCalledFunction()->getFunctionType());
5626 CI.setOperand(0, MemCpy);
5631 // If we can determine a pointer alignment that is bigger than currently
5632 // set, update the alignment.
5633 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5634 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5635 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5636 unsigned Align = std::min(Alignment1, Alignment2);
5637 if (MI->getAlignment()->getRawValue() < Align) {
5638 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5641 } else if (isa<MemSetInst>(MI)) {
5642 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5643 if (MI->getAlignment()->getRawValue() < Alignment) {
5644 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5649 if (Changed) return II;
5651 switch (II->getIntrinsicID()) {
5653 case Intrinsic::ppc_altivec_lvx:
5654 case Intrinsic::ppc_altivec_lvxl:
5655 case Intrinsic::x86_sse_loadu_ps:
5656 case Intrinsic::x86_sse2_loadu_pd:
5657 case Intrinsic::x86_sse2_loadu_dq:
5658 // Turn PPC lvx -> load if the pointer is known aligned.
5659 // Turn X86 loadups -> load if the pointer is known aligned.
5660 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5661 Value *Ptr = InsertCastBefore(II->getOperand(1),
5662 PointerType::get(II->getType()), CI);
5663 return new LoadInst(Ptr);
5666 case Intrinsic::ppc_altivec_stvx:
5667 case Intrinsic::ppc_altivec_stvxl:
5668 // Turn stvx -> store if the pointer is known aligned.
5669 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
5670 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5671 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
5672 return new StoreInst(II->getOperand(1), Ptr);
5675 case Intrinsic::x86_sse_storeu_ps:
5676 case Intrinsic::x86_sse2_storeu_pd:
5677 case Intrinsic::x86_sse2_storeu_dq:
5678 case Intrinsic::x86_sse2_storel_dq:
5679 // Turn X86 storeu -> store if the pointer is known aligned.
5680 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5681 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5682 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5683 return new StoreInst(II->getOperand(2), Ptr);
5686 case Intrinsic::ppc_altivec_vperm:
5687 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5688 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5689 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5691 // Check that all of the elements are integer constants or undefs.
5692 bool AllEltsOk = true;
5693 for (unsigned i = 0; i != 16; ++i) {
5694 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5695 !isa<UndefValue>(Mask->getOperand(i))) {
5702 // Cast the input vectors to byte vectors.
5703 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5704 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5705 Value *Result = UndefValue::get(Op0->getType());
5707 // Only extract each element once.
5708 Value *ExtractedElts[32];
5709 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5711 for (unsigned i = 0; i != 16; ++i) {
5712 if (isa<UndefValue>(Mask->getOperand(i)))
5714 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5715 Idx &= 31; // Match the hardware behavior.
5717 if (ExtractedElts[Idx] == 0) {
5719 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5720 ConstantUInt::get(Type::UIntTy, Idx&15),
5722 InsertNewInstBefore(Elt, CI);
5723 ExtractedElts[Idx] = Elt;
5726 // Insert this value into the result vector.
5727 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5728 ConstantUInt::get(Type::UIntTy, i),
5730 InsertNewInstBefore(cast<Instruction>(Result), CI);
5732 return new CastInst(Result, CI.getType());
5737 case Intrinsic::stackrestore: {
5738 // If the save is right next to the restore, remove the restore. This can
5739 // happen when variable allocas are DCE'd.
5740 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5741 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5742 BasicBlock::iterator BI = SS;
5744 return EraseInstFromFunction(CI);
5748 // If the stack restore is in a return/unwind block and if there are no
5749 // allocas or calls between the restore and the return, nuke the restore.
5750 TerminatorInst *TI = II->getParent()->getTerminator();
5751 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5752 BasicBlock::iterator BI = II;
5753 bool CannotRemove = false;
5754 for (++BI; &*BI != TI; ++BI) {
5755 if (isa<AllocaInst>(BI) ||
5756 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5757 CannotRemove = true;
5762 return EraseInstFromFunction(CI);
5769 return visitCallSite(II);
5772 // InvokeInst simplification
5774 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
5775 return visitCallSite(&II);
5778 // visitCallSite - Improvements for call and invoke instructions.
5780 Instruction *InstCombiner::visitCallSite(CallSite CS) {
5781 bool Changed = false;
5783 // If the callee is a constexpr cast of a function, attempt to move the cast
5784 // to the arguments of the call/invoke.
5785 if (transformConstExprCastCall(CS)) return 0;
5787 Value *Callee = CS.getCalledValue();
5789 if (Function *CalleeF = dyn_cast<Function>(Callee))
5790 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5791 Instruction *OldCall = CS.getInstruction();
5792 // If the call and callee calling conventions don't match, this call must
5793 // be unreachable, as the call is undefined.
5794 new StoreInst(ConstantBool::True,
5795 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5796 if (!OldCall->use_empty())
5797 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5798 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5799 return EraseInstFromFunction(*OldCall);
5803 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5804 // This instruction is not reachable, just remove it. We insert a store to
5805 // undef so that we know that this code is not reachable, despite the fact
5806 // that we can't modify the CFG here.
5807 new StoreInst(ConstantBool::True,
5808 UndefValue::get(PointerType::get(Type::BoolTy)),
5809 CS.getInstruction());
5811 if (!CS.getInstruction()->use_empty())
5812 CS.getInstruction()->
5813 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5815 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5816 // Don't break the CFG, insert a dummy cond branch.
5817 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5818 ConstantBool::True, II);
5820 return EraseInstFromFunction(*CS.getInstruction());
5823 const PointerType *PTy = cast<PointerType>(Callee->getType());
5824 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5825 if (FTy->isVarArg()) {
5826 // See if we can optimize any arguments passed through the varargs area of
5828 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5829 E = CS.arg_end(); I != E; ++I)
5830 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5831 // If this cast does not effect the value passed through the varargs
5832 // area, we can eliminate the use of the cast.
5833 Value *Op = CI->getOperand(0);
5834 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5841 return Changed ? CS.getInstruction() : 0;
5844 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
5845 // attempt to move the cast to the arguments of the call/invoke.
5847 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5848 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5849 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
5850 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
5852 Function *Callee = cast<Function>(CE->getOperand(0));
5853 Instruction *Caller = CS.getInstruction();
5855 // Okay, this is a cast from a function to a different type. Unless doing so
5856 // would cause a type conversion of one of our arguments, change this call to
5857 // be a direct call with arguments casted to the appropriate types.
5859 const FunctionType *FT = Callee->getFunctionType();
5860 const Type *OldRetTy = Caller->getType();
5862 // Check to see if we are changing the return type...
5863 if (OldRetTy != FT->getReturnType()) {
5864 if (Callee->isExternal() &&
5865 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
5866 (isa<PointerType>(FT->getReturnType()) &&
5867 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
5868 && !Caller->use_empty())
5869 return false; // Cannot transform this return value...
5871 // If the callsite is an invoke instruction, and the return value is used by
5872 // a PHI node in a successor, we cannot change the return type of the call
5873 // because there is no place to put the cast instruction (without breaking
5874 // the critical edge). Bail out in this case.
5875 if (!Caller->use_empty())
5876 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5877 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5879 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5880 if (PN->getParent() == II->getNormalDest() ||
5881 PN->getParent() == II->getUnwindDest())
5885 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5886 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
5888 CallSite::arg_iterator AI = CS.arg_begin();
5889 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5890 const Type *ParamTy = FT->getParamType(i);
5891 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
5892 if (Callee->isExternal() && !isConvertible) return false;
5895 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5896 Callee->isExternal())
5897 return false; // Do not delete arguments unless we have a function body...
5899 // Okay, we decided that this is a safe thing to do: go ahead and start
5900 // inserting cast instructions as necessary...
5901 std::vector<Value*> Args;
5902 Args.reserve(NumActualArgs);
5904 AI = CS.arg_begin();
5905 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5906 const Type *ParamTy = FT->getParamType(i);
5907 if ((*AI)->getType() == ParamTy) {
5908 Args.push_back(*AI);
5910 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5915 // If the function takes more arguments than the call was taking, add them
5917 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5918 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5920 // If we are removing arguments to the function, emit an obnoxious warning...
5921 if (FT->getNumParams() < NumActualArgs)
5922 if (!FT->isVarArg()) {
5923 std::cerr << "WARNING: While resolving call to function '"
5924 << Callee->getName() << "' arguments were dropped!\n";
5926 // Add all of the arguments in their promoted form to the arg list...
5927 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5928 const Type *PTy = getPromotedType((*AI)->getType());
5929 if (PTy != (*AI)->getType()) {
5930 // Must promote to pass through va_arg area!
5931 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5932 InsertNewInstBefore(Cast, *Caller);
5933 Args.push_back(Cast);
5935 Args.push_back(*AI);
5940 if (FT->getReturnType() == Type::VoidTy)
5941 Caller->setName(""); // Void type should not have a name...
5944 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5945 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
5946 Args, Caller->getName(), Caller);
5947 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
5949 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
5950 if (cast<CallInst>(Caller)->isTailCall())
5951 cast<CallInst>(NC)->setTailCall();
5952 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
5955 // Insert a cast of the return type as necessary...
5957 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5958 if (NV->getType() != Type::VoidTy) {
5959 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
5961 // If this is an invoke instruction, we should insert it after the first
5962 // non-phi, instruction in the normal successor block.
5963 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5964 BasicBlock::iterator I = II->getNormalDest()->begin();
5965 while (isa<PHINode>(I)) ++I;
5966 InsertNewInstBefore(NC, *I);
5968 // Otherwise, it's a call, just insert cast right after the call instr
5969 InsertNewInstBefore(NC, *Caller);
5971 AddUsersToWorkList(*Caller);
5973 NV = UndefValue::get(Caller->getType());
5977 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5978 Caller->replaceAllUsesWith(NV);
5979 Caller->getParent()->getInstList().erase(Caller);
5980 removeFromWorkList(Caller);
5985 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5986 // operator and they all are only used by the PHI, PHI together their
5987 // inputs, and do the operation once, to the result of the PHI.
5988 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5989 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5991 // Scan the instruction, looking for input operations that can be folded away.
5992 // If all input operands to the phi are the same instruction (e.g. a cast from
5993 // the same type or "+42") we can pull the operation through the PHI, reducing
5994 // code size and simplifying code.
5995 Constant *ConstantOp = 0;
5996 const Type *CastSrcTy = 0;
5997 if (isa<CastInst>(FirstInst)) {
5998 CastSrcTy = FirstInst->getOperand(0)->getType();
5999 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6000 // Can fold binop or shift if the RHS is a constant.
6001 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6002 if (ConstantOp == 0) return 0;
6004 return 0; // Cannot fold this operation.
6007 // Check to see if all arguments are the same operation.
6008 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6009 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6010 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6011 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6014 if (I->getOperand(0)->getType() != CastSrcTy)
6015 return 0; // Cast operation must match.
6016 } else if (I->getOperand(1) != ConstantOp) {
6021 // Okay, they are all the same operation. Create a new PHI node of the
6022 // correct type, and PHI together all of the LHS's of the instructions.
6023 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6024 PN.getName()+".in");
6025 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
6027 Value *InVal = FirstInst->getOperand(0);
6028 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
6030 // Add all operands to the new PHI.
6031 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6032 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6033 if (NewInVal != InVal)
6035 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6040 // The new PHI unions all of the same values together. This is really
6041 // common, so we handle it intelligently here for compile-time speed.
6045 InsertNewInstBefore(NewPN, PN);
6049 // Insert and return the new operation.
6050 if (isa<CastInst>(FirstInst))
6051 return new CastInst(PhiVal, PN.getType());
6052 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
6053 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
6055 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
6056 PhiVal, ConstantOp);
6059 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6061 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6062 if (PN->use_empty()) return true;
6063 if (!PN->hasOneUse()) return false;
6065 // Remember this node, and if we find the cycle, return.
6066 if (!PotentiallyDeadPHIs.insert(PN).second)
6069 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6070 return DeadPHICycle(PU, PotentiallyDeadPHIs);
6075 // PHINode simplification
6077 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
6078 if (Value *V = PN.hasConstantValue())
6079 return ReplaceInstUsesWith(PN, V);
6081 // If the only user of this instruction is a cast instruction, and all of the
6082 // incoming values are constants, change this PHI to merge together the casted
6085 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6086 if (CI->getType() != PN.getType()) { // noop casts will be folded
6087 bool AllConstant = true;
6088 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6089 if (!isa<Constant>(PN.getIncomingValue(i))) {
6090 AllConstant = false;
6094 // Make a new PHI with all casted values.
6095 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6096 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6097 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6098 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6099 PN.getIncomingBlock(i));
6102 // Update the cast instruction.
6103 CI->setOperand(0, New);
6104 WorkList.push_back(CI); // revisit the cast instruction to fold.
6105 WorkList.push_back(New); // Make sure to revisit the new Phi
6106 return &PN; // PN is now dead!
6110 // If all PHI operands are the same operation, pull them through the PHI,
6111 // reducing code size.
6112 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6113 PN.getIncomingValue(0)->hasOneUse())
6114 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6117 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6118 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6119 // PHI)... break the cycle.
6121 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6122 std::set<PHINode*> PotentiallyDeadPHIs;
6123 PotentiallyDeadPHIs.insert(&PN);
6124 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6125 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6131 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6132 Instruction *InsertPoint,
6134 unsigned PS = IC->getTargetData().getPointerSize();
6135 const Type *VTy = V->getType();
6136 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6137 // We must insert a cast to ensure we sign-extend.
6138 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6139 V->getName()), *InsertPoint);
6140 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6145 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
6146 Value *PtrOp = GEP.getOperand(0);
6147 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
6148 // If so, eliminate the noop.
6149 if (GEP.getNumOperands() == 1)
6150 return ReplaceInstUsesWith(GEP, PtrOp);
6152 if (isa<UndefValue>(GEP.getOperand(0)))
6153 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6155 bool HasZeroPointerIndex = false;
6156 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6157 HasZeroPointerIndex = C->isNullValue();
6159 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
6160 return ReplaceInstUsesWith(GEP, PtrOp);
6162 // Eliminate unneeded casts for indices.
6163 bool MadeChange = false;
6164 gep_type_iterator GTI = gep_type_begin(GEP);
6165 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6166 if (isa<SequentialType>(*GTI)) {
6167 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6168 Value *Src = CI->getOperand(0);
6169 const Type *SrcTy = Src->getType();
6170 const Type *DestTy = CI->getType();
6171 if (Src->getType()->isInteger()) {
6172 if (SrcTy->getPrimitiveSizeInBits() ==
6173 DestTy->getPrimitiveSizeInBits()) {
6174 // We can always eliminate a cast from ulong or long to the other.
6175 // We can always eliminate a cast from uint to int or the other on
6176 // 32-bit pointer platforms.
6177 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
6179 GEP.setOperand(i, Src);
6181 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6182 SrcTy->getPrimitiveSize() == 4) {
6183 // We can always eliminate a cast from int to [u]long. We can
6184 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6186 if (SrcTy->isSigned() ||
6187 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
6189 GEP.setOperand(i, Src);
6194 // If we are using a wider index than needed for this platform, shrink it
6195 // to what we need. If the incoming value needs a cast instruction,
6196 // insert it. This explicit cast can make subsequent optimizations more
6198 Value *Op = GEP.getOperand(i);
6199 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
6200 if (Constant *C = dyn_cast<Constant>(Op)) {
6201 GEP.setOperand(i, ConstantExpr::getCast(C,
6202 TD->getIntPtrType()->getSignedVersion()));
6205 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6206 Op->getName()), GEP);
6207 GEP.setOperand(i, Op);
6211 // If this is a constant idx, make sure to canonicalize it to be a signed
6212 // operand, otherwise CSE and other optimizations are pessimized.
6213 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6214 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6215 CUI->getType()->getSignedVersion()));
6219 if (MadeChange) return &GEP;
6221 // Combine Indices - If the source pointer to this getelementptr instruction
6222 // is a getelementptr instruction, combine the indices of the two
6223 // getelementptr instructions into a single instruction.
6225 std::vector<Value*> SrcGEPOperands;
6226 if (User *Src = dyn_castGetElementPtr(PtrOp))
6227 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
6229 if (!SrcGEPOperands.empty()) {
6230 // Note that if our source is a gep chain itself that we wait for that
6231 // chain to be resolved before we perform this transformation. This
6232 // avoids us creating a TON of code in some cases.
6234 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6235 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6236 return 0; // Wait until our source is folded to completion.
6238 std::vector<Value *> Indices;
6240 // Find out whether the last index in the source GEP is a sequential idx.
6241 bool EndsWithSequential = false;
6242 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6243 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
6244 EndsWithSequential = !isa<StructType>(*I);
6246 // Can we combine the two pointer arithmetics offsets?
6247 if (EndsWithSequential) {
6248 // Replace: gep (gep %P, long B), long A, ...
6249 // With: T = long A+B; gep %P, T, ...
6251 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
6252 if (SO1 == Constant::getNullValue(SO1->getType())) {
6254 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6257 // If they aren't the same type, convert both to an integer of the
6258 // target's pointer size.
6259 if (SO1->getType() != GO1->getType()) {
6260 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6261 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6262 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6263 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6265 unsigned PS = TD->getPointerSize();
6266 if (SO1->getType()->getPrimitiveSize() == PS) {
6267 // Convert GO1 to SO1's type.
6268 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6270 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6271 // Convert SO1 to GO1's type.
6272 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6274 const Type *PT = TD->getIntPtrType();
6275 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6276 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6280 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6281 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6283 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6284 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
6288 // Recycle the GEP we already have if possible.
6289 if (SrcGEPOperands.size() == 2) {
6290 GEP.setOperand(0, SrcGEPOperands[0]);
6291 GEP.setOperand(1, Sum);
6294 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6295 SrcGEPOperands.end()-1);
6296 Indices.push_back(Sum);
6297 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6299 } else if (isa<Constant>(*GEP.idx_begin()) &&
6300 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
6301 SrcGEPOperands.size() != 1) {
6302 // Otherwise we can do the fold if the first index of the GEP is a zero
6303 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6304 SrcGEPOperands.end());
6305 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6308 if (!Indices.empty())
6309 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
6311 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
6312 // GEP of global variable. If all of the indices for this GEP are
6313 // constants, we can promote this to a constexpr instead of an instruction.
6315 // Scan for nonconstants...
6316 std::vector<Constant*> Indices;
6317 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6318 for (; I != E && isa<Constant>(*I); ++I)
6319 Indices.push_back(cast<Constant>(*I));
6321 if (I == E) { // If they are all constants...
6322 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
6324 // Replace all uses of the GEP with the new constexpr...
6325 return ReplaceInstUsesWith(GEP, CE);
6327 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6328 if (!isa<PointerType>(X->getType())) {
6329 // Not interesting. Source pointer must be a cast from pointer.
6330 } else if (HasZeroPointerIndex) {
6331 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6332 // into : GEP [10 x ubyte]* X, long 0, ...
6334 // This occurs when the program declares an array extern like "int X[];"
6336 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6337 const PointerType *XTy = cast<PointerType>(X->getType());
6338 if (const ArrayType *XATy =
6339 dyn_cast<ArrayType>(XTy->getElementType()))
6340 if (const ArrayType *CATy =
6341 dyn_cast<ArrayType>(CPTy->getElementType()))
6342 if (CATy->getElementType() == XATy->getElementType()) {
6343 // At this point, we know that the cast source type is a pointer
6344 // to an array of the same type as the destination pointer
6345 // array. Because the array type is never stepped over (there
6346 // is a leading zero) we can fold the cast into this GEP.
6347 GEP.setOperand(0, X);
6350 } else if (GEP.getNumOperands() == 2) {
6351 // Transform things like:
6352 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6353 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
6354 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6355 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6356 if (isa<ArrayType>(SrcElTy) &&
6357 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6358 TD->getTypeSize(ResElTy)) {
6359 Value *V = InsertNewInstBefore(
6360 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6361 GEP.getOperand(1), GEP.getName()), GEP);
6362 return new CastInst(V, GEP.getType());
6365 // Transform things like:
6366 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6367 // (where tmp = 8*tmp2) into:
6368 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6370 if (isa<ArrayType>(SrcElTy) &&
6371 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6372 uint64_t ArrayEltSize =
6373 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6375 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6376 // allow either a mul, shift, or constant here.
6378 ConstantInt *Scale = 0;
6379 if (ArrayEltSize == 1) {
6380 NewIdx = GEP.getOperand(1);
6381 Scale = ConstantInt::get(NewIdx->getType(), 1);
6382 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
6383 NewIdx = ConstantInt::get(CI->getType(), 1);
6385 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6386 if (Inst->getOpcode() == Instruction::Shl &&
6387 isa<ConstantInt>(Inst->getOperand(1))) {
6388 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6389 if (Inst->getType()->isSigned())
6390 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6392 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6393 NewIdx = Inst->getOperand(0);
6394 } else if (Inst->getOpcode() == Instruction::Mul &&
6395 isa<ConstantInt>(Inst->getOperand(1))) {
6396 Scale = cast<ConstantInt>(Inst->getOperand(1));
6397 NewIdx = Inst->getOperand(0);
6401 // If the index will be to exactly the right offset with the scale taken
6402 // out, perform the transformation.
6403 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6404 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6405 Scale = ConstantSInt::get(C->getType(),
6406 (int64_t)C->getRawValue() /
6407 (int64_t)ArrayEltSize);
6409 Scale = ConstantUInt::get(Scale->getType(),
6410 Scale->getRawValue() / ArrayEltSize);
6411 if (Scale->getRawValue() != 1) {
6412 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6413 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6414 NewIdx = InsertNewInstBefore(Sc, GEP);
6417 // Insert the new GEP instruction.
6419 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6420 NewIdx, GEP.getName());
6421 Idx = InsertNewInstBefore(Idx, GEP);
6422 return new CastInst(Idx, GEP.getType());
6431 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6432 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6433 if (AI.isArrayAllocation()) // Check C != 1
6434 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6435 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
6436 AllocationInst *New = 0;
6438 // Create and insert the replacement instruction...
6439 if (isa<MallocInst>(AI))
6440 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
6442 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
6443 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
6446 InsertNewInstBefore(New, AI);
6448 // Scan to the end of the allocation instructions, to skip over a block of
6449 // allocas if possible...
6451 BasicBlock::iterator It = New;
6452 while (isa<AllocationInst>(*It)) ++It;
6454 // Now that I is pointing to the first non-allocation-inst in the block,
6455 // insert our getelementptr instruction...
6457 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6458 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6459 New->getName()+".sub", It);
6461 // Now make everything use the getelementptr instead of the original
6463 return ReplaceInstUsesWith(AI, V);
6464 } else if (isa<UndefValue>(AI.getArraySize())) {
6465 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6468 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6469 // Note that we only do this for alloca's, because malloc should allocate and
6470 // return a unique pointer, even for a zero byte allocation.
6471 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
6472 TD->getTypeSize(AI.getAllocatedType()) == 0)
6473 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6478 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6479 Value *Op = FI.getOperand(0);
6481 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6482 if (CastInst *CI = dyn_cast<CastInst>(Op))
6483 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6484 FI.setOperand(0, CI->getOperand(0));
6488 // free undef -> unreachable.
6489 if (isa<UndefValue>(Op)) {
6490 // Insert a new store to null because we cannot modify the CFG here.
6491 new StoreInst(ConstantBool::True,
6492 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6493 return EraseInstFromFunction(FI);
6496 // If we have 'free null' delete the instruction. This can happen in stl code
6497 // when lots of inlining happens.
6498 if (isa<ConstantPointerNull>(Op))
6499 return EraseInstFromFunction(FI);
6505 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
6506 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6507 User *CI = cast<User>(LI.getOperand(0));
6508 Value *CastOp = CI->getOperand(0);
6510 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6511 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6512 const Type *SrcPTy = SrcTy->getElementType();
6514 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6515 isa<PackedType>(DestPTy)) {
6516 // If the source is an array, the code below will not succeed. Check to
6517 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6519 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6520 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6521 if (ASrcTy->getNumElements() != 0) {
6522 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6523 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6524 SrcTy = cast<PointerType>(CastOp->getType());
6525 SrcPTy = SrcTy->getElementType();
6528 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6529 isa<PackedType>(SrcPTy)) &&
6530 // Do not allow turning this into a load of an integer, which is then
6531 // casted to a pointer, this pessimizes pointer analysis a lot.
6532 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
6533 IC.getTargetData().getTypeSize(SrcPTy) ==
6534 IC.getTargetData().getTypeSize(DestPTy)) {
6536 // Okay, we are casting from one integer or pointer type to another of
6537 // the same size. Instead of casting the pointer before the load, cast
6538 // the result of the loaded value.
6539 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6541 LI.isVolatile()),LI);
6542 // Now cast the result of the load.
6543 return new CastInst(NewLoad, LI.getType());
6550 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
6551 /// from this value cannot trap. If it is not obviously safe to load from the
6552 /// specified pointer, we do a quick local scan of the basic block containing
6553 /// ScanFrom, to determine if the address is already accessed.
6554 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6555 // If it is an alloca or global variable, it is always safe to load from.
6556 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6558 // Otherwise, be a little bit agressive by scanning the local block where we
6559 // want to check to see if the pointer is already being loaded or stored
6560 // from/to. If so, the previous load or store would have already trapped,
6561 // so there is no harm doing an extra load (also, CSE will later eliminate
6562 // the load entirely).
6563 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6568 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6569 if (LI->getOperand(0) == V) return true;
6570 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6571 if (SI->getOperand(1) == V) return true;
6577 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6578 Value *Op = LI.getOperand(0);
6580 // load (cast X) --> cast (load X) iff safe
6581 if (CastInst *CI = dyn_cast<CastInst>(Op))
6582 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6585 // None of the following transforms are legal for volatile loads.
6586 if (LI.isVolatile()) return 0;
6588 if (&LI.getParent()->front() != &LI) {
6589 BasicBlock::iterator BBI = &LI; --BBI;
6590 // If the instruction immediately before this is a store to the same
6591 // address, do a simple form of store->load forwarding.
6592 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6593 if (SI->getOperand(1) == LI.getOperand(0))
6594 return ReplaceInstUsesWith(LI, SI->getOperand(0));
6595 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6596 if (LIB->getOperand(0) == LI.getOperand(0))
6597 return ReplaceInstUsesWith(LI, LIB);
6600 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6601 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6602 isa<UndefValue>(GEPI->getOperand(0))) {
6603 // Insert a new store to null instruction before the load to indicate
6604 // that this code is not reachable. We do this instead of inserting
6605 // an unreachable instruction directly because we cannot modify the
6607 new StoreInst(UndefValue::get(LI.getType()),
6608 Constant::getNullValue(Op->getType()), &LI);
6609 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6612 if (Constant *C = dyn_cast<Constant>(Op)) {
6613 // load null/undef -> undef
6614 if ((C->isNullValue() || isa<UndefValue>(C))) {
6615 // Insert a new store to null instruction before the load to indicate that
6616 // this code is not reachable. We do this instead of inserting an
6617 // unreachable instruction directly because we cannot modify the CFG.
6618 new StoreInst(UndefValue::get(LI.getType()),
6619 Constant::getNullValue(Op->getType()), &LI);
6620 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6623 // Instcombine load (constant global) into the value loaded.
6624 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6625 if (GV->isConstant() && !GV->isExternal())
6626 return ReplaceInstUsesWith(LI, GV->getInitializer());
6628 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6629 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6630 if (CE->getOpcode() == Instruction::GetElementPtr) {
6631 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6632 if (GV->isConstant() && !GV->isExternal())
6634 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
6635 return ReplaceInstUsesWith(LI, V);
6636 if (CE->getOperand(0)->isNullValue()) {
6637 // Insert a new store to null instruction before the load to indicate
6638 // that this code is not reachable. We do this instead of inserting
6639 // an unreachable instruction directly because we cannot modify the
6641 new StoreInst(UndefValue::get(LI.getType()),
6642 Constant::getNullValue(Op->getType()), &LI);
6643 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6646 } else if (CE->getOpcode() == Instruction::Cast) {
6647 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6652 if (Op->hasOneUse()) {
6653 // Change select and PHI nodes to select values instead of addresses: this
6654 // helps alias analysis out a lot, allows many others simplifications, and
6655 // exposes redundancy in the code.
6657 // Note that we cannot do the transformation unless we know that the
6658 // introduced loads cannot trap! Something like this is valid as long as
6659 // the condition is always false: load (select bool %C, int* null, int* %G),
6660 // but it would not be valid if we transformed it to load from null
6663 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6664 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
6665 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6666 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
6667 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
6668 SI->getOperand(1)->getName()+".val"), LI);
6669 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
6670 SI->getOperand(2)->getName()+".val"), LI);
6671 return new SelectInst(SI->getCondition(), V1, V2);
6674 // load (select (cond, null, P)) -> load P
6675 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6676 if (C->isNullValue()) {
6677 LI.setOperand(0, SI->getOperand(2));
6681 // load (select (cond, P, null)) -> load P
6682 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6683 if (C->isNullValue()) {
6684 LI.setOperand(0, SI->getOperand(1));
6688 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6689 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
6690 bool Safe = PN->getParent() == LI.getParent();
6692 // Scan all of the instructions between the PHI and the load to make
6693 // sure there are no instructions that might possibly alter the value
6694 // loaded from the PHI.
6696 BasicBlock::iterator I = &LI;
6697 for (--I; !isa<PHINode>(I); --I)
6698 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6704 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
6705 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
6706 PN->getIncomingBlock(i)->getTerminator()))
6711 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6712 InsertNewInstBefore(NewPN, *PN);
6713 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6715 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6716 BasicBlock *BB = PN->getIncomingBlock(i);
6717 Value *&TheLoad = LoadMap[BB];
6719 Value *InVal = PN->getIncomingValue(i);
6720 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6721 InVal->getName()+".val"),
6722 *BB->getTerminator());
6724 NewPN->addIncoming(TheLoad, BB);
6726 return ReplaceInstUsesWith(LI, NewPN);
6733 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6735 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6736 User *CI = cast<User>(SI.getOperand(1));
6737 Value *CastOp = CI->getOperand(0);
6739 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6740 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6741 const Type *SrcPTy = SrcTy->getElementType();
6743 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6744 // If the source is an array, the code below will not succeed. Check to
6745 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6747 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6748 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6749 if (ASrcTy->getNumElements() != 0) {
6750 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6751 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6752 SrcTy = cast<PointerType>(CastOp->getType());
6753 SrcPTy = SrcTy->getElementType();
6756 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
6757 IC.getTargetData().getTypeSize(SrcPTy) ==
6758 IC.getTargetData().getTypeSize(DestPTy)) {
6760 // Okay, we are casting from one integer or pointer type to another of
6761 // the same size. Instead of casting the pointer before the store, cast
6762 // the value to be stored.
6764 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6765 NewCast = ConstantExpr::getCast(C, SrcPTy);
6767 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6769 SI.getOperand(0)->getName()+".c"), SI);
6771 return new StoreInst(NewCast, CastOp);
6778 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6779 Value *Val = SI.getOperand(0);
6780 Value *Ptr = SI.getOperand(1);
6782 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
6783 EraseInstFromFunction(SI);
6788 // Do really simple DSE, to catch cases where there are several consequtive
6789 // stores to the same location, separated by a few arithmetic operations. This
6790 // situation often occurs with bitfield accesses.
6791 BasicBlock::iterator BBI = &SI;
6792 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6796 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6797 // Prev store isn't volatile, and stores to the same location?
6798 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6801 EraseInstFromFunction(*PrevSI);
6807 // Don't skip over loads or things that can modify memory.
6808 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6813 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
6815 // store X, null -> turns into 'unreachable' in SimplifyCFG
6816 if (isa<ConstantPointerNull>(Ptr)) {
6817 if (!isa<UndefValue>(Val)) {
6818 SI.setOperand(0, UndefValue::get(Val->getType()));
6819 if (Instruction *U = dyn_cast<Instruction>(Val))
6820 WorkList.push_back(U); // Dropped a use.
6823 return 0; // Do not modify these!
6826 // store undef, Ptr -> noop
6827 if (isa<UndefValue>(Val)) {
6828 EraseInstFromFunction(SI);
6833 // If the pointer destination is a cast, see if we can fold the cast into the
6835 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6836 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6838 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6839 if (CE->getOpcode() == Instruction::Cast)
6840 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6844 // If this store is the last instruction in the basic block, and if the block
6845 // ends with an unconditional branch, try to move it to the successor block.
6847 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6848 if (BI->isUnconditional()) {
6849 // Check to see if the successor block has exactly two incoming edges. If
6850 // so, see if the other predecessor contains a store to the same location.
6851 // if so, insert a PHI node (if needed) and move the stores down.
6852 BasicBlock *Dest = BI->getSuccessor(0);
6854 pred_iterator PI = pred_begin(Dest);
6855 BasicBlock *Other = 0;
6856 if (*PI != BI->getParent())
6859 if (PI != pred_end(Dest)) {
6860 if (*PI != BI->getParent())
6865 if (++PI != pred_end(Dest))
6868 if (Other) { // If only one other pred...
6869 BBI = Other->getTerminator();
6870 // Make sure this other block ends in an unconditional branch and that
6871 // there is an instruction before the branch.
6872 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6873 BBI != Other->begin()) {
6875 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6877 // If this instruction is a store to the same location.
6878 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6879 // Okay, we know we can perform this transformation. Insert a PHI
6880 // node now if we need it.
6881 Value *MergedVal = OtherStore->getOperand(0);
6882 if (MergedVal != SI.getOperand(0)) {
6883 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6884 PN->reserveOperandSpace(2);
6885 PN->addIncoming(SI.getOperand(0), SI.getParent());
6886 PN->addIncoming(OtherStore->getOperand(0), Other);
6887 MergedVal = InsertNewInstBefore(PN, Dest->front());
6890 // Advance to a place where it is safe to insert the new store and
6892 BBI = Dest->begin();
6893 while (isa<PHINode>(BBI)) ++BBI;
6894 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6895 OtherStore->isVolatile()), *BBI);
6897 // Nuke the old stores.
6898 EraseInstFromFunction(SI);
6899 EraseInstFromFunction(*OtherStore);
6911 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6912 // Change br (not X), label True, label False to: br X, label False, True
6914 BasicBlock *TrueDest;
6915 BasicBlock *FalseDest;
6916 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6917 !isa<Constant>(X)) {
6918 // Swap Destinations and condition...
6920 BI.setSuccessor(0, FalseDest);
6921 BI.setSuccessor(1, TrueDest);
6925 // Cannonicalize setne -> seteq
6926 Instruction::BinaryOps Op; Value *Y;
6927 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6928 TrueDest, FalseDest)))
6929 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6930 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6931 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6932 std::string Name = I->getName(); I->setName("");
6933 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6934 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
6935 // Swap Destinations and condition...
6936 BI.setCondition(NewSCC);
6937 BI.setSuccessor(0, FalseDest);
6938 BI.setSuccessor(1, TrueDest);
6939 removeFromWorkList(I);
6940 I->getParent()->getInstList().erase(I);
6941 WorkList.push_back(cast<Instruction>(NewSCC));
6948 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6949 Value *Cond = SI.getCondition();
6950 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6951 if (I->getOpcode() == Instruction::Add)
6952 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6953 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6954 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
6955 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
6957 SI.setOperand(0, I->getOperand(0));
6958 WorkList.push_back(I);
6965 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6966 /// is to leave as a vector operation.
6967 static bool CheapToScalarize(Value *V, bool isConstant) {
6968 if (isa<ConstantAggregateZero>(V))
6970 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6971 if (isConstant) return true;
6972 // If all elts are the same, we can extract.
6973 Constant *Op0 = C->getOperand(0);
6974 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6975 if (C->getOperand(i) != Op0)
6979 Instruction *I = dyn_cast<Instruction>(V);
6980 if (!I) return false;
6982 // Insert element gets simplified to the inserted element or is deleted if
6983 // this is constant idx extract element and its a constant idx insertelt.
6984 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6985 isa<ConstantInt>(I->getOperand(2)))
6987 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6989 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6990 if (BO->hasOneUse() &&
6991 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6992 CheapToScalarize(BO->getOperand(1), isConstant)))
6998 /// FindScalarElement - Given a vector and an element number, see if the scalar
6999 /// value is already around as a register, for example if it were inserted then
7000 /// extracted from the vector.
7001 static Value *FindScalarElement(Value *V, unsigned EltNo) {
7002 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7003 const PackedType *PTy = cast<PackedType>(V->getType());
7004 unsigned Width = PTy->getNumElements();
7005 if (EltNo >= Width) // Out of range access.
7006 return UndefValue::get(PTy->getElementType());
7008 if (isa<UndefValue>(V))
7009 return UndefValue::get(PTy->getElementType());
7010 else if (isa<ConstantAggregateZero>(V))
7011 return Constant::getNullValue(PTy->getElementType());
7012 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7013 return CP->getOperand(EltNo);
7014 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7015 // If this is an insert to a variable element, we don't know what it is.
7016 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7017 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7019 // If this is an insert to the element we are looking for, return the
7021 if (EltNo == IIElt) return III->getOperand(1);
7023 // Otherwise, the insertelement doesn't modify the value, recurse on its
7025 return FindScalarElement(III->getOperand(0), EltNo);
7026 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
7027 if (isa<ConstantAggregateZero>(SVI->getOperand(2))) {
7028 return FindScalarElement(SVI->getOperand(0), 0);
7029 } else if (ConstantPacked *CP =
7030 dyn_cast<ConstantPacked>(SVI->getOperand(2))) {
7031 if (isa<UndefValue>(CP->getOperand(EltNo)))
7032 return UndefValue::get(PTy->getElementType());
7033 unsigned InEl = cast<ConstantUInt>(CP->getOperand(EltNo))->getValue();
7035 return FindScalarElement(SVI->getOperand(0), InEl);
7037 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7041 // Otherwise, we don't know.
7045 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
7047 // If packed val is undef, replace extract with scalar undef.
7048 if (isa<UndefValue>(EI.getOperand(0)))
7049 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7051 // If packed val is constant 0, replace extract with scalar 0.
7052 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7053 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7055 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7056 // If packed val is constant with uniform operands, replace EI
7057 // with that operand
7058 Constant *op0 = C->getOperand(0);
7059 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7060 if (C->getOperand(i) != op0) {
7065 return ReplaceInstUsesWith(EI, op0);
7068 // If extracting a specified index from the vector, see if we can recursively
7069 // find a previously computed scalar that was inserted into the vector.
7070 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
7071 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7072 return ReplaceInstUsesWith(EI, Elt);
7075 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
7076 if (I->hasOneUse()) {
7077 // Push extractelement into predecessor operation if legal and
7078 // profitable to do so
7079 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
7080 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7081 if (CheapToScalarize(BO, isConstantElt)) {
7082 ExtractElementInst *newEI0 =
7083 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7084 EI.getName()+".lhs");
7085 ExtractElementInst *newEI1 =
7086 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7087 EI.getName()+".rhs");
7088 InsertNewInstBefore(newEI0, EI);
7089 InsertNewInstBefore(newEI1, EI);
7090 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7092 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7093 Value *Ptr = InsertCastBefore(I->getOperand(0),
7094 PointerType::get(EI.getType()), EI);
7095 GetElementPtrInst *GEP =
7096 new GetElementPtrInst(Ptr, EI.getOperand(1),
7097 I->getName() + ".gep");
7098 InsertNewInstBefore(GEP, EI);
7099 return new LoadInst(GEP);
7100 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7101 // Extracting the inserted element?
7102 if (IE->getOperand(2) == EI.getOperand(1))
7103 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7104 // If the inserted and extracted elements are constants, they must not
7105 // be the same value, extract from the pre-inserted value instead.
7106 if (isa<Constant>(IE->getOperand(2)) &&
7107 isa<Constant>(EI.getOperand(1))) {
7108 AddUsesToWorkList(EI);
7109 EI.setOperand(0, IE->getOperand(0));
7117 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7118 /// elements from either LHS or RHS, return the shuffle mask and true.
7119 /// Otherwise, return false.
7120 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7121 std::vector<Constant*> &Mask) {
7122 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7123 "Invalid CollectSingleShuffleElements");
7124 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7126 if (isa<UndefValue>(V)) {
7127 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7129 } else if (V == LHS) {
7130 for (unsigned i = 0; i != NumElts; ++i)
7131 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7133 } else if (V == RHS) {
7134 for (unsigned i = 0; i != NumElts; ++i)
7135 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7137 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7138 // If this is an insert of an extract from some other vector, include it.
7139 Value *VecOp = IEI->getOperand(0);
7140 Value *ScalarOp = IEI->getOperand(1);
7141 Value *IdxOp = IEI->getOperand(2);
7143 if (!isa<ConstantInt>(IdxOp))
7145 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7147 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7148 // Okay, we can handle this if the vector we are insertinting into is
7150 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7151 // If so, update the mask to reflect the inserted undef.
7152 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7155 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7156 if (isa<ConstantInt>(EI->getOperand(1)) &&
7157 EI->getOperand(0)->getType() == V->getType()) {
7158 unsigned ExtractedIdx =
7159 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7161 // This must be extracting from either LHS or RHS.
7162 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7163 // Okay, we can handle this if the vector we are insertinting into is
7165 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7166 // If so, update the mask to reflect the inserted value.
7167 if (EI->getOperand(0) == LHS) {
7168 Mask[InsertedIdx & (NumElts-1)] =
7169 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7171 assert(EI->getOperand(0) == RHS);
7172 Mask[InsertedIdx & (NumElts-1)] =
7173 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7182 // TODO: Handle shufflevector here!
7187 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7188 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7189 /// that computes V and the LHS value of the shuffle.
7190 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
7192 assert(isa<PackedType>(V->getType()) &&
7193 (RHS == 0 || V->getType() == RHS->getType()) &&
7194 "Invalid shuffle!");
7195 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7197 if (isa<UndefValue>(V)) {
7198 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7200 } else if (isa<ConstantAggregateZero>(V)) {
7201 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7203 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7204 // If this is an insert of an extract from some other vector, include it.
7205 Value *VecOp = IEI->getOperand(0);
7206 Value *ScalarOp = IEI->getOperand(1);
7207 Value *IdxOp = IEI->getOperand(2);
7209 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7210 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7211 EI->getOperand(0)->getType() == V->getType()) {
7212 unsigned ExtractedIdx =
7213 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7214 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7216 // Either the extracted from or inserted into vector must be RHSVec,
7217 // otherwise we'd end up with a shuffle of three inputs.
7218 if (EI->getOperand(0) == RHS || RHS == 0) {
7219 RHS = EI->getOperand(0);
7220 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
7221 Mask[InsertedIdx & (NumElts-1)] =
7222 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7227 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
7228 // Everything but the extracted element is replaced with the RHS.
7229 for (unsigned i = 0; i != NumElts; ++i) {
7230 if (i != InsertedIdx)
7231 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7236 // If this insertelement is a chain that comes from exactly these two
7237 // vectors, return the vector and the effective shuffle.
7238 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7239 return EI->getOperand(0);
7244 // TODO: Handle shufflevector here!
7246 // Otherwise, can't do anything fancy. Return an identity vector.
7247 for (unsigned i = 0; i != NumElts; ++i)
7248 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7252 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7253 Value *VecOp = IE.getOperand(0);
7254 Value *ScalarOp = IE.getOperand(1);
7255 Value *IdxOp = IE.getOperand(2);
7257 // If the inserted element was extracted from some other vector, and if the
7258 // indexes are constant, try to turn this into a shufflevector operation.
7259 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7260 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7261 EI->getOperand(0)->getType() == IE.getType()) {
7262 unsigned NumVectorElts = IE.getType()->getNumElements();
7263 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7264 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7266 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7267 return ReplaceInstUsesWith(IE, VecOp);
7269 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7270 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7272 // If we are extracting a value from a vector, then inserting it right
7273 // back into the same place, just use the input vector.
7274 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7275 return ReplaceInstUsesWith(IE, VecOp);
7277 // We could theoretically do this for ANY input. However, doing so could
7278 // turn chains of insertelement instructions into a chain of shufflevector
7279 // instructions, and right now we do not merge shufflevectors. As such,
7280 // only do this in a situation where it is clear that there is benefit.
7281 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7282 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7283 // the values of VecOp, except then one read from EIOp0.
7284 // Build a new shuffle mask.
7285 std::vector<Constant*> Mask;
7286 if (isa<UndefValue>(VecOp))
7287 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7289 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7290 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7293 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7294 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7295 ConstantPacked::get(Mask));
7298 // If this insertelement isn't used by some other insertelement, turn it
7299 // (and any insertelements it points to), into one big shuffle.
7300 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7301 std::vector<Constant*> Mask;
7303 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7304 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7305 // We now have a shuffle of LHS, RHS, Mask.
7306 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
7315 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7316 Value *LHS = SVI.getOperand(0);
7317 Value *RHS = SVI.getOperand(1);
7318 Constant *Mask = cast<Constant>(SVI.getOperand(2));
7320 bool MadeChange = false;
7322 if (isa<UndefValue>(Mask))
7323 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7325 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7326 // the undef, change them to undefs.
7328 // Canonicalize shuffle(x,x) -> shuffle(x,undef)
7330 if (isa<UndefValue>(LHS)) {
7331 // shuffle(undef,undef,mask) -> undef.
7332 return ReplaceInstUsesWith(SVI, LHS);
7335 if (!isa<ConstantAggregateZero>(Mask)) {
7336 // Remap any references to RHS to use LHS.
7337 ConstantPacked *CP = cast<ConstantPacked>(Mask);
7338 std::vector<Constant*> Elts;
7339 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7340 Elts.push_back(CP->getOperand(i));
7341 if (isa<UndefValue>(CP->getOperand(i)))
7343 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7345 Elts.back() = ConstantUInt::get(Type::UIntTy, MV & (e-1));
7347 Mask = ConstantPacked::get(Elts);
7349 SVI.setOperand(1, UndefValue::get(RHS->getType()));
7350 SVI.setOperand(2, Mask);
7354 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7355 if (isa<UndefValue>(LHS)) {
7356 // shuffle(undef,x,<0,0,0,0>) -> undef.
7357 if (isa<ConstantAggregateZero>(Mask))
7358 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7360 ConstantPacked *CPM = cast<ConstantPacked>(Mask);
7361 std::vector<Constant*> Elts;
7362 for (unsigned i = 0, e = CPM->getNumOperands(); i != e; ++i) {
7363 if (isa<UndefValue>(CPM->getOperand(i)))
7364 Elts.push_back(CPM->getOperand(i));
7366 unsigned EltNo = cast<ConstantUInt>(CPM->getOperand(i))->getRawValue();
7368 Elts.push_back(ConstantUInt::get(Type::UIntTy, EltNo-e));
7369 else // Referring to the undef.
7370 Elts.push_back(UndefValue::get(Type::UIntTy));
7373 return new ShuffleVectorInst(RHS, LHS, ConstantPacked::get(Elts));
7376 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Mask)) {
7377 bool isLHSID = true, isRHSID = true;
7379 // Analyze the shuffle.
7380 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7381 if (isa<UndefValue>(CP->getOperand(i)))
7383 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7385 // Is this an identity shuffle of the LHS value?
7386 isLHSID &= (MV == i);
7388 // Is this an identity shuffle of the RHS value?
7389 isRHSID &= (MV-e == i);
7392 // Eliminate identity shuffles.
7393 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7394 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
7397 return MadeChange ? &SVI : 0;
7402 void InstCombiner::removeFromWorkList(Instruction *I) {
7403 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7408 /// TryToSinkInstruction - Try to move the specified instruction from its
7409 /// current block into the beginning of DestBlock, which can only happen if it's
7410 /// safe to move the instruction past all of the instructions between it and the
7411 /// end of its block.
7412 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7413 assert(I->hasOneUse() && "Invariants didn't hold!");
7415 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7416 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
7418 // Do not sink alloca instructions out of the entry block.
7419 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7422 // We can only sink load instructions if there is nothing between the load and
7423 // the end of block that could change the value.
7424 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7425 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7427 if (Scan->mayWriteToMemory())
7431 BasicBlock::iterator InsertPos = DestBlock->begin();
7432 while (isa<PHINode>(InsertPos)) ++InsertPos;
7434 I->moveBefore(InsertPos);
7439 /// OptimizeConstantExpr - Given a constant expression and target data layout
7440 /// information, symbolically evaluation the constant expr to something simpler
7442 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7445 Constant *Ptr = CE->getOperand(0);
7446 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7447 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7448 // If this is a constant expr gep that is effectively computing an
7449 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7450 bool isFoldableGEP = true;
7451 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7452 if (!isa<ConstantInt>(CE->getOperand(i)))
7453 isFoldableGEP = false;
7454 if (isFoldableGEP) {
7455 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7456 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7457 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7458 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7459 return ConstantExpr::getCast(C, CE->getType());
7467 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7468 /// all reachable code to the worklist.
7470 /// This has a couple of tricks to make the code faster and more powerful. In
7471 /// particular, we constant fold and DCE instructions as we go, to avoid adding
7472 /// them to the worklist (this significantly speeds up instcombine on code where
7473 /// many instructions are dead or constant). Additionally, if we find a branch
7474 /// whose condition is a known constant, we only visit the reachable successors.
7476 static void AddReachableCodeToWorklist(BasicBlock *BB,
7477 std::set<BasicBlock*> &Visited,
7478 std::vector<Instruction*> &WorkList,
7479 const TargetData *TD) {
7480 // We have now visited this block! If we've already been here, bail out.
7481 if (!Visited.insert(BB).second) return;
7483 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7484 Instruction *Inst = BBI++;
7486 // DCE instruction if trivially dead.
7487 if (isInstructionTriviallyDead(Inst)) {
7489 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7490 Inst->eraseFromParent();
7494 // ConstantProp instruction if trivially constant.
7495 if (Constant *C = ConstantFoldInstruction(Inst)) {
7496 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7497 C = OptimizeConstantExpr(CE, TD);
7498 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7499 Inst->replaceAllUsesWith(C);
7501 Inst->eraseFromParent();
7505 WorkList.push_back(Inst);
7508 // Recursively visit successors. If this is a branch or switch on a constant,
7509 // only visit the reachable successor.
7510 TerminatorInst *TI = BB->getTerminator();
7511 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7512 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7513 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
7514 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7518 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7519 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7520 // See if this is an explicit destination.
7521 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7522 if (SI->getCaseValue(i) == Cond) {
7523 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
7527 // Otherwise it is the default destination.
7528 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
7533 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
7534 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
7537 bool InstCombiner::runOnFunction(Function &F) {
7538 bool Changed = false;
7539 TD = &getAnalysis<TargetData>();
7542 // Do a depth-first traversal of the function, populate the worklist with
7543 // the reachable instructions. Ignore blocks that are not reachable. Keep
7544 // track of which blocks we visit.
7545 std::set<BasicBlock*> Visited;
7546 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
7548 // Do a quick scan over the function. If we find any blocks that are
7549 // unreachable, remove any instructions inside of them. This prevents
7550 // the instcombine code from having to deal with some bad special cases.
7551 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7552 if (!Visited.count(BB)) {
7553 Instruction *Term = BB->getTerminator();
7554 while (Term != BB->begin()) { // Remove instrs bottom-up
7555 BasicBlock::iterator I = Term; --I;
7557 DEBUG(std::cerr << "IC: DCE: " << *I);
7560 if (!I->use_empty())
7561 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7562 I->eraseFromParent();
7567 while (!WorkList.empty()) {
7568 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7569 WorkList.pop_back();
7571 // Check to see if we can DCE the instruction.
7572 if (isInstructionTriviallyDead(I)) {
7573 // Add operands to the worklist.
7574 if (I->getNumOperands() < 4)
7575 AddUsesToWorkList(*I);
7578 DEBUG(std::cerr << "IC: DCE: " << *I);
7580 I->eraseFromParent();
7581 removeFromWorkList(I);
7585 // Instruction isn't dead, see if we can constant propagate it.
7586 if (Constant *C = ConstantFoldInstruction(I)) {
7587 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7588 C = OptimizeConstantExpr(CE, TD);
7589 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7591 // Add operands to the worklist.
7592 AddUsesToWorkList(*I);
7593 ReplaceInstUsesWith(*I, C);
7596 I->eraseFromParent();
7597 removeFromWorkList(I);
7601 // See if we can trivially sink this instruction to a successor basic block.
7602 if (I->hasOneUse()) {
7603 BasicBlock *BB = I->getParent();
7604 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7605 if (UserParent != BB) {
7606 bool UserIsSuccessor = false;
7607 // See if the user is one of our successors.
7608 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7609 if (*SI == UserParent) {
7610 UserIsSuccessor = true;
7614 // If the user is one of our immediate successors, and if that successor
7615 // only has us as a predecessors (we'd have to split the critical edge
7616 // otherwise), we can keep going.
7617 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7618 next(pred_begin(UserParent)) == pred_end(UserParent))
7619 // Okay, the CFG is simple enough, try to sink this instruction.
7620 Changed |= TryToSinkInstruction(I, UserParent);
7624 // Now that we have an instruction, try combining it to simplify it...
7625 if (Instruction *Result = visit(*I)) {
7627 // Should we replace the old instruction with a new one?
7629 DEBUG(std::cerr << "IC: Old = " << *I
7630 << " New = " << *Result);
7632 // Everything uses the new instruction now.
7633 I->replaceAllUsesWith(Result);
7635 // Push the new instruction and any users onto the worklist.
7636 WorkList.push_back(Result);
7637 AddUsersToWorkList(*Result);
7639 // Move the name to the new instruction first...
7640 std::string OldName = I->getName(); I->setName("");
7641 Result->setName(OldName);
7643 // Insert the new instruction into the basic block...
7644 BasicBlock *InstParent = I->getParent();
7645 BasicBlock::iterator InsertPos = I;
7647 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7648 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7651 InstParent->getInstList().insert(InsertPos, Result);
7653 // Make sure that we reprocess all operands now that we reduced their
7655 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7656 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7657 WorkList.push_back(OpI);
7659 // Instructions can end up on the worklist more than once. Make sure
7660 // we do not process an instruction that has been deleted.
7661 removeFromWorkList(I);
7663 // Erase the old instruction.
7664 InstParent->getInstList().erase(I);
7666 DEBUG(std::cerr << "IC: MOD = " << *I);
7668 // If the instruction was modified, it's possible that it is now dead.
7669 // if so, remove it.
7670 if (isInstructionTriviallyDead(I)) {
7671 // Make sure we process all operands now that we are reducing their
7673 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7674 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7675 WorkList.push_back(OpI);
7677 // Instructions may end up in the worklist more than once. Erase all
7678 // occurrences of this instruction.
7679 removeFromWorkList(I);
7680 I->eraseFromParent();
7682 WorkList.push_back(Result);
7683 AddUsersToWorkList(*Result);
7693 FunctionPass *llvm::createInstructionCombiningPass() {
7694 return new InstCombiner();