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);
259 Instruction *MatchBSwap(BinaryOperator &I);
261 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
264 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
267 // getComplexity: Assign a complexity or rank value to LLVM Values...
268 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
269 static unsigned getComplexity(Value *V) {
270 if (isa<Instruction>(V)) {
271 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
275 if (isa<Argument>(V)) return 3;
276 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
279 // isOnlyUse - Return true if this instruction will be deleted if we stop using
281 static bool isOnlyUse(Value *V) {
282 return V->hasOneUse() || isa<Constant>(V);
285 // getPromotedType - Return the specified type promoted as it would be to pass
286 // though a va_arg area...
287 static const Type *getPromotedType(const Type *Ty) {
288 switch (Ty->getTypeID()) {
289 case Type::SByteTyID:
290 case Type::ShortTyID: return Type::IntTy;
291 case Type::UByteTyID:
292 case Type::UShortTyID: return Type::UIntTy;
293 case Type::FloatTyID: return Type::DoubleTy;
298 /// isCast - If the specified operand is a CastInst or a constant expr cast,
299 /// return the operand value, otherwise return null.
300 static Value *isCast(Value *V) {
301 if (CastInst *I = dyn_cast<CastInst>(V))
302 return I->getOperand(0);
303 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
304 if (CE->getOpcode() == Instruction::Cast)
305 return CE->getOperand(0);
316 /// getCastType - In the future, we will split the cast instruction into these
317 /// various types. Until then, we have to do the analysis here.
318 static CastType getCastType(const Type *Src, const Type *Dest) {
319 assert(Src->isIntegral() && Dest->isIntegral() &&
320 "Only works on integral types!");
321 unsigned SrcSize = Src->getPrimitiveSizeInBits();
322 unsigned DestSize = Dest->getPrimitiveSizeInBits();
324 if (SrcSize == DestSize) return Noop;
325 if (SrcSize > DestSize) return Truncate;
326 if (Src->isSigned()) return Signext;
331 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
334 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
335 const Type *DstTy, TargetData *TD) {
337 // It is legal to eliminate the instruction if casting A->B->A if the sizes
338 // are identical and the bits don't get reinterpreted (for example
339 // int->float->int would not be allowed).
340 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
343 // If we are casting between pointer and integer types, treat pointers as
344 // integers of the appropriate size for the code below.
345 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
346 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
347 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
349 // Allow free casting and conversion of sizes as long as the sign doesn't
351 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
352 CastType FirstCast = getCastType(SrcTy, MidTy);
353 CastType SecondCast = getCastType(MidTy, DstTy);
355 // Capture the effect of these two casts. If the result is a legal cast,
356 // the CastType is stored here, otherwise a special code is used.
357 static const unsigned CastResult[] = {
358 // First cast is noop
360 // First cast is a truncate
361 1, 1, 4, 4, // trunc->extend is not safe to eliminate
362 // First cast is a sign ext
363 2, 5, 2, 4, // signext->zeroext never ok
364 // First cast is a zero ext
368 unsigned Result = CastResult[FirstCast*4+SecondCast];
370 default: assert(0 && "Illegal table value!");
375 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
376 // truncates, we could eliminate more casts.
377 return (unsigned)getCastType(SrcTy, DstTy) == Result;
379 return false; // Not possible to eliminate this here.
381 // Sign or zero extend followed by truncate is always ok if the result
382 // is a truncate or noop.
383 CastType ResultCast = getCastType(SrcTy, DstTy);
384 if (ResultCast == Noop || ResultCast == Truncate)
386 // Otherwise we are still growing the value, we are only safe if the
387 // result will match the sign/zeroextendness of the result.
388 return ResultCast == FirstCast;
392 // If this is a cast from 'float -> double -> integer', cast from
393 // 'float -> integer' directly, as the value isn't changed by the
394 // float->double conversion.
395 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
396 DstTy->isIntegral() &&
397 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
400 // Packed type conversions don't modify bits.
401 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
407 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
408 /// in any code being generated. It does not require codegen if V is simple
409 /// enough or if the cast can be folded into other casts.
410 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
411 if (V->getType() == Ty || isa<Constant>(V)) return false;
413 // If this is a noop cast, it isn't real codegen.
414 if (V->getType()->isLosslesslyConvertibleTo(Ty))
417 // If this is another cast that can be eliminated, it isn't codegen either.
418 if (const CastInst *CI = dyn_cast<CastInst>(V))
419 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
425 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
426 /// InsertBefore instruction. This is specialized a bit to avoid inserting
427 /// casts that are known to not do anything...
429 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
430 Instruction *InsertBefore) {
431 if (V->getType() == DestTy) return V;
432 if (Constant *C = dyn_cast<Constant>(V))
433 return ConstantExpr::getCast(C, DestTy);
435 CastInst *CI = new CastInst(V, DestTy, V->getName());
436 InsertNewInstBefore(CI, *InsertBefore);
440 // SimplifyCommutative - This performs a few simplifications for commutative
443 // 1. Order operands such that they are listed from right (least complex) to
444 // left (most complex). This puts constants before unary operators before
447 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
448 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
450 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
451 bool Changed = false;
452 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
453 Changed = !I.swapOperands();
455 if (!I.isAssociative()) return Changed;
456 Instruction::BinaryOps Opcode = I.getOpcode();
457 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
458 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
459 if (isa<Constant>(I.getOperand(1))) {
460 Constant *Folded = ConstantExpr::get(I.getOpcode(),
461 cast<Constant>(I.getOperand(1)),
462 cast<Constant>(Op->getOperand(1)));
463 I.setOperand(0, Op->getOperand(0));
464 I.setOperand(1, Folded);
466 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
467 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
468 isOnlyUse(Op) && isOnlyUse(Op1)) {
469 Constant *C1 = cast<Constant>(Op->getOperand(1));
470 Constant *C2 = cast<Constant>(Op1->getOperand(1));
472 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
473 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
474 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
477 WorkList.push_back(New);
478 I.setOperand(0, New);
479 I.setOperand(1, Folded);
486 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
487 // if the LHS is a constant zero (which is the 'negate' form).
489 static inline Value *dyn_castNegVal(Value *V) {
490 if (BinaryOperator::isNeg(V))
491 return BinaryOperator::getNegArgument(V);
493 // Constants can be considered to be negated values if they can be folded.
494 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
495 return ConstantExpr::getNeg(C);
499 static inline Value *dyn_castNotVal(Value *V) {
500 if (BinaryOperator::isNot(V))
501 return BinaryOperator::getNotArgument(V);
503 // Constants can be considered to be not'ed values...
504 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
505 return ConstantExpr::getNot(C);
509 // dyn_castFoldableMul - If this value is a multiply that can be folded into
510 // other computations (because it has a constant operand), return the
511 // non-constant operand of the multiply, and set CST to point to the multiplier.
512 // Otherwise, return null.
514 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
515 if (V->hasOneUse() && V->getType()->isInteger())
516 if (Instruction *I = dyn_cast<Instruction>(V)) {
517 if (I->getOpcode() == Instruction::Mul)
518 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
519 return I->getOperand(0);
520 if (I->getOpcode() == Instruction::Shl)
521 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
522 // The multiplier is really 1 << CST.
523 Constant *One = ConstantInt::get(V->getType(), 1);
524 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
525 return I->getOperand(0);
531 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
532 /// expression, return it.
533 static User *dyn_castGetElementPtr(Value *V) {
534 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
535 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
536 if (CE->getOpcode() == Instruction::GetElementPtr)
537 return cast<User>(V);
541 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
542 static ConstantInt *AddOne(ConstantInt *C) {
543 return cast<ConstantInt>(ConstantExpr::getAdd(C,
544 ConstantInt::get(C->getType(), 1)));
546 static ConstantInt *SubOne(ConstantInt *C) {
547 return cast<ConstantInt>(ConstantExpr::getSub(C,
548 ConstantInt::get(C->getType(), 1)));
551 /// GetConstantInType - Return a ConstantInt with the specified type and value.
553 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
554 if (Ty->isUnsigned())
555 return ConstantUInt::get(Ty, Val);
556 else if (Ty->getTypeID() == Type::BoolTyID)
557 return ConstantBool::get(Val);
559 SVal <<= 64-Ty->getPrimitiveSizeInBits();
560 SVal >>= 64-Ty->getPrimitiveSizeInBits();
561 return ConstantSInt::get(Ty, SVal);
565 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
566 /// known to be either zero or one and return them in the KnownZero/KnownOne
567 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
569 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
570 uint64_t &KnownOne, unsigned Depth = 0) {
571 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
572 // we cannot optimize based on the assumption that it is zero without changing
573 // it to be an explicit zero. If we don't change it to zero, other code could
574 // optimized based on the contradictory assumption that it is non-zero.
575 // Because instcombine aggressively folds operations with undef args anyway,
576 // this won't lose us code quality.
577 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
578 // We know all of the bits for a constant!
579 KnownOne = CI->getZExtValue() & Mask;
580 KnownZero = ~KnownOne & Mask;
584 KnownZero = KnownOne = 0; // Don't know anything.
585 if (Depth == 6 || Mask == 0)
586 return; // Limit search depth.
588 uint64_t KnownZero2, KnownOne2;
589 Instruction *I = dyn_cast<Instruction>(V);
592 Mask &= V->getType()->getIntegralTypeMask();
594 switch (I->getOpcode()) {
595 case Instruction::And:
596 // If either the LHS or the RHS are Zero, the result is zero.
597 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
599 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
600 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
601 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
603 // Output known-1 bits are only known if set in both the LHS & RHS.
604 KnownOne &= KnownOne2;
605 // Output known-0 are known to be clear if zero in either the LHS | RHS.
606 KnownZero |= KnownZero2;
608 case Instruction::Or:
609 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
611 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
612 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
613 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
615 // Output known-0 bits are only known if clear in both the LHS & RHS.
616 KnownZero &= KnownZero2;
617 // Output known-1 are known to be set if set in either the LHS | RHS.
618 KnownOne |= KnownOne2;
620 case Instruction::Xor: {
621 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
622 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
623 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
624 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
626 // Output known-0 bits are known if clear or set in both the LHS & RHS.
627 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
628 // Output known-1 are known to be set if set in only one of the LHS, RHS.
629 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
630 KnownZero = KnownZeroOut;
633 case Instruction::Select:
634 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
635 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
636 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
637 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
639 // Only known if known in both the LHS and RHS.
640 KnownOne &= KnownOne2;
641 KnownZero &= KnownZero2;
643 case Instruction::Cast: {
644 const Type *SrcTy = I->getOperand(0)->getType();
645 if (!SrcTy->isIntegral()) return;
647 // If this is an integer truncate or noop, just look in the input.
648 if (SrcTy->getPrimitiveSizeInBits() >=
649 I->getType()->getPrimitiveSizeInBits()) {
650 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654 // Sign or Zero extension. Compute the bits in the result that are not
655 // present in the input.
656 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
657 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
659 // Handle zero extension.
660 if (!SrcTy->isSigned()) {
661 Mask &= SrcTy->getIntegralTypeMask();
662 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
663 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
664 // The top bits are known to be zero.
665 KnownZero |= NewBits;
668 Mask &= SrcTy->getIntegralTypeMask();
669 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
670 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
672 // If the sign bit of the input is known set or clear, then we know the
673 // top bits of the result.
674 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
675 if (KnownZero & InSignBit) { // Input sign bit known zero
676 KnownZero |= NewBits;
677 KnownOne &= ~NewBits;
678 } else if (KnownOne & InSignBit) { // Input sign bit known set
680 KnownZero &= ~NewBits;
681 } else { // Input sign bit unknown
682 KnownZero &= ~NewBits;
683 KnownOne &= ~NewBits;
688 case Instruction::Shl:
689 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
690 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
691 Mask >>= SA->getValue();
692 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
693 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
694 KnownZero <<= SA->getValue();
695 KnownOne <<= SA->getValue();
696 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
700 case Instruction::Shr:
701 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
702 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
703 // Compute the new bits that are at the top now.
704 uint64_t HighBits = (1ULL << SA->getValue())-1;
705 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
707 if (I->getType()->isUnsigned()) { // Unsigned shift right.
708 Mask <<= SA->getValue();
709 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
710 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
711 KnownZero >>= SA->getValue();
712 KnownOne >>= SA->getValue();
713 KnownZero |= HighBits; // high bits known zero.
715 Mask <<= SA->getValue();
716 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
717 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
718 KnownZero >>= SA->getValue();
719 KnownOne >>= SA->getValue();
721 // Handle the sign bits.
722 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
723 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
725 if (KnownZero & SignBit) { // New bits are known zero.
726 KnownZero |= HighBits;
727 } else if (KnownOne & SignBit) { // New bits are known one.
728 KnownOne |= HighBits;
737 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
738 /// this predicate to simplify operations downstream. Mask is known to be zero
739 /// for bits that V cannot have.
740 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
741 uint64_t KnownZero, KnownOne;
742 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
743 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
744 return (KnownZero & Mask) == Mask;
747 /// ShrinkDemandedConstant - Check to see if the specified operand of the
748 /// specified instruction is a constant integer. If so, check to see if there
749 /// are any bits set in the constant that are not demanded. If so, shrink the
750 /// constant and return true.
751 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
753 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
754 if (!OpC) return false;
756 // If there are no bits set that aren't demanded, nothing to do.
757 if ((~Demanded & OpC->getZExtValue()) == 0)
760 // This is producing any bits that are not needed, shrink the RHS.
761 uint64_t Val = Demanded & OpC->getZExtValue();
762 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
766 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
767 // set of known zero and one bits, compute the maximum and minimum values that
768 // could have the specified known zero and known one bits, returning them in
770 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
773 int64_t &Min, int64_t &Max) {
774 uint64_t TypeBits = Ty->getIntegralTypeMask();
775 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
777 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
779 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
780 // bit if it is unknown.
782 Max = KnownOne|UnknownBits;
784 if (SignBit & UnknownBits) { // Sign bit is unknown
789 // Sign extend the min/max values.
790 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
791 Min = (Min << ShAmt) >> ShAmt;
792 Max = (Max << ShAmt) >> ShAmt;
795 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
796 // a set of known zero and one bits, compute the maximum and minimum values that
797 // could have the specified known zero and known one bits, returning them in
799 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
804 uint64_t TypeBits = Ty->getIntegralTypeMask();
805 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
807 // The minimum value is when the unknown bits are all zeros.
809 // The maximum value is when the unknown bits are all ones.
810 Max = KnownOne|UnknownBits;
814 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
815 /// DemandedMask bits of the result of V are ever used downstream. If we can
816 /// use this information to simplify V, do so and return true. Otherwise,
817 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
818 /// the expression (used to simplify the caller). The KnownZero/One bits may
819 /// only be accurate for those bits in the DemandedMask.
820 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
821 uint64_t &KnownZero, uint64_t &KnownOne,
823 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
824 // We know all of the bits for a constant!
825 KnownOne = CI->getZExtValue() & DemandedMask;
826 KnownZero = ~KnownOne & DemandedMask;
830 KnownZero = KnownOne = 0;
831 if (!V->hasOneUse()) { // Other users may use these bits.
832 if (Depth != 0) { // Not at the root.
833 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
834 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
837 // If this is the root being simplified, allow it to have multiple uses,
838 // just set the DemandedMask to all bits.
839 DemandedMask = V->getType()->getIntegralTypeMask();
840 } else if (DemandedMask == 0) { // Not demanding any bits from V.
841 if (V != UndefValue::get(V->getType()))
842 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
844 } else if (Depth == 6) { // Limit search depth.
848 Instruction *I = dyn_cast<Instruction>(V);
849 if (!I) return false; // Only analyze instructions.
851 DemandedMask &= V->getType()->getIntegralTypeMask();
853 uint64_t KnownZero2, KnownOne2;
854 switch (I->getOpcode()) {
856 case Instruction::And:
857 // If either the LHS or the RHS are Zero, the result is zero.
858 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
859 KnownZero, KnownOne, Depth+1))
861 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
863 // If something is known zero on the RHS, the bits aren't demanded on the
865 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
866 KnownZero2, KnownOne2, Depth+1))
868 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
870 // If all of the demanded bits are known one on one side, return the other.
871 // These bits cannot contribute to the result of the 'and'.
872 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
873 return UpdateValueUsesWith(I, I->getOperand(0));
874 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
875 return UpdateValueUsesWith(I, I->getOperand(1));
877 // If all of the demanded bits in the inputs are known zeros, return zero.
878 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
879 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
881 // If the RHS is a constant, see if we can simplify it.
882 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
883 return UpdateValueUsesWith(I, I);
885 // Output known-1 bits are only known if set in both the LHS & RHS.
886 KnownOne &= KnownOne2;
887 // Output known-0 are known to be clear if zero in either the LHS | RHS.
888 KnownZero |= KnownZero2;
890 case Instruction::Or:
891 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892 KnownZero, KnownOne, Depth+1))
894 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
895 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
896 KnownZero2, KnownOne2, Depth+1))
898 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
900 // If all of the demanded bits are known zero on one side, return the other.
901 // These bits cannot contribute to the result of the 'or'.
902 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
903 return UpdateValueUsesWith(I, I->getOperand(0));
904 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
905 return UpdateValueUsesWith(I, I->getOperand(1));
907 // If all of the potentially set bits on one side are known to be set on
908 // the other side, just use the 'other' side.
909 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
910 (DemandedMask & (~KnownZero)))
911 return UpdateValueUsesWith(I, I->getOperand(0));
912 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
913 (DemandedMask & (~KnownZero2)))
914 return UpdateValueUsesWith(I, I->getOperand(1));
916 // If the RHS is a constant, see if we can simplify it.
917 if (ShrinkDemandedConstant(I, 1, DemandedMask))
918 return UpdateValueUsesWith(I, I);
920 // Output known-0 bits are only known if clear in both the LHS & RHS.
921 KnownZero &= KnownZero2;
922 // Output known-1 are known to be set if set in either the LHS | RHS.
923 KnownOne |= KnownOne2;
925 case Instruction::Xor: {
926 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
927 KnownZero, KnownOne, Depth+1))
929 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
930 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
931 KnownZero2, KnownOne2, Depth+1))
933 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
935 // If all of the demanded bits are known zero on one side, return the other.
936 // These bits cannot contribute to the result of the 'xor'.
937 if ((DemandedMask & KnownZero) == DemandedMask)
938 return UpdateValueUsesWith(I, I->getOperand(0));
939 if ((DemandedMask & KnownZero2) == DemandedMask)
940 return UpdateValueUsesWith(I, I->getOperand(1));
942 // Output known-0 bits are known if clear or set in both the LHS & RHS.
943 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
944 // Output known-1 are known to be set if set in only one of the LHS, RHS.
945 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
947 // If all of the unknown bits are known to be zero on one side or the other
948 // (but not both) turn this into an *inclusive* or.
949 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
950 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
951 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
953 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
955 InsertNewInstBefore(Or, *I);
956 return UpdateValueUsesWith(I, Or);
960 // If all of the demanded bits on one side are known, and all of the set
961 // bits on that side are also known to be set on the other side, turn this
962 // into an AND, as we know the bits will be cleared.
963 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
964 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
965 if ((KnownOne & KnownOne2) == KnownOne) {
966 Constant *AndC = GetConstantInType(I->getType(),
967 ~KnownOne & DemandedMask);
969 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
970 InsertNewInstBefore(And, *I);
971 return UpdateValueUsesWith(I, And);
975 // If the RHS is a constant, see if we can simplify it.
976 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
977 if (ShrinkDemandedConstant(I, 1, DemandedMask))
978 return UpdateValueUsesWith(I, I);
980 KnownZero = KnownZeroOut;
981 KnownOne = KnownOneOut;
984 case Instruction::Select:
985 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
986 KnownZero, KnownOne, Depth+1))
988 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
989 KnownZero2, KnownOne2, Depth+1))
991 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
992 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
994 // If the operands are constants, see if we can simplify them.
995 if (ShrinkDemandedConstant(I, 1, DemandedMask))
996 return UpdateValueUsesWith(I, I);
997 if (ShrinkDemandedConstant(I, 2, DemandedMask))
998 return UpdateValueUsesWith(I, I);
1000 // Only known if known in both the LHS and RHS.
1001 KnownOne &= KnownOne2;
1002 KnownZero &= KnownZero2;
1004 case Instruction::Cast: {
1005 const Type *SrcTy = I->getOperand(0)->getType();
1006 if (!SrcTy->isIntegral()) return false;
1008 // If this is an integer truncate or noop, just look in the input.
1009 if (SrcTy->getPrimitiveSizeInBits() >=
1010 I->getType()->getPrimitiveSizeInBits()) {
1011 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1012 KnownZero, KnownOne, Depth+1))
1014 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1018 // Sign or Zero extension. Compute the bits in the result that are not
1019 // present in the input.
1020 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1021 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1023 // Handle zero extension.
1024 if (!SrcTy->isSigned()) {
1025 DemandedMask &= SrcTy->getIntegralTypeMask();
1026 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1027 KnownZero, KnownOne, Depth+1))
1029 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1030 // The top bits are known to be zero.
1031 KnownZero |= NewBits;
1034 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1035 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1037 // If any of the sign extended bits are demanded, we know that the sign
1039 if (NewBits & DemandedMask)
1040 InputDemandedBits |= InSignBit;
1042 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1043 KnownZero, KnownOne, Depth+1))
1045 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1047 // If the sign bit of the input is known set or clear, then we know the
1048 // top bits of the result.
1050 // If the input sign bit is known zero, or if the NewBits are not demanded
1051 // convert this into a zero extension.
1052 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1053 // Convert to unsigned first.
1054 Instruction *NewVal;
1055 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
1056 I->getOperand(0)->getName());
1057 InsertNewInstBefore(NewVal, *I);
1058 // Then cast that to the destination type.
1059 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1060 InsertNewInstBefore(NewVal, *I);
1061 return UpdateValueUsesWith(I, NewVal);
1062 } else if (KnownOne & InSignBit) { // Input sign bit known set
1063 KnownOne |= NewBits;
1064 KnownZero &= ~NewBits;
1065 } else { // Input sign bit unknown
1066 KnownZero &= ~NewBits;
1067 KnownOne &= ~NewBits;
1072 case Instruction::Shl:
1073 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1074 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1075 KnownZero, KnownOne, Depth+1))
1077 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1078 KnownZero <<= SA->getValue();
1079 KnownOne <<= SA->getValue();
1080 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1083 case Instruction::Shr:
1084 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1085 unsigned ShAmt = SA->getValue();
1087 // Compute the new bits that are at the top now.
1088 uint64_t HighBits = (1ULL << ShAmt)-1;
1089 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
1090 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1091 if (I->getType()->isUnsigned()) { // Unsigned shift right.
1092 if (SimplifyDemandedBits(I->getOperand(0),
1093 (DemandedMask << ShAmt) & TypeMask,
1094 KnownZero, KnownOne, Depth+1))
1096 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1097 KnownZero &= TypeMask;
1098 KnownOne &= TypeMask;
1099 KnownZero >>= ShAmt;
1101 KnownZero |= HighBits; // high bits known zero.
1102 } else { // Signed shift right.
1103 if (SimplifyDemandedBits(I->getOperand(0),
1104 (DemandedMask << ShAmt) & TypeMask,
1105 KnownZero, KnownOne, Depth+1))
1107 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1108 KnownZero &= TypeMask;
1109 KnownOne &= TypeMask;
1110 KnownZero >>= SA->getValue();
1111 KnownOne >>= SA->getValue();
1113 // Handle the sign bits.
1114 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1115 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1117 // If the input sign bit is known to be zero, or if none of the top bits
1118 // are demanded, turn this into an unsigned shift right.
1119 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1120 // Convert the input to unsigned.
1121 Instruction *NewVal;
1122 NewVal = new CastInst(I->getOperand(0),
1123 I->getType()->getUnsignedVersion(),
1124 I->getOperand(0)->getName());
1125 InsertNewInstBefore(NewVal, *I);
1126 // Perform the unsigned shift right.
1127 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1128 InsertNewInstBefore(NewVal, *I);
1129 // Then cast that to the destination type.
1130 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1131 InsertNewInstBefore(NewVal, *I);
1132 return UpdateValueUsesWith(I, NewVal);
1133 } else if (KnownOne & SignBit) { // New bits are known one.
1134 KnownOne |= HighBits;
1141 // If the client is only demanding bits that we know, return the known
1143 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1144 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1148 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1149 // true when both operands are equal...
1151 static bool isTrueWhenEqual(Instruction &I) {
1152 return I.getOpcode() == Instruction::SetEQ ||
1153 I.getOpcode() == Instruction::SetGE ||
1154 I.getOpcode() == Instruction::SetLE;
1157 /// AssociativeOpt - Perform an optimization on an associative operator. This
1158 /// function is designed to check a chain of associative operators for a
1159 /// potential to apply a certain optimization. Since the optimization may be
1160 /// applicable if the expression was reassociated, this checks the chain, then
1161 /// reassociates the expression as necessary to expose the optimization
1162 /// opportunity. This makes use of a special Functor, which must define
1163 /// 'shouldApply' and 'apply' methods.
1165 template<typename Functor>
1166 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1167 unsigned Opcode = Root.getOpcode();
1168 Value *LHS = Root.getOperand(0);
1170 // Quick check, see if the immediate LHS matches...
1171 if (F.shouldApply(LHS))
1172 return F.apply(Root);
1174 // Otherwise, if the LHS is not of the same opcode as the root, return.
1175 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1176 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1177 // Should we apply this transform to the RHS?
1178 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1180 // If not to the RHS, check to see if we should apply to the LHS...
1181 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1182 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1186 // If the functor wants to apply the optimization to the RHS of LHSI,
1187 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1189 BasicBlock *BB = Root.getParent();
1191 // Now all of the instructions are in the current basic block, go ahead
1192 // and perform the reassociation.
1193 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1195 // First move the selected RHS to the LHS of the root...
1196 Root.setOperand(0, LHSI->getOperand(1));
1198 // Make what used to be the LHS of the root be the user of the root...
1199 Value *ExtraOperand = TmpLHSI->getOperand(1);
1200 if (&Root == TmpLHSI) {
1201 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1204 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1205 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1206 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1207 BasicBlock::iterator ARI = &Root; ++ARI;
1208 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1211 // Now propagate the ExtraOperand down the chain of instructions until we
1213 while (TmpLHSI != LHSI) {
1214 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1215 // Move the instruction to immediately before the chain we are
1216 // constructing to avoid breaking dominance properties.
1217 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1218 BB->getInstList().insert(ARI, NextLHSI);
1221 Value *NextOp = NextLHSI->getOperand(1);
1222 NextLHSI->setOperand(1, ExtraOperand);
1224 ExtraOperand = NextOp;
1227 // Now that the instructions are reassociated, have the functor perform
1228 // the transformation...
1229 return F.apply(Root);
1232 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1238 // AddRHS - Implements: X + X --> X << 1
1241 AddRHS(Value *rhs) : RHS(rhs) {}
1242 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1243 Instruction *apply(BinaryOperator &Add) const {
1244 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1245 ConstantInt::get(Type::UByteTy, 1));
1249 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1251 struct AddMaskingAnd {
1253 AddMaskingAnd(Constant *c) : C2(c) {}
1254 bool shouldApply(Value *LHS) const {
1256 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1257 ConstantExpr::getAnd(C1, C2)->isNullValue();
1259 Instruction *apply(BinaryOperator &Add) const {
1260 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1264 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1266 if (isa<CastInst>(I)) {
1267 if (Constant *SOC = dyn_cast<Constant>(SO))
1268 return ConstantExpr::getCast(SOC, I.getType());
1270 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1271 SO->getName() + ".cast"), I);
1274 // Figure out if the constant is the left or the right argument.
1275 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1276 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1278 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1280 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1281 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1284 Value *Op0 = SO, *Op1 = ConstOperand;
1286 std::swap(Op0, Op1);
1288 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1289 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1290 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1291 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1293 assert(0 && "Unknown binary instruction type!");
1296 return IC->InsertNewInstBefore(New, I);
1299 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1300 // constant as the other operand, try to fold the binary operator into the
1301 // select arguments. This also works for Cast instructions, which obviously do
1302 // not have a second operand.
1303 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1305 // Don't modify shared select instructions
1306 if (!SI->hasOneUse()) return 0;
1307 Value *TV = SI->getOperand(1);
1308 Value *FV = SI->getOperand(2);
1310 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1311 // Bool selects with constant operands can be folded to logical ops.
1312 if (SI->getType() == Type::BoolTy) return 0;
1314 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1315 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1317 return new SelectInst(SI->getCondition(), SelectTrueVal,
1324 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1325 /// node as operand #0, see if we can fold the instruction into the PHI (which
1326 /// is only possible if all operands to the PHI are constants).
1327 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1328 PHINode *PN = cast<PHINode>(I.getOperand(0));
1329 unsigned NumPHIValues = PN->getNumIncomingValues();
1330 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1331 !isa<Constant>(PN->getIncomingValue(0))) return 0;
1333 // Check to see if all of the operands of the PHI are constants. If not, we
1334 // cannot do the transformation.
1335 for (unsigned i = 1; i != NumPHIValues; ++i)
1336 if (!isa<Constant>(PN->getIncomingValue(i)))
1339 // Okay, we can do the transformation: create the new PHI node.
1340 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1342 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1343 InsertNewInstBefore(NewPN, *PN);
1345 // Next, add all of the operands to the PHI.
1346 if (I.getNumOperands() == 2) {
1347 Constant *C = cast<Constant>(I.getOperand(1));
1348 for (unsigned i = 0; i != NumPHIValues; ++i) {
1349 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1350 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1351 PN->getIncomingBlock(i));
1354 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1355 const Type *RetTy = I.getType();
1356 for (unsigned i = 0; i != NumPHIValues; ++i) {
1357 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1358 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1359 PN->getIncomingBlock(i));
1362 return ReplaceInstUsesWith(I, NewPN);
1365 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1366 bool Changed = SimplifyCommutative(I);
1367 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1369 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1370 // X + undef -> undef
1371 if (isa<UndefValue>(RHS))
1372 return ReplaceInstUsesWith(I, RHS);
1375 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1376 if (RHSC->isNullValue())
1377 return ReplaceInstUsesWith(I, LHS);
1378 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1379 if (CFP->isExactlyValue(-0.0))
1380 return ReplaceInstUsesWith(I, LHS);
1383 // X + (signbit) --> X ^ signbit
1384 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1385 uint64_t Val = CI->getZExtValue();
1386 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1387 return BinaryOperator::createXor(LHS, RHS);
1390 if (isa<PHINode>(LHS))
1391 if (Instruction *NV = FoldOpIntoPhi(I))
1394 ConstantInt *XorRHS = 0;
1396 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1397 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1398 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1399 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1401 uint64_t C0080Val = 1ULL << 31;
1402 int64_t CFF80Val = -C0080Val;
1405 if (TySizeBits > Size) {
1407 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1408 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1409 if (RHSSExt == CFF80Val) {
1410 if (XorRHS->getZExtValue() == C0080Val)
1412 } else if (RHSZExt == C0080Val) {
1413 if (XorRHS->getSExtValue() == CFF80Val)
1417 // This is a sign extend if the top bits are known zero.
1418 uint64_t Mask = ~0ULL;
1419 Mask <<= 64-(TySizeBits-Size);
1420 Mask &= XorLHS->getType()->getIntegralTypeMask();
1421 if (!MaskedValueIsZero(XorLHS, Mask))
1422 Size = 0; // Not a sign ext, but can't be any others either.
1429 } while (Size >= 8);
1432 const Type *MiddleType = 0;
1435 case 32: MiddleType = Type::IntTy; break;
1436 case 16: MiddleType = Type::ShortTy; break;
1437 case 8: MiddleType = Type::SByteTy; break;
1440 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1441 InsertNewInstBefore(NewTrunc, I);
1442 return new CastInst(NewTrunc, I.getType());
1448 if (I.getType()->isInteger()) {
1449 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1451 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1452 if (RHSI->getOpcode() == Instruction::Sub)
1453 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1454 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1456 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1457 if (LHSI->getOpcode() == Instruction::Sub)
1458 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1459 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1464 if (Value *V = dyn_castNegVal(LHS))
1465 return BinaryOperator::createSub(RHS, V);
1468 if (!isa<Constant>(RHS))
1469 if (Value *V = dyn_castNegVal(RHS))
1470 return BinaryOperator::createSub(LHS, V);
1474 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1475 if (X == RHS) // X*C + X --> X * (C+1)
1476 return BinaryOperator::createMul(RHS, AddOne(C2));
1478 // X*C1 + X*C2 --> X * (C1+C2)
1480 if (X == dyn_castFoldableMul(RHS, C1))
1481 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1484 // X + X*C --> X * (C+1)
1485 if (dyn_castFoldableMul(RHS, C2) == LHS)
1486 return BinaryOperator::createMul(LHS, AddOne(C2));
1489 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1490 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1491 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1493 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1495 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1496 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1497 return BinaryOperator::createSub(C, X);
1500 // (X & FF00) + xx00 -> (X+xx00) & FF00
1501 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1502 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1503 if (Anded == CRHS) {
1504 // See if all bits from the first bit set in the Add RHS up are included
1505 // in the mask. First, get the rightmost bit.
1506 uint64_t AddRHSV = CRHS->getRawValue();
1508 // Form a mask of all bits from the lowest bit added through the top.
1509 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1510 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1512 // See if the and mask includes all of these bits.
1513 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
1515 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1516 // Okay, the xform is safe. Insert the new add pronto.
1517 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1518 LHS->getName()), I);
1519 return BinaryOperator::createAnd(NewAdd, C2);
1524 // Try to fold constant add into select arguments.
1525 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1526 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1530 return Changed ? &I : 0;
1533 // isSignBit - Return true if the value represented by the constant only has the
1534 // highest order bit set.
1535 static bool isSignBit(ConstantInt *CI) {
1536 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1537 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1540 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1542 static Value *RemoveNoopCast(Value *V) {
1543 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1544 const Type *CTy = CI->getType();
1545 const Type *OpTy = CI->getOperand(0)->getType();
1546 if (CTy->isInteger() && OpTy->isInteger()) {
1547 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1548 return RemoveNoopCast(CI->getOperand(0));
1549 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1550 return RemoveNoopCast(CI->getOperand(0));
1555 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1558 if (Op0 == Op1) // sub X, X -> 0
1559 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1561 // If this is a 'B = x-(-A)', change to B = x+A...
1562 if (Value *V = dyn_castNegVal(Op1))
1563 return BinaryOperator::createAdd(Op0, V);
1565 if (isa<UndefValue>(Op0))
1566 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1567 if (isa<UndefValue>(Op1))
1568 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1570 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1571 // Replace (-1 - A) with (~A)...
1572 if (C->isAllOnesValue())
1573 return BinaryOperator::createNot(Op1);
1575 // C - ~X == X + (1+C)
1577 if (match(Op1, m_Not(m_Value(X))))
1578 return BinaryOperator::createAdd(X,
1579 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1580 // -((uint)X >> 31) -> ((int)X >> 31)
1581 // -((int)X >> 31) -> ((uint)X >> 31)
1582 if (C->isNullValue()) {
1583 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1584 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1585 if (SI->getOpcode() == Instruction::Shr)
1586 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1588 if (SI->getType()->isSigned())
1589 NewTy = SI->getType()->getUnsignedVersion();
1591 NewTy = SI->getType()->getSignedVersion();
1592 // Check to see if we are shifting out everything but the sign bit.
1593 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
1594 // Ok, the transformation is safe. Insert a cast of the incoming
1595 // value, then the new shift, then the new cast.
1596 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1597 SI->getOperand(0)->getName());
1598 Value *InV = InsertNewInstBefore(FirstCast, I);
1599 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1601 if (NewShift->getType() == I.getType())
1604 InV = InsertNewInstBefore(NewShift, I);
1605 return new CastInst(NewShift, I.getType());
1611 // Try to fold constant sub into select arguments.
1612 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1613 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1616 if (isa<PHINode>(Op0))
1617 if (Instruction *NV = FoldOpIntoPhi(I))
1621 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1622 if (Op1I->getOpcode() == Instruction::Add &&
1623 !Op0->getType()->isFloatingPoint()) {
1624 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1625 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1626 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1627 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1628 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1629 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1630 // C1-(X+C2) --> (C1-C2)-X
1631 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1632 Op1I->getOperand(0));
1636 if (Op1I->hasOneUse()) {
1637 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1638 // is not used by anyone else...
1640 if (Op1I->getOpcode() == Instruction::Sub &&
1641 !Op1I->getType()->isFloatingPoint()) {
1642 // Swap the two operands of the subexpr...
1643 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1644 Op1I->setOperand(0, IIOp1);
1645 Op1I->setOperand(1, IIOp0);
1647 // Create the new top level add instruction...
1648 return BinaryOperator::createAdd(Op0, Op1);
1651 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1653 if (Op1I->getOpcode() == Instruction::And &&
1654 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1655 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1658 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1659 return BinaryOperator::createAnd(Op0, NewNot);
1662 // -(X sdiv C) -> (X sdiv -C)
1663 if (Op1I->getOpcode() == Instruction::Div)
1664 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1665 if (CSI->isNullValue())
1666 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1667 return BinaryOperator::createDiv(Op1I->getOperand(0),
1668 ConstantExpr::getNeg(DivRHS));
1670 // X - X*C --> X * (1-C)
1671 ConstantInt *C2 = 0;
1672 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1674 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1675 return BinaryOperator::createMul(Op0, CP1);
1680 if (!Op0->getType()->isFloatingPoint())
1681 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1682 if (Op0I->getOpcode() == Instruction::Add) {
1683 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1684 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1685 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1686 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1687 } else if (Op0I->getOpcode() == Instruction::Sub) {
1688 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1689 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1693 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1694 if (X == Op1) { // X*C - X --> X * (C-1)
1695 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1696 return BinaryOperator::createMul(Op1, CP1);
1699 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1700 if (X == dyn_castFoldableMul(Op1, C2))
1701 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1706 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1707 /// really just returns true if the most significant (sign) bit is set.
1708 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1709 if (RHS->getType()->isSigned()) {
1710 // True if source is LHS < 0 or LHS <= -1
1711 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1712 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1714 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1715 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1716 // the size of the integer type.
1717 if (Opcode == Instruction::SetGE)
1718 return RHSC->getValue() ==
1719 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1720 if (Opcode == Instruction::SetGT)
1721 return RHSC->getValue() ==
1722 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1727 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1728 bool Changed = SimplifyCommutative(I);
1729 Value *Op0 = I.getOperand(0);
1731 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1732 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1734 // Simplify mul instructions with a constant RHS...
1735 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1736 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1738 // ((X << C1)*C2) == (X * (C2 << C1))
1739 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1740 if (SI->getOpcode() == Instruction::Shl)
1741 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1742 return BinaryOperator::createMul(SI->getOperand(0),
1743 ConstantExpr::getShl(CI, ShOp));
1745 if (CI->isNullValue())
1746 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1747 if (CI->equalsInt(1)) // X * 1 == X
1748 return ReplaceInstUsesWith(I, Op0);
1749 if (CI->isAllOnesValue()) // X * -1 == 0 - X
1750 return BinaryOperator::createNeg(Op0, I.getName());
1752 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1753 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1754 uint64_t C = Log2_64(Val);
1755 return new ShiftInst(Instruction::Shl, Op0,
1756 ConstantUInt::get(Type::UByteTy, C));
1758 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1759 if (Op1F->isNullValue())
1760 return ReplaceInstUsesWith(I, Op1);
1762 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1763 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1764 if (Op1F->getValue() == 1.0)
1765 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1768 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1769 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1770 isa<ConstantInt>(Op0I->getOperand(1))) {
1771 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1772 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1774 InsertNewInstBefore(Add, I);
1775 Value *C1C2 = ConstantExpr::getMul(Op1,
1776 cast<Constant>(Op0I->getOperand(1)));
1777 return BinaryOperator::createAdd(Add, C1C2);
1781 // Try to fold constant mul into select arguments.
1782 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1783 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1786 if (isa<PHINode>(Op0))
1787 if (Instruction *NV = FoldOpIntoPhi(I))
1791 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1792 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1793 return BinaryOperator::createMul(Op0v, Op1v);
1795 // If one of the operands of the multiply is a cast from a boolean value, then
1796 // we know the bool is either zero or one, so this is a 'masking' multiply.
1797 // See if we can simplify things based on how the boolean was originally
1799 CastInst *BoolCast = 0;
1800 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1801 if (CI->getOperand(0)->getType() == Type::BoolTy)
1804 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1805 if (CI->getOperand(0)->getType() == Type::BoolTy)
1808 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1809 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1810 const Type *SCOpTy = SCIOp0->getType();
1812 // If the setcc is true iff the sign bit of X is set, then convert this
1813 // multiply into a shift/and combination.
1814 if (isa<ConstantInt>(SCIOp1) &&
1815 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1816 // Shift the X value right to turn it into "all signbits".
1817 Constant *Amt = ConstantUInt::get(Type::UByteTy,
1818 SCOpTy->getPrimitiveSizeInBits()-1);
1819 if (SCIOp0->getType()->isUnsigned()) {
1820 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1821 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1822 SCIOp0->getName()), I);
1826 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1827 BoolCast->getOperand(0)->getName()+
1830 // If the multiply type is not the same as the source type, sign extend
1831 // or truncate to the multiply type.
1832 if (I.getType() != V->getType())
1833 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1835 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1836 return BinaryOperator::createAnd(V, OtherOp);
1841 return Changed ? &I : 0;
1844 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1845 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1847 if (isa<UndefValue>(Op0)) // undef / X -> 0
1848 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1849 if (isa<UndefValue>(Op1))
1850 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1852 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1854 if (RHS->equalsInt(1))
1855 return ReplaceInstUsesWith(I, Op0);
1858 if (RHS->isAllOnesValue())
1859 return BinaryOperator::createNeg(Op0);
1861 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1862 if (LHS->getOpcode() == Instruction::Div)
1863 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1864 // (X / C1) / C2 -> X / (C1*C2)
1865 return BinaryOperator::createDiv(LHS->getOperand(0),
1866 ConstantExpr::getMul(RHS, LHSRHS));
1869 // Check to see if this is an unsigned division with an exact power of 2,
1870 // if so, convert to a right shift.
1871 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1872 if (uint64_t Val = C->getValue()) // Don't break X / 0
1873 if (isPowerOf2_64(Val)) {
1874 uint64_t C = Log2_64(Val);
1875 return new ShiftInst(Instruction::Shr, Op0,
1876 ConstantUInt::get(Type::UByteTy, C));
1880 if (RHS->getType()->isSigned())
1881 if (Value *LHSNeg = dyn_castNegVal(Op0))
1882 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1884 if (!RHS->isNullValue()) {
1885 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1886 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1888 if (isa<PHINode>(Op0))
1889 if (Instruction *NV = FoldOpIntoPhi(I))
1894 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1895 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1896 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1897 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1898 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1899 if (STO->getValue() == 0) { // Couldn't be this argument.
1900 I.setOperand(1, SFO);
1902 } else if (SFO->getValue() == 0) {
1903 I.setOperand(1, STO);
1907 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1908 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1909 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1910 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1911 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1912 TC, SI->getName()+".t");
1913 TSI = InsertNewInstBefore(TSI, I);
1915 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1916 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1917 FC, SI->getName()+".f");
1918 FSI = InsertNewInstBefore(FSI, I);
1919 return new SelectInst(SI->getOperand(0), TSI, FSI);
1923 // 0 / X == 0, we don't need to preserve faults!
1924 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1925 if (LHS->equalsInt(0))
1926 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1928 if (I.getType()->isSigned()) {
1929 // If the sign bits of both operands are zero (i.e. we can prove they are
1930 // unsigned inputs), turn this into a udiv.
1931 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1932 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1933 const Type *NTy = Op0->getType()->getUnsignedVersion();
1934 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1935 InsertNewInstBefore(LHS, I);
1937 if (Constant *R = dyn_cast<Constant>(Op1))
1938 RHS = ConstantExpr::getCast(R, NTy);
1940 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1941 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1942 InsertNewInstBefore(Div, I);
1943 return new CastInst(Div, I.getType());
1946 // Known to be an unsigned division.
1947 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1948 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1949 if (RHSI->getOpcode() == Instruction::Shl &&
1950 isa<ConstantUInt>(RHSI->getOperand(0))) {
1951 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1952 if (isPowerOf2_64(C1)) {
1953 unsigned C2 = Log2_64(C1);
1954 Value *Add = RHSI->getOperand(1);
1956 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1957 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1960 return new ShiftInst(Instruction::Shr, Op0, Add);
1970 /// GetFactor - If we can prove that the specified value is at least a multiple
1971 /// of some factor, return that factor.
1972 static Constant *GetFactor(Value *V) {
1973 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1976 // Unless we can be tricky, we know this is a multiple of 1.
1977 Constant *Result = ConstantInt::get(V->getType(), 1);
1979 Instruction *I = dyn_cast<Instruction>(V);
1980 if (!I) return Result;
1982 if (I->getOpcode() == Instruction::Mul) {
1983 // Handle multiplies by a constant, etc.
1984 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1985 GetFactor(I->getOperand(1)));
1986 } else if (I->getOpcode() == Instruction::Shl) {
1987 // (X<<C) -> X * (1 << C)
1988 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1989 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1990 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1992 } else if (I->getOpcode() == Instruction::And) {
1993 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1994 // X & 0xFFF0 is known to be a multiple of 16.
1995 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1996 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1997 return ConstantExpr::getShl(Result,
1998 ConstantUInt::get(Type::UByteTy, Zeros));
2000 } else if (I->getOpcode() == Instruction::Cast) {
2001 Value *Op = I->getOperand(0);
2002 // Only handle int->int casts.
2003 if (!Op->getType()->isInteger()) return Result;
2004 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2009 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
2010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2012 // 0 % X == 0, we don't need to preserve faults!
2013 if (Constant *LHS = dyn_cast<Constant>(Op0))
2014 if (LHS->isNullValue())
2015 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2017 if (isa<UndefValue>(Op0)) // undef % X -> 0
2018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2019 if (isa<UndefValue>(Op1))
2020 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2022 if (I.getType()->isSigned()) {
2023 if (Value *RHSNeg = dyn_castNegVal(Op1))
2024 if (!isa<ConstantSInt>(RHSNeg) ||
2025 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
2027 AddUsesToWorkList(I);
2028 I.setOperand(1, RHSNeg);
2032 // If the top bits of both operands are zero (i.e. we can prove they are
2033 // unsigned inputs), turn this into a urem.
2034 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2035 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2036 const Type *NTy = Op0->getType()->getUnsignedVersion();
2037 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2038 InsertNewInstBefore(LHS, I);
2040 if (Constant *R = dyn_cast<Constant>(Op1))
2041 RHS = ConstantExpr::getCast(R, NTy);
2043 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2044 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2045 InsertNewInstBefore(Rem, I);
2046 return new CastInst(Rem, I.getType());
2050 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2051 // X % 0 == undef, we don't need to preserve faults!
2052 if (RHS->equalsInt(0))
2053 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2055 if (RHS->equalsInt(1)) // X % 1 == 0
2056 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2058 // Check to see if this is an unsigned remainder with an exact power of 2,
2059 // if so, convert to a bitwise and.
2060 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
2061 if (isPowerOf2_64(C->getValue()))
2062 return BinaryOperator::createAnd(Op0, SubOne(C));
2064 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2065 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2066 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2068 } else if (isa<PHINode>(Op0I)) {
2069 if (Instruction *NV = FoldOpIntoPhi(I))
2073 // X*C1%C2 --> 0 iff C1%C2 == 0
2074 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2075 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2079 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2080 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2081 if (I.getType()->isUnsigned() &&
2082 RHSI->getOpcode() == Instruction::Shl &&
2083 isa<ConstantUInt>(RHSI->getOperand(0))) {
2084 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2085 if (isPowerOf2_64(C1)) {
2086 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2087 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2089 return BinaryOperator::createAnd(Op0, Add);
2093 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2094 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2095 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2096 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2097 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
2098 if (STO->getValue() == 0) { // Couldn't be this argument.
2099 I.setOperand(1, SFO);
2101 } else if (SFO->getValue() == 0) {
2102 I.setOperand(1, STO);
2106 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2107 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2108 SubOne(STO), SI->getName()+".t"), I);
2109 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2110 SubOne(SFO), SI->getName()+".f"), I);
2111 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2119 // isMaxValueMinusOne - return true if this is Max-1
2120 static bool isMaxValueMinusOne(const ConstantInt *C) {
2121 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2122 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
2124 const ConstantSInt *CS = cast<ConstantSInt>(C);
2126 // Calculate 0111111111..11111
2127 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2128 int64_t Val = INT64_MAX; // All ones
2129 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2130 return CS->getValue() == Val-1;
2133 // isMinValuePlusOne - return true if this is Min+1
2134 static bool isMinValuePlusOne(const ConstantInt *C) {
2135 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2136 return CU->getValue() == 1;
2138 const ConstantSInt *CS = cast<ConstantSInt>(C);
2140 // Calculate 1111111111000000000000
2141 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2142 int64_t Val = -1; // All ones
2143 Val <<= TypeBits-1; // Shift over to the right spot
2144 return CS->getValue() == Val+1;
2147 // isOneBitSet - Return true if there is exactly one bit set in the specified
2149 static bool isOneBitSet(const ConstantInt *CI) {
2150 uint64_t V = CI->getRawValue();
2151 return V && (V & (V-1)) == 0;
2154 #if 0 // Currently unused
2155 // isLowOnes - Return true if the constant is of the form 0+1+.
2156 static bool isLowOnes(const ConstantInt *CI) {
2157 uint64_t V = CI->getRawValue();
2159 // There won't be bits set in parts that the type doesn't contain.
2160 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2162 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2163 return U && V && (U & V) == 0;
2167 // isHighOnes - Return true if the constant is of the form 1+0+.
2168 // This is the same as lowones(~X).
2169 static bool isHighOnes(const ConstantInt *CI) {
2170 uint64_t V = ~CI->getRawValue();
2171 if (~V == 0) return false; // 0's does not match "1+"
2173 // There won't be bits set in parts that the type doesn't contain.
2174 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2176 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2177 return U && V && (U & V) == 0;
2181 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2182 /// are carefully arranged to allow folding of expressions such as:
2184 /// (A < B) | (A > B) --> (A != B)
2186 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2187 /// represents that the comparison is true if A == B, and bit value '1' is true
2190 static unsigned getSetCondCode(const SetCondInst *SCI) {
2191 switch (SCI->getOpcode()) {
2193 case Instruction::SetGT: return 1;
2194 case Instruction::SetEQ: return 2;
2195 case Instruction::SetGE: return 3;
2196 case Instruction::SetLT: return 4;
2197 case Instruction::SetNE: return 5;
2198 case Instruction::SetLE: return 6;
2201 assert(0 && "Invalid SetCC opcode!");
2206 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2207 /// opcode and two operands into either a constant true or false, or a brand new
2208 /// SetCC instruction.
2209 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2211 case 0: return ConstantBool::False;
2212 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2213 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2214 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2215 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2216 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2217 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2218 case 7: return ConstantBool::True;
2219 default: assert(0 && "Illegal SetCCCode!"); return 0;
2223 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2224 struct FoldSetCCLogical {
2227 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2228 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2229 bool shouldApply(Value *V) const {
2230 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2231 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2232 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2235 Instruction *apply(BinaryOperator &Log) const {
2236 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2237 if (SCI->getOperand(0) != LHS) {
2238 assert(SCI->getOperand(1) == LHS);
2239 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2242 unsigned LHSCode = getSetCondCode(SCI);
2243 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2245 switch (Log.getOpcode()) {
2246 case Instruction::And: Code = LHSCode & RHSCode; break;
2247 case Instruction::Or: Code = LHSCode | RHSCode; break;
2248 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2249 default: assert(0 && "Illegal logical opcode!"); return 0;
2252 Value *RV = getSetCCValue(Code, LHS, RHS);
2253 if (Instruction *I = dyn_cast<Instruction>(RV))
2255 // Otherwise, it's a constant boolean value...
2256 return IC.ReplaceInstUsesWith(Log, RV);
2260 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2261 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2262 // guaranteed to be either a shift instruction or a binary operator.
2263 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2264 ConstantIntegral *OpRHS,
2265 ConstantIntegral *AndRHS,
2266 BinaryOperator &TheAnd) {
2267 Value *X = Op->getOperand(0);
2268 Constant *Together = 0;
2269 if (!isa<ShiftInst>(Op))
2270 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2272 switch (Op->getOpcode()) {
2273 case Instruction::Xor:
2274 if (Op->hasOneUse()) {
2275 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2276 std::string OpName = Op->getName(); Op->setName("");
2277 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2278 InsertNewInstBefore(And, TheAnd);
2279 return BinaryOperator::createXor(And, Together);
2282 case Instruction::Or:
2283 if (Together == AndRHS) // (X | C) & C --> C
2284 return ReplaceInstUsesWith(TheAnd, AndRHS);
2286 if (Op->hasOneUse() && Together != OpRHS) {
2287 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2288 std::string Op0Name = Op->getName(); Op->setName("");
2289 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2290 InsertNewInstBefore(Or, TheAnd);
2291 return BinaryOperator::createAnd(Or, AndRHS);
2294 case Instruction::Add:
2295 if (Op->hasOneUse()) {
2296 // Adding a one to a single bit bit-field should be turned into an XOR
2297 // of the bit. First thing to check is to see if this AND is with a
2298 // single bit constant.
2299 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
2301 // Clear bits that are not part of the constant.
2302 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2304 // If there is only one bit set...
2305 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2306 // Ok, at this point, we know that we are masking the result of the
2307 // ADD down to exactly one bit. If the constant we are adding has
2308 // no bits set below this bit, then we can eliminate the ADD.
2309 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
2311 // Check to see if any bits below the one bit set in AndRHSV are set.
2312 if ((AddRHS & (AndRHSV-1)) == 0) {
2313 // If not, the only thing that can effect the output of the AND is
2314 // the bit specified by AndRHSV. If that bit is set, the effect of
2315 // the XOR is to toggle the bit. If it is clear, then the ADD has
2317 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2318 TheAnd.setOperand(0, X);
2321 std::string Name = Op->getName(); Op->setName("");
2322 // Pull the XOR out of the AND.
2323 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2324 InsertNewInstBefore(NewAnd, TheAnd);
2325 return BinaryOperator::createXor(NewAnd, AndRHS);
2332 case Instruction::Shl: {
2333 // We know that the AND will not produce any of the bits shifted in, so if
2334 // the anded constant includes them, clear them now!
2336 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2337 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2338 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2340 if (CI == ShlMask) { // Masking out bits that the shift already masks
2341 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2342 } else if (CI != AndRHS) { // Reducing bits set in and.
2343 TheAnd.setOperand(1, CI);
2348 case Instruction::Shr:
2349 // We know that the AND will not produce any of the bits shifted in, so if
2350 // the anded constant includes them, clear them now! This only applies to
2351 // unsigned shifts, because a signed shr may bring in set bits!
2353 if (AndRHS->getType()->isUnsigned()) {
2354 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2355 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2356 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2358 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2359 return ReplaceInstUsesWith(TheAnd, Op);
2360 } else if (CI != AndRHS) {
2361 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2364 } else { // Signed shr.
2365 // See if this is shifting in some sign extension, then masking it out
2367 if (Op->hasOneUse()) {
2368 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2369 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2370 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2371 if (CI == AndRHS) { // Masking out bits shifted in.
2372 // Make the argument unsigned.
2373 Value *ShVal = Op->getOperand(0);
2374 ShVal = InsertCastBefore(ShVal,
2375 ShVal->getType()->getUnsignedVersion(),
2377 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2378 OpRHS, Op->getName()),
2380 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2381 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2384 return new CastInst(ShVal, Op->getType());
2394 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2395 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2396 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2397 /// insert new instructions.
2398 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2399 bool Inside, Instruction &IB) {
2400 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2401 "Lo is not <= Hi in range emission code!");
2403 if (Lo == Hi) // Trivially false.
2404 return new SetCondInst(Instruction::SetNE, V, V);
2405 if (cast<ConstantIntegral>(Lo)->isMinValue())
2406 return new SetCondInst(Instruction::SetLT, V, Hi);
2408 Constant *AddCST = ConstantExpr::getNeg(Lo);
2409 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2410 InsertNewInstBefore(Add, IB);
2411 // Convert to unsigned for the comparison.
2412 const Type *UnsType = Add->getType()->getUnsignedVersion();
2413 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2414 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2415 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2416 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2419 if (Lo == Hi) // Trivially true.
2420 return new SetCondInst(Instruction::SetEQ, V, V);
2422 Hi = SubOne(cast<ConstantInt>(Hi));
2423 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2424 return new SetCondInst(Instruction::SetGT, V, Hi);
2426 // Emit X-Lo > Hi-Lo-1
2427 Constant *AddCST = ConstantExpr::getNeg(Lo);
2428 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2429 InsertNewInstBefore(Add, IB);
2430 // Convert to unsigned for the comparison.
2431 const Type *UnsType = Add->getType()->getUnsignedVersion();
2432 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2433 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2434 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2435 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2438 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2439 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2440 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2441 // not, since all 1s are not contiguous.
2442 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2443 uint64_t V = Val->getRawValue();
2444 if (!isShiftedMask_64(V)) return false;
2446 // look for the first zero bit after the run of ones
2447 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2448 // look for the first non-zero bit
2449 ME = 64-CountLeadingZeros_64(V);
2455 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2456 /// where isSub determines whether the operator is a sub. If we can fold one of
2457 /// the following xforms:
2459 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2460 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2461 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2463 /// return (A +/- B).
2465 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2466 ConstantIntegral *Mask, bool isSub,
2468 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2469 if (!LHSI || LHSI->getNumOperands() != 2 ||
2470 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2472 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2474 switch (LHSI->getOpcode()) {
2476 case Instruction::And:
2477 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2478 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2479 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2482 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2483 // part, we don't need any explicit masks to take them out of A. If that
2484 // is all N is, ignore it.
2486 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2487 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2489 if (MaskedValueIsZero(RHS, Mask))
2494 case Instruction::Or:
2495 case Instruction::Xor:
2496 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2497 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2498 ConstantExpr::getAnd(N, Mask)->isNullValue())
2505 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2507 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2508 return InsertNewInstBefore(New, I);
2511 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2512 bool Changed = SimplifyCommutative(I);
2513 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2515 if (isa<UndefValue>(Op1)) // X & undef -> 0
2516 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2520 return ReplaceInstUsesWith(I, Op1);
2522 // See if we can simplify any instructions used by the instruction whose sole
2523 // purpose is to compute bits we don't care about.
2524 uint64_t KnownZero, KnownOne;
2525 if (!isa<PackedType>(I.getType()) &&
2526 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2527 KnownZero, KnownOne))
2530 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2531 uint64_t AndRHSMask = AndRHS->getZExtValue();
2532 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2533 uint64_t NotAndRHS = AndRHSMask^TypeMask;
2535 // Optimize a variety of ((val OP C1) & C2) combinations...
2536 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2537 Instruction *Op0I = cast<Instruction>(Op0);
2538 Value *Op0LHS = Op0I->getOperand(0);
2539 Value *Op0RHS = Op0I->getOperand(1);
2540 switch (Op0I->getOpcode()) {
2541 case Instruction::Xor:
2542 case Instruction::Or:
2543 // If the mask is only needed on one incoming arm, push it up.
2544 if (Op0I->hasOneUse()) {
2545 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2546 // Not masking anything out for the LHS, move to RHS.
2547 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2548 Op0RHS->getName()+".masked");
2549 InsertNewInstBefore(NewRHS, I);
2550 return BinaryOperator::create(
2551 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2553 if (!isa<Constant>(Op0RHS) &&
2554 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2555 // Not masking anything out for the RHS, move to LHS.
2556 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2557 Op0LHS->getName()+".masked");
2558 InsertNewInstBefore(NewLHS, I);
2559 return BinaryOperator::create(
2560 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2565 case Instruction::Add:
2566 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2567 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2568 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2569 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2570 return BinaryOperator::createAnd(V, AndRHS);
2571 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2572 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
2575 case Instruction::Sub:
2576 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2577 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2578 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2579 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2580 return BinaryOperator::createAnd(V, AndRHS);
2584 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2585 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2587 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2588 const Type *SrcTy = CI->getOperand(0)->getType();
2590 // If this is an integer truncation or change from signed-to-unsigned, and
2591 // if the source is an and/or with immediate, transform it. This
2592 // frequently occurs for bitfield accesses.
2593 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2594 if (SrcTy->getPrimitiveSizeInBits() >=
2595 I.getType()->getPrimitiveSizeInBits() &&
2596 CastOp->getNumOperands() == 2)
2597 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2598 if (CastOp->getOpcode() == Instruction::And) {
2599 // Change: and (cast (and X, C1) to T), C2
2600 // into : and (cast X to T), trunc(C1)&C2
2601 // This will folds the two ands together, which may allow other
2603 Instruction *NewCast =
2604 new CastInst(CastOp->getOperand(0), I.getType(),
2605 CastOp->getName()+".shrunk");
2606 NewCast = InsertNewInstBefore(NewCast, I);
2608 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2609 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2610 return BinaryOperator::createAnd(NewCast, C3);
2611 } else if (CastOp->getOpcode() == Instruction::Or) {
2612 // Change: and (cast (or X, C1) to T), C2
2613 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2614 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2615 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2616 return ReplaceInstUsesWith(I, AndRHS);
2621 // Try to fold constant and into select arguments.
2622 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2623 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2625 if (isa<PHINode>(Op0))
2626 if (Instruction *NV = FoldOpIntoPhi(I))
2630 Value *Op0NotVal = dyn_castNotVal(Op0);
2631 Value *Op1NotVal = dyn_castNotVal(Op1);
2633 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2634 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2636 // (~A & ~B) == (~(A | B)) - De Morgan's Law
2637 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2638 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2639 I.getName()+".demorgan");
2640 InsertNewInstBefore(Or, I);
2641 return BinaryOperator::createNot(Or);
2645 Value *A = 0, *B = 0;
2646 ConstantInt *C1 = 0, *C2 = 0;
2647 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2648 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2649 return ReplaceInstUsesWith(I, Op1);
2650 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2651 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2652 return ReplaceInstUsesWith(I, Op0);
2654 if (Op0->hasOneUse() &&
2655 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2656 if (A == Op1) { // (A^B)&A -> A&(A^B)
2657 I.swapOperands(); // Simplify below
2658 std::swap(Op0, Op1);
2659 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2660 cast<BinaryOperator>(Op0)->swapOperands();
2661 I.swapOperands(); // Simplify below
2662 std::swap(Op0, Op1);
2665 if (Op1->hasOneUse() &&
2666 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2667 if (B == Op0) { // B&(A^B) -> B&(B^A)
2668 cast<BinaryOperator>(Op1)->swapOperands();
2671 if (A == Op0) { // A&(A^B) -> A & ~B
2672 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2673 InsertNewInstBefore(NotB, I);
2674 return BinaryOperator::createAnd(A, NotB);
2680 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2681 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2682 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2685 Value *LHSVal, *RHSVal;
2686 ConstantInt *LHSCst, *RHSCst;
2687 Instruction::BinaryOps LHSCC, RHSCC;
2688 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2689 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2690 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2691 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2692 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2693 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2694 // Ensure that the larger constant is on the RHS.
2695 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2696 SetCondInst *LHS = cast<SetCondInst>(Op0);
2697 if (cast<ConstantBool>(Cmp)->getValue()) {
2698 std::swap(LHS, RHS);
2699 std::swap(LHSCst, RHSCst);
2700 std::swap(LHSCC, RHSCC);
2703 // At this point, we know we have have two setcc instructions
2704 // comparing a value against two constants and and'ing the result
2705 // together. Because of the above check, we know that we only have
2706 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2707 // FoldSetCCLogical check above), that the two constants are not
2709 assert(LHSCst != RHSCst && "Compares not folded above?");
2712 default: assert(0 && "Unknown integer condition code!");
2713 case Instruction::SetEQ:
2715 default: assert(0 && "Unknown integer condition code!");
2716 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2717 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2718 return ReplaceInstUsesWith(I, ConstantBool::False);
2719 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2720 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2721 return ReplaceInstUsesWith(I, LHS);
2723 case Instruction::SetNE:
2725 default: assert(0 && "Unknown integer condition code!");
2726 case Instruction::SetLT:
2727 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2728 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2729 break; // (X != 13 & X < 15) -> no change
2730 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2731 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2732 return ReplaceInstUsesWith(I, RHS);
2733 case Instruction::SetNE:
2734 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2735 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2736 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2737 LHSVal->getName()+".off");
2738 InsertNewInstBefore(Add, I);
2739 const Type *UnsType = Add->getType()->getUnsignedVersion();
2740 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2741 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2742 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2743 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2745 break; // (X != 13 & X != 15) -> no change
2748 case Instruction::SetLT:
2750 default: assert(0 && "Unknown integer condition code!");
2751 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2752 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2753 return ReplaceInstUsesWith(I, ConstantBool::False);
2754 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2755 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2756 return ReplaceInstUsesWith(I, LHS);
2758 case Instruction::SetGT:
2760 default: assert(0 && "Unknown integer condition code!");
2761 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2762 return ReplaceInstUsesWith(I, LHS);
2763 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2764 return ReplaceInstUsesWith(I, RHS);
2765 case Instruction::SetNE:
2766 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2767 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2768 break; // (X > 13 & X != 15) -> no change
2769 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2770 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2776 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2777 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2778 const Type *SrcTy = Op0C->getOperand(0)->getType();
2779 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2780 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
2781 // Only do this if the casts both really cause code to be generated.
2782 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2783 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
2784 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2785 Op1C->getOperand(0),
2787 InsertNewInstBefore(NewOp, I);
2788 return new CastInst(NewOp, I.getType());
2792 return Changed ? &I : 0;
2795 /// CollectBSwapParts - Look to see if the specified value defines a single byte
2796 /// in the result. If it does, and if the specified byte hasn't been filled in
2797 /// yet, fill it in and return false.
2798 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
2799 Instruction *I = dyn_cast<Instruction>(V);
2800 if (I == 0) return true;
2802 // If this is an or instruction, it is an inner node of the bswap.
2803 if (I->getOpcode() == Instruction::Or)
2804 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
2805 CollectBSwapParts(I->getOperand(1), ByteValues);
2807 // If this is a shift by a constant int, and it is "24", then its operand
2808 // defines a byte. We only handle unsigned types here.
2809 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
2810 // Not shifting the entire input by N-1 bytes?
2811 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
2812 8*(ByteValues.size()-1))
2816 if (I->getOpcode() == Instruction::Shl) {
2817 // X << 24 defines the top byte with the lowest of the input bytes.
2818 DestNo = ByteValues.size()-1;
2820 // X >>u 24 defines the low byte with the highest of the input bytes.
2824 // If the destination byte value is already defined, the values are or'd
2825 // together, which isn't a bswap (unless it's an or of the same bits).
2826 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
2828 ByteValues[DestNo] = I->getOperand(0);
2832 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
2834 Value *Shift = 0, *ShiftLHS = 0;
2835 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
2836 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
2837 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
2839 Instruction *SI = cast<Instruction>(Shift);
2841 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
2842 if (ShiftAmt->getRawValue() & 7 ||
2843 ShiftAmt->getRawValue() > 8*ByteValues.size())
2846 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
2848 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
2849 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
2851 // Unknown mask for bswap.
2852 if (DestByte == ByteValues.size()) return true;
2854 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
2856 if (SI->getOpcode() == Instruction::Shl)
2857 SrcByte = DestByte - ShiftBytes;
2859 SrcByte = DestByte + ShiftBytes;
2861 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
2862 if (SrcByte != ByteValues.size()-DestByte-1)
2865 // If the destination byte value is already defined, the values are or'd
2866 // together, which isn't a bswap (unless it's an or of the same bits).
2867 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
2869 ByteValues[DestByte] = SI->getOperand(0);
2873 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2874 /// If so, insert the new bswap intrinsic and return it.
2875 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
2876 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
2877 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
2880 /// ByteValues - For each byte of the result, we keep track of which value
2881 /// defines each byte.
2882 std::vector<Value*> ByteValues;
2883 ByteValues.resize(I.getType()->getPrimitiveSize());
2885 // Try to find all the pieces corresponding to the bswap.
2886 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
2887 CollectBSwapParts(I.getOperand(1), ByteValues))
2890 // Check to see if all of the bytes come from the same value.
2891 Value *V = ByteValues[0];
2892 if (V == 0) return 0; // Didn't find a byte? Must be zero.
2894 // Check to make sure that all of the bytes come from the same value.
2895 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
2896 if (ByteValues[i] != V)
2899 // If they do then *success* we can turn this into a bswap. Figure out what
2900 // bswap to make it into.
2901 Module *M = I.getParent()->getParent()->getParent();
2903 if (I.getType() == Type::UShortTy)
2904 FnName = "llvm.bswap.i16";
2905 else if (I.getType() == Type::UIntTy)
2906 FnName = "llvm.bswap.i32";
2907 else if (I.getType() == Type::ULongTy)
2908 FnName = "llvm.bswap.i64";
2910 assert(0 && "Unknown integer type!");
2911 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
2913 return new CallInst(F, V);
2917 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2918 bool Changed = SimplifyCommutative(I);
2919 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2921 if (isa<UndefValue>(Op1))
2922 return ReplaceInstUsesWith(I, // X | undef -> -1
2923 ConstantIntegral::getAllOnesValue(I.getType()));
2927 return ReplaceInstUsesWith(I, Op0);
2929 // See if we can simplify any instructions used by the instruction whose sole
2930 // purpose is to compute bits we don't care about.
2931 uint64_t KnownZero, KnownOne;
2932 if (!isa<PackedType>(I.getType()) &&
2933 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2934 KnownZero, KnownOne))
2938 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2939 ConstantInt *C1 = 0; Value *X = 0;
2940 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2941 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2942 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2944 InsertNewInstBefore(Or, I);
2945 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2948 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2949 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2950 std::string Op0Name = Op0->getName(); Op0->setName("");
2951 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2952 InsertNewInstBefore(Or, I);
2953 return BinaryOperator::createXor(Or,
2954 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2957 // Try to fold constant and into select arguments.
2958 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2959 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2961 if (isa<PHINode>(Op0))
2962 if (Instruction *NV = FoldOpIntoPhi(I))
2966 Value *A = 0, *B = 0;
2967 ConstantInt *C1 = 0, *C2 = 0;
2969 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2970 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2971 return ReplaceInstUsesWith(I, Op1);
2972 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2973 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2974 return ReplaceInstUsesWith(I, Op0);
2976 // (A | B) | C and A | (B | C) -> bswap if possible.
2977 if (match(Op0, m_Or(m_Value(), m_Value())) ||
2978 match(Op1, m_Or(m_Value(), m_Value()))) {
2979 if (Instruction *BSwap = MatchBSwap(I))
2983 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2984 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2985 MaskedValueIsZero(Op1, C1->getZExtValue())) {
2986 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2988 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2991 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2992 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2993 MaskedValueIsZero(Op0, C1->getZExtValue())) {
2994 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2996 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2999 // (A & C1)|(B & C2)
3000 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3001 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3003 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3004 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3007 // If we have: ((V + N) & C1) | (V & C2)
3008 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3009 // replace with V+N.
3010 if (C1 == ConstantExpr::getNot(C2)) {
3011 Value *V1 = 0, *V2 = 0;
3012 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3013 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3014 // Add commutes, try both ways.
3015 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3016 return ReplaceInstUsesWith(I, A);
3017 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3018 return ReplaceInstUsesWith(I, A);
3020 // Or commutes, try both ways.
3021 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3022 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3023 // Add commutes, try both ways.
3024 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3025 return ReplaceInstUsesWith(I, B);
3026 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3027 return ReplaceInstUsesWith(I, B);
3032 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3033 if (A == Op1) // ~A | A == -1
3034 return ReplaceInstUsesWith(I,
3035 ConstantIntegral::getAllOnesValue(I.getType()));
3039 // Note, A is still live here!
3040 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3042 return ReplaceInstUsesWith(I,
3043 ConstantIntegral::getAllOnesValue(I.getType()));
3045 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3046 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3047 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3048 I.getName()+".demorgan"), I);
3049 return BinaryOperator::createNot(And);
3053 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3054 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3055 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3058 Value *LHSVal, *RHSVal;
3059 ConstantInt *LHSCst, *RHSCst;
3060 Instruction::BinaryOps LHSCC, RHSCC;
3061 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3062 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3063 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3064 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3065 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3066 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3067 // Ensure that the larger constant is on the RHS.
3068 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3069 SetCondInst *LHS = cast<SetCondInst>(Op0);
3070 if (cast<ConstantBool>(Cmp)->getValue()) {
3071 std::swap(LHS, RHS);
3072 std::swap(LHSCst, RHSCst);
3073 std::swap(LHSCC, RHSCC);
3076 // At this point, we know we have have two setcc instructions
3077 // comparing a value against two constants and or'ing the result
3078 // together. Because of the above check, we know that we only have
3079 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3080 // FoldSetCCLogical check above), that the two constants are not
3082 assert(LHSCst != RHSCst && "Compares not folded above?");
3085 default: assert(0 && "Unknown integer condition code!");
3086 case Instruction::SetEQ:
3088 default: assert(0 && "Unknown integer condition code!");
3089 case Instruction::SetEQ:
3090 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3091 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3092 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3093 LHSVal->getName()+".off");
3094 InsertNewInstBefore(Add, I);
3095 const Type *UnsType = Add->getType()->getUnsignedVersion();
3096 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3097 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3098 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3099 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3101 break; // (X == 13 | X == 15) -> no change
3103 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3105 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3106 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3107 return ReplaceInstUsesWith(I, RHS);
3110 case Instruction::SetNE:
3112 default: assert(0 && "Unknown integer condition code!");
3113 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3114 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3115 return ReplaceInstUsesWith(I, LHS);
3116 case Instruction::SetNE: // (X != 13 | X != 15) -> true
3117 case Instruction::SetLT: // (X != 13 | X < 15) -> true
3118 return ReplaceInstUsesWith(I, ConstantBool::True);
3121 case Instruction::SetLT:
3123 default: assert(0 && "Unknown integer condition code!");
3124 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3126 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3127 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3128 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3129 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3130 return ReplaceInstUsesWith(I, RHS);
3133 case Instruction::SetGT:
3135 default: assert(0 && "Unknown integer condition code!");
3136 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3137 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3138 return ReplaceInstUsesWith(I, LHS);
3139 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3140 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3141 return ReplaceInstUsesWith(I, ConstantBool::True);
3147 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3148 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3149 const Type *SrcTy = Op0C->getOperand(0)->getType();
3150 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3151 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3152 // Only do this if the casts both really cause code to be generated.
3153 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3154 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3155 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3156 Op1C->getOperand(0),
3158 InsertNewInstBefore(NewOp, I);
3159 return new CastInst(NewOp, I.getType());
3164 return Changed ? &I : 0;
3167 // XorSelf - Implements: X ^ X --> 0
3170 XorSelf(Value *rhs) : RHS(rhs) {}
3171 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3172 Instruction *apply(BinaryOperator &Xor) const {
3178 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3179 bool Changed = SimplifyCommutative(I);
3180 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3182 if (isa<UndefValue>(Op1))
3183 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3185 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3186 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3187 assert(Result == &I && "AssociativeOpt didn't work?");
3188 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3191 // See if we can simplify any instructions used by the instruction whose sole
3192 // purpose is to compute bits we don't care about.
3193 uint64_t KnownZero, KnownOne;
3194 if (!isa<PackedType>(I.getType()) &&
3195 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3196 KnownZero, KnownOne))
3199 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3200 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3201 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3202 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3203 if (RHS == ConstantBool::True && SCI->hasOneUse())
3204 return new SetCondInst(SCI->getInverseCondition(),
3205 SCI->getOperand(0), SCI->getOperand(1));
3207 // ~(c-X) == X-c-1 == X+(-c-1)
3208 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3209 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3210 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3211 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3212 ConstantInt::get(I.getType(), 1));
3213 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3216 // ~(~X & Y) --> (X | ~Y)
3217 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3218 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3219 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3221 BinaryOperator::createNot(Op0I->getOperand(1),
3222 Op0I->getOperand(1)->getName()+".not");
3223 InsertNewInstBefore(NotY, I);
3224 return BinaryOperator::createOr(Op0NotVal, NotY);
3228 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3229 if (Op0I->getOpcode() == Instruction::Add) {
3230 // ~(X-c) --> (-c-1)-X
3231 if (RHS->isAllOnesValue()) {
3232 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3233 return BinaryOperator::createSub(
3234 ConstantExpr::getSub(NegOp0CI,
3235 ConstantInt::get(I.getType(), 1)),
3236 Op0I->getOperand(0));
3238 } else if (Op0I->getOpcode() == Instruction::Or) {
3239 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3240 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3241 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3242 // Anything in both C1 and C2 is known to be zero, remove it from
3244 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3245 NewRHS = ConstantExpr::getAnd(NewRHS,
3246 ConstantExpr::getNot(CommonBits));
3247 WorkList.push_back(Op0I);
3248 I.setOperand(0, Op0I->getOperand(0));
3249 I.setOperand(1, NewRHS);
3255 // Try to fold constant and into select arguments.
3256 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3257 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3259 if (isa<PHINode>(Op0))
3260 if (Instruction *NV = FoldOpIntoPhi(I))
3264 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
3266 return ReplaceInstUsesWith(I,
3267 ConstantIntegral::getAllOnesValue(I.getType()));
3269 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
3271 return ReplaceInstUsesWith(I,
3272 ConstantIntegral::getAllOnesValue(I.getType()));
3274 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3275 if (Op1I->getOpcode() == Instruction::Or) {
3276 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
3277 Op1I->swapOperands();
3279 std::swap(Op0, Op1);
3280 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
3281 I.swapOperands(); // Simplified below.
3282 std::swap(Op0, Op1);
3284 } else if (Op1I->getOpcode() == Instruction::Xor) {
3285 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3286 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3287 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3288 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3289 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3290 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3291 Op1I->swapOperands();
3292 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3293 I.swapOperands(); // Simplified below.
3294 std::swap(Op0, Op1);
3298 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3299 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3300 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3301 Op0I->swapOperands();
3302 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3303 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3304 InsertNewInstBefore(NotB, I);
3305 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3307 } else if (Op0I->getOpcode() == Instruction::Xor) {
3308 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3309 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3310 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3311 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3312 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3313 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3314 Op0I->swapOperands();
3315 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3316 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3317 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3318 InsertNewInstBefore(N, I);
3319 return BinaryOperator::createAnd(N, Op1);
3323 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3324 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3325 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3328 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3329 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3330 const Type *SrcTy = Op0C->getOperand(0)->getType();
3331 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3332 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3333 // Only do this if the casts both really cause code to be generated.
3334 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3335 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3336 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3337 Op1C->getOperand(0),
3339 InsertNewInstBefore(NewOp, I);
3340 return new CastInst(NewOp, I.getType());
3344 return Changed ? &I : 0;
3347 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3348 /// overflowed for this type.
3349 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3351 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3352 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3355 static bool isPositive(ConstantInt *C) {
3356 return cast<ConstantSInt>(C)->getValue() >= 0;
3359 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3360 /// overflowed for this type.
3361 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3363 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3365 if (In1->getType()->isUnsigned())
3366 return cast<ConstantUInt>(Result)->getValue() <
3367 cast<ConstantUInt>(In1)->getValue();
3368 if (isPositive(In1) != isPositive(In2))
3370 if (isPositive(In1))
3371 return cast<ConstantSInt>(Result)->getValue() <
3372 cast<ConstantSInt>(In1)->getValue();
3373 return cast<ConstantSInt>(Result)->getValue() >
3374 cast<ConstantSInt>(In1)->getValue();
3377 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3378 /// code necessary to compute the offset from the base pointer (without adding
3379 /// in the base pointer). Return the result as a signed integer of intptr size.
3380 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3381 TargetData &TD = IC.getTargetData();
3382 gep_type_iterator GTI = gep_type_begin(GEP);
3383 const Type *UIntPtrTy = TD.getIntPtrType();
3384 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3385 Value *Result = Constant::getNullValue(SIntPtrTy);
3387 // Build a mask for high order bits.
3388 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3390 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3391 Value *Op = GEP->getOperand(i);
3392 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3393 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3395 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3396 if (!OpC->isNullValue()) {
3397 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3398 Scale = ConstantExpr::getMul(OpC, Scale);
3399 if (Constant *RC = dyn_cast<Constant>(Result))
3400 Result = ConstantExpr::getAdd(RC, Scale);
3402 // Emit an add instruction.
3403 Result = IC.InsertNewInstBefore(
3404 BinaryOperator::createAdd(Result, Scale,
3405 GEP->getName()+".offs"), I);
3409 // Convert to correct type.
3410 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3411 Op->getName()+".c"), I);
3413 // We'll let instcombine(mul) convert this to a shl if possible.
3414 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3415 GEP->getName()+".idx"), I);
3417 // Emit an add instruction.
3418 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3419 GEP->getName()+".offs"), I);
3425 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3426 /// else. At this point we know that the GEP is on the LHS of the comparison.
3427 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3428 Instruction::BinaryOps Cond,
3430 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3432 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3433 if (isa<PointerType>(CI->getOperand(0)->getType()))
3434 RHS = CI->getOperand(0);
3436 Value *PtrBase = GEPLHS->getOperand(0);
3437 if (PtrBase == RHS) {
3438 // As an optimization, we don't actually have to compute the actual value of
3439 // OFFSET if this is a seteq or setne comparison, just return whether each
3440 // index is zero or not.
3441 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3442 Instruction *InVal = 0;
3443 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3444 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3446 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3447 if (isa<UndefValue>(C)) // undef index -> undef.
3448 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3449 if (C->isNullValue())
3451 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3452 EmitIt = false; // This is indexing into a zero sized array?
3453 } else if (isa<ConstantInt>(C))
3454 return ReplaceInstUsesWith(I, // No comparison is needed here.
3455 ConstantBool::get(Cond == Instruction::SetNE));
3460 new SetCondInst(Cond, GEPLHS->getOperand(i),
3461 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3465 InVal = InsertNewInstBefore(InVal, I);
3466 InsertNewInstBefore(Comp, I);
3467 if (Cond == Instruction::SetNE) // True if any are unequal
3468 InVal = BinaryOperator::createOr(InVal, Comp);
3469 else // True if all are equal
3470 InVal = BinaryOperator::createAnd(InVal, Comp);
3478 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3479 ConstantBool::get(Cond == Instruction::SetEQ));
3482 // Only lower this if the setcc is the only user of the GEP or if we expect
3483 // the result to fold to a constant!
3484 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3485 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3486 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3487 return new SetCondInst(Cond, Offset,
3488 Constant::getNullValue(Offset->getType()));
3490 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3491 // If the base pointers are different, but the indices are the same, just
3492 // compare the base pointer.
3493 if (PtrBase != GEPRHS->getOperand(0)) {
3494 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3495 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3496 GEPRHS->getOperand(0)->getType();
3498 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3499 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3500 IndicesTheSame = false;
3504 // If all indices are the same, just compare the base pointers.
3506 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3507 GEPRHS->getOperand(0));
3509 // Otherwise, the base pointers are different and the indices are
3510 // different, bail out.
3514 // If one of the GEPs has all zero indices, recurse.
3515 bool AllZeros = true;
3516 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3517 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3518 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3523 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3524 SetCondInst::getSwappedCondition(Cond), I);
3526 // If the other GEP has all zero indices, recurse.
3528 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3529 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3530 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3535 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3537 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3538 // If the GEPs only differ by one index, compare it.
3539 unsigned NumDifferences = 0; // Keep track of # differences.
3540 unsigned DiffOperand = 0; // The operand that differs.
3541 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3542 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3543 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3544 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3545 // Irreconcilable differences.
3549 if (NumDifferences++) break;
3554 if (NumDifferences == 0) // SAME GEP?
3555 return ReplaceInstUsesWith(I, // No comparison is needed here.
3556 ConstantBool::get(Cond == Instruction::SetEQ));
3557 else if (NumDifferences == 1) {
3558 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3559 Value *RHSV = GEPRHS->getOperand(DiffOperand);
3561 // Convert the operands to signed values to make sure to perform a
3562 // signed comparison.
3563 const Type *NewTy = LHSV->getType()->getSignedVersion();
3564 if (LHSV->getType() != NewTy)
3565 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3566 LHSV->getName()), I);
3567 if (RHSV->getType() != NewTy)
3568 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3569 RHSV->getName()), I);
3570 return new SetCondInst(Cond, LHSV, RHSV);
3574 // Only lower this if the setcc is the only user of the GEP or if we expect
3575 // the result to fold to a constant!
3576 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3577 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3578 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3579 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3580 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3581 return new SetCondInst(Cond, L, R);
3588 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3589 bool Changed = SimplifyCommutative(I);
3590 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3591 const Type *Ty = Op0->getType();
3595 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3597 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3598 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3600 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3601 // addresses never equal each other! We already know that Op0 != Op1.
3602 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3603 isa<ConstantPointerNull>(Op0)) &&
3604 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3605 isa<ConstantPointerNull>(Op1)))
3606 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3608 // setcc's with boolean values can always be turned into bitwise operations
3609 if (Ty == Type::BoolTy) {
3610 switch (I.getOpcode()) {
3611 default: assert(0 && "Invalid setcc instruction!");
3612 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
3613 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3614 InsertNewInstBefore(Xor, I);
3615 return BinaryOperator::createNot(Xor);
3617 case Instruction::SetNE:
3618 return BinaryOperator::createXor(Op0, Op1);
3620 case Instruction::SetGT:
3621 std::swap(Op0, Op1); // Change setgt -> setlt
3623 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3624 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3625 InsertNewInstBefore(Not, I);
3626 return BinaryOperator::createAnd(Not, Op1);
3628 case Instruction::SetGE:
3629 std::swap(Op0, Op1); // Change setge -> setle
3631 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3632 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3633 InsertNewInstBefore(Not, I);
3634 return BinaryOperator::createOr(Not, Op1);
3639 // See if we are doing a comparison between a constant and an instruction that
3640 // can be folded into the comparison.
3641 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3642 // Check to see if we are comparing against the minimum or maximum value...
3643 if (CI->isMinValue()) {
3644 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3645 return ReplaceInstUsesWith(I, ConstantBool::False);
3646 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3647 return ReplaceInstUsesWith(I, ConstantBool::True);
3648 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3649 return BinaryOperator::createSetEQ(Op0, Op1);
3650 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3651 return BinaryOperator::createSetNE(Op0, Op1);
3653 } else if (CI->isMaxValue()) {
3654 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3655 return ReplaceInstUsesWith(I, ConstantBool::False);
3656 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3657 return ReplaceInstUsesWith(I, ConstantBool::True);
3658 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3659 return BinaryOperator::createSetEQ(Op0, Op1);
3660 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3661 return BinaryOperator::createSetNE(Op0, Op1);
3663 // Comparing against a value really close to min or max?
3664 } else if (isMinValuePlusOne(CI)) {
3665 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3666 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3667 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3668 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3670 } else if (isMaxValueMinusOne(CI)) {
3671 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3672 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3673 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3674 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3677 // If we still have a setle or setge instruction, turn it into the
3678 // appropriate setlt or setgt instruction. Since the border cases have
3679 // already been handled above, this requires little checking.
3681 if (I.getOpcode() == Instruction::SetLE)
3682 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3683 if (I.getOpcode() == Instruction::SetGE)
3684 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3687 // See if we can fold the comparison based on bits known to be zero or one
3689 uint64_t KnownZero, KnownOne;
3690 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3691 KnownZero, KnownOne, 0))
3694 // Given the known and unknown bits, compute a range that the LHS could be
3696 if (KnownOne | KnownZero) {
3697 if (Ty->isUnsigned()) { // Unsigned comparison.
3699 uint64_t RHSVal = CI->getZExtValue();
3700 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3702 switch (I.getOpcode()) { // LE/GE have been folded already.
3703 default: assert(0 && "Unknown setcc opcode!");
3704 case Instruction::SetEQ:
3705 if (Max < RHSVal || Min > RHSVal)
3706 return ReplaceInstUsesWith(I, ConstantBool::False);
3708 case Instruction::SetNE:
3709 if (Max < RHSVal || Min > RHSVal)
3710 return ReplaceInstUsesWith(I, ConstantBool::True);
3712 case Instruction::SetLT:
3713 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3714 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3716 case Instruction::SetGT:
3717 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3718 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3721 } else { // Signed comparison.
3723 int64_t RHSVal = CI->getSExtValue();
3724 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3726 switch (I.getOpcode()) { // LE/GE have been folded already.
3727 default: assert(0 && "Unknown setcc opcode!");
3728 case Instruction::SetEQ:
3729 if (Max < RHSVal || Min > RHSVal)
3730 return ReplaceInstUsesWith(I, ConstantBool::False);
3732 case Instruction::SetNE:
3733 if (Max < RHSVal || Min > RHSVal)
3734 return ReplaceInstUsesWith(I, ConstantBool::True);
3736 case Instruction::SetLT:
3737 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3738 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3740 case Instruction::SetGT:
3741 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3742 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3749 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3750 switch (LHSI->getOpcode()) {
3751 case Instruction::And:
3752 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3753 LHSI->getOperand(0)->hasOneUse()) {
3754 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3755 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3756 // happens a LOT in code produced by the C front-end, for bitfield
3758 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
3759 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3761 // Check to see if there is a noop-cast between the shift and the and.
3763 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3764 if (CI->getOperand(0)->getType()->isIntegral() &&
3765 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3766 CI->getType()->getPrimitiveSizeInBits())
3767 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3770 ConstantUInt *ShAmt;
3771 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
3772 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3773 const Type *AndTy = AndCST->getType(); // Type of the and.
3775 // We can fold this as long as we can't shift unknown bits
3776 // into the mask. This can only happen with signed shift
3777 // rights, as they sign-extend.
3779 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
3782 // To test for the bad case of the signed shr, see if any
3783 // of the bits shifted in could be tested after the mask.
3784 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3785 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3787 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
3789 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3791 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3797 if (Shift->getOpcode() == Instruction::Shl)
3798 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3800 NewCst = ConstantExpr::getShl(CI, ShAmt);
3802 // Check to see if we are shifting out any of the bits being
3804 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3805 // If we shifted bits out, the fold is not going to work out.
3806 // As a special case, check to see if this means that the
3807 // result is always true or false now.
3808 if (I.getOpcode() == Instruction::SetEQ)
3809 return ReplaceInstUsesWith(I, ConstantBool::False);
3810 if (I.getOpcode() == Instruction::SetNE)
3811 return ReplaceInstUsesWith(I, ConstantBool::True);
3813 I.setOperand(1, NewCst);
3814 Constant *NewAndCST;
3815 if (Shift->getOpcode() == Instruction::Shl)
3816 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3818 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3819 LHSI->setOperand(1, NewAndCST);
3821 LHSI->setOperand(0, Shift->getOperand(0));
3823 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3825 LHSI->setOperand(0, NewCast);
3827 WorkList.push_back(Shift); // Shift is dead.
3828 AddUsesToWorkList(I);
3836 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3837 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3838 switch (I.getOpcode()) {
3840 case Instruction::SetEQ:
3841 case Instruction::SetNE: {
3842 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3844 // Check that the shift amount is in range. If not, don't perform
3845 // undefined shifts. When the shift is visited it will be
3847 if (ShAmt->getValue() >= TypeBits)
3850 // If we are comparing against bits always shifted out, the
3851 // comparison cannot succeed.
3853 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3854 if (Comp != CI) {// Comparing against a bit that we know is zero.
3855 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3856 Constant *Cst = ConstantBool::get(IsSetNE);
3857 return ReplaceInstUsesWith(I, Cst);
3860 if (LHSI->hasOneUse()) {
3861 // Otherwise strength reduce the shift into an and.
3862 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3863 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3866 if (CI->getType()->isUnsigned()) {
3867 Mask = ConstantUInt::get(CI->getType(), Val);
3868 } else if (ShAmtVal != 0) {
3869 Mask = ConstantSInt::get(CI->getType(), Val);
3871 Mask = ConstantInt::getAllOnesValue(CI->getType());
3875 BinaryOperator::createAnd(LHSI->getOperand(0),
3876 Mask, LHSI->getName()+".mask");
3877 Value *And = InsertNewInstBefore(AndI, I);
3878 return new SetCondInst(I.getOpcode(), And,
3879 ConstantExpr::getUShr(CI, ShAmt));
3886 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
3887 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3888 switch (I.getOpcode()) {
3890 case Instruction::SetEQ:
3891 case Instruction::SetNE: {
3893 // Check that the shift amount is in range. If not, don't perform
3894 // undefined shifts. When the shift is visited it will be
3896 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3897 if (ShAmt->getValue() >= TypeBits)
3900 // If we are comparing against bits always shifted out, the
3901 // comparison cannot succeed.
3903 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
3905 if (Comp != CI) {// Comparing against a bit that we know is zero.
3906 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3907 Constant *Cst = ConstantBool::get(IsSetNE);
3908 return ReplaceInstUsesWith(I, Cst);
3911 if (LHSI->hasOneUse() || CI->isNullValue()) {
3912 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3914 // Otherwise strength reduce the shift into an and.
3915 uint64_t Val = ~0ULL; // All ones.
3916 Val <<= ShAmtVal; // Shift over to the right spot.
3919 if (CI->getType()->isUnsigned()) {
3920 Val &= ~0ULL >> (64-TypeBits);
3921 Mask = ConstantUInt::get(CI->getType(), Val);
3923 Mask = ConstantSInt::get(CI->getType(), Val);
3927 BinaryOperator::createAnd(LHSI->getOperand(0),
3928 Mask, LHSI->getName()+".mask");
3929 Value *And = InsertNewInstBefore(AndI, I);
3930 return new SetCondInst(I.getOpcode(), And,
3931 ConstantExpr::getShl(CI, ShAmt));
3939 case Instruction::Div:
3940 // Fold: (div X, C1) op C2 -> range check
3941 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3942 // Fold this div into the comparison, producing a range check.
3943 // Determine, based on the divide type, what the range is being
3944 // checked. If there is an overflow on the low or high side, remember
3945 // it, otherwise compute the range [low, hi) bounding the new value.
3946 bool LoOverflow = false, HiOverflow = 0;
3947 ConstantInt *LoBound = 0, *HiBound = 0;
3950 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3952 Instruction::BinaryOps Opcode = I.getOpcode();
3954 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3955 } else if (LHSI->getType()->isUnsigned()) { // udiv
3957 LoOverflow = ProdOV;
3958 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3959 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3960 if (CI->isNullValue()) { // (X / pos) op 0
3962 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3964 } else if (isPositive(CI)) { // (X / pos) op pos
3966 LoOverflow = ProdOV;
3967 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3968 } else { // (X / pos) op neg
3969 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3970 LoOverflow = AddWithOverflow(LoBound, Prod,
3971 cast<ConstantInt>(DivRHSH));
3973 HiOverflow = ProdOV;
3975 } else { // Divisor is < 0.
3976 if (CI->isNullValue()) { // (X / neg) op 0
3977 LoBound = AddOne(DivRHS);
3978 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
3979 if (HiBound == DivRHS)
3980 LoBound = 0; // - INTMIN = INTMIN
3981 } else if (isPositive(CI)) { // (X / neg) op pos
3982 HiOverflow = LoOverflow = ProdOV;
3984 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3985 HiBound = AddOne(Prod);
3986 } else { // (X / neg) op neg
3988 LoOverflow = HiOverflow = ProdOV;
3989 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3992 // Dividing by a negate swaps the condition.
3993 Opcode = SetCondInst::getSwappedCondition(Opcode);
3997 Value *X = LHSI->getOperand(0);
3999 default: assert(0 && "Unhandled setcc opcode!");
4000 case Instruction::SetEQ:
4001 if (LoOverflow && HiOverflow)
4002 return ReplaceInstUsesWith(I, ConstantBool::False);
4003 else if (HiOverflow)
4004 return new SetCondInst(Instruction::SetGE, X, LoBound);
4005 else if (LoOverflow)
4006 return new SetCondInst(Instruction::SetLT, X, HiBound);
4008 return InsertRangeTest(X, LoBound, HiBound, true, I);
4009 case Instruction::SetNE:
4010 if (LoOverflow && HiOverflow)
4011 return ReplaceInstUsesWith(I, ConstantBool::True);
4012 else if (HiOverflow)
4013 return new SetCondInst(Instruction::SetLT, X, LoBound);
4014 else if (LoOverflow)
4015 return new SetCondInst(Instruction::SetGE, X, HiBound);
4017 return InsertRangeTest(X, LoBound, HiBound, false, I);
4018 case Instruction::SetLT:
4020 return ReplaceInstUsesWith(I, ConstantBool::False);
4021 return new SetCondInst(Instruction::SetLT, X, LoBound);
4022 case Instruction::SetGT:
4024 return ReplaceInstUsesWith(I, ConstantBool::False);
4025 return new SetCondInst(Instruction::SetGE, X, HiBound);
4032 // Simplify seteq and setne instructions...
4033 if (I.getOpcode() == Instruction::SetEQ ||
4034 I.getOpcode() == Instruction::SetNE) {
4035 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4037 // If the first operand is (and|or|xor) with a constant, and the second
4038 // operand is a constant, simplify a bit.
4039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4040 switch (BO->getOpcode()) {
4041 case Instruction::Rem:
4042 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4043 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4045 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4046 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4047 if (isPowerOf2_64(V)) {
4048 unsigned L2 = Log2_64(V);
4049 const Type *UTy = BO->getType()->getUnsignedVersion();
4050 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4052 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4053 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4054 RHSCst, BO->getName()), I);
4055 return BinaryOperator::create(I.getOpcode(), NewRem,
4056 Constant::getNullValue(UTy));
4061 case Instruction::Add:
4062 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4063 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4064 if (BO->hasOneUse())
4065 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4066 ConstantExpr::getSub(CI, BOp1C));
4067 } else if (CI->isNullValue()) {
4068 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4069 // efficiently invertible, or if the add has just this one use.
4070 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4072 if (Value *NegVal = dyn_castNegVal(BOp1))
4073 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4074 else if (Value *NegVal = dyn_castNegVal(BOp0))
4075 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4076 else if (BO->hasOneUse()) {
4077 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4079 InsertNewInstBefore(Neg, I);
4080 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4084 case Instruction::Xor:
4085 // For the xor case, we can xor two constants together, eliminating
4086 // the explicit xor.
4087 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4088 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4089 ConstantExpr::getXor(CI, BOC));
4092 case Instruction::Sub:
4093 // Replace (([sub|xor] A, B) != 0) with (A != B)
4094 if (CI->isNullValue())
4095 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4099 case Instruction::Or:
4100 // If bits are being or'd in that are not present in the constant we
4101 // are comparing against, then the comparison could never succeed!
4102 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4103 Constant *NotCI = ConstantExpr::getNot(CI);
4104 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4105 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4109 case Instruction::And:
4110 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4111 // If bits are being compared against that are and'd out, then the
4112 // comparison can never succeed!
4113 if (!ConstantExpr::getAnd(CI,
4114 ConstantExpr::getNot(BOC))->isNullValue())
4115 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4117 // If we have ((X & C) == C), turn it into ((X & C) != 0).
4118 if (CI == BOC && isOneBitSet(CI))
4119 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4120 Instruction::SetNE, Op0,
4121 Constant::getNullValue(CI->getType()));
4123 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4124 // to be a signed value as appropriate.
4125 if (isSignBit(BOC)) {
4126 Value *X = BO->getOperand(0);
4127 // If 'X' is not signed, insert a cast now...
4128 if (!BOC->getType()->isSigned()) {
4129 const Type *DestTy = BOC->getType()->getSignedVersion();
4130 X = InsertCastBefore(X, DestTy, I);
4132 return new SetCondInst(isSetNE ? Instruction::SetLT :
4133 Instruction::SetGE, X,
4134 Constant::getNullValue(X->getType()));
4137 // ((X & ~7) == 0) --> X < 8
4138 if (CI->isNullValue() && isHighOnes(BOC)) {
4139 Value *X = BO->getOperand(0);
4140 Constant *NegX = ConstantExpr::getNeg(BOC);
4142 // If 'X' is signed, insert a cast now.
4143 if (NegX->getType()->isSigned()) {
4144 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4145 X = InsertCastBefore(X, DestTy, I);
4146 NegX = ConstantExpr::getCast(NegX, DestTy);
4149 return new SetCondInst(isSetNE ? Instruction::SetGE :
4150 Instruction::SetLT, X, NegX);
4157 } else { // Not a SetEQ/SetNE
4158 // If the LHS is a cast from an integral value of the same size,
4159 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4160 Value *CastOp = Cast->getOperand(0);
4161 const Type *SrcTy = CastOp->getType();
4162 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4163 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4164 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4165 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4166 "Source and destination signednesses should differ!");
4167 if (Cast->getType()->isSigned()) {
4168 // If this is a signed comparison, check for comparisons in the
4169 // vicinity of zero.
4170 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4172 return BinaryOperator::createSetGT(CastOp,
4173 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4174 else if (I.getOpcode() == Instruction::SetGT &&
4175 cast<ConstantSInt>(CI)->getValue() == -1)
4176 // X > -1 => x < 128
4177 return BinaryOperator::createSetLT(CastOp,
4178 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4180 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4181 if (I.getOpcode() == Instruction::SetLT &&
4182 CUI->getValue() == 1ULL << (SrcTySize-1))
4183 // X < 128 => X > -1
4184 return BinaryOperator::createSetGT(CastOp,
4185 ConstantSInt::get(SrcTy, -1));
4186 else if (I.getOpcode() == Instruction::SetGT &&
4187 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
4189 return BinaryOperator::createSetLT(CastOp,
4190 Constant::getNullValue(SrcTy));
4197 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4198 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4199 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4200 switch (LHSI->getOpcode()) {
4201 case Instruction::GetElementPtr:
4202 if (RHSC->isNullValue()) {
4203 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4204 bool isAllZeros = true;
4205 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4206 if (!isa<Constant>(LHSI->getOperand(i)) ||
4207 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4212 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4213 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4217 case Instruction::PHI:
4218 if (Instruction *NV = FoldOpIntoPhi(I))
4221 case Instruction::Select:
4222 // If either operand of the select is a constant, we can fold the
4223 // comparison into the select arms, which will cause one to be
4224 // constant folded and the select turned into a bitwise or.
4225 Value *Op1 = 0, *Op2 = 0;
4226 if (LHSI->hasOneUse()) {
4227 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4228 // Fold the known value into the constant operand.
4229 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4230 // Insert a new SetCC of the other select operand.
4231 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4232 LHSI->getOperand(2), RHSC,
4234 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4235 // Fold the known value into the constant operand.
4236 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4237 // Insert a new SetCC of the other select operand.
4238 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4239 LHSI->getOperand(1), RHSC,
4245 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4250 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4251 if (User *GEP = dyn_castGetElementPtr(Op0))
4252 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4254 if (User *GEP = dyn_castGetElementPtr(Op1))
4255 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4256 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4259 // Test to see if the operands of the setcc are casted versions of other
4260 // values. If the cast can be stripped off both arguments, we do so now.
4261 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4262 Value *CastOp0 = CI->getOperand(0);
4263 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
4264 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
4265 (I.getOpcode() == Instruction::SetEQ ||
4266 I.getOpcode() == Instruction::SetNE)) {
4267 // We keep moving the cast from the left operand over to the right
4268 // operand, where it can often be eliminated completely.
4271 // If operand #1 is a cast instruction, see if we can eliminate it as
4273 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4274 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
4276 Op1 = CI2->getOperand(0);
4278 // If Op1 is a constant, we can fold the cast into the constant.
4279 if (Op1->getType() != Op0->getType())
4280 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4281 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4283 // Otherwise, cast the RHS right before the setcc
4284 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4285 InsertNewInstBefore(cast<Instruction>(Op1), I);
4287 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4290 // Handle the special case of: setcc (cast bool to X), <cst>
4291 // This comes up when you have code like
4294 // For generality, we handle any zero-extension of any operand comparison
4295 // with a constant or another cast from the same type.
4296 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4297 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4301 if (I.getOpcode() == Instruction::SetNE ||
4302 I.getOpcode() == Instruction::SetEQ) {
4304 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4305 (A == Op1 || B == Op1)) {
4306 // (A^B) == A -> B == 0
4307 Value *OtherVal = A == Op1 ? B : A;
4308 return BinaryOperator::create(I.getOpcode(), OtherVal,
4309 Constant::getNullValue(A->getType()));
4310 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4311 (A == Op0 || B == Op0)) {
4312 // A == (A^B) -> B == 0
4313 Value *OtherVal = A == Op0 ? B : A;
4314 return BinaryOperator::create(I.getOpcode(), OtherVal,
4315 Constant::getNullValue(A->getType()));
4316 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4317 // (A-B) == A -> B == 0
4318 return BinaryOperator::create(I.getOpcode(), B,
4319 Constant::getNullValue(B->getType()));
4320 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4321 // A == (A-B) -> B == 0
4322 return BinaryOperator::create(I.getOpcode(), B,
4323 Constant::getNullValue(B->getType()));
4326 return Changed ? &I : 0;
4329 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4330 // We only handle extending casts so far.
4332 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4333 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4334 const Type *SrcTy = LHSCIOp->getType();
4335 const Type *DestTy = SCI.getOperand(0)->getType();
4338 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
4341 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4342 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4343 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4345 // Is this a sign or zero extension?
4346 bool isSignSrc = SrcTy->isSigned();
4347 bool isSignDest = DestTy->isSigned();
4349 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4350 // Not an extension from the same type?
4351 RHSCIOp = CI->getOperand(0);
4352 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4353 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4354 // Compute the constant that would happen if we truncated to SrcTy then
4355 // reextended to DestTy.
4356 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4358 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4361 // If the value cannot be represented in the shorter type, we cannot emit
4362 // a simple comparison.
4363 if (SCI.getOpcode() == Instruction::SetEQ)
4364 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4365 if (SCI.getOpcode() == Instruction::SetNE)
4366 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4368 // Evaluate the comparison for LT.
4370 if (DestTy->isSigned()) {
4371 // We're performing a signed comparison.
4373 // Signed extend and signed comparison.
4374 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4375 Result = ConstantBool::False;
4377 Result = ConstantBool::True; // X < (large) --> true
4379 // Unsigned extend and signed comparison.
4380 if (cast<ConstantSInt>(CI)->getValue() < 0)
4381 Result = ConstantBool::False;
4383 Result = ConstantBool::True;
4386 // We're performing an unsigned comparison.
4388 // Unsigned extend & compare -> always true.
4389 Result = ConstantBool::True;
4391 // We're performing an unsigned comp with a sign extended value.
4392 // This is true if the input is >= 0. [aka >s -1]
4393 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4394 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4395 NegOne, SCI.getName()), SCI);
4399 // Finally, return the value computed.
4400 if (SCI.getOpcode() == Instruction::SetLT) {
4401 return ReplaceInstUsesWith(SCI, Result);
4403 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4404 if (Constant *CI = dyn_cast<Constant>(Result))
4405 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4407 return BinaryOperator::createNot(Result);
4414 // Okay, just insert a compare of the reduced operands now!
4415 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4418 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4419 assert(I.getOperand(1)->getType() == Type::UByteTy);
4420 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4421 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4423 // shl X, 0 == X and shr X, 0 == X
4424 // shl 0, X == 0 and shr 0, X == 0
4425 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4426 Op0 == Constant::getNullValue(Op0->getType()))
4427 return ReplaceInstUsesWith(I, Op0);
4429 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4430 if (!isLeftShift && I.getType()->isSigned())
4431 return ReplaceInstUsesWith(I, Op0);
4432 else // undef << X -> 0 AND undef >>u X -> 0
4433 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4435 if (isa<UndefValue>(Op1)) {
4436 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4437 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4439 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4442 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4444 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4445 if (CSI->isAllOnesValue())
4446 return ReplaceInstUsesWith(I, CSI);
4448 // Try to fold constant and into select arguments.
4449 if (isa<Constant>(Op0))
4450 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4451 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4454 // See if we can turn a signed shr into an unsigned shr.
4455 if (!isLeftShift && I.getType()->isSigned()) {
4456 if (MaskedValueIsZero(Op0,
4457 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4458 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4459 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4461 return new CastInst(V, I.getType());
4465 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4466 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4471 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4473 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4474 bool isSignedShift = Op0->getType()->isSigned();
4475 bool isUnsignedShift = !isSignedShift;
4477 // See if we can simplify any instructions used by the instruction whose sole
4478 // purpose is to compute bits we don't care about.
4479 uint64_t KnownZero, KnownOne;
4480 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4481 KnownZero, KnownOne))
4484 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4485 // of a signed value.
4487 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4488 if (Op1->getValue() >= TypeBits) {
4489 if (isUnsignedShift || isLeftShift)
4490 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4492 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4497 // ((X*C1) << C2) == (X * (C1 << C2))
4498 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4499 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4500 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4501 return BinaryOperator::createMul(BO->getOperand(0),
4502 ConstantExpr::getShl(BOOp, Op1));
4504 // Try to fold constant and into select arguments.
4505 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4506 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4508 if (isa<PHINode>(Op0))
4509 if (Instruction *NV = FoldOpIntoPhi(I))
4512 if (Op0->hasOneUse()) {
4513 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4514 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4517 switch (Op0BO->getOpcode()) {
4519 case Instruction::Add:
4520 case Instruction::And:
4521 case Instruction::Or:
4522 case Instruction::Xor:
4523 // These operators commute.
4524 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
4525 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4526 match(Op0BO->getOperand(1),
4527 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4528 Instruction *YS = new ShiftInst(Instruction::Shl,
4529 Op0BO->getOperand(0), Op1,
4531 InsertNewInstBefore(YS, I); // (Y << C)
4533 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4534 Op0BO->getOperand(1)->getName());
4535 InsertNewInstBefore(X, I); // (X + (Y << C))
4536 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4537 C2 = ConstantExpr::getShl(C2, Op1);
4538 return BinaryOperator::createAnd(X, C2);
4541 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4542 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4543 match(Op0BO->getOperand(1),
4544 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4545 m_ConstantInt(CC))) && V2 == Op1 &&
4546 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
4547 Instruction *YS = new ShiftInst(Instruction::Shl,
4548 Op0BO->getOperand(0), Op1,
4550 InsertNewInstBefore(YS, I); // (Y << C)
4552 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4553 V1->getName()+".mask");
4554 InsertNewInstBefore(XM, I); // X & (CC << C)
4556 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4560 case Instruction::Sub:
4561 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4562 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4563 match(Op0BO->getOperand(0),
4564 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4565 Instruction *YS = new ShiftInst(Instruction::Shl,
4566 Op0BO->getOperand(1), Op1,
4568 InsertNewInstBefore(YS, I); // (Y << C)
4570 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
4571 Op0BO->getOperand(0)->getName());
4572 InsertNewInstBefore(X, I); // (X + (Y << C))
4573 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4574 C2 = ConstantExpr::getShl(C2, Op1);
4575 return BinaryOperator::createAnd(X, C2);
4578 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
4579 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4580 match(Op0BO->getOperand(0),
4581 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4582 m_ConstantInt(CC))) && V2 == Op1 &&
4583 cast<BinaryOperator>(Op0BO->getOperand(0))
4584 ->getOperand(0)->hasOneUse()) {
4585 Instruction *YS = new ShiftInst(Instruction::Shl,
4586 Op0BO->getOperand(1), Op1,
4588 InsertNewInstBefore(YS, I); // (Y << C)
4590 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4591 V1->getName()+".mask");
4592 InsertNewInstBefore(XM, I); // X & (CC << C)
4594 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
4601 // If the operand is an bitwise operator with a constant RHS, and the
4602 // shift is the only use, we can pull it out of the shift.
4603 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4604 bool isValid = true; // Valid only for And, Or, Xor
4605 bool highBitSet = false; // Transform if high bit of constant set?
4607 switch (Op0BO->getOpcode()) {
4608 default: isValid = false; break; // Do not perform transform!
4609 case Instruction::Add:
4610 isValid = isLeftShift;
4612 case Instruction::Or:
4613 case Instruction::Xor:
4616 case Instruction::And:
4621 // If this is a signed shift right, and the high bit is modified
4622 // by the logical operation, do not perform the transformation.
4623 // The highBitSet boolean indicates the value of the high bit of
4624 // the constant which would cause it to be modified for this
4627 if (isValid && !isLeftShift && isSignedShift) {
4628 uint64_t Val = Op0C->getRawValue();
4629 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4633 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4635 Instruction *NewShift =
4636 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4639 InsertNewInstBefore(NewShift, I);
4641 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4648 // Find out if this is a shift of a shift by a constant.
4649 ShiftInst *ShiftOp = 0;
4650 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
4652 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4653 // If this is a noop-integer case of a shift instruction, use the shift.
4654 if (CI->getOperand(0)->getType()->isInteger() &&
4655 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4656 CI->getType()->getPrimitiveSizeInBits() &&
4657 isa<ShiftInst>(CI->getOperand(0))) {
4658 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4662 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4663 // Find the operands and properties of the input shift. Note that the
4664 // signedness of the input shift may differ from the current shift if there
4665 // is a noop cast between the two.
4666 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4667 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
4668 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
4670 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4672 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4673 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4675 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4676 if (isLeftShift == isShiftOfLeftShift) {
4677 // Do not fold these shifts if the first one is signed and the second one
4678 // is unsigned and this is a right shift. Further, don't do any folding
4680 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4683 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4684 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4685 Amt = Op0->getType()->getPrimitiveSizeInBits();
4687 Value *Op = ShiftOp->getOperand(0);
4688 if (isShiftOfSignedShift != isSignedShift)
4689 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4690 return new ShiftInst(I.getOpcode(), Op,
4691 ConstantUInt::get(Type::UByteTy, Amt));
4694 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4695 // signed types, we can only support the (A >> c1) << c2 configuration,
4696 // because it can not turn an arbitrary bit of A into a sign bit.
4697 if (isUnsignedShift || isLeftShift) {
4698 // Calculate bitmask for what gets shifted off the edge.
4699 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4701 C = ConstantExpr::getShl(C, ShiftAmt1C);
4703 C = ConstantExpr::getUShr(C, ShiftAmt1C);
4705 Value *Op = ShiftOp->getOperand(0);
4706 if (isShiftOfSignedShift != isSignedShift)
4707 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4710 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4711 InsertNewInstBefore(Mask, I);
4713 // Figure out what flavor of shift we should use...
4714 if (ShiftAmt1 == ShiftAmt2) {
4715 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
4716 } else if (ShiftAmt1 < ShiftAmt2) {
4717 return new ShiftInst(I.getOpcode(), Mask,
4718 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
4719 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4720 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4721 // Make sure to emit an unsigned shift right, not a signed one.
4722 Mask = InsertNewInstBefore(new CastInst(Mask,
4723 Mask->getType()->getUnsignedVersion(),
4725 Mask = new ShiftInst(Instruction::Shr, Mask,
4726 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4727 InsertNewInstBefore(Mask, I);
4728 return new CastInst(Mask, I.getType());
4730 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4731 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4734 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4735 Op = InsertNewInstBefore(new CastInst(Mask,
4736 I.getType()->getSignedVersion(),
4737 Mask->getName()), I);
4738 Instruction *Shift =
4739 new ShiftInst(ShiftOp->getOpcode(), Op,
4740 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4741 InsertNewInstBefore(Shift, I);
4743 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4744 C = ConstantExpr::getShl(C, Op1);
4745 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4746 InsertNewInstBefore(Mask, I);
4747 return new CastInst(Mask, I.getType());
4750 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
4751 // this case, C1 == C2 and C1 is 8, 16, or 32.
4752 if (ShiftAmt1 == ShiftAmt2) {
4753 const Type *SExtType = 0;
4754 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
4755 case 8 : SExtType = Type::SByteTy; break;
4756 case 16: SExtType = Type::ShortTy; break;
4757 case 32: SExtType = Type::IntTy; break;
4761 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4763 InsertNewInstBefore(NewTrunc, I);
4764 return new CastInst(NewTrunc, I.getType());
4773 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4774 /// expression. If so, decompose it, returning some value X, such that Val is
4777 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4779 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4780 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4781 Offset = CI->getValue();
4783 return ConstantUInt::get(Type::UIntTy, 0);
4784 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4785 if (I->getNumOperands() == 2) {
4786 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4787 if (I->getOpcode() == Instruction::Shl) {
4788 // This is a value scaled by '1 << the shift amt'.
4789 Scale = 1U << CUI->getValue();
4791 return I->getOperand(0);
4792 } else if (I->getOpcode() == Instruction::Mul) {
4793 // This value is scaled by 'CUI'.
4794 Scale = CUI->getValue();
4796 return I->getOperand(0);
4797 } else if (I->getOpcode() == Instruction::Add) {
4798 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4801 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4803 Offset += CUI->getValue();
4804 if (SubScale > 1 && (Offset % SubScale == 0)) {
4813 // Otherwise, we can't look past this.
4820 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4821 /// try to eliminate the cast by moving the type information into the alloc.
4822 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4823 AllocationInst &AI) {
4824 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
4825 if (!PTy) return 0; // Not casting the allocation to a pointer type.
4827 // Remove any uses of AI that are dead.
4828 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4829 std::vector<Instruction*> DeadUsers;
4830 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4831 Instruction *User = cast<Instruction>(*UI++);
4832 if (isInstructionTriviallyDead(User)) {
4833 while (UI != E && *UI == User)
4834 ++UI; // If this instruction uses AI more than once, don't break UI.
4836 // Add operands to the worklist.
4837 AddUsesToWorkList(*User);
4839 DEBUG(std::cerr << "IC: DCE: " << *User);
4841 User->eraseFromParent();
4842 removeFromWorkList(User);
4846 // Get the type really allocated and the type casted to.
4847 const Type *AllocElTy = AI.getAllocatedType();
4848 const Type *CastElTy = PTy->getElementType();
4849 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4851 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4852 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4853 if (CastElTyAlign < AllocElTyAlign) return 0;
4855 // If the allocation has multiple uses, only promote it if we are strictly
4856 // increasing the alignment of the resultant allocation. If we keep it the
4857 // same, we open the door to infinite loops of various kinds.
4858 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4860 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4861 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4862 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4864 // See if we can satisfy the modulus by pulling a scale out of the array
4866 unsigned ArraySizeScale, ArrayOffset;
4867 Value *NumElements = // See if the array size is a decomposable linear expr.
4868 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4870 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4872 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4873 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
4875 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4880 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4881 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4882 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4883 else if (Scale != 1) {
4884 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4885 Amt = InsertNewInstBefore(Tmp, AI);
4889 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4890 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4891 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4892 Amt = InsertNewInstBefore(Tmp, AI);
4895 std::string Name = AI.getName(); AI.setName("");
4896 AllocationInst *New;
4897 if (isa<MallocInst>(AI))
4898 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4900 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4901 InsertNewInstBefore(New, AI);
4903 // If the allocation has multiple uses, insert a cast and change all things
4904 // that used it to use the new cast. This will also hack on CI, but it will
4906 if (!AI.hasOneUse()) {
4907 AddUsesToWorkList(AI);
4908 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4909 InsertNewInstBefore(NewCast, AI);
4910 AI.replaceAllUsesWith(NewCast);
4912 return ReplaceInstUsesWith(CI, New);
4915 /// CanEvaluateInDifferentType - Return true if we can take the specified value
4916 /// and return it without inserting any new casts. This is used by code that
4917 /// tries to decide whether promoting or shrinking integer operations to wider
4918 /// or smaller types will allow us to eliminate a truncate or extend.
4919 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
4920 int &NumCastsRemoved) {
4921 if (isa<Constant>(V)) return true;
4923 Instruction *I = dyn_cast<Instruction>(V);
4924 if (!I || !I->hasOneUse()) return false;
4926 switch (I->getOpcode()) {
4927 case Instruction::And:
4928 case Instruction::Or:
4929 case Instruction::Xor:
4930 // These operators can all arbitrarily be extended or truncated.
4931 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
4932 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
4933 case Instruction::Cast:
4934 // If this is a cast from the destination type, we can trivially eliminate
4935 // it, and this will remove a cast overall.
4936 if (I->getOperand(0)->getType() == Ty) {
4937 // If the first operand is itself a cast, and is eliminable, do not count
4938 // this as an eliminable cast. We would prefer to eliminate those two
4940 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
4946 // TODO: Can handle more cases here.
4953 /// EvaluateInDifferentType - Given an expression that
4954 /// CanEvaluateInDifferentType returns true for, actually insert the code to
4955 /// evaluate the expression.
4956 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
4957 if (Constant *C = dyn_cast<Constant>(V))
4958 return ConstantExpr::getCast(C, Ty);
4960 // Otherwise, it must be an instruction.
4961 Instruction *I = cast<Instruction>(V);
4962 Instruction *Res = 0;
4963 switch (I->getOpcode()) {
4964 case Instruction::And:
4965 case Instruction::Or:
4966 case Instruction::Xor: {
4967 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
4968 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
4969 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
4970 LHS, RHS, I->getName());
4973 case Instruction::Cast:
4974 // If this is a cast from the destination type, return the input.
4975 if (I->getOperand(0)->getType() == Ty)
4976 return I->getOperand(0);
4978 // TODO: Can handle more cases here.
4979 assert(0 && "Unreachable!");
4983 return InsertNewInstBefore(Res, *I);
4987 // CastInst simplification
4989 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4990 Value *Src = CI.getOperand(0);
4992 // If the user is casting a value to the same type, eliminate this cast
4994 if (CI.getType() == Src->getType())
4995 return ReplaceInstUsesWith(CI, Src);
4997 if (isa<UndefValue>(Src)) // cast undef -> undef
4998 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5000 // If casting the result of another cast instruction, try to eliminate this
5003 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5004 Value *A = CSrc->getOperand(0);
5005 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5006 CI.getType(), TD)) {
5007 // This instruction now refers directly to the cast's src operand. This
5008 // has a good chance of making CSrc dead.
5009 CI.setOperand(0, CSrc->getOperand(0));
5013 // If this is an A->B->A cast, and we are dealing with integral types, try
5014 // to convert this into a logical 'and' instruction.
5016 if (A->getType()->isInteger() &&
5017 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
5018 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
5019 CSrc->getType()->getPrimitiveSizeInBits() <
5020 CI.getType()->getPrimitiveSizeInBits()&&
5021 A->getType()->getPrimitiveSizeInBits() ==
5022 CI.getType()->getPrimitiveSizeInBits()) {
5023 assert(CSrc->getType() != Type::ULongTy &&
5024 "Cannot have type bigger than ulong!");
5025 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
5026 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5028 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5029 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5030 if (And->getType() != CI.getType()) {
5031 And->setName(CSrc->getName()+".mask");
5032 InsertNewInstBefore(And, CI);
5033 And = new CastInst(And, CI.getType());
5039 // If this is a cast to bool, turn it into the appropriate setne instruction.
5040 if (CI.getType() == Type::BoolTy)
5041 return BinaryOperator::createSetNE(CI.getOperand(0),
5042 Constant::getNullValue(CI.getOperand(0)->getType()));
5044 // See if we can simplify any instructions used by the LHS whose sole
5045 // purpose is to compute bits we don't care about.
5046 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5047 uint64_t KnownZero, KnownOne;
5048 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5049 KnownZero, KnownOne))
5053 // If casting the result of a getelementptr instruction with no offset, turn
5054 // this into a cast of the original pointer!
5056 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5057 bool AllZeroOperands = true;
5058 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5059 if (!isa<Constant>(GEP->getOperand(i)) ||
5060 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5061 AllZeroOperands = false;
5064 if (AllZeroOperands) {
5065 CI.setOperand(0, GEP->getOperand(0));
5070 // If we are casting a malloc or alloca to a pointer to a type of the same
5071 // size, rewrite the allocation instruction to allocate the "right" type.
5073 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5074 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5077 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5078 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5080 if (isa<PHINode>(Src))
5081 if (Instruction *NV = FoldOpIntoPhi(CI))
5084 // If the source and destination are pointers, and this cast is equivalent to
5085 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5086 // This can enhance SROA and other transforms that want type-safe pointers.
5087 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5088 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5089 const Type *DstTy = DstPTy->getElementType();
5090 const Type *SrcTy = SrcPTy->getElementType();
5092 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5093 unsigned NumZeros = 0;
5094 while (SrcTy != DstTy &&
5095 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
5096 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5100 // If we found a path from the src to dest, create the getelementptr now.
5101 if (SrcTy == DstTy) {
5102 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5103 return new GetElementPtrInst(Src, Idxs);
5107 // If the source value is an instruction with only this use, we can attempt to
5108 // propagate the cast into the instruction. Also, only handle integral types
5110 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
5111 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
5112 CI.getType()->isInteger()) { // Don't mess with casts to bool here
5114 int NumCastsRemoved = 0;
5115 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5116 // If this cast is a truncate, evaluting in a different type always
5117 // eliminates the cast, so it is always a win. If this is a noop-cast
5118 // this just removes a noop cast which isn't pointful, but simplifies
5119 // the code. If this is a zero-extension, we need to do an AND to
5120 // maintain the clear top-part of the computation, so we require that
5121 // the input have eliminated at least one cast. If this is a sign
5122 // extension, we insert two new casts (to do the extension) so we
5123 // require that two casts have been eliminated.
5125 switch (getCastType(Src->getType(), CI.getType())) {
5126 default: assert(0 && "Unknown cast type!");
5132 DoXForm = NumCastsRemoved >= 1;
5135 DoXForm = NumCastsRemoved >= 2;
5140 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5141 assert(Res->getType() == CI.getType());
5142 switch (getCastType(Src->getType(), CI.getType())) {
5143 default: assert(0 && "Unknown cast type!");
5146 // Just replace this cast with the result.
5147 return ReplaceInstUsesWith(CI, Res);
5149 // We need to emit an AND to clear the high bits.
5150 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5151 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5152 assert(SrcBitSize < DestBitSize && "Not a zext?");
5153 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5154 C = ConstantExpr::getCast(C, CI.getType());
5155 return BinaryOperator::createAnd(Res, C);
5158 // We need to emit a cast to truncate, then a cast to sext.
5159 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5165 const Type *DestTy = CI.getType();
5166 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5167 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5169 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5170 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5172 switch (SrcI->getOpcode()) {
5173 case Instruction::Add:
5174 case Instruction::Mul:
5175 case Instruction::And:
5176 case Instruction::Or:
5177 case Instruction::Xor:
5178 // If we are discarding information, or just changing the sign, rewrite.
5179 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5180 // Don't insert two casts if they cannot be eliminated. We allow two
5181 // casts to be inserted if the sizes are the same. This could only be
5182 // converting signedness, which is a noop.
5183 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5184 !ValueRequiresCast(Op0, DestTy, TD)) {
5185 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5186 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5187 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5188 ->getOpcode(), Op0c, Op1c);
5192 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5193 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5194 Op1 == ConstantBool::True &&
5195 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5196 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5197 return BinaryOperator::createXor(New,
5198 ConstantInt::get(CI.getType(), 1));
5201 case Instruction::Shl:
5202 // Allow changing the sign of the source operand. Do not allow changing
5203 // the size of the shift, UNLESS the shift amount is a constant. We
5204 // mush not change variable sized shifts to a smaller size, because it
5205 // is undefined to shift more bits out than exist in the value.
5206 if (DestBitSize == SrcBitSize ||
5207 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5208 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5209 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5212 case Instruction::Shr:
5213 // If this is a signed shr, and if all bits shifted in are about to be
5214 // truncated off, turn it into an unsigned shr to allow greater
5216 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5217 isa<ConstantInt>(Op1)) {
5218 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5219 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5220 // Convert to unsigned.
5221 Value *N1 = InsertOperandCastBefore(Op0,
5222 Op0->getType()->getUnsignedVersion(), &CI);
5223 // Insert the new shift, which is now unsigned.
5224 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5225 Op1, Src->getName()), CI);
5226 return new CastInst(N1, CI.getType());
5231 case Instruction::SetEQ:
5232 case Instruction::SetNE:
5233 // We if we are just checking for a seteq of a single bit and casting it
5234 // to an integer. If so, shift the bit to the appropriate place then
5235 // cast to integer to avoid the comparison.
5236 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5237 uint64_t Op1CV = Op1C->getZExtValue();
5238 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5239 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5240 // cast (X == 1) to int --> X iff X has only the low bit set.
5241 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5242 // cast (X != 0) to int --> X iff X has only the low bit set.
5243 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5244 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5245 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5246 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5247 // If Op1C some other power of two, convert:
5248 uint64_t KnownZero, KnownOne;
5249 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5250 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5252 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5253 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5254 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5255 // (X&4) == 2 --> false
5256 // (X&4) != 2 --> true
5257 Constant *Res = ConstantBool::get(isSetNE);
5258 Res = ConstantExpr::getCast(Res, CI.getType());
5259 return ReplaceInstUsesWith(CI, Res);
5262 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5265 // Perform an unsigned shr by shiftamt. Convert input to
5266 // unsigned if it is signed.
5267 if (In->getType()->isSigned())
5268 In = InsertNewInstBefore(new CastInst(In,
5269 In->getType()->getUnsignedVersion(), In->getName()),CI);
5270 // Insert the shift to put the result in the low bit.
5271 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
5272 ConstantInt::get(Type::UByteTy, ShiftAmt),
5273 In->getName()+".lobit"), CI);
5276 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5277 Constant *One = ConstantInt::get(In->getType(), 1);
5278 In = BinaryOperator::createXor(In, One, "tmp");
5279 InsertNewInstBefore(cast<Instruction>(In), CI);
5282 if (CI.getType() == In->getType())
5283 return ReplaceInstUsesWith(CI, In);
5285 return new CastInst(In, CI.getType());
5293 if (SrcI->hasOneUse()) {
5294 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5295 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5296 // because the inputs are known to be a vector. Check to see if this is
5297 // a cast to a vector with the same # elts.
5298 if (isa<PackedType>(CI.getType()) &&
5299 cast<PackedType>(CI.getType())->getNumElements() ==
5300 SVI->getType()->getNumElements()) {
5302 // If either of the operands is a cast from CI.getType(), then
5303 // evaluating the shuffle in the casted destination's type will allow
5304 // us to eliminate at least one cast.
5305 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5306 Tmp->getOperand(0)->getType() == CI.getType()) ||
5307 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
5308 Tmp->getOperand(0)->getType() == CI.getType())) {
5309 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5311 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5313 // Return a new shuffle vector. Use the same element ID's, as we
5314 // know the vector types match #elts.
5315 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5325 /// GetSelectFoldableOperands - We want to turn code that looks like this:
5327 /// %D = select %cond, %C, %A
5329 /// %C = select %cond, %B, 0
5332 /// Assuming that the specified instruction is an operand to the select, return
5333 /// a bitmask indicating which operands of this instruction are foldable if they
5334 /// equal the other incoming value of the select.
5336 static unsigned GetSelectFoldableOperands(Instruction *I) {
5337 switch (I->getOpcode()) {
5338 case Instruction::Add:
5339 case Instruction::Mul:
5340 case Instruction::And:
5341 case Instruction::Or:
5342 case Instruction::Xor:
5343 return 3; // Can fold through either operand.
5344 case Instruction::Sub: // Can only fold on the amount subtracted.
5345 case Instruction::Shl: // Can only fold on the shift amount.
5346 case Instruction::Shr:
5349 return 0; // Cannot fold
5353 /// GetSelectFoldableConstant - For the same transformation as the previous
5354 /// function, return the identity constant that goes into the select.
5355 static Constant *GetSelectFoldableConstant(Instruction *I) {
5356 switch (I->getOpcode()) {
5357 default: assert(0 && "This cannot happen!"); abort();
5358 case Instruction::Add:
5359 case Instruction::Sub:
5360 case Instruction::Or:
5361 case Instruction::Xor:
5362 return Constant::getNullValue(I->getType());
5363 case Instruction::Shl:
5364 case Instruction::Shr:
5365 return Constant::getNullValue(Type::UByteTy);
5366 case Instruction::And:
5367 return ConstantInt::getAllOnesValue(I->getType());
5368 case Instruction::Mul:
5369 return ConstantInt::get(I->getType(), 1);
5373 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5374 /// have the same opcode and only one use each. Try to simplify this.
5375 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5377 if (TI->getNumOperands() == 1) {
5378 // If this is a non-volatile load or a cast from the same type,
5380 if (TI->getOpcode() == Instruction::Cast) {
5381 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5384 return 0; // unknown unary op.
5387 // Fold this by inserting a select from the input values.
5388 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5389 FI->getOperand(0), SI.getName()+".v");
5390 InsertNewInstBefore(NewSI, SI);
5391 return new CastInst(NewSI, TI->getType());
5394 // Only handle binary operators here.
5395 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5398 // Figure out if the operations have any operands in common.
5399 Value *MatchOp, *OtherOpT, *OtherOpF;
5401 if (TI->getOperand(0) == FI->getOperand(0)) {
5402 MatchOp = TI->getOperand(0);
5403 OtherOpT = TI->getOperand(1);
5404 OtherOpF = FI->getOperand(1);
5405 MatchIsOpZero = true;
5406 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5407 MatchOp = TI->getOperand(1);
5408 OtherOpT = TI->getOperand(0);
5409 OtherOpF = FI->getOperand(0);
5410 MatchIsOpZero = false;
5411 } else if (!TI->isCommutative()) {
5413 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5414 MatchOp = TI->getOperand(0);
5415 OtherOpT = TI->getOperand(1);
5416 OtherOpF = FI->getOperand(0);
5417 MatchIsOpZero = true;
5418 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5419 MatchOp = TI->getOperand(1);
5420 OtherOpT = TI->getOperand(0);
5421 OtherOpF = FI->getOperand(1);
5422 MatchIsOpZero = true;
5427 // If we reach here, they do have operations in common.
5428 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5429 OtherOpF, SI.getName()+".v");
5430 InsertNewInstBefore(NewSI, SI);
5432 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5434 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5436 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5439 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5441 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5445 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
5446 Value *CondVal = SI.getCondition();
5447 Value *TrueVal = SI.getTrueValue();
5448 Value *FalseVal = SI.getFalseValue();
5450 // select true, X, Y -> X
5451 // select false, X, Y -> Y
5452 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
5453 if (C == ConstantBool::True)
5454 return ReplaceInstUsesWith(SI, TrueVal);
5456 assert(C == ConstantBool::False);
5457 return ReplaceInstUsesWith(SI, FalseVal);
5460 // select C, X, X -> X
5461 if (TrueVal == FalseVal)
5462 return ReplaceInstUsesWith(SI, TrueVal);
5464 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5465 return ReplaceInstUsesWith(SI, FalseVal);
5466 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5467 return ReplaceInstUsesWith(SI, TrueVal);
5468 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5469 if (isa<Constant>(TrueVal))
5470 return ReplaceInstUsesWith(SI, TrueVal);
5472 return ReplaceInstUsesWith(SI, FalseVal);
5475 if (SI.getType() == Type::BoolTy)
5476 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5477 if (C == ConstantBool::True) {
5478 // Change: A = select B, true, C --> A = or B, C
5479 return BinaryOperator::createOr(CondVal, FalseVal);
5481 // Change: A = select B, false, C --> A = and !B, C
5483 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5484 "not."+CondVal->getName()), SI);
5485 return BinaryOperator::createAnd(NotCond, FalseVal);
5487 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5488 if (C == ConstantBool::False) {
5489 // Change: A = select B, C, false --> A = and B, C
5490 return BinaryOperator::createAnd(CondVal, TrueVal);
5492 // Change: A = select B, C, true --> A = or !B, C
5494 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5495 "not."+CondVal->getName()), SI);
5496 return BinaryOperator::createOr(NotCond, TrueVal);
5500 // Selecting between two integer constants?
5501 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5502 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5503 // select C, 1, 0 -> cast C to int
5504 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5505 return new CastInst(CondVal, SI.getType());
5506 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5507 // select C, 0, 1 -> cast !C to int
5509 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5510 "not."+CondVal->getName()), SI);
5511 return new CastInst(NotCond, SI.getType());
5514 // If one of the constants is zero (we know they can't both be) and we
5515 // have a setcc instruction with zero, and we have an 'and' with the
5516 // non-constant value, eliminate this whole mess. This corresponds to
5517 // cases like this: ((X & 27) ? 27 : 0)
5518 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5519 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5520 if ((IC->getOpcode() == Instruction::SetEQ ||
5521 IC->getOpcode() == Instruction::SetNE) &&
5522 isa<ConstantInt>(IC->getOperand(1)) &&
5523 cast<Constant>(IC->getOperand(1))->isNullValue())
5524 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5525 if (ICA->getOpcode() == Instruction::And &&
5526 isa<ConstantInt>(ICA->getOperand(1)) &&
5527 (ICA->getOperand(1) == TrueValC ||
5528 ICA->getOperand(1) == FalseValC) &&
5529 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5530 // Okay, now we know that everything is set up, we just don't
5531 // know whether we have a setne or seteq and whether the true or
5532 // false val is the zero.
5533 bool ShouldNotVal = !TrueValC->isNullValue();
5534 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5537 V = InsertNewInstBefore(BinaryOperator::create(
5538 Instruction::Xor, V, ICA->getOperand(1)), SI);
5539 return ReplaceInstUsesWith(SI, V);
5543 // See if we are selecting two values based on a comparison of the two values.
5544 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5545 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5546 // Transform (X == Y) ? X : Y -> Y
5547 if (SCI->getOpcode() == Instruction::SetEQ)
5548 return ReplaceInstUsesWith(SI, FalseVal);
5549 // Transform (X != Y) ? X : Y -> X
5550 if (SCI->getOpcode() == Instruction::SetNE)
5551 return ReplaceInstUsesWith(SI, TrueVal);
5552 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5554 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5555 // Transform (X == Y) ? Y : X -> X
5556 if (SCI->getOpcode() == Instruction::SetEQ)
5557 return ReplaceInstUsesWith(SI, FalseVal);
5558 // Transform (X != Y) ? Y : X -> Y
5559 if (SCI->getOpcode() == Instruction::SetNE)
5560 return ReplaceInstUsesWith(SI, TrueVal);
5561 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5565 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5566 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5567 if (TI->hasOneUse() && FI->hasOneUse()) {
5568 bool isInverse = false;
5569 Instruction *AddOp = 0, *SubOp = 0;
5571 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5572 if (TI->getOpcode() == FI->getOpcode())
5573 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5576 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5577 // even legal for FP.
5578 if (TI->getOpcode() == Instruction::Sub &&
5579 FI->getOpcode() == Instruction::Add) {
5580 AddOp = FI; SubOp = TI;
5581 } else if (FI->getOpcode() == Instruction::Sub &&
5582 TI->getOpcode() == Instruction::Add) {
5583 AddOp = TI; SubOp = FI;
5587 Value *OtherAddOp = 0;
5588 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5589 OtherAddOp = AddOp->getOperand(1);
5590 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5591 OtherAddOp = AddOp->getOperand(0);
5595 // So at this point we know we have (Y -> OtherAddOp):
5596 // select C, (add X, Y), (sub X, Z)
5597 Value *NegVal; // Compute -Z
5598 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5599 NegVal = ConstantExpr::getNeg(C);
5601 NegVal = InsertNewInstBefore(
5602 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
5605 Value *NewTrueOp = OtherAddOp;
5606 Value *NewFalseOp = NegVal;
5608 std::swap(NewTrueOp, NewFalseOp);
5609 Instruction *NewSel =
5610 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5612 NewSel = InsertNewInstBefore(NewSel, SI);
5613 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
5618 // See if we can fold the select into one of our operands.
5619 if (SI.getType()->isInteger()) {
5620 // See the comment above GetSelectFoldableOperands for a description of the
5621 // transformation we are doing here.
5622 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5623 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5624 !isa<Constant>(FalseVal))
5625 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5626 unsigned OpToFold = 0;
5627 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5629 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5634 Constant *C = GetSelectFoldableConstant(TVI);
5635 std::string Name = TVI->getName(); TVI->setName("");
5636 Instruction *NewSel =
5637 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5639 InsertNewInstBefore(NewSel, SI);
5640 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5641 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5642 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5643 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5645 assert(0 && "Unknown instruction!!");
5650 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5651 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5652 !isa<Constant>(TrueVal))
5653 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5654 unsigned OpToFold = 0;
5655 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5657 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5662 Constant *C = GetSelectFoldableConstant(FVI);
5663 std::string Name = FVI->getName(); FVI->setName("");
5664 Instruction *NewSel =
5665 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5667 InsertNewInstBefore(NewSel, SI);
5668 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5669 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5670 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5671 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5673 assert(0 && "Unknown instruction!!");
5679 if (BinaryOperator::isNot(CondVal)) {
5680 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5681 SI.setOperand(1, FalseVal);
5682 SI.setOperand(2, TrueVal);
5689 /// GetKnownAlignment - If the specified pointer has an alignment that we can
5690 /// determine, return it, otherwise return 0.
5691 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5692 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5693 unsigned Align = GV->getAlignment();
5694 if (Align == 0 && TD)
5695 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5697 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5698 unsigned Align = AI->getAlignment();
5699 if (Align == 0 && TD) {
5700 if (isa<AllocaInst>(AI))
5701 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5702 else if (isa<MallocInst>(AI)) {
5703 // Malloc returns maximally aligned memory.
5704 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5705 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5706 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5710 } else if (isa<CastInst>(V) ||
5711 (isa<ConstantExpr>(V) &&
5712 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5713 User *CI = cast<User>(V);
5714 if (isa<PointerType>(CI->getOperand(0)->getType()))
5715 return GetKnownAlignment(CI->getOperand(0), TD);
5717 } else if (isa<GetElementPtrInst>(V) ||
5718 (isa<ConstantExpr>(V) &&
5719 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5720 User *GEPI = cast<User>(V);
5721 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5722 if (BaseAlignment == 0) return 0;
5724 // If all indexes are zero, it is just the alignment of the base pointer.
5725 bool AllZeroOperands = true;
5726 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5727 if (!isa<Constant>(GEPI->getOperand(i)) ||
5728 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5729 AllZeroOperands = false;
5732 if (AllZeroOperands)
5733 return BaseAlignment;
5735 // Otherwise, if the base alignment is >= the alignment we expect for the
5736 // base pointer type, then we know that the resultant pointer is aligned at
5737 // least as much as its type requires.
5740 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5741 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
5743 const Type *GEPTy = GEPI->getType();
5744 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5752 /// visitCallInst - CallInst simplification. This mostly only handles folding
5753 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5754 /// the heavy lifting.
5756 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
5757 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5758 if (!II) return visitCallSite(&CI);
5760 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5762 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
5763 bool Changed = false;
5765 // memmove/cpy/set of zero bytes is a noop.
5766 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5767 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5769 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5770 if (CI->getRawValue() == 1) {
5771 // Replace the instruction with just byte operations. We would
5772 // transform other cases to loads/stores, but we don't know if
5773 // alignment is sufficient.
5777 // If we have a memmove and the source operation is a constant global,
5778 // then the source and dest pointers can't alias, so we can change this
5779 // into a call to memcpy.
5780 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
5781 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5782 if (GVSrc->isConstant()) {
5783 Module *M = CI.getParent()->getParent()->getParent();
5785 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5787 Name = "llvm.memcpy.i32";
5789 Name = "llvm.memcpy.i64";
5790 Function *MemCpy = M->getOrInsertFunction(Name,
5791 CI.getCalledFunction()->getFunctionType());
5792 CI.setOperand(0, MemCpy);
5797 // If we can determine a pointer alignment that is bigger than currently
5798 // set, update the alignment.
5799 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5800 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5801 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5802 unsigned Align = std::min(Alignment1, Alignment2);
5803 if (MI->getAlignment()->getRawValue() < Align) {
5804 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5807 } else if (isa<MemSetInst>(MI)) {
5808 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5809 if (MI->getAlignment()->getRawValue() < Alignment) {
5810 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5815 if (Changed) return II;
5817 switch (II->getIntrinsicID()) {
5819 case Intrinsic::ppc_altivec_lvx:
5820 case Intrinsic::ppc_altivec_lvxl:
5821 case Intrinsic::x86_sse_loadu_ps:
5822 case Intrinsic::x86_sse2_loadu_pd:
5823 case Intrinsic::x86_sse2_loadu_dq:
5824 // Turn PPC lvx -> load if the pointer is known aligned.
5825 // Turn X86 loadups -> load if the pointer is known aligned.
5826 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5827 Value *Ptr = InsertCastBefore(II->getOperand(1),
5828 PointerType::get(II->getType()), CI);
5829 return new LoadInst(Ptr);
5832 case Intrinsic::ppc_altivec_stvx:
5833 case Intrinsic::ppc_altivec_stvxl:
5834 // Turn stvx -> store if the pointer is known aligned.
5835 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
5836 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5837 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
5838 return new StoreInst(II->getOperand(1), Ptr);
5841 case Intrinsic::x86_sse_storeu_ps:
5842 case Intrinsic::x86_sse2_storeu_pd:
5843 case Intrinsic::x86_sse2_storeu_dq:
5844 case Intrinsic::x86_sse2_storel_dq:
5845 // Turn X86 storeu -> store if the pointer is known aligned.
5846 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5847 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5848 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5849 return new StoreInst(II->getOperand(2), Ptr);
5852 case Intrinsic::ppc_altivec_vperm:
5853 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5854 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5855 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5857 // Check that all of the elements are integer constants or undefs.
5858 bool AllEltsOk = true;
5859 for (unsigned i = 0; i != 16; ++i) {
5860 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5861 !isa<UndefValue>(Mask->getOperand(i))) {
5868 // Cast the input vectors to byte vectors.
5869 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5870 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5871 Value *Result = UndefValue::get(Op0->getType());
5873 // Only extract each element once.
5874 Value *ExtractedElts[32];
5875 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5877 for (unsigned i = 0; i != 16; ++i) {
5878 if (isa<UndefValue>(Mask->getOperand(i)))
5880 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5881 Idx &= 31; // Match the hardware behavior.
5883 if (ExtractedElts[Idx] == 0) {
5885 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5886 ConstantUInt::get(Type::UIntTy, Idx&15),
5888 InsertNewInstBefore(Elt, CI);
5889 ExtractedElts[Idx] = Elt;
5892 // Insert this value into the result vector.
5893 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5894 ConstantUInt::get(Type::UIntTy, i),
5896 InsertNewInstBefore(cast<Instruction>(Result), CI);
5898 return new CastInst(Result, CI.getType());
5903 case Intrinsic::stackrestore: {
5904 // If the save is right next to the restore, remove the restore. This can
5905 // happen when variable allocas are DCE'd.
5906 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5907 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5908 BasicBlock::iterator BI = SS;
5910 return EraseInstFromFunction(CI);
5914 // If the stack restore is in a return/unwind block and if there are no
5915 // allocas or calls between the restore and the return, nuke the restore.
5916 TerminatorInst *TI = II->getParent()->getTerminator();
5917 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5918 BasicBlock::iterator BI = II;
5919 bool CannotRemove = false;
5920 for (++BI; &*BI != TI; ++BI) {
5921 if (isa<AllocaInst>(BI) ||
5922 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5923 CannotRemove = true;
5928 return EraseInstFromFunction(CI);
5935 return visitCallSite(II);
5938 // InvokeInst simplification
5940 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
5941 return visitCallSite(&II);
5944 // visitCallSite - Improvements for call and invoke instructions.
5946 Instruction *InstCombiner::visitCallSite(CallSite CS) {
5947 bool Changed = false;
5949 // If the callee is a constexpr cast of a function, attempt to move the cast
5950 // to the arguments of the call/invoke.
5951 if (transformConstExprCastCall(CS)) return 0;
5953 Value *Callee = CS.getCalledValue();
5955 if (Function *CalleeF = dyn_cast<Function>(Callee))
5956 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5957 Instruction *OldCall = CS.getInstruction();
5958 // If the call and callee calling conventions don't match, this call must
5959 // be unreachable, as the call is undefined.
5960 new StoreInst(ConstantBool::True,
5961 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5962 if (!OldCall->use_empty())
5963 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5964 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5965 return EraseInstFromFunction(*OldCall);
5969 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5970 // This instruction is not reachable, just remove it. We insert a store to
5971 // undef so that we know that this code is not reachable, despite the fact
5972 // that we can't modify the CFG here.
5973 new StoreInst(ConstantBool::True,
5974 UndefValue::get(PointerType::get(Type::BoolTy)),
5975 CS.getInstruction());
5977 if (!CS.getInstruction()->use_empty())
5978 CS.getInstruction()->
5979 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5981 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5982 // Don't break the CFG, insert a dummy cond branch.
5983 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5984 ConstantBool::True, II);
5986 return EraseInstFromFunction(*CS.getInstruction());
5989 const PointerType *PTy = cast<PointerType>(Callee->getType());
5990 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5991 if (FTy->isVarArg()) {
5992 // See if we can optimize any arguments passed through the varargs area of
5994 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5995 E = CS.arg_end(); I != E; ++I)
5996 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5997 // If this cast does not effect the value passed through the varargs
5998 // area, we can eliminate the use of the cast.
5999 Value *Op = CI->getOperand(0);
6000 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6007 return Changed ? CS.getInstruction() : 0;
6010 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6011 // attempt to move the cast to the arguments of the call/invoke.
6013 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6014 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6015 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6016 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
6018 Function *Callee = cast<Function>(CE->getOperand(0));
6019 Instruction *Caller = CS.getInstruction();
6021 // Okay, this is a cast from a function to a different type. Unless doing so
6022 // would cause a type conversion of one of our arguments, change this call to
6023 // be a direct call with arguments casted to the appropriate types.
6025 const FunctionType *FT = Callee->getFunctionType();
6026 const Type *OldRetTy = Caller->getType();
6028 // Check to see if we are changing the return type...
6029 if (OldRetTy != FT->getReturnType()) {
6030 if (Callee->isExternal() &&
6031 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6032 (isa<PointerType>(FT->getReturnType()) &&
6033 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
6034 && !Caller->use_empty())
6035 return false; // Cannot transform this return value...
6037 // If the callsite is an invoke instruction, and the return value is used by
6038 // a PHI node in a successor, we cannot change the return type of the call
6039 // because there is no place to put the cast instruction (without breaking
6040 // the critical edge). Bail out in this case.
6041 if (!Caller->use_empty())
6042 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6043 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6045 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6046 if (PN->getParent() == II->getNormalDest() ||
6047 PN->getParent() == II->getUnwindDest())
6051 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6052 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6054 CallSite::arg_iterator AI = CS.arg_begin();
6055 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6056 const Type *ParamTy = FT->getParamType(i);
6057 const Type *ActTy = (*AI)->getType();
6058 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6059 //Either we can cast directly, or we can upconvert the argument
6060 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6061 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6062 ParamTy->isSigned() == ActTy->isSigned() &&
6063 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6064 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6066 if (Callee->isExternal() && !isConvertible) return false;
6069 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6070 Callee->isExternal())
6071 return false; // Do not delete arguments unless we have a function body...
6073 // Okay, we decided that this is a safe thing to do: go ahead and start
6074 // inserting cast instructions as necessary...
6075 std::vector<Value*> Args;
6076 Args.reserve(NumActualArgs);
6078 AI = CS.arg_begin();
6079 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6080 const Type *ParamTy = FT->getParamType(i);
6081 if ((*AI)->getType() == ParamTy) {
6082 Args.push_back(*AI);
6084 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6089 // If the function takes more arguments than the call was taking, add them
6091 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6092 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6094 // If we are removing arguments to the function, emit an obnoxious warning...
6095 if (FT->getNumParams() < NumActualArgs)
6096 if (!FT->isVarArg()) {
6097 std::cerr << "WARNING: While resolving call to function '"
6098 << Callee->getName() << "' arguments were dropped!\n";
6100 // Add all of the arguments in their promoted form to the arg list...
6101 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6102 const Type *PTy = getPromotedType((*AI)->getType());
6103 if (PTy != (*AI)->getType()) {
6104 // Must promote to pass through va_arg area!
6105 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6106 InsertNewInstBefore(Cast, *Caller);
6107 Args.push_back(Cast);
6109 Args.push_back(*AI);
6114 if (FT->getReturnType() == Type::VoidTy)
6115 Caller->setName(""); // Void type should not have a name...
6118 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6119 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
6120 Args, Caller->getName(), Caller);
6121 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
6123 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
6124 if (cast<CallInst>(Caller)->isTailCall())
6125 cast<CallInst>(NC)->setTailCall();
6126 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
6129 // Insert a cast of the return type as necessary...
6131 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6132 if (NV->getType() != Type::VoidTy) {
6133 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
6135 // If this is an invoke instruction, we should insert it after the first
6136 // non-phi, instruction in the normal successor block.
6137 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6138 BasicBlock::iterator I = II->getNormalDest()->begin();
6139 while (isa<PHINode>(I)) ++I;
6140 InsertNewInstBefore(NC, *I);
6142 // Otherwise, it's a call, just insert cast right after the call instr
6143 InsertNewInstBefore(NC, *Caller);
6145 AddUsersToWorkList(*Caller);
6147 NV = UndefValue::get(Caller->getType());
6151 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6152 Caller->replaceAllUsesWith(NV);
6153 Caller->getParent()->getInstList().erase(Caller);
6154 removeFromWorkList(Caller);
6159 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6160 // operator and they all are only used by the PHI, PHI together their
6161 // inputs, and do the operation once, to the result of the PHI.
6162 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6163 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6165 // Scan the instruction, looking for input operations that can be folded away.
6166 // If all input operands to the phi are the same instruction (e.g. a cast from
6167 // the same type or "+42") we can pull the operation through the PHI, reducing
6168 // code size and simplifying code.
6169 Constant *ConstantOp = 0;
6170 const Type *CastSrcTy = 0;
6171 if (isa<CastInst>(FirstInst)) {
6172 CastSrcTy = FirstInst->getOperand(0)->getType();
6173 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6174 // Can fold binop or shift if the RHS is a constant.
6175 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6176 if (ConstantOp == 0) return 0;
6178 return 0; // Cannot fold this operation.
6181 // Check to see if all arguments are the same operation.
6182 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6183 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6184 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6185 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6188 if (I->getOperand(0)->getType() != CastSrcTy)
6189 return 0; // Cast operation must match.
6190 } else if (I->getOperand(1) != ConstantOp) {
6195 // Okay, they are all the same operation. Create a new PHI node of the
6196 // correct type, and PHI together all of the LHS's of the instructions.
6197 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6198 PN.getName()+".in");
6199 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
6201 Value *InVal = FirstInst->getOperand(0);
6202 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
6204 // Add all operands to the new PHI.
6205 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6206 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6207 if (NewInVal != InVal)
6209 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6214 // The new PHI unions all of the same values together. This is really
6215 // common, so we handle it intelligently here for compile-time speed.
6219 InsertNewInstBefore(NewPN, PN);
6223 // Insert and return the new operation.
6224 if (isa<CastInst>(FirstInst))
6225 return new CastInst(PhiVal, PN.getType());
6226 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
6227 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
6229 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
6230 PhiVal, ConstantOp);
6233 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6235 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6236 if (PN->use_empty()) return true;
6237 if (!PN->hasOneUse()) return false;
6239 // Remember this node, and if we find the cycle, return.
6240 if (!PotentiallyDeadPHIs.insert(PN).second)
6243 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6244 return DeadPHICycle(PU, PotentiallyDeadPHIs);
6249 // PHINode simplification
6251 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
6252 if (Value *V = PN.hasConstantValue())
6253 return ReplaceInstUsesWith(PN, V);
6255 // If the only user of this instruction is a cast instruction, and all of the
6256 // incoming values are constants, change this PHI to merge together the casted
6259 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6260 if (CI->getType() != PN.getType()) { // noop casts will be folded
6261 bool AllConstant = true;
6262 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6263 if (!isa<Constant>(PN.getIncomingValue(i))) {
6264 AllConstant = false;
6268 // Make a new PHI with all casted values.
6269 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6270 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6271 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6272 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6273 PN.getIncomingBlock(i));
6276 // Update the cast instruction.
6277 CI->setOperand(0, New);
6278 WorkList.push_back(CI); // revisit the cast instruction to fold.
6279 WorkList.push_back(New); // Make sure to revisit the new Phi
6280 return &PN; // PN is now dead!
6284 // If all PHI operands are the same operation, pull them through the PHI,
6285 // reducing code size.
6286 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6287 PN.getIncomingValue(0)->hasOneUse())
6288 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6291 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6292 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6293 // PHI)... break the cycle.
6295 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6296 std::set<PHINode*> PotentiallyDeadPHIs;
6297 PotentiallyDeadPHIs.insert(&PN);
6298 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6299 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6305 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6306 Instruction *InsertPoint,
6308 unsigned PS = IC->getTargetData().getPointerSize();
6309 const Type *VTy = V->getType();
6310 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6311 // We must insert a cast to ensure we sign-extend.
6312 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6313 V->getName()), *InsertPoint);
6314 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6319 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
6320 Value *PtrOp = GEP.getOperand(0);
6321 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
6322 // If so, eliminate the noop.
6323 if (GEP.getNumOperands() == 1)
6324 return ReplaceInstUsesWith(GEP, PtrOp);
6326 if (isa<UndefValue>(GEP.getOperand(0)))
6327 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6329 bool HasZeroPointerIndex = false;
6330 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6331 HasZeroPointerIndex = C->isNullValue();
6333 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
6334 return ReplaceInstUsesWith(GEP, PtrOp);
6336 // Eliminate unneeded casts for indices.
6337 bool MadeChange = false;
6338 gep_type_iterator GTI = gep_type_begin(GEP);
6339 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6340 if (isa<SequentialType>(*GTI)) {
6341 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6342 Value *Src = CI->getOperand(0);
6343 const Type *SrcTy = Src->getType();
6344 const Type *DestTy = CI->getType();
6345 if (Src->getType()->isInteger()) {
6346 if (SrcTy->getPrimitiveSizeInBits() ==
6347 DestTy->getPrimitiveSizeInBits()) {
6348 // We can always eliminate a cast from ulong or long to the other.
6349 // We can always eliminate a cast from uint to int or the other on
6350 // 32-bit pointer platforms.
6351 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
6353 GEP.setOperand(i, Src);
6355 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6356 SrcTy->getPrimitiveSize() == 4) {
6357 // We can always eliminate a cast from int to [u]long. We can
6358 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6360 if (SrcTy->isSigned() ||
6361 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
6363 GEP.setOperand(i, Src);
6368 // If we are using a wider index than needed for this platform, shrink it
6369 // to what we need. If the incoming value needs a cast instruction,
6370 // insert it. This explicit cast can make subsequent optimizations more
6372 Value *Op = GEP.getOperand(i);
6373 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
6374 if (Constant *C = dyn_cast<Constant>(Op)) {
6375 GEP.setOperand(i, ConstantExpr::getCast(C,
6376 TD->getIntPtrType()->getSignedVersion()));
6379 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6380 Op->getName()), GEP);
6381 GEP.setOperand(i, Op);
6385 // If this is a constant idx, make sure to canonicalize it to be a signed
6386 // operand, otherwise CSE and other optimizations are pessimized.
6387 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6388 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6389 CUI->getType()->getSignedVersion()));
6393 if (MadeChange) return &GEP;
6395 // Combine Indices - If the source pointer to this getelementptr instruction
6396 // is a getelementptr instruction, combine the indices of the two
6397 // getelementptr instructions into a single instruction.
6399 std::vector<Value*> SrcGEPOperands;
6400 if (User *Src = dyn_castGetElementPtr(PtrOp))
6401 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
6403 if (!SrcGEPOperands.empty()) {
6404 // Note that if our source is a gep chain itself that we wait for that
6405 // chain to be resolved before we perform this transformation. This
6406 // avoids us creating a TON of code in some cases.
6408 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6409 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6410 return 0; // Wait until our source is folded to completion.
6412 std::vector<Value *> Indices;
6414 // Find out whether the last index in the source GEP is a sequential idx.
6415 bool EndsWithSequential = false;
6416 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6417 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
6418 EndsWithSequential = !isa<StructType>(*I);
6420 // Can we combine the two pointer arithmetics offsets?
6421 if (EndsWithSequential) {
6422 // Replace: gep (gep %P, long B), long A, ...
6423 // With: T = long A+B; gep %P, T, ...
6425 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
6426 if (SO1 == Constant::getNullValue(SO1->getType())) {
6428 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6431 // If they aren't the same type, convert both to an integer of the
6432 // target's pointer size.
6433 if (SO1->getType() != GO1->getType()) {
6434 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6435 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6436 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6437 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6439 unsigned PS = TD->getPointerSize();
6440 if (SO1->getType()->getPrimitiveSize() == PS) {
6441 // Convert GO1 to SO1's type.
6442 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6444 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6445 // Convert SO1 to GO1's type.
6446 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6448 const Type *PT = TD->getIntPtrType();
6449 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6450 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6454 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6455 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6457 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6458 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
6462 // Recycle the GEP we already have if possible.
6463 if (SrcGEPOperands.size() == 2) {
6464 GEP.setOperand(0, SrcGEPOperands[0]);
6465 GEP.setOperand(1, Sum);
6468 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6469 SrcGEPOperands.end()-1);
6470 Indices.push_back(Sum);
6471 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6473 } else if (isa<Constant>(*GEP.idx_begin()) &&
6474 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
6475 SrcGEPOperands.size() != 1) {
6476 // Otherwise we can do the fold if the first index of the GEP is a zero
6477 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6478 SrcGEPOperands.end());
6479 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6482 if (!Indices.empty())
6483 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
6485 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
6486 // GEP of global variable. If all of the indices for this GEP are
6487 // constants, we can promote this to a constexpr instead of an instruction.
6489 // Scan for nonconstants...
6490 std::vector<Constant*> Indices;
6491 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6492 for (; I != E && isa<Constant>(*I); ++I)
6493 Indices.push_back(cast<Constant>(*I));
6495 if (I == E) { // If they are all constants...
6496 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
6498 // Replace all uses of the GEP with the new constexpr...
6499 return ReplaceInstUsesWith(GEP, CE);
6501 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6502 if (!isa<PointerType>(X->getType())) {
6503 // Not interesting. Source pointer must be a cast from pointer.
6504 } else if (HasZeroPointerIndex) {
6505 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6506 // into : GEP [10 x ubyte]* X, long 0, ...
6508 // This occurs when the program declares an array extern like "int X[];"
6510 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6511 const PointerType *XTy = cast<PointerType>(X->getType());
6512 if (const ArrayType *XATy =
6513 dyn_cast<ArrayType>(XTy->getElementType()))
6514 if (const ArrayType *CATy =
6515 dyn_cast<ArrayType>(CPTy->getElementType()))
6516 if (CATy->getElementType() == XATy->getElementType()) {
6517 // At this point, we know that the cast source type is a pointer
6518 // to an array of the same type as the destination pointer
6519 // array. Because the array type is never stepped over (there
6520 // is a leading zero) we can fold the cast into this GEP.
6521 GEP.setOperand(0, X);
6524 } else if (GEP.getNumOperands() == 2) {
6525 // Transform things like:
6526 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6527 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
6528 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6529 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6530 if (isa<ArrayType>(SrcElTy) &&
6531 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6532 TD->getTypeSize(ResElTy)) {
6533 Value *V = InsertNewInstBefore(
6534 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6535 GEP.getOperand(1), GEP.getName()), GEP);
6536 return new CastInst(V, GEP.getType());
6539 // Transform things like:
6540 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6541 // (where tmp = 8*tmp2) into:
6542 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6544 if (isa<ArrayType>(SrcElTy) &&
6545 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6546 uint64_t ArrayEltSize =
6547 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6549 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6550 // allow either a mul, shift, or constant here.
6552 ConstantInt *Scale = 0;
6553 if (ArrayEltSize == 1) {
6554 NewIdx = GEP.getOperand(1);
6555 Scale = ConstantInt::get(NewIdx->getType(), 1);
6556 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
6557 NewIdx = ConstantInt::get(CI->getType(), 1);
6559 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6560 if (Inst->getOpcode() == Instruction::Shl &&
6561 isa<ConstantInt>(Inst->getOperand(1))) {
6562 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6563 if (Inst->getType()->isSigned())
6564 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6566 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6567 NewIdx = Inst->getOperand(0);
6568 } else if (Inst->getOpcode() == Instruction::Mul &&
6569 isa<ConstantInt>(Inst->getOperand(1))) {
6570 Scale = cast<ConstantInt>(Inst->getOperand(1));
6571 NewIdx = Inst->getOperand(0);
6575 // If the index will be to exactly the right offset with the scale taken
6576 // out, perform the transformation.
6577 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6578 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6579 Scale = ConstantSInt::get(C->getType(),
6580 (int64_t)C->getRawValue() /
6581 (int64_t)ArrayEltSize);
6583 Scale = ConstantUInt::get(Scale->getType(),
6584 Scale->getRawValue() / ArrayEltSize);
6585 if (Scale->getRawValue() != 1) {
6586 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6587 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6588 NewIdx = InsertNewInstBefore(Sc, GEP);
6591 // Insert the new GEP instruction.
6593 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6594 NewIdx, GEP.getName());
6595 Idx = InsertNewInstBefore(Idx, GEP);
6596 return new CastInst(Idx, GEP.getType());
6605 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6606 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6607 if (AI.isArrayAllocation()) // Check C != 1
6608 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6609 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
6610 AllocationInst *New = 0;
6612 // Create and insert the replacement instruction...
6613 if (isa<MallocInst>(AI))
6614 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
6616 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
6617 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
6620 InsertNewInstBefore(New, AI);
6622 // Scan to the end of the allocation instructions, to skip over a block of
6623 // allocas if possible...
6625 BasicBlock::iterator It = New;
6626 while (isa<AllocationInst>(*It)) ++It;
6628 // Now that I is pointing to the first non-allocation-inst in the block,
6629 // insert our getelementptr instruction...
6631 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6632 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6633 New->getName()+".sub", It);
6635 // Now make everything use the getelementptr instead of the original
6637 return ReplaceInstUsesWith(AI, V);
6638 } else if (isa<UndefValue>(AI.getArraySize())) {
6639 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6642 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6643 // Note that we only do this for alloca's, because malloc should allocate and
6644 // return a unique pointer, even for a zero byte allocation.
6645 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
6646 TD->getTypeSize(AI.getAllocatedType()) == 0)
6647 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6652 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6653 Value *Op = FI.getOperand(0);
6655 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6656 if (CastInst *CI = dyn_cast<CastInst>(Op))
6657 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6658 FI.setOperand(0, CI->getOperand(0));
6662 // free undef -> unreachable.
6663 if (isa<UndefValue>(Op)) {
6664 // Insert a new store to null because we cannot modify the CFG here.
6665 new StoreInst(ConstantBool::True,
6666 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6667 return EraseInstFromFunction(FI);
6670 // If we have 'free null' delete the instruction. This can happen in stl code
6671 // when lots of inlining happens.
6672 if (isa<ConstantPointerNull>(Op))
6673 return EraseInstFromFunction(FI);
6679 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
6680 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6681 User *CI = cast<User>(LI.getOperand(0));
6682 Value *CastOp = CI->getOperand(0);
6684 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6685 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6686 const Type *SrcPTy = SrcTy->getElementType();
6688 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6689 isa<PackedType>(DestPTy)) {
6690 // If the source is an array, the code below will not succeed. Check to
6691 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6693 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6694 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6695 if (ASrcTy->getNumElements() != 0) {
6696 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6697 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6698 SrcTy = cast<PointerType>(CastOp->getType());
6699 SrcPTy = SrcTy->getElementType();
6702 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6703 isa<PackedType>(SrcPTy)) &&
6704 // Do not allow turning this into a load of an integer, which is then
6705 // casted to a pointer, this pessimizes pointer analysis a lot.
6706 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
6707 IC.getTargetData().getTypeSize(SrcPTy) ==
6708 IC.getTargetData().getTypeSize(DestPTy)) {
6710 // Okay, we are casting from one integer or pointer type to another of
6711 // the same size. Instead of casting the pointer before the load, cast
6712 // the result of the loaded value.
6713 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6715 LI.isVolatile()),LI);
6716 // Now cast the result of the load.
6717 return new CastInst(NewLoad, LI.getType());
6724 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
6725 /// from this value cannot trap. If it is not obviously safe to load from the
6726 /// specified pointer, we do a quick local scan of the basic block containing
6727 /// ScanFrom, to determine if the address is already accessed.
6728 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6729 // If it is an alloca or global variable, it is always safe to load from.
6730 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6732 // Otherwise, be a little bit agressive by scanning the local block where we
6733 // want to check to see if the pointer is already being loaded or stored
6734 // from/to. If so, the previous load or store would have already trapped,
6735 // so there is no harm doing an extra load (also, CSE will later eliminate
6736 // the load entirely).
6737 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6742 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6743 if (LI->getOperand(0) == V) return true;
6744 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6745 if (SI->getOperand(1) == V) return true;
6751 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6752 Value *Op = LI.getOperand(0);
6754 // load (cast X) --> cast (load X) iff safe
6755 if (CastInst *CI = dyn_cast<CastInst>(Op))
6756 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6759 // None of the following transforms are legal for volatile loads.
6760 if (LI.isVolatile()) return 0;
6762 if (&LI.getParent()->front() != &LI) {
6763 BasicBlock::iterator BBI = &LI; --BBI;
6764 // If the instruction immediately before this is a store to the same
6765 // address, do a simple form of store->load forwarding.
6766 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6767 if (SI->getOperand(1) == LI.getOperand(0))
6768 return ReplaceInstUsesWith(LI, SI->getOperand(0));
6769 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6770 if (LIB->getOperand(0) == LI.getOperand(0))
6771 return ReplaceInstUsesWith(LI, LIB);
6774 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6775 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6776 isa<UndefValue>(GEPI->getOperand(0))) {
6777 // Insert a new store to null instruction before the load to indicate
6778 // that this code is not reachable. We do this instead of inserting
6779 // an unreachable instruction directly because we cannot modify the
6781 new StoreInst(UndefValue::get(LI.getType()),
6782 Constant::getNullValue(Op->getType()), &LI);
6783 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6786 if (Constant *C = dyn_cast<Constant>(Op)) {
6787 // load null/undef -> undef
6788 if ((C->isNullValue() || isa<UndefValue>(C))) {
6789 // Insert a new store to null instruction before the load to indicate that
6790 // this code is not reachable. We do this instead of inserting an
6791 // unreachable instruction directly because we cannot modify the CFG.
6792 new StoreInst(UndefValue::get(LI.getType()),
6793 Constant::getNullValue(Op->getType()), &LI);
6794 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6797 // Instcombine load (constant global) into the value loaded.
6798 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6799 if (GV->isConstant() && !GV->isExternal())
6800 return ReplaceInstUsesWith(LI, GV->getInitializer());
6802 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6803 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6804 if (CE->getOpcode() == Instruction::GetElementPtr) {
6805 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6806 if (GV->isConstant() && !GV->isExternal())
6808 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
6809 return ReplaceInstUsesWith(LI, V);
6810 if (CE->getOperand(0)->isNullValue()) {
6811 // Insert a new store to null instruction before the load to indicate
6812 // that this code is not reachable. We do this instead of inserting
6813 // an unreachable instruction directly because we cannot modify the
6815 new StoreInst(UndefValue::get(LI.getType()),
6816 Constant::getNullValue(Op->getType()), &LI);
6817 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6820 } else if (CE->getOpcode() == Instruction::Cast) {
6821 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6826 if (Op->hasOneUse()) {
6827 // Change select and PHI nodes to select values instead of addresses: this
6828 // helps alias analysis out a lot, allows many others simplifications, and
6829 // exposes redundancy in the code.
6831 // Note that we cannot do the transformation unless we know that the
6832 // introduced loads cannot trap! Something like this is valid as long as
6833 // the condition is always false: load (select bool %C, int* null, int* %G),
6834 // but it would not be valid if we transformed it to load from null
6837 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6838 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
6839 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6840 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
6841 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
6842 SI->getOperand(1)->getName()+".val"), LI);
6843 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
6844 SI->getOperand(2)->getName()+".val"), LI);
6845 return new SelectInst(SI->getCondition(), V1, V2);
6848 // load (select (cond, null, P)) -> load P
6849 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6850 if (C->isNullValue()) {
6851 LI.setOperand(0, SI->getOperand(2));
6855 // load (select (cond, P, null)) -> load P
6856 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6857 if (C->isNullValue()) {
6858 LI.setOperand(0, SI->getOperand(1));
6862 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6863 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
6864 bool Safe = PN->getParent() == LI.getParent();
6866 // Scan all of the instructions between the PHI and the load to make
6867 // sure there are no instructions that might possibly alter the value
6868 // loaded from the PHI.
6870 BasicBlock::iterator I = &LI;
6871 for (--I; !isa<PHINode>(I); --I)
6872 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6878 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
6879 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
6880 PN->getIncomingBlock(i)->getTerminator()))
6885 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6886 InsertNewInstBefore(NewPN, *PN);
6887 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6889 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6890 BasicBlock *BB = PN->getIncomingBlock(i);
6891 Value *&TheLoad = LoadMap[BB];
6893 Value *InVal = PN->getIncomingValue(i);
6894 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6895 InVal->getName()+".val"),
6896 *BB->getTerminator());
6898 NewPN->addIncoming(TheLoad, BB);
6900 return ReplaceInstUsesWith(LI, NewPN);
6907 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6909 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6910 User *CI = cast<User>(SI.getOperand(1));
6911 Value *CastOp = CI->getOperand(0);
6913 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6914 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6915 const Type *SrcPTy = SrcTy->getElementType();
6917 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6918 // If the source is an array, the code below will not succeed. Check to
6919 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6921 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6922 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6923 if (ASrcTy->getNumElements() != 0) {
6924 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6925 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6926 SrcTy = cast<PointerType>(CastOp->getType());
6927 SrcPTy = SrcTy->getElementType();
6930 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
6931 IC.getTargetData().getTypeSize(SrcPTy) ==
6932 IC.getTargetData().getTypeSize(DestPTy)) {
6934 // Okay, we are casting from one integer or pointer type to another of
6935 // the same size. Instead of casting the pointer before the store, cast
6936 // the value to be stored.
6938 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6939 NewCast = ConstantExpr::getCast(C, SrcPTy);
6941 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6943 SI.getOperand(0)->getName()+".c"), SI);
6945 return new StoreInst(NewCast, CastOp);
6952 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6953 Value *Val = SI.getOperand(0);
6954 Value *Ptr = SI.getOperand(1);
6956 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
6957 EraseInstFromFunction(SI);
6962 // Do really simple DSE, to catch cases where there are several consequtive
6963 // stores to the same location, separated by a few arithmetic operations. This
6964 // situation often occurs with bitfield accesses.
6965 BasicBlock::iterator BBI = &SI;
6966 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6970 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6971 // Prev store isn't volatile, and stores to the same location?
6972 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6975 EraseInstFromFunction(*PrevSI);
6981 // If this is a load, we have to stop. However, if the loaded value is from
6982 // the pointer we're loading and is producing the pointer we're storing,
6983 // then *this* store is dead (X = load P; store X -> P).
6984 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6985 if (LI == Val && LI->getOperand(0) == Ptr) {
6986 EraseInstFromFunction(SI);
6990 // Otherwise, this is a load from some other location. Stores before it
6995 // Don't skip over loads or things that can modify memory.
6996 if (BBI->mayWriteToMemory())
7001 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
7003 // store X, null -> turns into 'unreachable' in SimplifyCFG
7004 if (isa<ConstantPointerNull>(Ptr)) {
7005 if (!isa<UndefValue>(Val)) {
7006 SI.setOperand(0, UndefValue::get(Val->getType()));
7007 if (Instruction *U = dyn_cast<Instruction>(Val))
7008 WorkList.push_back(U); // Dropped a use.
7011 return 0; // Do not modify these!
7014 // store undef, Ptr -> noop
7015 if (isa<UndefValue>(Val)) {
7016 EraseInstFromFunction(SI);
7021 // If the pointer destination is a cast, see if we can fold the cast into the
7023 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7024 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7026 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7027 if (CE->getOpcode() == Instruction::Cast)
7028 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7032 // If this store is the last instruction in the basic block, and if the block
7033 // ends with an unconditional branch, try to move it to the successor block.
7035 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7036 if (BI->isUnconditional()) {
7037 // Check to see if the successor block has exactly two incoming edges. If
7038 // so, see if the other predecessor contains a store to the same location.
7039 // if so, insert a PHI node (if needed) and move the stores down.
7040 BasicBlock *Dest = BI->getSuccessor(0);
7042 pred_iterator PI = pred_begin(Dest);
7043 BasicBlock *Other = 0;
7044 if (*PI != BI->getParent())
7047 if (PI != pred_end(Dest)) {
7048 if (*PI != BI->getParent())
7053 if (++PI != pred_end(Dest))
7056 if (Other) { // If only one other pred...
7057 BBI = Other->getTerminator();
7058 // Make sure this other block ends in an unconditional branch and that
7059 // there is an instruction before the branch.
7060 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7061 BBI != Other->begin()) {
7063 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7065 // If this instruction is a store to the same location.
7066 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7067 // Okay, we know we can perform this transformation. Insert a PHI
7068 // node now if we need it.
7069 Value *MergedVal = OtherStore->getOperand(0);
7070 if (MergedVal != SI.getOperand(0)) {
7071 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7072 PN->reserveOperandSpace(2);
7073 PN->addIncoming(SI.getOperand(0), SI.getParent());
7074 PN->addIncoming(OtherStore->getOperand(0), Other);
7075 MergedVal = InsertNewInstBefore(PN, Dest->front());
7078 // Advance to a place where it is safe to insert the new store and
7080 BBI = Dest->begin();
7081 while (isa<PHINode>(BBI)) ++BBI;
7082 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7083 OtherStore->isVolatile()), *BBI);
7085 // Nuke the old stores.
7086 EraseInstFromFunction(SI);
7087 EraseInstFromFunction(*OtherStore);
7099 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7100 // Change br (not X), label True, label False to: br X, label False, True
7102 BasicBlock *TrueDest;
7103 BasicBlock *FalseDest;
7104 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7105 !isa<Constant>(X)) {
7106 // Swap Destinations and condition...
7108 BI.setSuccessor(0, FalseDest);
7109 BI.setSuccessor(1, TrueDest);
7113 // Cannonicalize setne -> seteq
7114 Instruction::BinaryOps Op; Value *Y;
7115 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7116 TrueDest, FalseDest)))
7117 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7118 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7119 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7120 std::string Name = I->getName(); I->setName("");
7121 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7122 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
7123 // Swap Destinations and condition...
7124 BI.setCondition(NewSCC);
7125 BI.setSuccessor(0, FalseDest);
7126 BI.setSuccessor(1, TrueDest);
7127 removeFromWorkList(I);
7128 I->getParent()->getInstList().erase(I);
7129 WorkList.push_back(cast<Instruction>(NewSCC));
7136 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7137 Value *Cond = SI.getCondition();
7138 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7139 if (I->getOpcode() == Instruction::Add)
7140 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7141 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7142 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
7143 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
7145 SI.setOperand(0, I->getOperand(0));
7146 WorkList.push_back(I);
7153 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7154 /// is to leave as a vector operation.
7155 static bool CheapToScalarize(Value *V, bool isConstant) {
7156 if (isa<ConstantAggregateZero>(V))
7158 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7159 if (isConstant) return true;
7160 // If all elts are the same, we can extract.
7161 Constant *Op0 = C->getOperand(0);
7162 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7163 if (C->getOperand(i) != Op0)
7167 Instruction *I = dyn_cast<Instruction>(V);
7168 if (!I) return false;
7170 // Insert element gets simplified to the inserted element or is deleted if
7171 // this is constant idx extract element and its a constant idx insertelt.
7172 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7173 isa<ConstantInt>(I->getOperand(2)))
7175 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7177 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7178 if (BO->hasOneUse() &&
7179 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7180 CheapToScalarize(BO->getOperand(1), isConstant)))
7186 /// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7187 /// elements into values that are larger than the #elts in the input.
7188 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7189 unsigned NElts = SVI->getType()->getNumElements();
7190 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7191 return std::vector<unsigned>(NElts, 0);
7192 if (isa<UndefValue>(SVI->getOperand(2)))
7193 return std::vector<unsigned>(NElts, 2*NElts);
7195 std::vector<unsigned> Result;
7196 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7197 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7198 if (isa<UndefValue>(CP->getOperand(i)))
7199 Result.push_back(NElts*2); // undef -> 8
7201 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7205 /// FindScalarElement - Given a vector and an element number, see if the scalar
7206 /// value is already around as a register, for example if it were inserted then
7207 /// extracted from the vector.
7208 static Value *FindScalarElement(Value *V, unsigned EltNo) {
7209 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7210 const PackedType *PTy = cast<PackedType>(V->getType());
7211 unsigned Width = PTy->getNumElements();
7212 if (EltNo >= Width) // Out of range access.
7213 return UndefValue::get(PTy->getElementType());
7215 if (isa<UndefValue>(V))
7216 return UndefValue::get(PTy->getElementType());
7217 else if (isa<ConstantAggregateZero>(V))
7218 return Constant::getNullValue(PTy->getElementType());
7219 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7220 return CP->getOperand(EltNo);
7221 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7222 // If this is an insert to a variable element, we don't know what it is.
7223 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7224 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7226 // If this is an insert to the element we are looking for, return the
7228 if (EltNo == IIElt) return III->getOperand(1);
7230 // Otherwise, the insertelement doesn't modify the value, recurse on its
7232 return FindScalarElement(III->getOperand(0), EltNo);
7233 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
7234 unsigned InEl = getShuffleMask(SVI)[EltNo];
7236 return FindScalarElement(SVI->getOperand(0), InEl);
7237 else if (InEl < Width*2)
7238 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7240 return UndefValue::get(PTy->getElementType());
7243 // Otherwise, we don't know.
7247 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
7249 // If packed val is undef, replace extract with scalar undef.
7250 if (isa<UndefValue>(EI.getOperand(0)))
7251 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7253 // If packed val is constant 0, replace extract with scalar 0.
7254 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7255 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7257 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7258 // If packed val is constant with uniform operands, replace EI
7259 // with that operand
7260 Constant *op0 = C->getOperand(0);
7261 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7262 if (C->getOperand(i) != op0) {
7267 return ReplaceInstUsesWith(EI, op0);
7270 // If extracting a specified index from the vector, see if we can recursively
7271 // find a previously computed scalar that was inserted into the vector.
7272 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
7273 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7274 return ReplaceInstUsesWith(EI, Elt);
7277 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
7278 if (I->hasOneUse()) {
7279 // Push extractelement into predecessor operation if legal and
7280 // profitable to do so
7281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
7282 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7283 if (CheapToScalarize(BO, isConstantElt)) {
7284 ExtractElementInst *newEI0 =
7285 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7286 EI.getName()+".lhs");
7287 ExtractElementInst *newEI1 =
7288 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7289 EI.getName()+".rhs");
7290 InsertNewInstBefore(newEI0, EI);
7291 InsertNewInstBefore(newEI1, EI);
7292 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7294 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7295 Value *Ptr = InsertCastBefore(I->getOperand(0),
7296 PointerType::get(EI.getType()), EI);
7297 GetElementPtrInst *GEP =
7298 new GetElementPtrInst(Ptr, EI.getOperand(1),
7299 I->getName() + ".gep");
7300 InsertNewInstBefore(GEP, EI);
7301 return new LoadInst(GEP);
7304 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7305 // Extracting the inserted element?
7306 if (IE->getOperand(2) == EI.getOperand(1))
7307 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7308 // If the inserted and extracted elements are constants, they must not
7309 // be the same value, extract from the pre-inserted value instead.
7310 if (isa<Constant>(IE->getOperand(2)) &&
7311 isa<Constant>(EI.getOperand(1))) {
7312 AddUsesToWorkList(EI);
7313 EI.setOperand(0, IE->getOperand(0));
7316 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7317 // If this is extracting an element from a shufflevector, figure out where
7318 // it came from and extract from the appropriate input element instead.
7319 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
7320 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7322 if (SrcIdx < SVI->getType()->getNumElements())
7323 Src = SVI->getOperand(0);
7324 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7325 SrcIdx -= SVI->getType()->getNumElements();
7326 Src = SVI->getOperand(1);
7328 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7330 return new ExtractElementInst(Src,
7331 ConstantUInt::get(Type::UIntTy, SrcIdx));
7338 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7339 /// elements from either LHS or RHS, return the shuffle mask and true.
7340 /// Otherwise, return false.
7341 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7342 std::vector<Constant*> &Mask) {
7343 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7344 "Invalid CollectSingleShuffleElements");
7345 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7347 if (isa<UndefValue>(V)) {
7348 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7350 } else if (V == LHS) {
7351 for (unsigned i = 0; i != NumElts; ++i)
7352 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7354 } else if (V == RHS) {
7355 for (unsigned i = 0; i != NumElts; ++i)
7356 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7358 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7359 // If this is an insert of an extract from some other vector, include it.
7360 Value *VecOp = IEI->getOperand(0);
7361 Value *ScalarOp = IEI->getOperand(1);
7362 Value *IdxOp = IEI->getOperand(2);
7364 if (!isa<ConstantInt>(IdxOp))
7366 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7368 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7369 // Okay, we can handle this if the vector we are insertinting into is
7371 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7372 // If so, update the mask to reflect the inserted undef.
7373 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7376 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7377 if (isa<ConstantInt>(EI->getOperand(1)) &&
7378 EI->getOperand(0)->getType() == V->getType()) {
7379 unsigned ExtractedIdx =
7380 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7382 // This must be extracting from either LHS or RHS.
7383 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7384 // Okay, we can handle this if the vector we are insertinting into is
7386 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7387 // If so, update the mask to reflect the inserted value.
7388 if (EI->getOperand(0) == LHS) {
7389 Mask[InsertedIdx & (NumElts-1)] =
7390 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7392 assert(EI->getOperand(0) == RHS);
7393 Mask[InsertedIdx & (NumElts-1)] =
7394 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7403 // TODO: Handle shufflevector here!
7408 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7409 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7410 /// that computes V and the LHS value of the shuffle.
7411 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
7413 assert(isa<PackedType>(V->getType()) &&
7414 (RHS == 0 || V->getType() == RHS->getType()) &&
7415 "Invalid shuffle!");
7416 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7418 if (isa<UndefValue>(V)) {
7419 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7421 } else if (isa<ConstantAggregateZero>(V)) {
7422 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7424 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7425 // If this is an insert of an extract from some other vector, include it.
7426 Value *VecOp = IEI->getOperand(0);
7427 Value *ScalarOp = IEI->getOperand(1);
7428 Value *IdxOp = IEI->getOperand(2);
7430 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7431 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7432 EI->getOperand(0)->getType() == V->getType()) {
7433 unsigned ExtractedIdx =
7434 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7435 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7437 // Either the extracted from or inserted into vector must be RHSVec,
7438 // otherwise we'd end up with a shuffle of three inputs.
7439 if (EI->getOperand(0) == RHS || RHS == 0) {
7440 RHS = EI->getOperand(0);
7441 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
7442 Mask[InsertedIdx & (NumElts-1)] =
7443 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7448 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
7449 // Everything but the extracted element is replaced with the RHS.
7450 for (unsigned i = 0; i != NumElts; ++i) {
7451 if (i != InsertedIdx)
7452 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7457 // If this insertelement is a chain that comes from exactly these two
7458 // vectors, return the vector and the effective shuffle.
7459 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7460 return EI->getOperand(0);
7465 // TODO: Handle shufflevector here!
7467 // Otherwise, can't do anything fancy. Return an identity vector.
7468 for (unsigned i = 0; i != NumElts; ++i)
7469 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7473 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7474 Value *VecOp = IE.getOperand(0);
7475 Value *ScalarOp = IE.getOperand(1);
7476 Value *IdxOp = IE.getOperand(2);
7478 // If the inserted element was extracted from some other vector, and if the
7479 // indexes are constant, try to turn this into a shufflevector operation.
7480 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7481 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7482 EI->getOperand(0)->getType() == IE.getType()) {
7483 unsigned NumVectorElts = IE.getType()->getNumElements();
7484 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7485 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7487 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7488 return ReplaceInstUsesWith(IE, VecOp);
7490 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7491 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7493 // If we are extracting a value from a vector, then inserting it right
7494 // back into the same place, just use the input vector.
7495 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7496 return ReplaceInstUsesWith(IE, VecOp);
7498 // We could theoretically do this for ANY input. However, doing so could
7499 // turn chains of insertelement instructions into a chain of shufflevector
7500 // instructions, and right now we do not merge shufflevectors. As such,
7501 // only do this in a situation where it is clear that there is benefit.
7502 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7503 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7504 // the values of VecOp, except then one read from EIOp0.
7505 // Build a new shuffle mask.
7506 std::vector<Constant*> Mask;
7507 if (isa<UndefValue>(VecOp))
7508 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7510 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7511 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7514 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7515 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7516 ConstantPacked::get(Mask));
7519 // If this insertelement isn't used by some other insertelement, turn it
7520 // (and any insertelements it points to), into one big shuffle.
7521 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7522 std::vector<Constant*> Mask;
7524 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7525 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7526 // We now have a shuffle of LHS, RHS, Mask.
7527 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
7536 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7537 Value *LHS = SVI.getOperand(0);
7538 Value *RHS = SVI.getOperand(1);
7539 std::vector<unsigned> Mask = getShuffleMask(&SVI);
7541 bool MadeChange = false;
7543 if (isa<UndefValue>(SVI.getOperand(2)))
7544 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7546 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7547 // the undef, change them to undefs.
7549 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7550 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7551 if (LHS == RHS || isa<UndefValue>(LHS)) {
7552 if (isa<UndefValue>(LHS) && LHS == RHS) {
7553 // shuffle(undef,undef,mask) -> undef.
7554 return ReplaceInstUsesWith(SVI, LHS);
7557 // Remap any references to RHS to use LHS.
7558 std::vector<Constant*> Elts;
7559 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7561 Elts.push_back(UndefValue::get(Type::UIntTy));
7563 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7564 (Mask[i] < e && isa<UndefValue>(LHS)))
7565 Mask[i] = 2*e; // Turn into undef.
7567 Mask[i] &= (e-1); // Force to LHS.
7568 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7571 SVI.setOperand(0, SVI.getOperand(1));
7572 SVI.setOperand(1, UndefValue::get(RHS->getType()));
7573 SVI.setOperand(2, ConstantPacked::get(Elts));
7574 LHS = SVI.getOperand(0);
7575 RHS = SVI.getOperand(1);
7579 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
7580 bool isLHSID = true, isRHSID = true;
7582 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7583 if (Mask[i] >= e*2) continue; // Ignore undef values.
7584 // Is this an identity shuffle of the LHS value?
7585 isLHSID &= (Mask[i] == i);
7587 // Is this an identity shuffle of the RHS value?
7588 isRHSID &= (Mask[i]-e == i);
7591 // Eliminate identity shuffles.
7592 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7593 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
7595 // If the LHS is a shufflevector itself, see if we can combine it with this
7596 // one without producing an unusual shuffle. Here we are really conservative:
7597 // we are absolutely afraid of producing a shuffle mask not in the input
7598 // program, because the code gen may not be smart enough to turn a merged
7599 // shuffle into two specific shuffles: it may produce worse code. As such,
7600 // we only merge two shuffles if the result is one of the two input shuffle
7601 // masks. In this case, merging the shuffles just removes one instruction,
7602 // which we know is safe. This is good for things like turning:
7603 // (splat(splat)) -> splat.
7604 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7605 if (isa<UndefValue>(RHS)) {
7606 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7608 std::vector<unsigned> NewMask;
7609 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7611 NewMask.push_back(2*e);
7613 NewMask.push_back(LHSMask[Mask[i]]);
7615 // If the result mask is equal to the src shuffle or this shuffle mask, do
7617 if (NewMask == LHSMask || NewMask == Mask) {
7618 std::vector<Constant*> Elts;
7619 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7620 if (NewMask[i] >= e*2) {
7621 Elts.push_back(UndefValue::get(Type::UIntTy));
7623 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7626 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7627 LHSSVI->getOperand(1),
7628 ConstantPacked::get(Elts));
7633 return MadeChange ? &SVI : 0;
7638 void InstCombiner::removeFromWorkList(Instruction *I) {
7639 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7644 /// TryToSinkInstruction - Try to move the specified instruction from its
7645 /// current block into the beginning of DestBlock, which can only happen if it's
7646 /// safe to move the instruction past all of the instructions between it and the
7647 /// end of its block.
7648 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7649 assert(I->hasOneUse() && "Invariants didn't hold!");
7651 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7652 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
7654 // Do not sink alloca instructions out of the entry block.
7655 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7658 // We can only sink load instructions if there is nothing between the load and
7659 // the end of block that could change the value.
7660 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7661 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7663 if (Scan->mayWriteToMemory())
7667 BasicBlock::iterator InsertPos = DestBlock->begin();
7668 while (isa<PHINode>(InsertPos)) ++InsertPos;
7670 I->moveBefore(InsertPos);
7675 /// OptimizeConstantExpr - Given a constant expression and target data layout
7676 /// information, symbolically evaluation the constant expr to something simpler
7678 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7681 Constant *Ptr = CE->getOperand(0);
7682 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7683 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7684 // If this is a constant expr gep that is effectively computing an
7685 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7686 bool isFoldableGEP = true;
7687 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7688 if (!isa<ConstantInt>(CE->getOperand(i)))
7689 isFoldableGEP = false;
7690 if (isFoldableGEP) {
7691 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7692 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7693 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7694 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7695 return ConstantExpr::getCast(C, CE->getType());
7703 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7704 /// all reachable code to the worklist.
7706 /// This has a couple of tricks to make the code faster and more powerful. In
7707 /// particular, we constant fold and DCE instructions as we go, to avoid adding
7708 /// them to the worklist (this significantly speeds up instcombine on code where
7709 /// many instructions are dead or constant). Additionally, if we find a branch
7710 /// whose condition is a known constant, we only visit the reachable successors.
7712 static void AddReachableCodeToWorklist(BasicBlock *BB,
7713 std::set<BasicBlock*> &Visited,
7714 std::vector<Instruction*> &WorkList,
7715 const TargetData *TD) {
7716 // We have now visited this block! If we've already been here, bail out.
7717 if (!Visited.insert(BB).second) return;
7719 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7720 Instruction *Inst = BBI++;
7722 // DCE instruction if trivially dead.
7723 if (isInstructionTriviallyDead(Inst)) {
7725 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7726 Inst->eraseFromParent();
7730 // ConstantProp instruction if trivially constant.
7731 if (Constant *C = ConstantFoldInstruction(Inst)) {
7732 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7733 C = OptimizeConstantExpr(CE, TD);
7734 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7735 Inst->replaceAllUsesWith(C);
7737 Inst->eraseFromParent();
7741 WorkList.push_back(Inst);
7744 // Recursively visit successors. If this is a branch or switch on a constant,
7745 // only visit the reachable successor.
7746 TerminatorInst *TI = BB->getTerminator();
7747 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7748 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7749 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
7750 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7754 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7755 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7756 // See if this is an explicit destination.
7757 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7758 if (SI->getCaseValue(i) == Cond) {
7759 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
7763 // Otherwise it is the default destination.
7764 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
7769 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
7770 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
7773 bool InstCombiner::runOnFunction(Function &F) {
7774 bool Changed = false;
7775 TD = &getAnalysis<TargetData>();
7778 // Do a depth-first traversal of the function, populate the worklist with
7779 // the reachable instructions. Ignore blocks that are not reachable. Keep
7780 // track of which blocks we visit.
7781 std::set<BasicBlock*> Visited;
7782 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
7784 // Do a quick scan over the function. If we find any blocks that are
7785 // unreachable, remove any instructions inside of them. This prevents
7786 // the instcombine code from having to deal with some bad special cases.
7787 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7788 if (!Visited.count(BB)) {
7789 Instruction *Term = BB->getTerminator();
7790 while (Term != BB->begin()) { // Remove instrs bottom-up
7791 BasicBlock::iterator I = Term; --I;
7793 DEBUG(std::cerr << "IC: DCE: " << *I);
7796 if (!I->use_empty())
7797 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7798 I->eraseFromParent();
7803 while (!WorkList.empty()) {
7804 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7805 WorkList.pop_back();
7807 // Check to see if we can DCE the instruction.
7808 if (isInstructionTriviallyDead(I)) {
7809 // Add operands to the worklist.
7810 if (I->getNumOperands() < 4)
7811 AddUsesToWorkList(*I);
7814 DEBUG(std::cerr << "IC: DCE: " << *I);
7816 I->eraseFromParent();
7817 removeFromWorkList(I);
7821 // Instruction isn't dead, see if we can constant propagate it.
7822 if (Constant *C = ConstantFoldInstruction(I)) {
7823 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7824 C = OptimizeConstantExpr(CE, TD);
7825 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7827 // Add operands to the worklist.
7828 AddUsesToWorkList(*I);
7829 ReplaceInstUsesWith(*I, C);
7832 I->eraseFromParent();
7833 removeFromWorkList(I);
7837 // See if we can trivially sink this instruction to a successor basic block.
7838 if (I->hasOneUse()) {
7839 BasicBlock *BB = I->getParent();
7840 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7841 if (UserParent != BB) {
7842 bool UserIsSuccessor = false;
7843 // See if the user is one of our successors.
7844 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7845 if (*SI == UserParent) {
7846 UserIsSuccessor = true;
7850 // If the user is one of our immediate successors, and if that successor
7851 // only has us as a predecessors (we'd have to split the critical edge
7852 // otherwise), we can keep going.
7853 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7854 next(pred_begin(UserParent)) == pred_end(UserParent))
7855 // Okay, the CFG is simple enough, try to sink this instruction.
7856 Changed |= TryToSinkInstruction(I, UserParent);
7860 // Now that we have an instruction, try combining it to simplify it...
7861 if (Instruction *Result = visit(*I)) {
7863 // Should we replace the old instruction with a new one?
7865 DEBUG(std::cerr << "IC: Old = " << *I
7866 << " New = " << *Result);
7868 // Everything uses the new instruction now.
7869 I->replaceAllUsesWith(Result);
7871 // Push the new instruction and any users onto the worklist.
7872 WorkList.push_back(Result);
7873 AddUsersToWorkList(*Result);
7875 // Move the name to the new instruction first...
7876 std::string OldName = I->getName(); I->setName("");
7877 Result->setName(OldName);
7879 // Insert the new instruction into the basic block...
7880 BasicBlock *InstParent = I->getParent();
7881 BasicBlock::iterator InsertPos = I;
7883 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7884 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7887 InstParent->getInstList().insert(InsertPos, Result);
7889 // Make sure that we reprocess all operands now that we reduced their
7891 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7892 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7893 WorkList.push_back(OpI);
7895 // Instructions can end up on the worklist more than once. Make sure
7896 // we do not process an instruction that has been deleted.
7897 removeFromWorkList(I);
7899 // Erase the old instruction.
7900 InstParent->getInstList().erase(I);
7902 DEBUG(std::cerr << "IC: MOD = " << *I);
7904 // If the instruction was modified, it's possible that it is now dead.
7905 // if so, remove it.
7906 if (isInstructionTriviallyDead(I)) {
7907 // Make sure we process all operands now that we are reducing their
7909 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7910 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7911 WorkList.push_back(OpI);
7913 // Instructions may end up in the worklist more than once. Erase all
7914 // occurrences of this instruction.
7915 removeFromWorkList(I);
7916 I->eraseFromParent();
7918 WorkList.push_back(Result);
7919 AddUsersToWorkList(*Result);
7929 FunctionPass *llvm::createInstructionCombiningPass() {
7930 return new InstCombiner();