1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All SetCC instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
57 using namespace llvm::PatternMatch;
60 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
64 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
66 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
69 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
73 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
77 void AddUsersToWorkList(Value &I) {
78 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
80 WorkList.push_back(cast<Instruction>(*UI));
83 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
92 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93 /// dead. Add all of its operands to the worklist, turning them into
94 /// undef's to reduce the number of uses of those instructions.
96 /// Return the specified operand before it is turned into an undef.
98 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99 Value *R = I.getOperand(op);
101 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103 WorkList.push_back(Op);
104 // Set the operand to undef to drop the use.
105 I.setOperand(i, UndefValue::get(Op->getType()));
111 // removeFromWorkList - remove all instances of I from the worklist.
112 void removeFromWorkList(Instruction *I);
114 virtual bool runOnFunction(Function &F);
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117 AU.addRequired<TargetData>();
118 AU.addPreservedID(LCSSAID);
119 AU.setPreservesCFG();
122 TargetData &getTargetData() const { return *TD; }
124 // Visitation implementation - Implement instruction combining for different
125 // instruction types. The semantics are as follows:
127 // null - No change was made
128 // I - Change was made, I is still valid, I may be dead though
129 // otherwise - Change was made, replace I with returned instruction
131 Instruction *visitAdd(BinaryOperator &I);
132 Instruction *visitSub(BinaryOperator &I);
133 Instruction *visitMul(BinaryOperator &I);
134 Instruction *visitDiv(BinaryOperator &I);
135 Instruction *visitRem(BinaryOperator &I);
136 Instruction *visitAnd(BinaryOperator &I);
137 Instruction *visitOr (BinaryOperator &I);
138 Instruction *visitXor(BinaryOperator &I);
139 Instruction *visitSetCondInst(SetCondInst &I);
140 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
142 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
143 Instruction::BinaryOps Cond, Instruction &I);
144 Instruction *visitShiftInst(ShiftInst &I);
145 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
147 Instruction *visitCastInst(CastInst &CI);
148 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
150 Instruction *visitSelectInst(SelectInst &CI);
151 Instruction *visitCallInst(CallInst &CI);
152 Instruction *visitInvokeInst(InvokeInst &II);
153 Instruction *visitPHINode(PHINode &PN);
154 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
155 Instruction *visitAllocationInst(AllocationInst &AI);
156 Instruction *visitFreeInst(FreeInst &FI);
157 Instruction *visitLoadInst(LoadInst &LI);
158 Instruction *visitStoreInst(StoreInst &SI);
159 Instruction *visitBranchInst(BranchInst &BI);
160 Instruction *visitSwitchInst(SwitchInst &SI);
161 Instruction *visitInsertElementInst(InsertElementInst &IE);
162 Instruction *visitExtractElementInst(ExtractElementInst &EI);
163 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
165 // visitInstruction - Specify what to return for unhandled instructions...
166 Instruction *visitInstruction(Instruction &I) { return 0; }
169 Instruction *visitCallSite(CallSite CS);
170 bool transformConstExprCastCall(CallSite CS);
173 // InsertNewInstBefore - insert an instruction New before instruction Old
174 // in the program. Add the new instruction to the worklist.
176 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
177 assert(New && New->getParent() == 0 &&
178 "New instruction already inserted into a basic block!");
179 BasicBlock *BB = Old.getParent();
180 BB->getInstList().insert(&Old, New); // Insert inst
181 WorkList.push_back(New); // Add to worklist
185 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
186 /// This also adds the cast to the worklist. Finally, this returns the
188 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
189 if (V->getType() == Ty) return V;
191 if (Constant *CV = dyn_cast<Constant>(V))
192 return ConstantExpr::getCast(CV, Ty);
194 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
195 WorkList.push_back(C);
199 // ReplaceInstUsesWith - This method is to be used when an instruction is
200 // found to be dead, replacable with another preexisting expression. Here
201 // we add all uses of I to the worklist, replace all uses of I with the new
202 // value, then return I, so that the inst combiner will know that I was
205 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
206 AddUsersToWorkList(I); // Add all modified instrs to worklist
208 I.replaceAllUsesWith(V);
211 // If we are replacing the instruction with itself, this must be in a
212 // segment of unreachable code, so just clobber the instruction.
213 I.replaceAllUsesWith(UndefValue::get(I.getType()));
218 // UpdateValueUsesWith - This method is to be used when an value is
219 // found to be replacable with another preexisting expression or was
220 // updated. Here we add all uses of I to the worklist, replace all uses of
221 // I with the new value (unless the instruction was just updated), then
222 // return true, so that the inst combiner will know that I was modified.
224 bool UpdateValueUsesWith(Value *Old, Value *New) {
225 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
227 Old->replaceAllUsesWith(New);
228 if (Instruction *I = dyn_cast<Instruction>(Old))
229 WorkList.push_back(I);
230 if (Instruction *I = dyn_cast<Instruction>(New))
231 WorkList.push_back(I);
235 // EraseInstFromFunction - When dealing with an instruction that has side
236 // effects or produces a void value, we can't rely on DCE to delete the
237 // instruction. Instead, visit methods should return the value returned by
239 Instruction *EraseInstFromFunction(Instruction &I) {
240 assert(I.use_empty() && "Cannot erase instruction that is used!");
241 AddUsesToWorkList(I);
242 removeFromWorkList(&I);
244 return 0; // Don't do anything with FI
248 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
249 /// InsertBefore instruction. This is specialized a bit to avoid inserting
250 /// casts that are known to not do anything...
252 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
253 Instruction *InsertBefore);
255 // SimplifyCommutative - This performs a few simplifications for commutative
257 bool SimplifyCommutative(BinaryOperator &I);
259 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
260 uint64_t &KnownZero, uint64_t &KnownOne,
263 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
264 uint64_t &UndefElts, unsigned Depth = 0);
266 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
267 // PHI node as operand #0, see if we can fold the instruction into the PHI
268 // (which is only possible if all operands to the PHI are constants).
269 Instruction *FoldOpIntoPhi(Instruction &I);
271 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
272 // operator and they all are only used by the PHI, PHI together their
273 // inputs, and do the operation once, to the result of the PHI.
274 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
276 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
277 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
279 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
280 bool isSub, Instruction &I);
281 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
282 bool Inside, Instruction &IB);
283 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
284 Instruction *MatchBSwap(BinaryOperator &I);
286 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
289 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
292 // getComplexity: Assign a complexity or rank value to LLVM Values...
293 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
294 static unsigned getComplexity(Value *V) {
295 if (isa<Instruction>(V)) {
296 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
300 if (isa<Argument>(V)) return 3;
301 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
304 // isOnlyUse - Return true if this instruction will be deleted if we stop using
306 static bool isOnlyUse(Value *V) {
307 return V->hasOneUse() || isa<Constant>(V);
310 // getPromotedType - Return the specified type promoted as it would be to pass
311 // though a va_arg area...
312 static const Type *getPromotedType(const Type *Ty) {
313 switch (Ty->getTypeID()) {
314 case Type::SByteTyID:
315 case Type::ShortTyID: return Type::IntTy;
316 case Type::UByteTyID:
317 case Type::UShortTyID: return Type::UIntTy;
318 case Type::FloatTyID: return Type::DoubleTy;
323 /// isCast - If the specified operand is a CastInst or a constant expr cast,
324 /// return the operand value, otherwise return null.
325 static Value *isCast(Value *V) {
326 if (CastInst *I = dyn_cast<CastInst>(V))
327 return I->getOperand(0);
328 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
329 if (CE->getOpcode() == Instruction::Cast)
330 return CE->getOperand(0);
341 /// getCastType - In the future, we will split the cast instruction into these
342 /// various types. Until then, we have to do the analysis here.
343 static CastType getCastType(const Type *Src, const Type *Dest) {
344 assert(Src->isIntegral() && Dest->isIntegral() &&
345 "Only works on integral types!");
346 unsigned SrcSize = Src->getPrimitiveSizeInBits();
347 unsigned DestSize = Dest->getPrimitiveSizeInBits();
349 if (SrcSize == DestSize) return Noop;
350 if (SrcSize > DestSize) return Truncate;
351 if (Src->isSigned()) return Signext;
356 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
359 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
360 const Type *DstTy, TargetData *TD) {
362 // It is legal to eliminate the instruction if casting A->B->A if the sizes
363 // are identical and the bits don't get reinterpreted (for example
364 // int->float->int would not be allowed).
365 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
368 // If we are casting between pointer and integer types, treat pointers as
369 // integers of the appropriate size for the code below.
370 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
371 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
372 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
374 // Allow free casting and conversion of sizes as long as the sign doesn't
376 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
377 CastType FirstCast = getCastType(SrcTy, MidTy);
378 CastType SecondCast = getCastType(MidTy, DstTy);
380 // Capture the effect of these two casts. If the result is a legal cast,
381 // the CastType is stored here, otherwise a special code is used.
382 static const unsigned CastResult[] = {
383 // First cast is noop
385 // First cast is a truncate
386 1, 1, 4, 4, // trunc->extend is not safe to eliminate
387 // First cast is a sign ext
388 2, 5, 2, 4, // signext->zeroext never ok
389 // First cast is a zero ext
393 unsigned Result = CastResult[FirstCast*4+SecondCast];
395 default: assert(0 && "Illegal table value!");
400 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
401 // truncates, we could eliminate more casts.
402 return (unsigned)getCastType(SrcTy, DstTy) == Result;
404 return false; // Not possible to eliminate this here.
406 // Sign or zero extend followed by truncate is always ok if the result
407 // is a truncate or noop.
408 CastType ResultCast = getCastType(SrcTy, DstTy);
409 if (ResultCast == Noop || ResultCast == Truncate)
411 // Otherwise we are still growing the value, we are only safe if the
412 // result will match the sign/zeroextendness of the result.
413 return ResultCast == FirstCast;
417 // If this is a cast from 'float -> double -> integer', cast from
418 // 'float -> integer' directly, as the value isn't changed by the
419 // float->double conversion.
420 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
421 DstTy->isIntegral() &&
422 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
425 // Packed type conversions don't modify bits.
426 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
432 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
433 /// in any code being generated. It does not require codegen if V is simple
434 /// enough or if the cast can be folded into other casts.
435 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
436 if (V->getType() == Ty || isa<Constant>(V)) return false;
438 // If this is a noop cast, it isn't real codegen.
439 if (V->getType()->isLosslesslyConvertibleTo(Ty))
442 // If this is another cast that can be eliminated, it isn't codegen either.
443 if (const CastInst *CI = dyn_cast<CastInst>(V))
444 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
450 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
451 /// InsertBefore instruction. This is specialized a bit to avoid inserting
452 /// casts that are known to not do anything...
454 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
455 Instruction *InsertBefore) {
456 if (V->getType() == DestTy) return V;
457 if (Constant *C = dyn_cast<Constant>(V))
458 return ConstantExpr::getCast(C, DestTy);
460 CastInst *CI = new CastInst(V, DestTy, V->getName());
461 InsertNewInstBefore(CI, *InsertBefore);
465 // SimplifyCommutative - This performs a few simplifications for commutative
468 // 1. Order operands such that they are listed from right (least complex) to
469 // left (most complex). This puts constants before unary operators before
472 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
473 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
475 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
476 bool Changed = false;
477 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
478 Changed = !I.swapOperands();
480 if (!I.isAssociative()) return Changed;
481 Instruction::BinaryOps Opcode = I.getOpcode();
482 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
483 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
484 if (isa<Constant>(I.getOperand(1))) {
485 Constant *Folded = ConstantExpr::get(I.getOpcode(),
486 cast<Constant>(I.getOperand(1)),
487 cast<Constant>(Op->getOperand(1)));
488 I.setOperand(0, Op->getOperand(0));
489 I.setOperand(1, Folded);
491 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
492 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
493 isOnlyUse(Op) && isOnlyUse(Op1)) {
494 Constant *C1 = cast<Constant>(Op->getOperand(1));
495 Constant *C2 = cast<Constant>(Op1->getOperand(1));
497 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
498 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
499 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
502 WorkList.push_back(New);
503 I.setOperand(0, New);
504 I.setOperand(1, Folded);
511 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
512 // if the LHS is a constant zero (which is the 'negate' form).
514 static inline Value *dyn_castNegVal(Value *V) {
515 if (BinaryOperator::isNeg(V))
516 return BinaryOperator::getNegArgument(V);
518 // Constants can be considered to be negated values if they can be folded.
519 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
520 return ConstantExpr::getNeg(C);
524 static inline Value *dyn_castNotVal(Value *V) {
525 if (BinaryOperator::isNot(V))
526 return BinaryOperator::getNotArgument(V);
528 // Constants can be considered to be not'ed values...
529 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
530 return ConstantExpr::getNot(C);
534 // dyn_castFoldableMul - If this value is a multiply that can be folded into
535 // other computations (because it has a constant operand), return the
536 // non-constant operand of the multiply, and set CST to point to the multiplier.
537 // Otherwise, return null.
539 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
540 if (V->hasOneUse() && V->getType()->isInteger())
541 if (Instruction *I = dyn_cast<Instruction>(V)) {
542 if (I->getOpcode() == Instruction::Mul)
543 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
544 return I->getOperand(0);
545 if (I->getOpcode() == Instruction::Shl)
546 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
547 // The multiplier is really 1 << CST.
548 Constant *One = ConstantInt::get(V->getType(), 1);
549 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
550 return I->getOperand(0);
556 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
557 /// expression, return it.
558 static User *dyn_castGetElementPtr(Value *V) {
559 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
560 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
561 if (CE->getOpcode() == Instruction::GetElementPtr)
562 return cast<User>(V);
566 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
567 static ConstantInt *AddOne(ConstantInt *C) {
568 return cast<ConstantInt>(ConstantExpr::getAdd(C,
569 ConstantInt::get(C->getType(), 1)));
571 static ConstantInt *SubOne(ConstantInt *C) {
572 return cast<ConstantInt>(ConstantExpr::getSub(C,
573 ConstantInt::get(C->getType(), 1)));
576 /// GetConstantInType - Return a ConstantInt with the specified type and value.
578 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
579 if (Ty->isUnsigned())
580 return ConstantInt::get(Ty, Val);
581 else if (Ty->getTypeID() == Type::BoolTyID)
582 return ConstantBool::get(Val);
584 SVal <<= 64-Ty->getPrimitiveSizeInBits();
585 SVal >>= 64-Ty->getPrimitiveSizeInBits();
586 return ConstantInt::get(Ty, SVal);
590 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
591 /// known to be either zero or one and return them in the KnownZero/KnownOne
592 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
594 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
595 uint64_t &KnownOne, unsigned Depth = 0) {
596 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
597 // we cannot optimize based on the assumption that it is zero without changing
598 // it to be an explicit zero. If we don't change it to zero, other code could
599 // optimized based on the contradictory assumption that it is non-zero.
600 // Because instcombine aggressively folds operations with undef args anyway,
601 // this won't lose us code quality.
602 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
603 // We know all of the bits for a constant!
604 KnownOne = CI->getZExtValue() & Mask;
605 KnownZero = ~KnownOne & Mask;
609 KnownZero = KnownOne = 0; // Don't know anything.
610 if (Depth == 6 || Mask == 0)
611 return; // Limit search depth.
613 uint64_t KnownZero2, KnownOne2;
614 Instruction *I = dyn_cast<Instruction>(V);
617 Mask &= V->getType()->getIntegralTypeMask();
619 switch (I->getOpcode()) {
620 case Instruction::And:
621 // If either the LHS or the RHS are Zero, the result is zero.
622 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
624 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
625 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
626 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
628 // Output known-1 bits are only known if set in both the LHS & RHS.
629 KnownOne &= KnownOne2;
630 // Output known-0 are known to be clear if zero in either the LHS | RHS.
631 KnownZero |= KnownZero2;
633 case Instruction::Or:
634 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
636 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
637 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
638 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
640 // Output known-0 bits are only known if clear in both the LHS & RHS.
641 KnownZero &= KnownZero2;
642 // Output known-1 are known to be set if set in either the LHS | RHS.
643 KnownOne |= KnownOne2;
645 case Instruction::Xor: {
646 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
647 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
648 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
649 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
651 // Output known-0 bits are known if clear or set in both the LHS & RHS.
652 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
653 // Output known-1 are known to be set if set in only one of the LHS, RHS.
654 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
655 KnownZero = KnownZeroOut;
658 case Instruction::Select:
659 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
660 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
661 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
662 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
664 // Only known if known in both the LHS and RHS.
665 KnownOne &= KnownOne2;
666 KnownZero &= KnownZero2;
668 case Instruction::Cast: {
669 const Type *SrcTy = I->getOperand(0)->getType();
670 if (!SrcTy->isIntegral()) return;
672 // If this is an integer truncate or noop, just look in the input.
673 if (SrcTy->getPrimitiveSizeInBits() >=
674 I->getType()->getPrimitiveSizeInBits()) {
675 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
679 // Sign or Zero extension. Compute the bits in the result that are not
680 // present in the input.
681 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
682 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
684 // Handle zero extension.
685 if (!SrcTy->isSigned()) {
686 Mask &= SrcTy->getIntegralTypeMask();
687 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
688 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
689 // The top bits are known to be zero.
690 KnownZero |= NewBits;
693 Mask &= SrcTy->getIntegralTypeMask();
694 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
695 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 // If the sign bit of the input is known set or clear, then we know the
698 // top bits of the result.
699 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
700 if (KnownZero & InSignBit) { // Input sign bit known zero
701 KnownZero |= NewBits;
702 KnownOne &= ~NewBits;
703 } else if (KnownOne & InSignBit) { // Input sign bit known set
705 KnownZero &= ~NewBits;
706 } else { // Input sign bit unknown
707 KnownZero &= ~NewBits;
708 KnownOne &= ~NewBits;
713 case Instruction::Shl:
714 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
715 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
716 uint64_t ShiftAmt = SA->getZExtValue();
718 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
719 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
720 KnownZero <<= ShiftAmt;
721 KnownOne <<= ShiftAmt;
722 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
726 case Instruction::Shr:
727 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
728 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
729 // Compute the new bits that are at the top now.
730 uint64_t ShiftAmt = SA->getZExtValue();
731 uint64_t HighBits = (1ULL << ShiftAmt)-1;
732 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
734 if (I->getType()->isUnsigned()) { // Unsigned shift right.
736 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
737 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
738 KnownZero >>= ShiftAmt;
739 KnownOne >>= ShiftAmt;
740 KnownZero |= HighBits; // high bits known zero.
743 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
744 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
745 KnownZero >>= ShiftAmt;
746 KnownOne >>= ShiftAmt;
748 // Handle the sign bits.
749 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
750 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
752 if (KnownZero & SignBit) { // New bits are known zero.
753 KnownZero |= HighBits;
754 } else if (KnownOne & SignBit) { // New bits are known one.
755 KnownOne |= HighBits;
764 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
765 /// this predicate to simplify operations downstream. Mask is known to be zero
766 /// for bits that V cannot have.
767 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
768 uint64_t KnownZero, KnownOne;
769 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
771 return (KnownZero & Mask) == Mask;
774 /// ShrinkDemandedConstant - Check to see if the specified operand of the
775 /// specified instruction is a constant integer. If so, check to see if there
776 /// are any bits set in the constant that are not demanded. If so, shrink the
777 /// constant and return true.
778 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
780 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
781 if (!OpC) return false;
783 // If there are no bits set that aren't demanded, nothing to do.
784 if ((~Demanded & OpC->getZExtValue()) == 0)
787 // This is producing any bits that are not needed, shrink the RHS.
788 uint64_t Val = Demanded & OpC->getZExtValue();
789 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
793 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
794 // set of known zero and one bits, compute the maximum and minimum values that
795 // could have the specified known zero and known one bits, returning them in
797 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
800 int64_t &Min, int64_t &Max) {
801 uint64_t TypeBits = Ty->getIntegralTypeMask();
802 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
804 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
806 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
807 // bit if it is unknown.
809 Max = KnownOne|UnknownBits;
811 if (SignBit & UnknownBits) { // Sign bit is unknown
816 // Sign extend the min/max values.
817 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
818 Min = (Min << ShAmt) >> ShAmt;
819 Max = (Max << ShAmt) >> ShAmt;
822 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
823 // a set of known zero and one bits, compute the maximum and minimum values that
824 // could have the specified known zero and known one bits, returning them in
826 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
831 uint64_t TypeBits = Ty->getIntegralTypeMask();
832 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
834 // The minimum value is when the unknown bits are all zeros.
836 // The maximum value is when the unknown bits are all ones.
837 Max = KnownOne|UnknownBits;
841 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
842 /// DemandedMask bits of the result of V are ever used downstream. If we can
843 /// use this information to simplify V, do so and return true. Otherwise,
844 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
845 /// the expression (used to simplify the caller). The KnownZero/One bits may
846 /// only be accurate for those bits in the DemandedMask.
847 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
848 uint64_t &KnownZero, uint64_t &KnownOne,
850 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
851 // We know all of the bits for a constant!
852 KnownOne = CI->getZExtValue() & DemandedMask;
853 KnownZero = ~KnownOne & DemandedMask;
857 KnownZero = KnownOne = 0;
858 if (!V->hasOneUse()) { // Other users may use these bits.
859 if (Depth != 0) { // Not at the root.
860 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
861 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
864 // If this is the root being simplified, allow it to have multiple uses,
865 // just set the DemandedMask to all bits.
866 DemandedMask = V->getType()->getIntegralTypeMask();
867 } else if (DemandedMask == 0) { // Not demanding any bits from V.
868 if (V != UndefValue::get(V->getType()))
869 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
871 } else if (Depth == 6) { // Limit search depth.
875 Instruction *I = dyn_cast<Instruction>(V);
876 if (!I) return false; // Only analyze instructions.
878 DemandedMask &= V->getType()->getIntegralTypeMask();
880 uint64_t KnownZero2, KnownOne2;
881 switch (I->getOpcode()) {
883 case Instruction::And:
884 // If either the LHS or the RHS are Zero, the result is zero.
885 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
886 KnownZero, KnownOne, Depth+1))
888 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
890 // If something is known zero on the RHS, the bits aren't demanded on the
892 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
893 KnownZero2, KnownOne2, Depth+1))
895 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
897 // If all of the demanded bits are known one on one side, return the other.
898 // These bits cannot contribute to the result of the 'and'.
899 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
900 return UpdateValueUsesWith(I, I->getOperand(0));
901 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
902 return UpdateValueUsesWith(I, I->getOperand(1));
904 // If all of the demanded bits in the inputs are known zeros, return zero.
905 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
906 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
908 // If the RHS is a constant, see if we can simplify it.
909 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
910 return UpdateValueUsesWith(I, I);
912 // Output known-1 bits are only known if set in both the LHS & RHS.
913 KnownOne &= KnownOne2;
914 // Output known-0 are known to be clear if zero in either the LHS | RHS.
915 KnownZero |= KnownZero2;
917 case Instruction::Or:
918 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
919 KnownZero, KnownOne, Depth+1))
921 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
922 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
923 KnownZero2, KnownOne2, Depth+1))
925 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
927 // If all of the demanded bits are known zero on one side, return the other.
928 // These bits cannot contribute to the result of the 'or'.
929 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
930 return UpdateValueUsesWith(I, I->getOperand(0));
931 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
932 return UpdateValueUsesWith(I, I->getOperand(1));
934 // If all of the potentially set bits on one side are known to be set on
935 // the other side, just use the 'other' side.
936 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
937 (DemandedMask & (~KnownZero)))
938 return UpdateValueUsesWith(I, I->getOperand(0));
939 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
940 (DemandedMask & (~KnownZero2)))
941 return UpdateValueUsesWith(I, I->getOperand(1));
943 // If the RHS is a constant, see if we can simplify it.
944 if (ShrinkDemandedConstant(I, 1, DemandedMask))
945 return UpdateValueUsesWith(I, I);
947 // Output known-0 bits are only known if clear in both the LHS & RHS.
948 KnownZero &= KnownZero2;
949 // Output known-1 are known to be set if set in either the LHS | RHS.
950 KnownOne |= KnownOne2;
952 case Instruction::Xor: {
953 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
954 KnownZero, KnownOne, Depth+1))
956 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
957 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
958 KnownZero2, KnownOne2, Depth+1))
960 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
962 // If all of the demanded bits are known zero on one side, return the other.
963 // These bits cannot contribute to the result of the 'xor'.
964 if ((DemandedMask & KnownZero) == DemandedMask)
965 return UpdateValueUsesWith(I, I->getOperand(0));
966 if ((DemandedMask & KnownZero2) == DemandedMask)
967 return UpdateValueUsesWith(I, I->getOperand(1));
969 // Output known-0 bits are known if clear or set in both the LHS & RHS.
970 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
971 // Output known-1 are known to be set if set in only one of the LHS, RHS.
972 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
974 // If all of the unknown bits are known to be zero on one side or the other
975 // (but not both) turn this into an *inclusive* or.
976 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
977 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
978 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
980 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
982 InsertNewInstBefore(Or, *I);
983 return UpdateValueUsesWith(I, Or);
987 // If all of the demanded bits on one side are known, and all of the set
988 // bits on that side are also known to be set on the other side, turn this
989 // into an AND, as we know the bits will be cleared.
990 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
991 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
992 if ((KnownOne & KnownOne2) == KnownOne) {
993 Constant *AndC = GetConstantInType(I->getType(),
994 ~KnownOne & DemandedMask);
996 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
997 InsertNewInstBefore(And, *I);
998 return UpdateValueUsesWith(I, And);
1002 // If the RHS is a constant, see if we can simplify it.
1003 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1004 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1005 return UpdateValueUsesWith(I, I);
1007 KnownZero = KnownZeroOut;
1008 KnownOne = KnownOneOut;
1011 case Instruction::Select:
1012 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1013 KnownZero, KnownOne, Depth+1))
1015 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1016 KnownZero2, KnownOne2, Depth+1))
1018 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1019 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1021 // If the operands are constants, see if we can simplify them.
1022 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1023 return UpdateValueUsesWith(I, I);
1024 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1025 return UpdateValueUsesWith(I, I);
1027 // Only known if known in both the LHS and RHS.
1028 KnownOne &= KnownOne2;
1029 KnownZero &= KnownZero2;
1031 case Instruction::Cast: {
1032 const Type *SrcTy = I->getOperand(0)->getType();
1033 if (!SrcTy->isIntegral()) return false;
1035 // If this is an integer truncate or noop, just look in the input.
1036 if (SrcTy->getPrimitiveSizeInBits() >=
1037 I->getType()->getPrimitiveSizeInBits()) {
1038 // Cast to bool is a comparison against 0, which demands all bits. We
1039 // can't propagate anything useful up.
1040 if (I->getType() == Type::BoolTy)
1043 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1044 KnownZero, KnownOne, Depth+1))
1046 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1050 // Sign or Zero extension. Compute the bits in the result that are not
1051 // present in the input.
1052 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1053 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1055 // Handle zero extension.
1056 if (!SrcTy->isSigned()) {
1057 DemandedMask &= SrcTy->getIntegralTypeMask();
1058 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1059 KnownZero, KnownOne, Depth+1))
1061 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1062 // The top bits are known to be zero.
1063 KnownZero |= NewBits;
1066 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1067 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1069 // If any of the sign extended bits are demanded, we know that the sign
1071 if (NewBits & DemandedMask)
1072 InputDemandedBits |= InSignBit;
1074 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1075 KnownZero, KnownOne, Depth+1))
1077 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1079 // If the sign bit of the input is known set or clear, then we know the
1080 // top bits of the result.
1082 // If the input sign bit is known zero, or if the NewBits are not demanded
1083 // convert this into a zero extension.
1084 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1085 // Convert to unsigned first.
1086 Instruction *NewVal;
1087 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
1088 I->getOperand(0)->getName());
1089 InsertNewInstBefore(NewVal, *I);
1090 // Then cast that to the destination type.
1091 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1092 InsertNewInstBefore(NewVal, *I);
1093 return UpdateValueUsesWith(I, NewVal);
1094 } else if (KnownOne & InSignBit) { // Input sign bit known set
1095 KnownOne |= NewBits;
1096 KnownZero &= ~NewBits;
1097 } else { // Input sign bit unknown
1098 KnownZero &= ~NewBits;
1099 KnownOne &= ~NewBits;
1104 case Instruction::Shl:
1105 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1106 uint64_t ShiftAmt = SA->getZExtValue();
1107 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
1108 KnownZero, KnownOne, Depth+1))
1110 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1111 KnownZero <<= ShiftAmt;
1112 KnownOne <<= ShiftAmt;
1113 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
1116 case Instruction::Shr:
1117 // If this is an arithmetic shift right and only the low-bit is set, we can
1118 // always convert this into a logical shr, even if the shift amount is
1119 // variable. The low bit of the shift cannot be an input sign bit unless
1120 // the shift amount is >= the size of the datatype, which is undefined.
1121 if (DemandedMask == 1 && I->getType()->isSigned()) {
1122 // Convert the input to unsigned.
1123 Instruction *NewVal = new CastInst(I->getOperand(0),
1124 I->getType()->getUnsignedVersion(),
1125 I->getOperand(0)->getName());
1126 InsertNewInstBefore(NewVal, *I);
1127 // Perform the unsigned shift right.
1128 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1130 InsertNewInstBefore(NewVal, *I);
1131 // Then cast that to the destination type.
1132 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1133 InsertNewInstBefore(NewVal, *I);
1134 return UpdateValueUsesWith(I, NewVal);
1137 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1138 unsigned ShiftAmt = SA->getZExtValue();
1140 // Compute the new bits that are at the top now.
1141 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1142 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1143 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1144 if (I->getType()->isUnsigned()) { // Unsigned shift right.
1145 if (SimplifyDemandedBits(I->getOperand(0),
1146 (DemandedMask << ShiftAmt) & TypeMask,
1147 KnownZero, KnownOne, Depth+1))
1149 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1150 KnownZero &= TypeMask;
1151 KnownOne &= TypeMask;
1152 KnownZero >>= ShiftAmt;
1153 KnownOne >>= ShiftAmt;
1154 KnownZero |= HighBits; // high bits known zero.
1155 } else { // Signed shift right.
1156 if (SimplifyDemandedBits(I->getOperand(0),
1157 (DemandedMask << ShiftAmt) & TypeMask,
1158 KnownZero, KnownOne, Depth+1))
1160 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1161 KnownZero &= TypeMask;
1162 KnownOne &= TypeMask;
1163 KnownZero >>= ShiftAmt;
1164 KnownOne >>= ShiftAmt;
1166 // Handle the sign bits.
1167 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1168 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
1170 // If the input sign bit is known to be zero, or if none of the top bits
1171 // are demanded, turn this into an unsigned shift right.
1172 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1173 // Convert the input to unsigned.
1174 Instruction *NewVal;
1175 NewVal = new CastInst(I->getOperand(0),
1176 I->getType()->getUnsignedVersion(),
1177 I->getOperand(0)->getName());
1178 InsertNewInstBefore(NewVal, *I);
1179 // Perform the unsigned shift right.
1180 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1181 InsertNewInstBefore(NewVal, *I);
1182 // Then cast that to the destination type.
1183 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1184 InsertNewInstBefore(NewVal, *I);
1185 return UpdateValueUsesWith(I, NewVal);
1186 } else if (KnownOne & SignBit) { // New bits are known one.
1187 KnownOne |= HighBits;
1194 // If the client is only demanding bits that we know, return the known
1196 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1197 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1202 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1203 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1204 /// actually used by the caller. This method analyzes which elements of the
1205 /// operand are undef and returns that information in UndefElts.
1207 /// If the information about demanded elements can be used to simplify the
1208 /// operation, the operation is simplified, then the resultant value is
1209 /// returned. This returns null if no change was made.
1210 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1211 uint64_t &UndefElts,
1213 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1214 assert(VWidth <= 64 && "Vector too wide to analyze!");
1215 uint64_t EltMask = ~0ULL >> (64-VWidth);
1216 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1217 "Invalid DemandedElts!");
1219 if (isa<UndefValue>(V)) {
1220 // If the entire vector is undefined, just return this info.
1221 UndefElts = EltMask;
1223 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1224 UndefElts = EltMask;
1225 return UndefValue::get(V->getType());
1229 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1230 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1231 Constant *Undef = UndefValue::get(EltTy);
1233 std::vector<Constant*> Elts;
1234 for (unsigned i = 0; i != VWidth; ++i)
1235 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1236 Elts.push_back(Undef);
1237 UndefElts |= (1ULL << i);
1238 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1239 Elts.push_back(Undef);
1240 UndefElts |= (1ULL << i);
1241 } else { // Otherwise, defined.
1242 Elts.push_back(CP->getOperand(i));
1245 // If we changed the constant, return it.
1246 Constant *NewCP = ConstantPacked::get(Elts);
1247 return NewCP != CP ? NewCP : 0;
1248 } else if (isa<ConstantAggregateZero>(V)) {
1249 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1251 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1252 Constant *Zero = Constant::getNullValue(EltTy);
1253 Constant *Undef = UndefValue::get(EltTy);
1254 std::vector<Constant*> Elts;
1255 for (unsigned i = 0; i != VWidth; ++i)
1256 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1257 UndefElts = DemandedElts ^ EltMask;
1258 return ConstantPacked::get(Elts);
1261 if (!V->hasOneUse()) { // Other users may use these bits.
1262 if (Depth != 0) { // Not at the root.
1263 // TODO: Just compute the UndefElts information recursively.
1267 } else if (Depth == 10) { // Limit search depth.
1271 Instruction *I = dyn_cast<Instruction>(V);
1272 if (!I) return false; // Only analyze instructions.
1274 bool MadeChange = false;
1275 uint64_t UndefElts2;
1277 switch (I->getOpcode()) {
1280 case Instruction::InsertElement: {
1281 // If this is a variable index, we don't know which element it overwrites.
1282 // demand exactly the same input as we produce.
1283 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1285 // Note that we can't propagate undef elt info, because we don't know
1286 // which elt is getting updated.
1287 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1288 UndefElts2, Depth+1);
1289 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1293 // If this is inserting an element that isn't demanded, remove this
1295 unsigned IdxNo = Idx->getZExtValue();
1296 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1297 return AddSoonDeadInstToWorklist(*I, 0);
1299 // Otherwise, the element inserted overwrites whatever was there, so the
1300 // input demanded set is simpler than the output set.
1301 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1302 DemandedElts & ~(1ULL << IdxNo),
1303 UndefElts, Depth+1);
1304 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1306 // The inserted element is defined.
1307 UndefElts |= 1ULL << IdxNo;
1311 case Instruction::And:
1312 case Instruction::Or:
1313 case Instruction::Xor:
1314 case Instruction::Add:
1315 case Instruction::Sub:
1316 case Instruction::Mul:
1317 // div/rem demand all inputs, because they don't want divide by zero.
1318 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1319 UndefElts, Depth+1);
1320 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1321 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1322 UndefElts2, Depth+1);
1323 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1325 // Output elements are undefined if both are undefined. Consider things
1326 // like undef&0. The result is known zero, not undef.
1327 UndefElts &= UndefElts2;
1330 case Instruction::Call: {
1331 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1333 switch (II->getIntrinsicID()) {
1336 // Binary vector operations that work column-wise. A dest element is a
1337 // function of the corresponding input elements from the two inputs.
1338 case Intrinsic::x86_sse_sub_ss:
1339 case Intrinsic::x86_sse_mul_ss:
1340 case Intrinsic::x86_sse_min_ss:
1341 case Intrinsic::x86_sse_max_ss:
1342 case Intrinsic::x86_sse2_sub_sd:
1343 case Intrinsic::x86_sse2_mul_sd:
1344 case Intrinsic::x86_sse2_min_sd:
1345 case Intrinsic::x86_sse2_max_sd:
1346 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1347 UndefElts, Depth+1);
1348 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1349 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1350 UndefElts2, Depth+1);
1351 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1353 // If only the low elt is demanded and this is a scalarizable intrinsic,
1354 // scalarize it now.
1355 if (DemandedElts == 1) {
1356 switch (II->getIntrinsicID()) {
1358 case Intrinsic::x86_sse_sub_ss:
1359 case Intrinsic::x86_sse_mul_ss:
1360 case Intrinsic::x86_sse2_sub_sd:
1361 case Intrinsic::x86_sse2_mul_sd:
1362 // TODO: Lower MIN/MAX/ABS/etc
1363 Value *LHS = II->getOperand(1);
1364 Value *RHS = II->getOperand(2);
1365 // Extract the element as scalars.
1366 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1367 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1369 switch (II->getIntrinsicID()) {
1370 default: assert(0 && "Case stmts out of sync!");
1371 case Intrinsic::x86_sse_sub_ss:
1372 case Intrinsic::x86_sse2_sub_sd:
1373 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1374 II->getName()), *II);
1376 case Intrinsic::x86_sse_mul_ss:
1377 case Intrinsic::x86_sse2_mul_sd:
1378 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1379 II->getName()), *II);
1384 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1386 InsertNewInstBefore(New, *II);
1387 AddSoonDeadInstToWorklist(*II, 0);
1392 // Output elements are undefined if both are undefined. Consider things
1393 // like undef&0. The result is known zero, not undef.
1394 UndefElts &= UndefElts2;
1400 return MadeChange ? I : 0;
1403 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1404 // true when both operands are equal...
1406 static bool isTrueWhenEqual(Instruction &I) {
1407 return I.getOpcode() == Instruction::SetEQ ||
1408 I.getOpcode() == Instruction::SetGE ||
1409 I.getOpcode() == Instruction::SetLE;
1412 /// AssociativeOpt - Perform an optimization on an associative operator. This
1413 /// function is designed to check a chain of associative operators for a
1414 /// potential to apply a certain optimization. Since the optimization may be
1415 /// applicable if the expression was reassociated, this checks the chain, then
1416 /// reassociates the expression as necessary to expose the optimization
1417 /// opportunity. This makes use of a special Functor, which must define
1418 /// 'shouldApply' and 'apply' methods.
1420 template<typename Functor>
1421 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1422 unsigned Opcode = Root.getOpcode();
1423 Value *LHS = Root.getOperand(0);
1425 // Quick check, see if the immediate LHS matches...
1426 if (F.shouldApply(LHS))
1427 return F.apply(Root);
1429 // Otherwise, if the LHS is not of the same opcode as the root, return.
1430 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1431 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1432 // Should we apply this transform to the RHS?
1433 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1435 // If not to the RHS, check to see if we should apply to the LHS...
1436 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1437 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1441 // If the functor wants to apply the optimization to the RHS of LHSI,
1442 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1444 BasicBlock *BB = Root.getParent();
1446 // Now all of the instructions are in the current basic block, go ahead
1447 // and perform the reassociation.
1448 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1450 // First move the selected RHS to the LHS of the root...
1451 Root.setOperand(0, LHSI->getOperand(1));
1453 // Make what used to be the LHS of the root be the user of the root...
1454 Value *ExtraOperand = TmpLHSI->getOperand(1);
1455 if (&Root == TmpLHSI) {
1456 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1459 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1460 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1461 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1462 BasicBlock::iterator ARI = &Root; ++ARI;
1463 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1466 // Now propagate the ExtraOperand down the chain of instructions until we
1468 while (TmpLHSI != LHSI) {
1469 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1470 // Move the instruction to immediately before the chain we are
1471 // constructing to avoid breaking dominance properties.
1472 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1473 BB->getInstList().insert(ARI, NextLHSI);
1476 Value *NextOp = NextLHSI->getOperand(1);
1477 NextLHSI->setOperand(1, ExtraOperand);
1479 ExtraOperand = NextOp;
1482 // Now that the instructions are reassociated, have the functor perform
1483 // the transformation...
1484 return F.apply(Root);
1487 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1493 // AddRHS - Implements: X + X --> X << 1
1496 AddRHS(Value *rhs) : RHS(rhs) {}
1497 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1498 Instruction *apply(BinaryOperator &Add) const {
1499 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1500 ConstantInt::get(Type::UByteTy, 1));
1504 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1506 struct AddMaskingAnd {
1508 AddMaskingAnd(Constant *c) : C2(c) {}
1509 bool shouldApply(Value *LHS) const {
1511 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1512 ConstantExpr::getAnd(C1, C2)->isNullValue();
1514 Instruction *apply(BinaryOperator &Add) const {
1515 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1519 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1521 if (isa<CastInst>(I)) {
1522 if (Constant *SOC = dyn_cast<Constant>(SO))
1523 return ConstantExpr::getCast(SOC, I.getType());
1525 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1526 SO->getName() + ".cast"), I);
1529 // Figure out if the constant is the left or the right argument.
1530 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1531 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1533 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1535 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1536 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1539 Value *Op0 = SO, *Op1 = ConstOperand;
1541 std::swap(Op0, Op1);
1543 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1544 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1545 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1546 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1548 assert(0 && "Unknown binary instruction type!");
1551 return IC->InsertNewInstBefore(New, I);
1554 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1555 // constant as the other operand, try to fold the binary operator into the
1556 // select arguments. This also works for Cast instructions, which obviously do
1557 // not have a second operand.
1558 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1560 // Don't modify shared select instructions
1561 if (!SI->hasOneUse()) return 0;
1562 Value *TV = SI->getOperand(1);
1563 Value *FV = SI->getOperand(2);
1565 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1566 // Bool selects with constant operands can be folded to logical ops.
1567 if (SI->getType() == Type::BoolTy) return 0;
1569 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1570 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1572 return new SelectInst(SI->getCondition(), SelectTrueVal,
1579 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1580 /// node as operand #0, see if we can fold the instruction into the PHI (which
1581 /// is only possible if all operands to the PHI are constants).
1582 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1583 PHINode *PN = cast<PHINode>(I.getOperand(0));
1584 unsigned NumPHIValues = PN->getNumIncomingValues();
1585 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1587 // Check to see if all of the operands of the PHI are constants. If there is
1588 // one non-constant value, remember the BB it is. If there is more than one
1590 BasicBlock *NonConstBB = 0;
1591 for (unsigned i = 0; i != NumPHIValues; ++i)
1592 if (!isa<Constant>(PN->getIncomingValue(i))) {
1593 if (NonConstBB) return 0; // More than one non-const value.
1594 NonConstBB = PN->getIncomingBlock(i);
1596 // If the incoming non-constant value is in I's block, we have an infinite
1598 if (NonConstBB == I.getParent())
1602 // If there is exactly one non-constant value, we can insert a copy of the
1603 // operation in that block. However, if this is a critical edge, we would be
1604 // inserting the computation one some other paths (e.g. inside a loop). Only
1605 // do this if the pred block is unconditionally branching into the phi block.
1607 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1608 if (!BI || !BI->isUnconditional()) return 0;
1611 // Okay, we can do the transformation: create the new PHI node.
1612 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1614 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1615 InsertNewInstBefore(NewPN, *PN);
1617 // Next, add all of the operands to the PHI.
1618 if (I.getNumOperands() == 2) {
1619 Constant *C = cast<Constant>(I.getOperand(1));
1620 for (unsigned i = 0; i != NumPHIValues; ++i) {
1622 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1623 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1625 assert(PN->getIncomingBlock(i) == NonConstBB);
1626 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1627 InV = BinaryOperator::create(BO->getOpcode(),
1628 PN->getIncomingValue(i), C, "phitmp",
1629 NonConstBB->getTerminator());
1630 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1631 InV = new ShiftInst(SI->getOpcode(),
1632 PN->getIncomingValue(i), C, "phitmp",
1633 NonConstBB->getTerminator());
1635 assert(0 && "Unknown binop!");
1637 WorkList.push_back(cast<Instruction>(InV));
1639 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1642 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1643 const Type *RetTy = I.getType();
1644 for (unsigned i = 0; i != NumPHIValues; ++i) {
1646 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1647 InV = ConstantExpr::getCast(InC, RetTy);
1649 assert(PN->getIncomingBlock(i) == NonConstBB);
1650 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1651 NonConstBB->getTerminator());
1652 WorkList.push_back(cast<Instruction>(InV));
1654 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1657 return ReplaceInstUsesWith(I, NewPN);
1660 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1661 bool Changed = SimplifyCommutative(I);
1662 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1664 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1665 // X + undef -> undef
1666 if (isa<UndefValue>(RHS))
1667 return ReplaceInstUsesWith(I, RHS);
1670 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1671 if (RHSC->isNullValue())
1672 return ReplaceInstUsesWith(I, LHS);
1673 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1674 if (CFP->isExactlyValue(-0.0))
1675 return ReplaceInstUsesWith(I, LHS);
1678 // X + (signbit) --> X ^ signbit
1679 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1680 uint64_t Val = CI->getZExtValue();
1681 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1682 return BinaryOperator::createXor(LHS, RHS);
1685 if (isa<PHINode>(LHS))
1686 if (Instruction *NV = FoldOpIntoPhi(I))
1689 ConstantInt *XorRHS = 0;
1691 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1692 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1693 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1694 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1696 uint64_t C0080Val = 1ULL << 31;
1697 int64_t CFF80Val = -C0080Val;
1700 if (TySizeBits > Size) {
1702 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1703 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1704 if (RHSSExt == CFF80Val) {
1705 if (XorRHS->getZExtValue() == C0080Val)
1707 } else if (RHSZExt == C0080Val) {
1708 if (XorRHS->getSExtValue() == CFF80Val)
1712 // This is a sign extend if the top bits are known zero.
1713 uint64_t Mask = ~0ULL;
1714 Mask <<= 64-(TySizeBits-Size);
1715 Mask &= XorLHS->getType()->getIntegralTypeMask();
1716 if (!MaskedValueIsZero(XorLHS, Mask))
1717 Size = 0; // Not a sign ext, but can't be any others either.
1724 } while (Size >= 8);
1727 const Type *MiddleType = 0;
1730 case 32: MiddleType = Type::IntTy; break;
1731 case 16: MiddleType = Type::ShortTy; break;
1732 case 8: MiddleType = Type::SByteTy; break;
1735 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1736 InsertNewInstBefore(NewTrunc, I);
1737 return new CastInst(NewTrunc, I.getType());
1743 if (I.getType()->isInteger()) {
1744 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1746 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1747 if (RHSI->getOpcode() == Instruction::Sub)
1748 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1749 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1751 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1752 if (LHSI->getOpcode() == Instruction::Sub)
1753 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1754 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1759 if (Value *V = dyn_castNegVal(LHS))
1760 return BinaryOperator::createSub(RHS, V);
1763 if (!isa<Constant>(RHS))
1764 if (Value *V = dyn_castNegVal(RHS))
1765 return BinaryOperator::createSub(LHS, V);
1769 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1770 if (X == RHS) // X*C + X --> X * (C+1)
1771 return BinaryOperator::createMul(RHS, AddOne(C2));
1773 // X*C1 + X*C2 --> X * (C1+C2)
1775 if (X == dyn_castFoldableMul(RHS, C1))
1776 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1779 // X + X*C --> X * (C+1)
1780 if (dyn_castFoldableMul(RHS, C2) == LHS)
1781 return BinaryOperator::createMul(LHS, AddOne(C2));
1784 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1785 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1786 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1788 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1790 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1791 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1792 return BinaryOperator::createSub(C, X);
1795 // (X & FF00) + xx00 -> (X+xx00) & FF00
1796 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1797 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1798 if (Anded == CRHS) {
1799 // See if all bits from the first bit set in the Add RHS up are included
1800 // in the mask. First, get the rightmost bit.
1801 uint64_t AddRHSV = CRHS->getZExtValue();
1803 // Form a mask of all bits from the lowest bit added through the top.
1804 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1805 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1807 // See if the and mask includes all of these bits.
1808 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1810 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1811 // Okay, the xform is safe. Insert the new add pronto.
1812 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1813 LHS->getName()), I);
1814 return BinaryOperator::createAnd(NewAdd, C2);
1819 // Try to fold constant add into select arguments.
1820 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1821 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1825 // add (cast *A to intptrtype) B -> cast (GEP (cast *A to sbyte*) B) -> intptrtype
1827 CastInst* CI = dyn_cast<CastInst>(LHS);
1830 CI = dyn_cast<CastInst>(RHS);
1833 if (CI && CI->getType()->isSized() &&
1834 (CI->getType()->getPrimitiveSize() ==
1835 TD->getIntPtrType()->getPrimitiveSize())
1836 && isa<PointerType>(CI->getOperand(0)->getType())) {
1837 Value* I2 = InsertCastBefore(CI->getOperand(0),
1838 PointerType::get(Type::SByteTy), I);
1839 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1840 return new CastInst(I2, CI->getType());
1844 return Changed ? &I : 0;
1847 // isSignBit - Return true if the value represented by the constant only has the
1848 // highest order bit set.
1849 static bool isSignBit(ConstantInt *CI) {
1850 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1851 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1854 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1856 static Value *RemoveNoopCast(Value *V) {
1857 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1858 const Type *CTy = CI->getType();
1859 const Type *OpTy = CI->getOperand(0)->getType();
1860 if (CTy->isInteger() && OpTy->isInteger()) {
1861 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1862 return RemoveNoopCast(CI->getOperand(0));
1863 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1864 return RemoveNoopCast(CI->getOperand(0));
1869 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1870 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1872 if (Op0 == Op1) // sub X, X -> 0
1873 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1875 // If this is a 'B = x-(-A)', change to B = x+A...
1876 if (Value *V = dyn_castNegVal(Op1))
1877 return BinaryOperator::createAdd(Op0, V);
1879 if (isa<UndefValue>(Op0))
1880 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1881 if (isa<UndefValue>(Op1))
1882 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1884 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1885 // Replace (-1 - A) with (~A)...
1886 if (C->isAllOnesValue())
1887 return BinaryOperator::createNot(Op1);
1889 // C - ~X == X + (1+C)
1891 if (match(Op1, m_Not(m_Value(X))))
1892 return BinaryOperator::createAdd(X,
1893 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1894 // -((uint)X >> 31) -> ((int)X >> 31)
1895 // -((int)X >> 31) -> ((uint)X >> 31)
1896 if (C->isNullValue()) {
1897 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1898 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1899 if (SI->getOpcode() == Instruction::Shr)
1900 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1902 if (SI->getType()->isSigned())
1903 NewTy = SI->getType()->getUnsignedVersion();
1905 NewTy = SI->getType()->getSignedVersion();
1906 // Check to see if we are shifting out everything but the sign bit.
1907 if (CU->getZExtValue() ==
1908 SI->getType()->getPrimitiveSizeInBits()-1) {
1909 // Ok, the transformation is safe. Insert a cast of the incoming
1910 // value, then the new shift, then the new cast.
1911 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1912 SI->getOperand(0)->getName());
1913 Value *InV = InsertNewInstBefore(FirstCast, I);
1914 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1916 if (NewShift->getType() == I.getType())
1919 InV = InsertNewInstBefore(NewShift, I);
1920 return new CastInst(NewShift, I.getType());
1926 // Try to fold constant sub into select arguments.
1927 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1928 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1931 if (isa<PHINode>(Op0))
1932 if (Instruction *NV = FoldOpIntoPhi(I))
1936 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1937 if (Op1I->getOpcode() == Instruction::Add &&
1938 !Op0->getType()->isFloatingPoint()) {
1939 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1940 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1941 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1942 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1943 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1944 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1945 // C1-(X+C2) --> (C1-C2)-X
1946 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1947 Op1I->getOperand(0));
1951 if (Op1I->hasOneUse()) {
1952 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1953 // is not used by anyone else...
1955 if (Op1I->getOpcode() == Instruction::Sub &&
1956 !Op1I->getType()->isFloatingPoint()) {
1957 // Swap the two operands of the subexpr...
1958 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1959 Op1I->setOperand(0, IIOp1);
1960 Op1I->setOperand(1, IIOp0);
1962 // Create the new top level add instruction...
1963 return BinaryOperator::createAdd(Op0, Op1);
1966 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1968 if (Op1I->getOpcode() == Instruction::And &&
1969 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1970 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1973 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1974 return BinaryOperator::createAnd(Op0, NewNot);
1977 // 0 - (X sdiv C) -> (X sdiv -C)
1978 if (Op1I->getOpcode() == Instruction::Div)
1979 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
1980 if (CSI->getType()->isSigned() && CSI->isNullValue())
1981 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1982 return BinaryOperator::createDiv(Op1I->getOperand(0),
1983 ConstantExpr::getNeg(DivRHS));
1985 // X - X*C --> X * (1-C)
1986 ConstantInt *C2 = 0;
1987 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1989 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1990 return BinaryOperator::createMul(Op0, CP1);
1995 if (!Op0->getType()->isFloatingPoint())
1996 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1997 if (Op0I->getOpcode() == Instruction::Add) {
1998 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1999 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2000 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2001 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2002 } else if (Op0I->getOpcode() == Instruction::Sub) {
2003 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2004 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2008 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2009 if (X == Op1) { // X*C - X --> X * (C-1)
2010 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2011 return BinaryOperator::createMul(Op1, CP1);
2014 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2015 if (X == dyn_castFoldableMul(Op1, C2))
2016 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2021 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2022 /// really just returns true if the most significant (sign) bit is set.
2023 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2024 if (RHS->getType()->isSigned()) {
2025 // True if source is LHS < 0 or LHS <= -1
2026 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2027 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2029 ConstantInt *RHSC = cast<ConstantInt>(RHS);
2030 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2031 // the size of the integer type.
2032 if (Opcode == Instruction::SetGE)
2033 return RHSC->getZExtValue() ==
2034 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
2035 if (Opcode == Instruction::SetGT)
2036 return RHSC->getZExtValue() ==
2037 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2042 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2043 bool Changed = SimplifyCommutative(I);
2044 Value *Op0 = I.getOperand(0);
2046 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2049 // Simplify mul instructions with a constant RHS...
2050 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2051 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2053 // ((X << C1)*C2) == (X * (C2 << C1))
2054 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2055 if (SI->getOpcode() == Instruction::Shl)
2056 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2057 return BinaryOperator::createMul(SI->getOperand(0),
2058 ConstantExpr::getShl(CI, ShOp));
2060 if (CI->isNullValue())
2061 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2062 if (CI->equalsInt(1)) // X * 1 == X
2063 return ReplaceInstUsesWith(I, Op0);
2064 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2065 return BinaryOperator::createNeg(Op0, I.getName());
2067 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2068 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2069 uint64_t C = Log2_64(Val);
2070 return new ShiftInst(Instruction::Shl, Op0,
2071 ConstantInt::get(Type::UByteTy, C));
2073 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2074 if (Op1F->isNullValue())
2075 return ReplaceInstUsesWith(I, Op1);
2077 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2078 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2079 if (Op1F->getValue() == 1.0)
2080 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2083 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2084 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2085 isa<ConstantInt>(Op0I->getOperand(1))) {
2086 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2087 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2089 InsertNewInstBefore(Add, I);
2090 Value *C1C2 = ConstantExpr::getMul(Op1,
2091 cast<Constant>(Op0I->getOperand(1)));
2092 return BinaryOperator::createAdd(Add, C1C2);
2096 // Try to fold constant mul into select arguments.
2097 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2098 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2101 if (isa<PHINode>(Op0))
2102 if (Instruction *NV = FoldOpIntoPhi(I))
2106 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2107 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2108 return BinaryOperator::createMul(Op0v, Op1v);
2110 // If one of the operands of the multiply is a cast from a boolean value, then
2111 // we know the bool is either zero or one, so this is a 'masking' multiply.
2112 // See if we can simplify things based on how the boolean was originally
2114 CastInst *BoolCast = 0;
2115 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2116 if (CI->getOperand(0)->getType() == Type::BoolTy)
2119 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2120 if (CI->getOperand(0)->getType() == Type::BoolTy)
2123 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2124 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2125 const Type *SCOpTy = SCIOp0->getType();
2127 // If the setcc is true iff the sign bit of X is set, then convert this
2128 // multiply into a shift/and combination.
2129 if (isa<ConstantInt>(SCIOp1) &&
2130 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
2131 // Shift the X value right to turn it into "all signbits".
2132 Constant *Amt = ConstantInt::get(Type::UByteTy,
2133 SCOpTy->getPrimitiveSizeInBits()-1);
2134 if (SCIOp0->getType()->isUnsigned()) {
2135 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
2136 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
2137 SCIOp0->getName()), I);
2141 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
2142 BoolCast->getOperand(0)->getName()+
2145 // If the multiply type is not the same as the source type, sign extend
2146 // or truncate to the multiply type.
2147 if (I.getType() != V->getType())
2148 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
2150 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2151 return BinaryOperator::createAnd(V, OtherOp);
2156 return Changed ? &I : 0;
2159 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
2160 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2162 if (isa<UndefValue>(Op0)) // undef / X -> 0
2163 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2164 if (isa<UndefValue>(Op1))
2165 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
2167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2169 if (RHS->equalsInt(1))
2170 return ReplaceInstUsesWith(I, Op0);
2173 if (RHS->isAllOnesValue())
2174 return BinaryOperator::createNeg(Op0);
2176 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2177 if (LHS->getOpcode() == Instruction::Div)
2178 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2179 // (X / C1) / C2 -> X / (C1*C2)
2180 return BinaryOperator::createDiv(LHS->getOperand(0),
2181 ConstantExpr::getMul(RHS, LHSRHS));
2184 // Check to see if this is an unsigned division with an exact power of 2,
2185 // if so, convert to a right shift.
2186 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2187 if (C->getType()->isUnsigned())
2188 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2189 if (isPowerOf2_64(Val)) {
2190 uint64_t C = Log2_64(Val);
2191 return new ShiftInst(Instruction::Shr, Op0,
2192 ConstantInt::get(Type::UByteTy, C));
2196 if (RHS->getType()->isSigned())
2197 if (Value *LHSNeg = dyn_castNegVal(Op0))
2198 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2200 if (!RHS->isNullValue()) {
2201 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2202 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2204 if (isa<PHINode>(Op0))
2205 if (Instruction *NV = FoldOpIntoPhi(I))
2210 // Handle div X, Cond?Y:Z
2211 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2212 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2213 // same basic block, then we replace the select with Y, and the condition of
2214 // the select with false (if the cond value is in the same BB). If the
2215 // select has uses other than the div, this allows them to be simplified
2217 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2218 if (ST->isNullValue()) {
2219 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2220 if (CondI && CondI->getParent() == I.getParent())
2221 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2222 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2223 I.setOperand(1, SI->getOperand(2));
2225 UpdateValueUsesWith(SI, SI->getOperand(2));
2228 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2229 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2230 if (ST->isNullValue()) {
2231 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2232 if (CondI && CondI->getParent() == I.getParent())
2233 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2234 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2235 I.setOperand(1, SI->getOperand(1));
2237 UpdateValueUsesWith(SI, SI->getOperand(1));
2241 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2242 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
2243 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2244 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2245 if (STO->getType()->isUnsigned() && SFO->getType()->isUnsigned()) {
2246 // STO == 0 and SFO == 0 handled above.
2247 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2248 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2249 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2250 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2251 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
2252 TC, SI->getName()+".t");
2253 TSI = InsertNewInstBefore(TSI, I);
2255 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2256 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
2257 FC, SI->getName()+".f");
2258 FSI = InsertNewInstBefore(FSI, I);
2259 return new SelectInst(SI->getOperand(0), TSI, FSI);
2264 // 0 / X == 0, we don't need to preserve faults!
2265 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2266 if (LHS->equalsInt(0))
2267 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2269 if (I.getType()->isSigned()) {
2270 // If the sign bits of both operands are zero (i.e. we can prove they are
2271 // unsigned inputs), turn this into a udiv.
2272 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2273 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2274 const Type *NTy = Op0->getType()->getUnsignedVersion();
2275 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2276 InsertNewInstBefore(LHS, I);
2278 if (Constant *R = dyn_cast<Constant>(Op1))
2279 RHS = ConstantExpr::getCast(R, NTy);
2281 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2282 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2283 InsertNewInstBefore(Div, I);
2284 return new CastInst(Div, I.getType());
2287 // Known to be an unsigned division.
2288 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2289 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2290 if (RHSI->getOpcode() == Instruction::Shl &&
2291 isa<ConstantInt>(RHSI->getOperand(0)) &&
2292 RHSI->getOperand(0)->getType()->isUnsigned()) {
2293 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2294 if (isPowerOf2_64(C1)) {
2295 uint64_t C2 = Log2_64(C1);
2296 Value *Add = RHSI->getOperand(1);
2298 Constant *C2V = ConstantInt::get(Add->getType(), C2);
2299 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2302 return new ShiftInst(Instruction::Shr, Op0, Add);
2312 /// GetFactor - If we can prove that the specified value is at least a multiple
2313 /// of some factor, return that factor.
2314 static Constant *GetFactor(Value *V) {
2315 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2318 // Unless we can be tricky, we know this is a multiple of 1.
2319 Constant *Result = ConstantInt::get(V->getType(), 1);
2321 Instruction *I = dyn_cast<Instruction>(V);
2322 if (!I) return Result;
2324 if (I->getOpcode() == Instruction::Mul) {
2325 // Handle multiplies by a constant, etc.
2326 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2327 GetFactor(I->getOperand(1)));
2328 } else if (I->getOpcode() == Instruction::Shl) {
2329 // (X<<C) -> X * (1 << C)
2330 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2331 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2332 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2334 } else if (I->getOpcode() == Instruction::And) {
2335 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2336 // X & 0xFFF0 is known to be a multiple of 16.
2337 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2338 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2339 return ConstantExpr::getShl(Result,
2340 ConstantInt::get(Type::UByteTy, Zeros));
2342 } else if (I->getOpcode() == Instruction::Cast) {
2343 Value *Op = I->getOperand(0);
2344 // Only handle int->int casts.
2345 if (!Op->getType()->isInteger()) return Result;
2346 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2351 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
2352 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2354 // 0 % X == 0, we don't need to preserve faults!
2355 if (Constant *LHS = dyn_cast<Constant>(Op0))
2356 if (LHS->isNullValue())
2357 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2359 if (isa<UndefValue>(Op0)) // undef % X -> 0
2360 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2361 if (isa<UndefValue>(Op1))
2362 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2364 if (I.getType()->isSigned()) {
2365 if (Value *RHSNeg = dyn_castNegVal(Op1))
2366 if (!isa<ConstantInt>(RHSNeg) || !RHSNeg->getType()->isSigned() ||
2367 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2369 AddUsesToWorkList(I);
2370 I.setOperand(1, RHSNeg);
2374 // If the top bits of both operands are zero (i.e. we can prove they are
2375 // unsigned inputs), turn this into a urem.
2376 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2377 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2378 const Type *NTy = Op0->getType()->getUnsignedVersion();
2379 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2380 InsertNewInstBefore(LHS, I);
2382 if (Constant *R = dyn_cast<Constant>(Op1))
2383 RHS = ConstantExpr::getCast(R, NTy);
2385 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2386 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2387 InsertNewInstBefore(Rem, I);
2388 return new CastInst(Rem, I.getType());
2392 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2393 // X % 0 == undef, we don't need to preserve faults!
2394 if (RHS->equalsInt(0))
2395 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2397 if (RHS->equalsInt(1)) // X % 1 == 0
2398 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2400 // Check to see if this is an unsigned remainder with an exact power of 2,
2401 // if so, convert to a bitwise and.
2402 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2403 if (RHS->getType()->isUnsigned())
2404 if (isPowerOf2_64(C->getZExtValue()))
2405 return BinaryOperator::createAnd(Op0, SubOne(C));
2407 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2408 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2409 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2411 } else if (isa<PHINode>(Op0I)) {
2412 if (Instruction *NV = FoldOpIntoPhi(I))
2416 // X*C1%C2 --> 0 iff C1%C2 == 0
2417 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2418 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2422 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2423 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2424 if (I.getType()->isUnsigned() &&
2425 RHSI->getOpcode() == Instruction::Shl &&
2426 isa<ConstantInt>(RHSI->getOperand(0)) &&
2427 RHSI->getOperand(0)->getType()->isUnsigned()) {
2428 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2429 if (isPowerOf2_64(C1)) {
2430 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2431 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2433 return BinaryOperator::createAnd(Op0, Add);
2437 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2438 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2439 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2440 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2441 // the same basic block, then we replace the select with Y, and the
2442 // condition of the select with false (if the cond value is in the same
2443 // BB). If the select has uses other than the div, this allows them to be
2445 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2446 if (ST->isNullValue()) {
2447 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2448 if (CondI && CondI->getParent() == I.getParent())
2449 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2450 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2451 I.setOperand(1, SI->getOperand(2));
2453 UpdateValueUsesWith(SI, SI->getOperand(2));
2456 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2457 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2458 if (ST->isNullValue()) {
2459 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2460 if (CondI && CondI->getParent() == I.getParent())
2461 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2462 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2463 I.setOperand(1, SI->getOperand(1));
2465 UpdateValueUsesWith(SI, SI->getOperand(1));
2470 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2471 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2472 if (STO->getType()->isUnsigned() && SFO->getType()->isUnsigned()) {
2473 // STO == 0 and SFO == 0 handled above.
2474 if (isPowerOf2_64(STO->getZExtValue()) &&
2475 isPowerOf2_64(SFO->getZExtValue())) {
2476 Value *TrueAnd = InsertNewInstBefore(
2477 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"),
2479 Value *FalseAnd = InsertNewInstBefore(
2480 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"),
2482 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2491 // isMaxValueMinusOne - return true if this is Max-1
2492 static bool isMaxValueMinusOne(const ConstantInt *C) {
2493 if (C->getType()->isUnsigned())
2494 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2496 // Calculate 0111111111..11111
2497 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2498 int64_t Val = INT64_MAX; // All ones
2499 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2500 return C->getSExtValue() == Val-1;
2503 // isMinValuePlusOne - return true if this is Min+1
2504 static bool isMinValuePlusOne(const ConstantInt *C) {
2505 if (C->getType()->isUnsigned())
2506 return C->getZExtValue() == 1;
2508 // Calculate 1111111111000000000000
2509 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2510 int64_t Val = -1; // All ones
2511 Val <<= TypeBits-1; // Shift over to the right spot
2512 return C->getSExtValue() == Val+1;
2515 // isOneBitSet - Return true if there is exactly one bit set in the specified
2517 static bool isOneBitSet(const ConstantInt *CI) {
2518 uint64_t V = CI->getZExtValue();
2519 return V && (V & (V-1)) == 0;
2522 #if 0 // Currently unused
2523 // isLowOnes - Return true if the constant is of the form 0+1+.
2524 static bool isLowOnes(const ConstantInt *CI) {
2525 uint64_t V = CI->getZExtValue();
2527 // There won't be bits set in parts that the type doesn't contain.
2528 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2530 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2531 return U && V && (U & V) == 0;
2535 // isHighOnes - Return true if the constant is of the form 1+0+.
2536 // This is the same as lowones(~X).
2537 static bool isHighOnes(const ConstantInt *CI) {
2538 uint64_t V = ~CI->getZExtValue();
2539 if (~V == 0) return false; // 0's does not match "1+"
2541 // There won't be bits set in parts that the type doesn't contain.
2542 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2544 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2545 return U && V && (U & V) == 0;
2549 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2550 /// are carefully arranged to allow folding of expressions such as:
2552 /// (A < B) | (A > B) --> (A != B)
2554 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2555 /// represents that the comparison is true if A == B, and bit value '1' is true
2558 static unsigned getSetCondCode(const SetCondInst *SCI) {
2559 switch (SCI->getOpcode()) {
2561 case Instruction::SetGT: return 1;
2562 case Instruction::SetEQ: return 2;
2563 case Instruction::SetGE: return 3;
2564 case Instruction::SetLT: return 4;
2565 case Instruction::SetNE: return 5;
2566 case Instruction::SetLE: return 6;
2569 assert(0 && "Invalid SetCC opcode!");
2574 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2575 /// opcode and two operands into either a constant true or false, or a brand new
2576 /// SetCC instruction.
2577 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2579 case 0: return ConstantBool::getFalse();
2580 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2581 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2582 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2583 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2584 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2585 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2586 case 7: return ConstantBool::getTrue();
2587 default: assert(0 && "Illegal SetCCCode!"); return 0;
2591 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2592 struct FoldSetCCLogical {
2595 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2596 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2597 bool shouldApply(Value *V) const {
2598 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2599 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2600 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2603 Instruction *apply(BinaryOperator &Log) const {
2604 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2605 if (SCI->getOperand(0) != LHS) {
2606 assert(SCI->getOperand(1) == LHS);
2607 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2610 unsigned LHSCode = getSetCondCode(SCI);
2611 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2613 switch (Log.getOpcode()) {
2614 case Instruction::And: Code = LHSCode & RHSCode; break;
2615 case Instruction::Or: Code = LHSCode | RHSCode; break;
2616 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2617 default: assert(0 && "Illegal logical opcode!"); return 0;
2620 Value *RV = getSetCCValue(Code, LHS, RHS);
2621 if (Instruction *I = dyn_cast<Instruction>(RV))
2623 // Otherwise, it's a constant boolean value...
2624 return IC.ReplaceInstUsesWith(Log, RV);
2628 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2629 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2630 // guaranteed to be either a shift instruction or a binary operator.
2631 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2632 ConstantIntegral *OpRHS,
2633 ConstantIntegral *AndRHS,
2634 BinaryOperator &TheAnd) {
2635 Value *X = Op->getOperand(0);
2636 Constant *Together = 0;
2637 if (!isa<ShiftInst>(Op))
2638 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2640 switch (Op->getOpcode()) {
2641 case Instruction::Xor:
2642 if (Op->hasOneUse()) {
2643 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2644 std::string OpName = Op->getName(); Op->setName("");
2645 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2646 InsertNewInstBefore(And, TheAnd);
2647 return BinaryOperator::createXor(And, Together);
2650 case Instruction::Or:
2651 if (Together == AndRHS) // (X | C) & C --> C
2652 return ReplaceInstUsesWith(TheAnd, AndRHS);
2654 if (Op->hasOneUse() && Together != OpRHS) {
2655 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2656 std::string Op0Name = Op->getName(); Op->setName("");
2657 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2658 InsertNewInstBefore(Or, TheAnd);
2659 return BinaryOperator::createAnd(Or, AndRHS);
2662 case Instruction::Add:
2663 if (Op->hasOneUse()) {
2664 // Adding a one to a single bit bit-field should be turned into an XOR
2665 // of the bit. First thing to check is to see if this AND is with a
2666 // single bit constant.
2667 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2669 // Clear bits that are not part of the constant.
2670 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2672 // If there is only one bit set...
2673 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2674 // Ok, at this point, we know that we are masking the result of the
2675 // ADD down to exactly one bit. If the constant we are adding has
2676 // no bits set below this bit, then we can eliminate the ADD.
2677 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2679 // Check to see if any bits below the one bit set in AndRHSV are set.
2680 if ((AddRHS & (AndRHSV-1)) == 0) {
2681 // If not, the only thing that can effect the output of the AND is
2682 // the bit specified by AndRHSV. If that bit is set, the effect of
2683 // the XOR is to toggle the bit. If it is clear, then the ADD has
2685 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2686 TheAnd.setOperand(0, X);
2689 std::string Name = Op->getName(); Op->setName("");
2690 // Pull the XOR out of the AND.
2691 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2692 InsertNewInstBefore(NewAnd, TheAnd);
2693 return BinaryOperator::createXor(NewAnd, AndRHS);
2700 case Instruction::Shl: {
2701 // We know that the AND will not produce any of the bits shifted in, so if
2702 // the anded constant includes them, clear them now!
2704 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2705 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2706 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2708 if (CI == ShlMask) { // Masking out bits that the shift already masks
2709 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2710 } else if (CI != AndRHS) { // Reducing bits set in and.
2711 TheAnd.setOperand(1, CI);
2716 case Instruction::Shr:
2717 // We know that the AND will not produce any of the bits shifted in, so if
2718 // the anded constant includes them, clear them now! This only applies to
2719 // unsigned shifts, because a signed shr may bring in set bits!
2721 if (AndRHS->getType()->isUnsigned()) {
2722 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2723 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2724 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2726 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2727 return ReplaceInstUsesWith(TheAnd, Op);
2728 } else if (CI != AndRHS) {
2729 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2732 } else { // Signed shr.
2733 // See if this is shifting in some sign extension, then masking it out
2735 if (Op->hasOneUse()) {
2736 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2737 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2738 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2739 if (CI == AndRHS) { // Masking out bits shifted in.
2740 // Make the argument unsigned.
2741 Value *ShVal = Op->getOperand(0);
2742 ShVal = InsertCastBefore(ShVal,
2743 ShVal->getType()->getUnsignedVersion(),
2745 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2746 OpRHS, Op->getName()),
2748 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2749 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2752 return new CastInst(ShVal, Op->getType());
2762 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2763 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2764 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2765 /// insert new instructions.
2766 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2767 bool Inside, Instruction &IB) {
2768 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2769 "Lo is not <= Hi in range emission code!");
2771 if (Lo == Hi) // Trivially false.
2772 return new SetCondInst(Instruction::SetNE, V, V);
2773 if (cast<ConstantIntegral>(Lo)->isMinValue())
2774 return new SetCondInst(Instruction::SetLT, V, Hi);
2776 Constant *AddCST = ConstantExpr::getNeg(Lo);
2777 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2778 InsertNewInstBefore(Add, IB);
2779 // Convert to unsigned for the comparison.
2780 const Type *UnsType = Add->getType()->getUnsignedVersion();
2781 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2782 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2783 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2784 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2787 if (Lo == Hi) // Trivially true.
2788 return new SetCondInst(Instruction::SetEQ, V, V);
2790 Hi = SubOne(cast<ConstantInt>(Hi));
2792 // V < 0 || V >= Hi ->'V > Hi-1'
2793 if (cast<ConstantIntegral>(Lo)->isMinValue())
2794 return new SetCondInst(Instruction::SetGT, V, Hi);
2796 // Emit X-Lo > Hi-Lo-1
2797 Constant *AddCST = ConstantExpr::getNeg(Lo);
2798 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2799 InsertNewInstBefore(Add, IB);
2800 // Convert to unsigned for the comparison.
2801 const Type *UnsType = Add->getType()->getUnsignedVersion();
2802 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2803 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2804 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2805 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2808 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2809 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2810 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2811 // not, since all 1s are not contiguous.
2812 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2813 uint64_t V = Val->getZExtValue();
2814 if (!isShiftedMask_64(V)) return false;
2816 // look for the first zero bit after the run of ones
2817 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2818 // look for the first non-zero bit
2819 ME = 64-CountLeadingZeros_64(V);
2825 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2826 /// where isSub determines whether the operator is a sub. If we can fold one of
2827 /// the following xforms:
2829 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2830 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2831 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2833 /// return (A +/- B).
2835 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2836 ConstantIntegral *Mask, bool isSub,
2838 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2839 if (!LHSI || LHSI->getNumOperands() != 2 ||
2840 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2842 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2844 switch (LHSI->getOpcode()) {
2846 case Instruction::And:
2847 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2848 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2849 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
2852 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2853 // part, we don't need any explicit masks to take them out of A. If that
2854 // is all N is, ignore it.
2856 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2857 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2859 if (MaskedValueIsZero(RHS, Mask))
2864 case Instruction::Or:
2865 case Instruction::Xor:
2866 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2867 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
2868 ConstantExpr::getAnd(N, Mask)->isNullValue())
2875 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2877 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2878 return InsertNewInstBefore(New, I);
2881 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2882 bool Changed = SimplifyCommutative(I);
2883 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2885 if (isa<UndefValue>(Op1)) // X & undef -> 0
2886 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2890 return ReplaceInstUsesWith(I, Op1);
2892 // See if we can simplify any instructions used by the instruction whose sole
2893 // purpose is to compute bits we don't care about.
2894 uint64_t KnownZero, KnownOne;
2895 if (!isa<PackedType>(I.getType()) &&
2896 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2897 KnownZero, KnownOne))
2900 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2901 uint64_t AndRHSMask = AndRHS->getZExtValue();
2902 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2903 uint64_t NotAndRHS = AndRHSMask^TypeMask;
2905 // Optimize a variety of ((val OP C1) & C2) combinations...
2906 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2907 Instruction *Op0I = cast<Instruction>(Op0);
2908 Value *Op0LHS = Op0I->getOperand(0);
2909 Value *Op0RHS = Op0I->getOperand(1);
2910 switch (Op0I->getOpcode()) {
2911 case Instruction::Xor:
2912 case Instruction::Or:
2913 // If the mask is only needed on one incoming arm, push it up.
2914 if (Op0I->hasOneUse()) {
2915 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2916 // Not masking anything out for the LHS, move to RHS.
2917 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2918 Op0RHS->getName()+".masked");
2919 InsertNewInstBefore(NewRHS, I);
2920 return BinaryOperator::create(
2921 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2923 if (!isa<Constant>(Op0RHS) &&
2924 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2925 // Not masking anything out for the RHS, move to LHS.
2926 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2927 Op0LHS->getName()+".masked");
2928 InsertNewInstBefore(NewLHS, I);
2929 return BinaryOperator::create(
2930 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2935 case Instruction::Add:
2936 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2937 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2938 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2939 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2940 return BinaryOperator::createAnd(V, AndRHS);
2941 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2942 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
2945 case Instruction::Sub:
2946 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2947 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2948 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2949 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2950 return BinaryOperator::createAnd(V, AndRHS);
2954 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2955 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2957 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2958 const Type *SrcTy = CI->getOperand(0)->getType();
2960 // If this is an integer truncation or change from signed-to-unsigned, and
2961 // if the source is an and/or with immediate, transform it. This
2962 // frequently occurs for bitfield accesses.
2963 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2964 if (SrcTy->getPrimitiveSizeInBits() >=
2965 I.getType()->getPrimitiveSizeInBits() &&
2966 CastOp->getNumOperands() == 2)
2967 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2968 if (CastOp->getOpcode() == Instruction::And) {
2969 // Change: and (cast (and X, C1) to T), C2
2970 // into : and (cast X to T), trunc(C1)&C2
2971 // This will folds the two ands together, which may allow other
2973 Instruction *NewCast =
2974 new CastInst(CastOp->getOperand(0), I.getType(),
2975 CastOp->getName()+".shrunk");
2976 NewCast = InsertNewInstBefore(NewCast, I);
2978 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2979 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2980 return BinaryOperator::createAnd(NewCast, C3);
2981 } else if (CastOp->getOpcode() == Instruction::Or) {
2982 // Change: and (cast (or X, C1) to T), C2
2983 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2984 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2985 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2986 return ReplaceInstUsesWith(I, AndRHS);
2991 // Try to fold constant and into select arguments.
2992 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2993 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2995 if (isa<PHINode>(Op0))
2996 if (Instruction *NV = FoldOpIntoPhi(I))
3000 Value *Op0NotVal = dyn_castNotVal(Op0);
3001 Value *Op1NotVal = dyn_castNotVal(Op1);
3003 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3006 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3007 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3008 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3009 I.getName()+".demorgan");
3010 InsertNewInstBefore(Or, I);
3011 return BinaryOperator::createNot(Or);
3015 Value *A = 0, *B = 0;
3016 ConstantInt *C1 = 0, *C2 = 0;
3017 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3018 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3019 return ReplaceInstUsesWith(I, Op1);
3020 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3021 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3022 return ReplaceInstUsesWith(I, Op0);
3024 if (Op0->hasOneUse() &&
3025 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3026 if (A == Op1) { // (A^B)&A -> A&(A^B)
3027 I.swapOperands(); // Simplify below
3028 std::swap(Op0, Op1);
3029 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3030 cast<BinaryOperator>(Op0)->swapOperands();
3031 I.swapOperands(); // Simplify below
3032 std::swap(Op0, Op1);
3035 if (Op1->hasOneUse() &&
3036 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3037 if (B == Op0) { // B&(A^B) -> B&(B^A)
3038 cast<BinaryOperator>(Op1)->swapOperands();
3041 if (A == Op0) { // A&(A^B) -> A & ~B
3042 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3043 InsertNewInstBefore(NotB, I);
3044 return BinaryOperator::createAnd(A, NotB);
3050 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3051 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
3052 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3055 Value *LHSVal, *RHSVal;
3056 ConstantInt *LHSCst, *RHSCst;
3057 Instruction::BinaryOps LHSCC, RHSCC;
3058 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3059 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3060 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3061 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3062 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3063 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3064 // Ensure that the larger constant is on the RHS.
3065 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3066 SetCondInst *LHS = cast<SetCondInst>(Op0);
3067 if (cast<ConstantBool>(Cmp)->getValue()) {
3068 std::swap(LHS, RHS);
3069 std::swap(LHSCst, RHSCst);
3070 std::swap(LHSCC, RHSCC);
3073 // At this point, we know we have have two setcc instructions
3074 // comparing a value against two constants and and'ing the result
3075 // together. Because of the above check, we know that we only have
3076 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3077 // FoldSetCCLogical check above), that the two constants are not
3079 assert(LHSCst != RHSCst && "Compares not folded above?");
3082 default: assert(0 && "Unknown integer condition code!");
3083 case Instruction::SetEQ:
3085 default: assert(0 && "Unknown integer condition code!");
3086 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3087 case Instruction::SetGT: // (X == 13 & X > 15) -> false
3088 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3089 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3090 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3091 return ReplaceInstUsesWith(I, LHS);
3093 case Instruction::SetNE:
3095 default: assert(0 && "Unknown integer condition code!");
3096 case Instruction::SetLT:
3097 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3098 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3099 break; // (X != 13 & X < 15) -> no change
3100 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3101 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3102 return ReplaceInstUsesWith(I, RHS);
3103 case Instruction::SetNE:
3104 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3105 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3106 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3107 LHSVal->getName()+".off");
3108 InsertNewInstBefore(Add, I);
3109 const Type *UnsType = Add->getType()->getUnsignedVersion();
3110 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3111 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3112 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3113 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3115 break; // (X != 13 & X != 15) -> no change
3118 case Instruction::SetLT:
3120 default: assert(0 && "Unknown integer condition code!");
3121 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3122 case Instruction::SetGT: // (X < 13 & X > 15) -> false
3123 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3124 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3125 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3126 return ReplaceInstUsesWith(I, LHS);
3128 case Instruction::SetGT:
3130 default: assert(0 && "Unknown integer condition code!");
3131 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3132 return ReplaceInstUsesWith(I, LHS);
3133 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3134 return ReplaceInstUsesWith(I, RHS);
3135 case Instruction::SetNE:
3136 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3137 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3138 break; // (X > 13 & X != 15) -> no change
3139 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3140 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
3146 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3147 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3148 const Type *SrcTy = Op0C->getOperand(0)->getType();
3149 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3150 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3151 // Only do this if the casts both really cause code to be generated.
3152 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3153 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3154 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3155 Op1C->getOperand(0),
3157 InsertNewInstBefore(NewOp, I);
3158 return new CastInst(NewOp, I.getType());
3162 return Changed ? &I : 0;
3165 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3166 /// in the result. If it does, and if the specified byte hasn't been filled in
3167 /// yet, fill it in and return false.
3168 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3169 Instruction *I = dyn_cast<Instruction>(V);
3170 if (I == 0) return true;
3172 // If this is an or instruction, it is an inner node of the bswap.
3173 if (I->getOpcode() == Instruction::Or)
3174 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3175 CollectBSwapParts(I->getOperand(1), ByteValues);
3177 // If this is a shift by a constant int, and it is "24", then its operand
3178 // defines a byte. We only handle unsigned types here.
3179 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3180 // Not shifting the entire input by N-1 bytes?
3181 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3182 8*(ByteValues.size()-1))
3186 if (I->getOpcode() == Instruction::Shl) {
3187 // X << 24 defines the top byte with the lowest of the input bytes.
3188 DestNo = ByteValues.size()-1;
3190 // X >>u 24 defines the low byte with the highest of the input bytes.
3194 // If the destination byte value is already defined, the values are or'd
3195 // together, which isn't a bswap (unless it's an or of the same bits).
3196 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3198 ByteValues[DestNo] = I->getOperand(0);
3202 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3204 Value *Shift = 0, *ShiftLHS = 0;
3205 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3206 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3207 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3209 Instruction *SI = cast<Instruction>(Shift);
3211 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3212 if (ShiftAmt->getZExtValue() & 7 ||
3213 ShiftAmt->getZExtValue() > 8*ByteValues.size())
3216 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3218 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3219 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3221 // Unknown mask for bswap.
3222 if (DestByte == ByteValues.size()) return true;
3224 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3226 if (SI->getOpcode() == Instruction::Shl)
3227 SrcByte = DestByte - ShiftBytes;
3229 SrcByte = DestByte + ShiftBytes;
3231 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3232 if (SrcByte != ByteValues.size()-DestByte-1)
3235 // If the destination byte value is already defined, the values are or'd
3236 // together, which isn't a bswap (unless it's an or of the same bits).
3237 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3239 ByteValues[DestByte] = SI->getOperand(0);
3243 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3244 /// If so, insert the new bswap intrinsic and return it.
3245 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3246 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3247 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3250 /// ByteValues - For each byte of the result, we keep track of which value
3251 /// defines each byte.
3252 std::vector<Value*> ByteValues;
3253 ByteValues.resize(I.getType()->getPrimitiveSize());
3255 // Try to find all the pieces corresponding to the bswap.
3256 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3257 CollectBSwapParts(I.getOperand(1), ByteValues))
3260 // Check to see if all of the bytes come from the same value.
3261 Value *V = ByteValues[0];
3262 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3264 // Check to make sure that all of the bytes come from the same value.
3265 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3266 if (ByteValues[i] != V)
3269 // If they do then *success* we can turn this into a bswap. Figure out what
3270 // bswap to make it into.
3271 Module *M = I.getParent()->getParent()->getParent();
3272 const char *FnName = 0;
3273 if (I.getType() == Type::UShortTy)
3274 FnName = "llvm.bswap.i16";
3275 else if (I.getType() == Type::UIntTy)
3276 FnName = "llvm.bswap.i32";
3277 else if (I.getType() == Type::ULongTy)
3278 FnName = "llvm.bswap.i64";
3280 assert(0 && "Unknown integer type!");
3281 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3283 return new CallInst(F, V);
3287 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3288 bool Changed = SimplifyCommutative(I);
3289 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3291 if (isa<UndefValue>(Op1))
3292 return ReplaceInstUsesWith(I, // X | undef -> -1
3293 ConstantIntegral::getAllOnesValue(I.getType()));
3297 return ReplaceInstUsesWith(I, Op0);
3299 // See if we can simplify any instructions used by the instruction whose sole
3300 // purpose is to compute bits we don't care about.
3301 uint64_t KnownZero, KnownOne;
3302 if (!isa<PackedType>(I.getType()) &&
3303 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3304 KnownZero, KnownOne))
3308 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3309 ConstantInt *C1 = 0; Value *X = 0;
3310 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3311 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3312 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3314 InsertNewInstBefore(Or, I);
3315 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3318 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3319 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3320 std::string Op0Name = Op0->getName(); Op0->setName("");
3321 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3322 InsertNewInstBefore(Or, I);
3323 return BinaryOperator::createXor(Or,
3324 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3327 // Try to fold constant and into select arguments.
3328 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3329 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3331 if (isa<PHINode>(Op0))
3332 if (Instruction *NV = FoldOpIntoPhi(I))
3336 Value *A = 0, *B = 0;
3337 ConstantInt *C1 = 0, *C2 = 0;
3339 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3340 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3341 return ReplaceInstUsesWith(I, Op1);
3342 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3343 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3344 return ReplaceInstUsesWith(I, Op0);
3346 // (A | B) | C and A | (B | C) -> bswap if possible.
3347 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3348 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3349 match(Op1, m_Or(m_Value(), m_Value())) ||
3350 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3351 match(Op1, m_Shift(m_Value(), m_Value())))) {
3352 if (Instruction *BSwap = MatchBSwap(I))
3356 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3357 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3358 MaskedValueIsZero(Op1, C1->getZExtValue())) {
3359 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3361 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3364 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3365 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3366 MaskedValueIsZero(Op0, C1->getZExtValue())) {
3367 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3369 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3372 // (A & C1)|(B & C2)
3373 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3374 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3376 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3377 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3380 // If we have: ((V + N) & C1) | (V & C2)
3381 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3382 // replace with V+N.
3383 if (C1 == ConstantExpr::getNot(C2)) {
3384 Value *V1 = 0, *V2 = 0;
3385 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3386 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3387 // Add commutes, try both ways.
3388 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3389 return ReplaceInstUsesWith(I, A);
3390 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3391 return ReplaceInstUsesWith(I, A);
3393 // Or commutes, try both ways.
3394 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3395 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3396 // Add commutes, try both ways.
3397 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3398 return ReplaceInstUsesWith(I, B);
3399 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3400 return ReplaceInstUsesWith(I, B);
3405 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3406 if (A == Op1) // ~A | A == -1
3407 return ReplaceInstUsesWith(I,
3408 ConstantIntegral::getAllOnesValue(I.getType()));
3412 // Note, A is still live here!
3413 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3415 return ReplaceInstUsesWith(I,
3416 ConstantIntegral::getAllOnesValue(I.getType()));
3418 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3419 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3420 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3421 I.getName()+".demorgan"), I);
3422 return BinaryOperator::createNot(And);
3426 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3427 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3428 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3431 Value *LHSVal, *RHSVal;
3432 ConstantInt *LHSCst, *RHSCst;
3433 Instruction::BinaryOps LHSCC, RHSCC;
3434 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3435 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3436 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3437 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3438 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3439 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3440 // Ensure that the larger constant is on the RHS.
3441 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3442 SetCondInst *LHS = cast<SetCondInst>(Op0);
3443 if (cast<ConstantBool>(Cmp)->getValue()) {
3444 std::swap(LHS, RHS);
3445 std::swap(LHSCst, RHSCst);
3446 std::swap(LHSCC, RHSCC);
3449 // At this point, we know we have have two setcc instructions
3450 // comparing a value against two constants and or'ing the result
3451 // together. Because of the above check, we know that we only have
3452 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3453 // FoldSetCCLogical check above), that the two constants are not
3455 assert(LHSCst != RHSCst && "Compares not folded above?");
3458 default: assert(0 && "Unknown integer condition code!");
3459 case Instruction::SetEQ:
3461 default: assert(0 && "Unknown integer condition code!");
3462 case Instruction::SetEQ:
3463 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3464 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3465 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3466 LHSVal->getName()+".off");
3467 InsertNewInstBefore(Add, I);
3468 const Type *UnsType = Add->getType()->getUnsignedVersion();
3469 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3470 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3471 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3472 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3474 break; // (X == 13 | X == 15) -> no change
3476 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3478 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3479 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3480 return ReplaceInstUsesWith(I, RHS);
3483 case Instruction::SetNE:
3485 default: assert(0 && "Unknown integer condition code!");
3486 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3487 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3488 return ReplaceInstUsesWith(I, LHS);
3489 case Instruction::SetNE: // (X != 13 | X != 15) -> true
3490 case Instruction::SetLT: // (X != 13 | X < 15) -> true
3491 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3494 case Instruction::SetLT:
3496 default: assert(0 && "Unknown integer condition code!");
3497 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3499 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3500 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3501 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3502 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3503 return ReplaceInstUsesWith(I, RHS);
3506 case Instruction::SetGT:
3508 default: assert(0 && "Unknown integer condition code!");
3509 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3510 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3511 return ReplaceInstUsesWith(I, LHS);
3512 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3513 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3514 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3520 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3521 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3522 const Type *SrcTy = Op0C->getOperand(0)->getType();
3523 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3524 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3525 // Only do this if the casts both really cause code to be generated.
3526 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3527 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3528 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3529 Op1C->getOperand(0),
3531 InsertNewInstBefore(NewOp, I);
3532 return new CastInst(NewOp, I.getType());
3537 return Changed ? &I : 0;
3540 // XorSelf - Implements: X ^ X --> 0
3543 XorSelf(Value *rhs) : RHS(rhs) {}
3544 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3545 Instruction *apply(BinaryOperator &Xor) const {
3551 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3552 bool Changed = SimplifyCommutative(I);
3553 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3555 if (isa<UndefValue>(Op1))
3556 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3558 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3559 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3560 assert(Result == &I && "AssociativeOpt didn't work?");
3561 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3564 // See if we can simplify any instructions used by the instruction whose sole
3565 // purpose is to compute bits we don't care about.
3566 uint64_t KnownZero, KnownOne;
3567 if (!isa<PackedType>(I.getType()) &&
3568 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3569 KnownZero, KnownOne))
3572 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3573 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3574 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3575 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3576 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
3577 return new SetCondInst(SCI->getInverseCondition(),
3578 SCI->getOperand(0), SCI->getOperand(1));
3580 // ~(c-X) == X-c-1 == X+(-c-1)
3581 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3582 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3583 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3584 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3585 ConstantInt::get(I.getType(), 1));
3586 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3589 // ~(~X & Y) --> (X | ~Y)
3590 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3591 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3592 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3594 BinaryOperator::createNot(Op0I->getOperand(1),
3595 Op0I->getOperand(1)->getName()+".not");
3596 InsertNewInstBefore(NotY, I);
3597 return BinaryOperator::createOr(Op0NotVal, NotY);
3601 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3602 if (Op0I->getOpcode() == Instruction::Add) {
3603 // ~(X-c) --> (-c-1)-X
3604 if (RHS->isAllOnesValue()) {
3605 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3606 return BinaryOperator::createSub(
3607 ConstantExpr::getSub(NegOp0CI,
3608 ConstantInt::get(I.getType(), 1)),
3609 Op0I->getOperand(0));
3611 } else if (Op0I->getOpcode() == Instruction::Or) {
3612 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3613 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3614 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3615 // Anything in both C1 and C2 is known to be zero, remove it from
3617 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3618 NewRHS = ConstantExpr::getAnd(NewRHS,
3619 ConstantExpr::getNot(CommonBits));
3620 WorkList.push_back(Op0I);
3621 I.setOperand(0, Op0I->getOperand(0));
3622 I.setOperand(1, NewRHS);
3628 // Try to fold constant and into select arguments.
3629 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3630 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3632 if (isa<PHINode>(Op0))
3633 if (Instruction *NV = FoldOpIntoPhi(I))
3637 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
3639 return ReplaceInstUsesWith(I,
3640 ConstantIntegral::getAllOnesValue(I.getType()));
3642 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
3644 return ReplaceInstUsesWith(I,
3645 ConstantIntegral::getAllOnesValue(I.getType()));
3647 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3648 if (Op1I->getOpcode() == Instruction::Or) {
3649 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
3650 Op1I->swapOperands();
3652 std::swap(Op0, Op1);
3653 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
3654 I.swapOperands(); // Simplified below.
3655 std::swap(Op0, Op1);
3657 } else if (Op1I->getOpcode() == Instruction::Xor) {
3658 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3659 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3660 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3661 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3662 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3663 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3664 Op1I->swapOperands();
3665 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3666 I.swapOperands(); // Simplified below.
3667 std::swap(Op0, Op1);
3671 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3672 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3673 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3674 Op0I->swapOperands();
3675 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3676 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3677 InsertNewInstBefore(NotB, I);
3678 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3680 } else if (Op0I->getOpcode() == Instruction::Xor) {
3681 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3682 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3683 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3684 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3685 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3686 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3687 Op0I->swapOperands();
3688 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3689 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3690 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3691 InsertNewInstBefore(N, I);
3692 return BinaryOperator::createAnd(N, Op1);
3696 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3697 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3698 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3701 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3702 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3703 const Type *SrcTy = Op0C->getOperand(0)->getType();
3704 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3705 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3706 // Only do this if the casts both really cause code to be generated.
3707 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3708 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3709 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3710 Op1C->getOperand(0),
3712 InsertNewInstBefore(NewOp, I);
3713 return new CastInst(NewOp, I.getType());
3717 return Changed ? &I : 0;
3720 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3721 /// overflowed for this type.
3722 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3724 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3725 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3728 static bool isPositive(ConstantInt *C) {
3729 return C->getSExtValue() >= 0;
3732 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3733 /// overflowed for this type.
3734 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3736 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3738 if (In1->getType()->isUnsigned())
3739 return cast<ConstantInt>(Result)->getZExtValue() <
3740 cast<ConstantInt>(In1)->getZExtValue();
3741 if (isPositive(In1) != isPositive(In2))
3743 if (isPositive(In1))
3744 return cast<ConstantInt>(Result)->getSExtValue() <
3745 cast<ConstantInt>(In1)->getSExtValue();
3746 return cast<ConstantInt>(Result)->getSExtValue() >
3747 cast<ConstantInt>(In1)->getSExtValue();
3750 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3751 /// code necessary to compute the offset from the base pointer (without adding
3752 /// in the base pointer). Return the result as a signed integer of intptr size.
3753 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3754 TargetData &TD = IC.getTargetData();
3755 gep_type_iterator GTI = gep_type_begin(GEP);
3756 const Type *UIntPtrTy = TD.getIntPtrType();
3757 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3758 Value *Result = Constant::getNullValue(SIntPtrTy);
3760 // Build a mask for high order bits.
3761 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3763 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3764 Value *Op = GEP->getOperand(i);
3765 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3766 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
3768 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3769 if (!OpC->isNullValue()) {
3770 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3771 Scale = ConstantExpr::getMul(OpC, Scale);
3772 if (Constant *RC = dyn_cast<Constant>(Result))
3773 Result = ConstantExpr::getAdd(RC, Scale);
3775 // Emit an add instruction.
3776 Result = IC.InsertNewInstBefore(
3777 BinaryOperator::createAdd(Result, Scale,
3778 GEP->getName()+".offs"), I);
3782 // Convert to correct type.
3783 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3784 Op->getName()+".c"), I);
3786 // We'll let instcombine(mul) convert this to a shl if possible.
3787 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3788 GEP->getName()+".idx"), I);
3790 // Emit an add instruction.
3791 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3792 GEP->getName()+".offs"), I);
3798 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3799 /// else. At this point we know that the GEP is on the LHS of the comparison.
3800 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3801 Instruction::BinaryOps Cond,
3803 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3805 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3806 if (isa<PointerType>(CI->getOperand(0)->getType()))
3807 RHS = CI->getOperand(0);
3809 Value *PtrBase = GEPLHS->getOperand(0);
3810 if (PtrBase == RHS) {
3811 // As an optimization, we don't actually have to compute the actual value of
3812 // OFFSET if this is a seteq or setne comparison, just return whether each
3813 // index is zero or not.
3814 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3815 Instruction *InVal = 0;
3816 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3817 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3819 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3820 if (isa<UndefValue>(C)) // undef index -> undef.
3821 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3822 if (C->isNullValue())
3824 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3825 EmitIt = false; // This is indexing into a zero sized array?
3826 } else if (isa<ConstantInt>(C))
3827 return ReplaceInstUsesWith(I, // No comparison is needed here.
3828 ConstantBool::get(Cond == Instruction::SetNE));
3833 new SetCondInst(Cond, GEPLHS->getOperand(i),
3834 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3838 InVal = InsertNewInstBefore(InVal, I);
3839 InsertNewInstBefore(Comp, I);
3840 if (Cond == Instruction::SetNE) // True if any are unequal
3841 InVal = BinaryOperator::createOr(InVal, Comp);
3842 else // True if all are equal
3843 InVal = BinaryOperator::createAnd(InVal, Comp);
3851 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3852 ConstantBool::get(Cond == Instruction::SetEQ));
3855 // Only lower this if the setcc is the only user of the GEP or if we expect
3856 // the result to fold to a constant!
3857 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3858 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3859 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3860 return new SetCondInst(Cond, Offset,
3861 Constant::getNullValue(Offset->getType()));
3863 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3864 // If the base pointers are different, but the indices are the same, just
3865 // compare the base pointer.
3866 if (PtrBase != GEPRHS->getOperand(0)) {
3867 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3868 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3869 GEPRHS->getOperand(0)->getType();
3871 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3872 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3873 IndicesTheSame = false;
3877 // If all indices are the same, just compare the base pointers.
3879 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3880 GEPRHS->getOperand(0));
3882 // Otherwise, the base pointers are different and the indices are
3883 // different, bail out.
3887 // If one of the GEPs has all zero indices, recurse.
3888 bool AllZeros = true;
3889 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3890 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3891 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3896 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3897 SetCondInst::getSwappedCondition(Cond), I);
3899 // If the other GEP has all zero indices, recurse.
3901 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3902 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3903 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3908 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3910 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3911 // If the GEPs only differ by one index, compare it.
3912 unsigned NumDifferences = 0; // Keep track of # differences.
3913 unsigned DiffOperand = 0; // The operand that differs.
3914 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3915 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3916 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3917 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3918 // Irreconcilable differences.
3922 if (NumDifferences++) break;
3927 if (NumDifferences == 0) // SAME GEP?
3928 return ReplaceInstUsesWith(I, // No comparison is needed here.
3929 ConstantBool::get(Cond == Instruction::SetEQ));
3930 else if (NumDifferences == 1) {
3931 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3932 Value *RHSV = GEPRHS->getOperand(DiffOperand);
3934 // Convert the operands to signed values to make sure to perform a
3935 // signed comparison.
3936 const Type *NewTy = LHSV->getType()->getSignedVersion();
3937 if (LHSV->getType() != NewTy)
3938 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3939 LHSV->getName()), I);
3940 if (RHSV->getType() != NewTy)
3941 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3942 RHSV->getName()), I);
3943 return new SetCondInst(Cond, LHSV, RHSV);
3947 // Only lower this if the setcc is the only user of the GEP or if we expect
3948 // the result to fold to a constant!
3949 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3950 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3951 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3952 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3953 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3954 return new SetCondInst(Cond, L, R);
3961 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3962 bool Changed = SimplifyCommutative(I);
3963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3964 const Type *Ty = Op0->getType();
3968 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3970 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3971 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3973 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3974 // addresses never equal each other! We already know that Op0 != Op1.
3975 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3976 isa<ConstantPointerNull>(Op0)) &&
3977 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3978 isa<ConstantPointerNull>(Op1)))
3979 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3981 // setcc's with boolean values can always be turned into bitwise operations
3982 if (Ty == Type::BoolTy) {
3983 switch (I.getOpcode()) {
3984 default: assert(0 && "Invalid setcc instruction!");
3985 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
3986 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3987 InsertNewInstBefore(Xor, I);
3988 return BinaryOperator::createNot(Xor);
3990 case Instruction::SetNE:
3991 return BinaryOperator::createXor(Op0, Op1);
3993 case Instruction::SetGT:
3994 std::swap(Op0, Op1); // Change setgt -> setlt
3996 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3997 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3998 InsertNewInstBefore(Not, I);
3999 return BinaryOperator::createAnd(Not, Op1);
4001 case Instruction::SetGE:
4002 std::swap(Op0, Op1); // Change setge -> setle
4004 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4005 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4006 InsertNewInstBefore(Not, I);
4007 return BinaryOperator::createOr(Not, Op1);
4012 // See if we are doing a comparison between a constant and an instruction that
4013 // can be folded into the comparison.
4014 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4015 // Check to see if we are comparing against the minimum or maximum value...
4016 if (CI->isMinValue()) {
4017 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
4018 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4019 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
4020 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4021 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4022 return BinaryOperator::createSetEQ(Op0, Op1);
4023 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4024 return BinaryOperator::createSetNE(Op0, Op1);
4026 } else if (CI->isMaxValue()) {
4027 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
4028 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4029 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
4030 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4031 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4032 return BinaryOperator::createSetEQ(Op0, Op1);
4033 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4034 return BinaryOperator::createSetNE(Op0, Op1);
4036 // Comparing against a value really close to min or max?
4037 } else if (isMinValuePlusOne(CI)) {
4038 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4039 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4040 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4041 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4043 } else if (isMaxValueMinusOne(CI)) {
4044 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4045 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4046 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4047 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4050 // If we still have a setle or setge instruction, turn it into the
4051 // appropriate setlt or setgt instruction. Since the border cases have
4052 // already been handled above, this requires little checking.
4054 if (I.getOpcode() == Instruction::SetLE)
4055 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4056 if (I.getOpcode() == Instruction::SetGE)
4057 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4060 // See if we can fold the comparison based on bits known to be zero or one
4062 uint64_t KnownZero, KnownOne;
4063 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4064 KnownZero, KnownOne, 0))
4067 // Given the known and unknown bits, compute a range that the LHS could be
4069 if (KnownOne | KnownZero) {
4070 if (Ty->isUnsigned()) { // Unsigned comparison.
4072 uint64_t RHSVal = CI->getZExtValue();
4073 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4075 switch (I.getOpcode()) { // LE/GE have been folded already.
4076 default: assert(0 && "Unknown setcc opcode!");
4077 case Instruction::SetEQ:
4078 if (Max < RHSVal || Min > RHSVal)
4079 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4081 case Instruction::SetNE:
4082 if (Max < RHSVal || Min > RHSVal)
4083 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4085 case Instruction::SetLT:
4087 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4089 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4091 case Instruction::SetGT:
4093 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4095 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4098 } else { // Signed comparison.
4100 int64_t RHSVal = CI->getSExtValue();
4101 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4103 switch (I.getOpcode()) { // LE/GE have been folded already.
4104 default: assert(0 && "Unknown setcc opcode!");
4105 case Instruction::SetEQ:
4106 if (Max < RHSVal || Min > RHSVal)
4107 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4109 case Instruction::SetNE:
4110 if (Max < RHSVal || Min > RHSVal)
4111 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4113 case Instruction::SetLT:
4115 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4117 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4119 case Instruction::SetGT:
4121 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4123 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4130 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4131 switch (LHSI->getOpcode()) {
4132 case Instruction::And:
4133 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4134 LHSI->getOperand(0)->hasOneUse()) {
4135 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4137 // If an operand is an AND of a truncating cast, we can widen the
4138 // and/compare to be the input width without changing the value
4139 // produced, eliminating a cast.
4140 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4141 // We can do this transformation if either the AND constant does not
4142 // have its sign bit set or if it is an equality comparison.
4143 // Extending a relational comparison when we're checking the sign
4144 // bit would not work.
4145 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4147 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4148 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4149 ConstantInt *NewCST;
4151 if (Cast->getOperand(0)->getType()->isSigned()) {
4152 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4153 AndCST->getZExtValue());
4154 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4155 CI->getZExtValue());
4157 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4158 AndCST->getZExtValue());
4159 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4160 CI->getZExtValue());
4162 Instruction *NewAnd =
4163 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4165 InsertNewInstBefore(NewAnd, I);
4166 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4170 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4171 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4172 // happens a LOT in code produced by the C front-end, for bitfield
4174 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4176 // Check to see if there is a noop-cast between the shift and the and.
4178 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4179 if (CI->getOperand(0)->getType()->isIntegral() &&
4180 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4181 CI->getType()->getPrimitiveSizeInBits())
4182 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4186 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4187 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4188 const Type *AndTy = AndCST->getType(); // Type of the and.
4190 // We can fold this as long as we can't shift unknown bits
4191 // into the mask. This can only happen with signed shift
4192 // rights, as they sign-extend.
4194 bool CanFold = Shift->isLogicalShift();
4196 // To test for the bad case of the signed shr, see if any
4197 // of the bits shifted in could be tested after the mask.
4198 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4199 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4201 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
4203 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4205 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4211 if (Shift->getOpcode() == Instruction::Shl)
4212 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4214 NewCst = ConstantExpr::getShl(CI, ShAmt);
4216 // Check to see if we are shifting out any of the bits being
4218 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4219 // If we shifted bits out, the fold is not going to work out.
4220 // As a special case, check to see if this means that the
4221 // result is always true or false now.
4222 if (I.getOpcode() == Instruction::SetEQ)
4223 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4224 if (I.getOpcode() == Instruction::SetNE)
4225 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4227 I.setOperand(1, NewCst);
4228 Constant *NewAndCST;
4229 if (Shift->getOpcode() == Instruction::Shl)
4230 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4232 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4233 LHSI->setOperand(1, NewAndCST);
4235 LHSI->setOperand(0, Shift->getOperand(0));
4237 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4239 LHSI->setOperand(0, NewCast);
4241 WorkList.push_back(Shift); // Shift is dead.
4242 AddUsesToWorkList(I);
4248 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4249 // preferable because it allows the C<<Y expression to be hoisted out
4250 // of a loop if Y is invariant and X is not.
4251 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4252 I.isEquality() && !Shift->isArithmeticShift() &&
4253 isa<Instruction>(Shift->getOperand(0))) {
4256 if (Shift->getOpcode() == Instruction::Shr) {
4257 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4260 // Make sure we insert a logical shift.
4261 Constant *NewAndCST = AndCST;
4262 if (AndCST->getType()->isSigned())
4263 NewAndCST = ConstantExpr::getCast(AndCST,
4264 AndCST->getType()->getUnsignedVersion());
4265 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4266 Shift->getOperand(1), "tmp");
4268 InsertNewInstBefore(cast<Instruction>(NS), I);
4270 // If C's sign doesn't agree with the and, insert a cast now.
4271 if (NS->getType() != LHSI->getType())
4272 NS = InsertCastBefore(NS, LHSI->getType(), I);
4274 Value *ShiftOp = Shift->getOperand(0);
4275 if (ShiftOp->getType() != LHSI->getType())
4276 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4278 // Compute X & (C << Y).
4279 Instruction *NewAnd =
4280 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4281 InsertNewInstBefore(NewAnd, I);
4283 I.setOperand(0, NewAnd);
4289 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
4290 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4291 if (I.isEquality()) {
4292 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4294 // Check that the shift amount is in range. If not, don't perform
4295 // undefined shifts. When the shift is visited it will be
4297 if (ShAmt->getZExtValue() >= TypeBits)
4300 // If we are comparing against bits always shifted out, the
4301 // comparison cannot succeed.
4303 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4304 if (Comp != CI) {// Comparing against a bit that we know is zero.
4305 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4306 Constant *Cst = ConstantBool::get(IsSetNE);
4307 return ReplaceInstUsesWith(I, Cst);
4310 if (LHSI->hasOneUse()) {
4311 // Otherwise strength reduce the shift into an and.
4312 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4313 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4316 if (CI->getType()->isUnsigned()) {
4317 Mask = ConstantInt::get(CI->getType(), Val);
4318 } else if (ShAmtVal != 0) {
4319 Mask = ConstantInt::get(CI->getType(), Val);
4321 Mask = ConstantInt::getAllOnesValue(CI->getType());
4325 BinaryOperator::createAnd(LHSI->getOperand(0),
4326 Mask, LHSI->getName()+".mask");
4327 Value *And = InsertNewInstBefore(AndI, I);
4328 return new SetCondInst(I.getOpcode(), And,
4329 ConstantExpr::getUShr(CI, ShAmt));
4335 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
4336 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4337 if (I.isEquality()) {
4338 // Check that the shift amount is in range. If not, don't perform
4339 // undefined shifts. When the shift is visited it will be
4341 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4342 if (ShAmt->getZExtValue() >= TypeBits)
4345 // If we are comparing against bits always shifted out, the
4346 // comparison cannot succeed.
4348 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
4350 if (Comp != CI) {// Comparing against a bit that we know is zero.
4351 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4352 Constant *Cst = ConstantBool::get(IsSetNE);
4353 return ReplaceInstUsesWith(I, Cst);
4356 if (LHSI->hasOneUse() || CI->isNullValue()) {
4357 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4359 // Otherwise strength reduce the shift into an and.
4360 uint64_t Val = ~0ULL; // All ones.
4361 Val <<= ShAmtVal; // Shift over to the right spot.
4364 if (CI->getType()->isUnsigned()) {
4365 Val &= ~0ULL >> (64-TypeBits);
4366 Mask = ConstantInt::get(CI->getType(), Val);
4368 Mask = ConstantInt::get(CI->getType(), Val);
4372 BinaryOperator::createAnd(LHSI->getOperand(0),
4373 Mask, LHSI->getName()+".mask");
4374 Value *And = InsertNewInstBefore(AndI, I);
4375 return new SetCondInst(I.getOpcode(), And,
4376 ConstantExpr::getShl(CI, ShAmt));
4382 case Instruction::Div:
4383 // Fold: (div X, C1) op C2 -> range check
4384 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4385 // Fold this div into the comparison, producing a range check.
4386 // Determine, based on the divide type, what the range is being
4387 // checked. If there is an overflow on the low or high side, remember
4388 // it, otherwise compute the range [low, hi) bounding the new value.
4389 bool LoOverflow = false, HiOverflow = 0;
4390 ConstantInt *LoBound = 0, *HiBound = 0;
4393 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4395 Instruction::BinaryOps Opcode = I.getOpcode();
4397 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4398 } else if (LHSI->getType()->isUnsigned()) { // udiv
4400 LoOverflow = ProdOV;
4401 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4402 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4403 if (CI->isNullValue()) { // (X / pos) op 0
4405 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4407 } else if (isPositive(CI)) { // (X / pos) op pos
4409 LoOverflow = ProdOV;
4410 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4411 } else { // (X / pos) op neg
4412 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4413 LoOverflow = AddWithOverflow(LoBound, Prod,
4414 cast<ConstantInt>(DivRHSH));
4416 HiOverflow = ProdOV;
4418 } else { // Divisor is < 0.
4419 if (CI->isNullValue()) { // (X / neg) op 0
4420 LoBound = AddOne(DivRHS);
4421 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4422 if (HiBound == DivRHS)
4423 LoBound = 0; // - INTMIN = INTMIN
4424 } else if (isPositive(CI)) { // (X / neg) op pos
4425 HiOverflow = LoOverflow = ProdOV;
4427 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4428 HiBound = AddOne(Prod);
4429 } else { // (X / neg) op neg
4431 LoOverflow = HiOverflow = ProdOV;
4432 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4435 // Dividing by a negate swaps the condition.
4436 Opcode = SetCondInst::getSwappedCondition(Opcode);
4440 Value *X = LHSI->getOperand(0);
4442 default: assert(0 && "Unhandled setcc opcode!");
4443 case Instruction::SetEQ:
4444 if (LoOverflow && HiOverflow)
4445 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4446 else if (HiOverflow)
4447 return new SetCondInst(Instruction::SetGE, X, LoBound);
4448 else if (LoOverflow)
4449 return new SetCondInst(Instruction::SetLT, X, HiBound);
4451 return InsertRangeTest(X, LoBound, HiBound, true, I);
4452 case Instruction::SetNE:
4453 if (LoOverflow && HiOverflow)
4454 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4455 else if (HiOverflow)
4456 return new SetCondInst(Instruction::SetLT, X, LoBound);
4457 else if (LoOverflow)
4458 return new SetCondInst(Instruction::SetGE, X, HiBound);
4460 return InsertRangeTest(X, LoBound, HiBound, false, I);
4461 case Instruction::SetLT:
4463 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4464 return new SetCondInst(Instruction::SetLT, X, LoBound);
4465 case Instruction::SetGT:
4467 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4468 return new SetCondInst(Instruction::SetGE, X, HiBound);
4475 // Simplify seteq and setne instructions...
4476 if (I.isEquality()) {
4477 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4479 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4480 // the second operand is a constant, simplify a bit.
4481 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4482 switch (BO->getOpcode()) {
4484 case Instruction::SRem:
4485 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4486 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4488 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4489 if (V > 1 && isPowerOf2_64(V)) {
4490 Value *NewRem = InsertNewInstBefore(
4491 BinaryOperator::createURem(BO->getOperand(0),
4494 return BinaryOperator::create(
4495 I.getOpcode(), NewRem,
4496 Constant::getNullValue(NewRem->getType()));
4502 case Instruction::Rem:
4503 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4504 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4505 BO->hasOneUse() && BO->getOperand(1)->getType()->isSigned()) {
4506 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4507 if (V > 1 && isPowerOf2_64(V)) {
4508 unsigned L2 = Log2_64(V);
4509 const Type *UTy = BO->getType()->getUnsignedVersion();
4510 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4512 Constant *RHSCst = ConstantInt::get(UTy, 1ULL << L2);
4513 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4514 RHSCst, BO->getName()), I);
4515 return BinaryOperator::create(I.getOpcode(), NewRem,
4516 Constant::getNullValue(UTy));
4520 case Instruction::Add:
4521 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4522 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4523 if (BO->hasOneUse())
4524 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4525 ConstantExpr::getSub(CI, BOp1C));
4526 } else if (CI->isNullValue()) {
4527 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4528 // efficiently invertible, or if the add has just this one use.
4529 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4531 if (Value *NegVal = dyn_castNegVal(BOp1))
4532 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4533 else if (Value *NegVal = dyn_castNegVal(BOp0))
4534 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4535 else if (BO->hasOneUse()) {
4536 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4538 InsertNewInstBefore(Neg, I);
4539 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4543 case Instruction::Xor:
4544 // For the xor case, we can xor two constants together, eliminating
4545 // the explicit xor.
4546 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4547 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4548 ConstantExpr::getXor(CI, BOC));
4551 case Instruction::Sub:
4552 // Replace (([sub|xor] A, B) != 0) with (A != B)
4553 if (CI->isNullValue())
4554 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4558 case Instruction::Or:
4559 // If bits are being or'd in that are not present in the constant we
4560 // are comparing against, then the comparison could never succeed!
4561 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4562 Constant *NotCI = ConstantExpr::getNot(CI);
4563 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4564 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4568 case Instruction::And:
4569 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4570 // If bits are being compared against that are and'd out, then the
4571 // comparison can never succeed!
4572 if (!ConstantExpr::getAnd(CI,
4573 ConstantExpr::getNot(BOC))->isNullValue())
4574 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4576 // If we have ((X & C) == C), turn it into ((X & C) != 0).
4577 if (CI == BOC && isOneBitSet(CI))
4578 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4579 Instruction::SetNE, Op0,
4580 Constant::getNullValue(CI->getType()));
4582 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4583 // to be a signed value as appropriate.
4584 if (isSignBit(BOC)) {
4585 Value *X = BO->getOperand(0);
4586 // If 'X' is not signed, insert a cast now...
4587 if (!BOC->getType()->isSigned()) {
4588 const Type *DestTy = BOC->getType()->getSignedVersion();
4589 X = InsertCastBefore(X, DestTy, I);
4591 return new SetCondInst(isSetNE ? Instruction::SetLT :
4592 Instruction::SetGE, X,
4593 Constant::getNullValue(X->getType()));
4596 // ((X & ~7) == 0) --> X < 8
4597 if (CI->isNullValue() && isHighOnes(BOC)) {
4598 Value *X = BO->getOperand(0);
4599 Constant *NegX = ConstantExpr::getNeg(BOC);
4601 // If 'X' is signed, insert a cast now.
4602 if (NegX->getType()->isSigned()) {
4603 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4604 X = InsertCastBefore(X, DestTy, I);
4605 NegX = ConstantExpr::getCast(NegX, DestTy);
4608 return new SetCondInst(isSetNE ? Instruction::SetGE :
4609 Instruction::SetLT, X, NegX);
4616 } else { // Not a SetEQ/SetNE
4617 // If the LHS is a cast from an integral value of the same size,
4618 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4619 Value *CastOp = Cast->getOperand(0);
4620 const Type *SrcTy = CastOp->getType();
4621 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4622 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4623 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4624 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4625 "Source and destination signednesses should differ!");
4626 if (Cast->getType()->isSigned()) {
4627 // If this is a signed comparison, check for comparisons in the
4628 // vicinity of zero.
4629 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4631 return BinaryOperator::createSetGT(CastOp,
4632 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4633 else if (I.getOpcode() == Instruction::SetGT &&
4634 cast<ConstantInt>(CI)->getSExtValue() == -1)
4635 // X > -1 => x < 128
4636 return BinaryOperator::createSetLT(CastOp,
4637 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4639 ConstantInt *CUI = cast<ConstantInt>(CI);
4640 if (I.getOpcode() == Instruction::SetLT &&
4641 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
4642 // X < 128 => X > -1
4643 return BinaryOperator::createSetGT(CastOp,
4644 ConstantInt::get(SrcTy, -1));
4645 else if (I.getOpcode() == Instruction::SetGT &&
4646 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
4648 return BinaryOperator::createSetLT(CastOp,
4649 Constant::getNullValue(SrcTy));
4656 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4657 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4658 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4659 switch (LHSI->getOpcode()) {
4660 case Instruction::GetElementPtr:
4661 if (RHSC->isNullValue()) {
4662 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4663 bool isAllZeros = true;
4664 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4665 if (!isa<Constant>(LHSI->getOperand(i)) ||
4666 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4671 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4672 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4676 case Instruction::PHI:
4677 if (Instruction *NV = FoldOpIntoPhi(I))
4680 case Instruction::Select:
4681 // If either operand of the select is a constant, we can fold the
4682 // comparison into the select arms, which will cause one to be
4683 // constant folded and the select turned into a bitwise or.
4684 Value *Op1 = 0, *Op2 = 0;
4685 if (LHSI->hasOneUse()) {
4686 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4687 // Fold the known value into the constant operand.
4688 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4689 // Insert a new SetCC of the other select operand.
4690 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4691 LHSI->getOperand(2), RHSC,
4693 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4694 // Fold the known value into the constant operand.
4695 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4696 // Insert a new SetCC of the other select operand.
4697 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4698 LHSI->getOperand(1), RHSC,
4704 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4709 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4710 if (User *GEP = dyn_castGetElementPtr(Op0))
4711 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4713 if (User *GEP = dyn_castGetElementPtr(Op1))
4714 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4715 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4718 // Test to see if the operands of the setcc are casted versions of other
4719 // values. If the cast can be stripped off both arguments, we do so now.
4720 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4721 Value *CastOp0 = CI->getOperand(0);
4722 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
4723 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
4724 // We keep moving the cast from the left operand over to the right
4725 // operand, where it can often be eliminated completely.
4728 // If operand #1 is a cast instruction, see if we can eliminate it as
4730 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4731 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
4733 Op1 = CI2->getOperand(0);
4735 // If Op1 is a constant, we can fold the cast into the constant.
4736 if (Op1->getType() != Op0->getType())
4737 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4738 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4740 // Otherwise, cast the RHS right before the setcc
4741 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4742 InsertNewInstBefore(cast<Instruction>(Op1), I);
4744 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4747 // Handle the special case of: setcc (cast bool to X), <cst>
4748 // This comes up when you have code like
4751 // For generality, we handle any zero-extension of any operand comparison
4752 // with a constant or another cast from the same type.
4753 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4754 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4758 if (I.isEquality()) {
4760 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4761 (A == Op1 || B == Op1)) {
4762 // (A^B) == A -> B == 0
4763 Value *OtherVal = A == Op1 ? B : A;
4764 return BinaryOperator::create(I.getOpcode(), OtherVal,
4765 Constant::getNullValue(A->getType()));
4766 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4767 (A == Op0 || B == Op0)) {
4768 // A == (A^B) -> B == 0
4769 Value *OtherVal = A == Op0 ? B : A;
4770 return BinaryOperator::create(I.getOpcode(), OtherVal,
4771 Constant::getNullValue(A->getType()));
4772 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4773 // (A-B) == A -> B == 0
4774 return BinaryOperator::create(I.getOpcode(), B,
4775 Constant::getNullValue(B->getType()));
4776 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4777 // A == (A-B) -> B == 0
4778 return BinaryOperator::create(I.getOpcode(), B,
4779 Constant::getNullValue(B->getType()));
4782 return Changed ? &I : 0;
4785 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4786 // We only handle extending casts so far.
4788 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4789 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4790 const Type *SrcTy = LHSCIOp->getType();
4791 const Type *DestTy = SCI.getOperand(0)->getType();
4794 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
4797 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4798 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4799 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4801 // Is this a sign or zero extension?
4802 bool isSignSrc = SrcTy->isSigned();
4803 bool isSignDest = DestTy->isSigned();
4805 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4806 // Not an extension from the same type?
4807 RHSCIOp = CI->getOperand(0);
4808 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4809 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4810 // Compute the constant that would happen if we truncated to SrcTy then
4811 // reextended to DestTy.
4812 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4814 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4815 // Make sure that src sign and dest sign match. For example,
4817 // %A = cast short %X to uint
4818 // %B = setgt uint %A, 1330
4820 // It is incorrect to transform this into
4822 // %B = setgt short %X, 1330
4824 // because %A may have negative value.
4825 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4826 // OR operation is EQ/NE.
4827 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
4832 // If the value cannot be represented in the shorter type, we cannot emit
4833 // a simple comparison.
4834 if (SCI.getOpcode() == Instruction::SetEQ)
4835 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
4836 if (SCI.getOpcode() == Instruction::SetNE)
4837 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
4839 // Evaluate the comparison for LT.
4841 if (DestTy->isSigned()) {
4842 // We're performing a signed comparison.
4844 // Signed extend and signed comparison.
4845 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
4846 Result = ConstantBool::getFalse();
4848 Result = ConstantBool::getTrue(); // X < (large) --> true
4850 // Unsigned extend and signed comparison.
4851 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
4852 Result = ConstantBool::getFalse();
4854 Result = ConstantBool::getTrue();
4857 // We're performing an unsigned comparison.
4859 // Unsigned extend & compare -> always true.
4860 Result = ConstantBool::getTrue();
4862 // We're performing an unsigned comp with a sign extended value.
4863 // This is true if the input is >= 0. [aka >s -1]
4864 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4865 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4866 NegOne, SCI.getName()), SCI);
4870 // Finally, return the value computed.
4871 if (SCI.getOpcode() == Instruction::SetLT) {
4872 return ReplaceInstUsesWith(SCI, Result);
4874 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4875 if (Constant *CI = dyn_cast<Constant>(Result))
4876 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4878 return BinaryOperator::createNot(Result);
4885 // Okay, just insert a compare of the reduced operands now!
4886 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4889 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4890 assert(I.getOperand(1)->getType() == Type::UByteTy);
4891 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4892 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4894 // shl X, 0 == X and shr X, 0 == X
4895 // shl 0, X == 0 and shr 0, X == 0
4896 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4897 Op0 == Constant::getNullValue(Op0->getType()))
4898 return ReplaceInstUsesWith(I, Op0);
4900 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4901 if (!isLeftShift && I.getType()->isSigned())
4902 return ReplaceInstUsesWith(I, Op0);
4903 else // undef << X -> 0 AND undef >>u X -> 0
4904 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4906 if (isa<UndefValue>(Op1)) {
4907 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4908 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4910 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4913 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4915 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
4916 if (CSI->isAllOnesValue())
4917 return ReplaceInstUsesWith(I, CSI);
4919 // Try to fold constant and into select arguments.
4920 if (isa<Constant>(Op0))
4921 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4922 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4925 // See if we can turn a signed shr into an unsigned shr.
4926 if (I.isArithmeticShift()) {
4927 if (MaskedValueIsZero(Op0,
4928 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4929 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4930 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4932 return new CastInst(V, I.getType());
4936 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
4937 if (CUI->getType()->isUnsigned())
4938 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4943 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
4945 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4946 bool isSignedShift = Op0->getType()->isSigned();
4947 bool isUnsignedShift = !isSignedShift;
4949 // See if we can simplify any instructions used by the instruction whose sole
4950 // purpose is to compute bits we don't care about.
4951 uint64_t KnownZero, KnownOne;
4952 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4953 KnownZero, KnownOne))
4956 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4957 // of a signed value.
4959 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4960 if (Op1->getZExtValue() >= TypeBits) {
4961 if (isUnsignedShift || isLeftShift)
4962 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4964 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
4969 // ((X*C1) << C2) == (X * (C1 << C2))
4970 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4971 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4972 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4973 return BinaryOperator::createMul(BO->getOperand(0),
4974 ConstantExpr::getShl(BOOp, Op1));
4976 // Try to fold constant and into select arguments.
4977 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4978 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4980 if (isa<PHINode>(Op0))
4981 if (Instruction *NV = FoldOpIntoPhi(I))
4984 if (Op0->hasOneUse()) {
4985 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4986 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4989 switch (Op0BO->getOpcode()) {
4991 case Instruction::Add:
4992 case Instruction::And:
4993 case Instruction::Or:
4994 case Instruction::Xor:
4995 // These operators commute.
4996 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
4997 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4998 match(Op0BO->getOperand(1),
4999 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5000 Instruction *YS = new ShiftInst(Instruction::Shl,
5001 Op0BO->getOperand(0), Op1,
5003 InsertNewInstBefore(YS, I); // (Y << C)
5005 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5006 Op0BO->getOperand(1)->getName());
5007 InsertNewInstBefore(X, I); // (X + (Y << C))
5008 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5009 C2 = ConstantExpr::getShl(C2, Op1);
5010 return BinaryOperator::createAnd(X, C2);
5013 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5014 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5015 match(Op0BO->getOperand(1),
5016 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5017 m_ConstantInt(CC))) && V2 == Op1 &&
5018 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5019 Instruction *YS = new ShiftInst(Instruction::Shl,
5020 Op0BO->getOperand(0), Op1,
5022 InsertNewInstBefore(YS, I); // (Y << C)
5024 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5025 V1->getName()+".mask");
5026 InsertNewInstBefore(XM, I); // X & (CC << C)
5028 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5032 case Instruction::Sub:
5033 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5034 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5035 match(Op0BO->getOperand(0),
5036 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5037 Instruction *YS = new ShiftInst(Instruction::Shl,
5038 Op0BO->getOperand(1), Op1,
5040 InsertNewInstBefore(YS, I); // (Y << C)
5042 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5043 Op0BO->getOperand(0)->getName());
5044 InsertNewInstBefore(X, I); // (X + (Y << C))
5045 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5046 C2 = ConstantExpr::getShl(C2, Op1);
5047 return BinaryOperator::createAnd(X, C2);
5050 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
5051 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5052 match(Op0BO->getOperand(0),
5053 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5054 m_ConstantInt(CC))) && V2 == Op1 &&
5055 cast<BinaryOperator>(Op0BO->getOperand(0))
5056 ->getOperand(0)->hasOneUse()) {
5057 Instruction *YS = new ShiftInst(Instruction::Shl,
5058 Op0BO->getOperand(1), Op1,
5060 InsertNewInstBefore(YS, I); // (Y << C)
5062 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5063 V1->getName()+".mask");
5064 InsertNewInstBefore(XM, I); // X & (CC << C)
5066 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5073 // If the operand is an bitwise operator with a constant RHS, and the
5074 // shift is the only use, we can pull it out of the shift.
5075 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5076 bool isValid = true; // Valid only for And, Or, Xor
5077 bool highBitSet = false; // Transform if high bit of constant set?
5079 switch (Op0BO->getOpcode()) {
5080 default: isValid = false; break; // Do not perform transform!
5081 case Instruction::Add:
5082 isValid = isLeftShift;
5084 case Instruction::Or:
5085 case Instruction::Xor:
5088 case Instruction::And:
5093 // If this is a signed shift right, and the high bit is modified
5094 // by the logical operation, do not perform the transformation.
5095 // The highBitSet boolean indicates the value of the high bit of
5096 // the constant which would cause it to be modified for this
5099 if (isValid && !isLeftShift && isSignedShift) {
5100 uint64_t Val = Op0C->getZExtValue();
5101 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5105 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5107 Instruction *NewShift =
5108 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5111 InsertNewInstBefore(NewShift, I);
5113 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5120 // Find out if this is a shift of a shift by a constant.
5121 ShiftInst *ShiftOp = 0;
5122 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5124 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5125 // If this is a noop-integer case of a shift instruction, use the shift.
5126 if (CI->getOperand(0)->getType()->isInteger() &&
5127 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5128 CI->getType()->getPrimitiveSizeInBits() &&
5129 isa<ShiftInst>(CI->getOperand(0))) {
5130 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5134 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5135 // Find the operands and properties of the input shift. Note that the
5136 // signedness of the input shift may differ from the current shift if there
5137 // is a noop cast between the two.
5138 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5139 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
5140 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5142 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5144 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5145 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5147 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5148 if (isLeftShift == isShiftOfLeftShift) {
5149 // Do not fold these shifts if the first one is signed and the second one
5150 // is unsigned and this is a right shift. Further, don't do any folding
5152 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5155 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5156 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5157 Amt = Op0->getType()->getPrimitiveSizeInBits();
5159 Value *Op = ShiftOp->getOperand(0);
5160 if (isShiftOfSignedShift != isSignedShift)
5161 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5162 return new ShiftInst(I.getOpcode(), Op,
5163 ConstantInt::get(Type::UByteTy, Amt));
5166 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5167 // signed types, we can only support the (A >> c1) << c2 configuration,
5168 // because it can not turn an arbitrary bit of A into a sign bit.
5169 if (isUnsignedShift || isLeftShift) {
5170 // Calculate bitmask for what gets shifted off the edge.
5171 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5173 C = ConstantExpr::getShl(C, ShiftAmt1C);
5175 C = ConstantExpr::getUShr(C, ShiftAmt1C);
5177 Value *Op = ShiftOp->getOperand(0);
5178 if (isShiftOfSignedShift != isSignedShift)
5179 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
5182 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5183 InsertNewInstBefore(Mask, I);
5185 // Figure out what flavor of shift we should use...
5186 if (ShiftAmt1 == ShiftAmt2) {
5187 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
5188 } else if (ShiftAmt1 < ShiftAmt2) {
5189 return new ShiftInst(I.getOpcode(), Mask,
5190 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
5191 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5192 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5193 // Make sure to emit an unsigned shift right, not a signed one.
5194 Mask = InsertNewInstBefore(new CastInst(Mask,
5195 Mask->getType()->getUnsignedVersion(),
5197 Mask = new ShiftInst(Instruction::Shr, Mask,
5198 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5199 InsertNewInstBefore(Mask, I);
5200 return new CastInst(Mask, I.getType());
5202 return new ShiftInst(ShiftOp->getOpcode(), Mask,
5203 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5206 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
5207 Op = InsertNewInstBefore(new CastInst(Mask,
5208 I.getType()->getSignedVersion(),
5209 Mask->getName()), I);
5210 Instruction *Shift =
5211 new ShiftInst(ShiftOp->getOpcode(), Op,
5212 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5213 InsertNewInstBefore(Shift, I);
5215 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5216 C = ConstantExpr::getShl(C, Op1);
5217 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5218 InsertNewInstBefore(Mask, I);
5219 return new CastInst(Mask, I.getType());
5222 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
5223 // this case, C1 == C2 and C1 is 8, 16, or 32.
5224 if (ShiftAmt1 == ShiftAmt2) {
5225 const Type *SExtType = 0;
5226 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5227 case 8 : SExtType = Type::SByteTy; break;
5228 case 16: SExtType = Type::ShortTy; break;
5229 case 32: SExtType = Type::IntTy; break;
5233 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5235 InsertNewInstBefore(NewTrunc, I);
5236 return new CastInst(NewTrunc, I.getType());
5245 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5246 /// expression. If so, decompose it, returning some value X, such that Val is
5249 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5251 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5252 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5253 if (CI->getType()->isUnsigned()) {
5254 Offset = CI->getZExtValue();
5256 return ConstantInt::get(Type::UIntTy, 0);
5258 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5259 if (I->getNumOperands() == 2) {
5260 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5261 if (CUI->getType()->isUnsigned()) {
5262 if (I->getOpcode() == Instruction::Shl) {
5263 // This is a value scaled by '1 << the shift amt'.
5264 Scale = 1U << CUI->getZExtValue();
5266 return I->getOperand(0);
5267 } else if (I->getOpcode() == Instruction::Mul) {
5268 // This value is scaled by 'CUI'.
5269 Scale = CUI->getZExtValue();
5271 return I->getOperand(0);
5272 } else if (I->getOpcode() == Instruction::Add) {
5273 // We have X+C. Check to see if we really have (X*C2)+C1,
5274 // where C1 is divisible by C2.
5277 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5278 Offset += CUI->getZExtValue();
5279 if (SubScale > 1 && (Offset % SubScale == 0)) {
5289 // Otherwise, we can't look past this.
5296 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5297 /// try to eliminate the cast by moving the type information into the alloc.
5298 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5299 AllocationInst &AI) {
5300 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5301 if (!PTy) return 0; // Not casting the allocation to a pointer type.
5303 // Remove any uses of AI that are dead.
5304 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5305 std::vector<Instruction*> DeadUsers;
5306 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5307 Instruction *User = cast<Instruction>(*UI++);
5308 if (isInstructionTriviallyDead(User)) {
5309 while (UI != E && *UI == User)
5310 ++UI; // If this instruction uses AI more than once, don't break UI.
5312 // Add operands to the worklist.
5313 AddUsesToWorkList(*User);
5315 DEBUG(std::cerr << "IC: DCE: " << *User);
5317 User->eraseFromParent();
5318 removeFromWorkList(User);
5322 // Get the type really allocated and the type casted to.
5323 const Type *AllocElTy = AI.getAllocatedType();
5324 const Type *CastElTy = PTy->getElementType();
5325 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5327 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5328 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5329 if (CastElTyAlign < AllocElTyAlign) return 0;
5331 // If the allocation has multiple uses, only promote it if we are strictly
5332 // increasing the alignment of the resultant allocation. If we keep it the
5333 // same, we open the door to infinite loops of various kinds.
5334 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5336 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5337 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5338 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5340 // See if we can satisfy the modulus by pulling a scale out of the array
5342 unsigned ArraySizeScale, ArrayOffset;
5343 Value *NumElements = // See if the array size is a decomposable linear expr.
5344 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5346 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5348 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5349 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
5351 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5356 // If the allocation size is constant, form a constant mul expression
5357 Amt = ConstantInt::get(Type::UIntTy, Scale);
5358 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5359 Amt = ConstantExpr::getMul(
5360 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5361 // otherwise multiply the amount and the number of elements
5362 else if (Scale != 1) {
5363 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5364 Amt = InsertNewInstBefore(Tmp, AI);
5368 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5369 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
5370 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5371 Amt = InsertNewInstBefore(Tmp, AI);
5374 std::string Name = AI.getName(); AI.setName("");
5375 AllocationInst *New;
5376 if (isa<MallocInst>(AI))
5377 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5379 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5380 InsertNewInstBefore(New, AI);
5382 // If the allocation has multiple uses, insert a cast and change all things
5383 // that used it to use the new cast. This will also hack on CI, but it will
5385 if (!AI.hasOneUse()) {
5386 AddUsesToWorkList(AI);
5387 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5388 InsertNewInstBefore(NewCast, AI);
5389 AI.replaceAllUsesWith(NewCast);
5391 return ReplaceInstUsesWith(CI, New);
5394 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5395 /// and return it without inserting any new casts. This is used by code that
5396 /// tries to decide whether promoting or shrinking integer operations to wider
5397 /// or smaller types will allow us to eliminate a truncate or extend.
5398 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5399 int &NumCastsRemoved) {
5400 if (isa<Constant>(V)) return true;
5402 Instruction *I = dyn_cast<Instruction>(V);
5403 if (!I || !I->hasOneUse()) return false;
5405 switch (I->getOpcode()) {
5406 case Instruction::And:
5407 case Instruction::Or:
5408 case Instruction::Xor:
5409 // These operators can all arbitrarily be extended or truncated.
5410 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5411 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5412 case Instruction::Cast:
5413 // If this is a cast from the destination type, we can trivially eliminate
5414 // it, and this will remove a cast overall.
5415 if (I->getOperand(0)->getType() == Ty) {
5416 // If the first operand is itself a cast, and is eliminable, do not count
5417 // this as an eliminable cast. We would prefer to eliminate those two
5419 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5425 // TODO: Can handle more cases here.
5432 /// EvaluateInDifferentType - Given an expression that
5433 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5434 /// evaluate the expression.
5435 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5436 if (Constant *C = dyn_cast<Constant>(V))
5437 return ConstantExpr::getCast(C, Ty);
5439 // Otherwise, it must be an instruction.
5440 Instruction *I = cast<Instruction>(V);
5441 Instruction *Res = 0;
5442 switch (I->getOpcode()) {
5443 case Instruction::And:
5444 case Instruction::Or:
5445 case Instruction::Xor: {
5446 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5447 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5448 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5449 LHS, RHS, I->getName());
5452 case Instruction::Cast:
5453 // If this is a cast from the destination type, return the input.
5454 if (I->getOperand(0)->getType() == Ty)
5455 return I->getOperand(0);
5457 // TODO: Can handle more cases here.
5458 assert(0 && "Unreachable!");
5462 return InsertNewInstBefore(Res, *I);
5466 // CastInst simplification
5468 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
5469 Value *Src = CI.getOperand(0);
5471 // If the user is casting a value to the same type, eliminate this cast
5473 if (CI.getType() == Src->getType())
5474 return ReplaceInstUsesWith(CI, Src);
5476 if (isa<UndefValue>(Src)) // cast undef -> undef
5477 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5479 // If casting the result of another cast instruction, try to eliminate this
5482 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5483 Value *A = CSrc->getOperand(0);
5484 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5485 CI.getType(), TD)) {
5486 // This instruction now refers directly to the cast's src operand. This
5487 // has a good chance of making CSrc dead.
5488 CI.setOperand(0, CSrc->getOperand(0));
5492 // If this is an A->B->A cast, and we are dealing with integral types, try
5493 // to convert this into a logical 'and' instruction.
5495 if (A->getType()->isInteger() &&
5496 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
5497 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
5498 CSrc->getType()->getPrimitiveSizeInBits() <
5499 CI.getType()->getPrimitiveSizeInBits()&&
5500 A->getType()->getPrimitiveSizeInBits() ==
5501 CI.getType()->getPrimitiveSizeInBits()) {
5502 assert(CSrc->getType() != Type::ULongTy &&
5503 "Cannot have type bigger than ulong!");
5504 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
5505 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
5507 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5508 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5509 if (And->getType() != CI.getType()) {
5510 And->setName(CSrc->getName()+".mask");
5511 InsertNewInstBefore(And, CI);
5512 And = new CastInst(And, CI.getType());
5518 // If this is a cast to bool, turn it into the appropriate setne instruction.
5519 if (CI.getType() == Type::BoolTy)
5520 return BinaryOperator::createSetNE(CI.getOperand(0),
5521 Constant::getNullValue(CI.getOperand(0)->getType()));
5523 // See if we can simplify any instructions used by the LHS whose sole
5524 // purpose is to compute bits we don't care about.
5525 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5526 uint64_t KnownZero, KnownOne;
5527 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5528 KnownZero, KnownOne))
5532 // If casting the result of a getelementptr instruction with no offset, turn
5533 // this into a cast of the original pointer!
5535 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5536 bool AllZeroOperands = true;
5537 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5538 if (!isa<Constant>(GEP->getOperand(i)) ||
5539 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5540 AllZeroOperands = false;
5543 if (AllZeroOperands) {
5544 CI.setOperand(0, GEP->getOperand(0));
5549 // If we are casting a malloc or alloca to a pointer to a type of the same
5550 // size, rewrite the allocation instruction to allocate the "right" type.
5552 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5553 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5556 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5557 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5559 if (isa<PHINode>(Src))
5560 if (Instruction *NV = FoldOpIntoPhi(CI))
5563 // If the source and destination are pointers, and this cast is equivalent to
5564 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5565 // This can enhance SROA and other transforms that want type-safe pointers.
5566 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5567 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5568 const Type *DstTy = DstPTy->getElementType();
5569 const Type *SrcTy = SrcPTy->getElementType();
5571 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5572 unsigned NumZeros = 0;
5573 while (SrcTy != DstTy &&
5574 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5575 SrcTy->getNumContainedTypes() /* not "{}" */) {
5576 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5580 // If we found a path from the src to dest, create the getelementptr now.
5581 if (SrcTy == DstTy) {
5582 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5583 return new GetElementPtrInst(Src, Idxs);
5587 // If the source value is an instruction with only this use, we can attempt to
5588 // propagate the cast into the instruction. Also, only handle integral types
5590 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
5591 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
5592 CI.getType()->isInteger()) { // Don't mess with casts to bool here
5594 int NumCastsRemoved = 0;
5595 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5596 // If this cast is a truncate, evaluting in a different type always
5597 // eliminates the cast, so it is always a win. If this is a noop-cast
5598 // this just removes a noop cast which isn't pointful, but simplifies
5599 // the code. If this is a zero-extension, we need to do an AND to
5600 // maintain the clear top-part of the computation, so we require that
5601 // the input have eliminated at least one cast. If this is a sign
5602 // extension, we insert two new casts (to do the extension) so we
5603 // require that two casts have been eliminated.
5605 switch (getCastType(Src->getType(), CI.getType())) {
5606 default: assert(0 && "Unknown cast type!");
5612 DoXForm = NumCastsRemoved >= 1;
5615 DoXForm = NumCastsRemoved >= 2;
5620 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5621 assert(Res->getType() == CI.getType());
5622 switch (getCastType(Src->getType(), CI.getType())) {
5623 default: assert(0 && "Unknown cast type!");
5626 // Just replace this cast with the result.
5627 return ReplaceInstUsesWith(CI, Res);
5629 // We need to emit an AND to clear the high bits.
5630 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5631 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5632 assert(SrcBitSize < DestBitSize && "Not a zext?");
5634 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5635 C = ConstantExpr::getCast(C, CI.getType());
5636 return BinaryOperator::createAnd(Res, C);
5639 // We need to emit a cast to truncate, then a cast to sext.
5640 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5646 const Type *DestTy = CI.getType();
5647 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5648 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5650 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5651 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5653 switch (SrcI->getOpcode()) {
5654 case Instruction::Add:
5655 case Instruction::Mul:
5656 case Instruction::And:
5657 case Instruction::Or:
5658 case Instruction::Xor:
5659 // If we are discarding information, or just changing the sign, rewrite.
5660 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5661 // Don't insert two casts if they cannot be eliminated. We allow two
5662 // casts to be inserted if the sizes are the same. This could only be
5663 // converting signedness, which is a noop.
5664 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5665 !ValueRequiresCast(Op0, DestTy, TD)) {
5666 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5667 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5668 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5669 ->getOpcode(), Op0c, Op1c);
5673 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5674 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5675 Op1 == ConstantBool::getTrue() &&
5676 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5677 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5678 return BinaryOperator::createXor(New,
5679 ConstantInt::get(CI.getType(), 1));
5682 case Instruction::Shl:
5683 // Allow changing the sign of the source operand. Do not allow changing
5684 // the size of the shift, UNLESS the shift amount is a constant. We
5685 // mush not change variable sized shifts to a smaller size, because it
5686 // is undefined to shift more bits out than exist in the value.
5687 if (DestBitSize == SrcBitSize ||
5688 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5689 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5690 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5693 case Instruction::Shr:
5694 // If this is a signed shr, and if all bits shifted in are about to be
5695 // truncated off, turn it into an unsigned shr to allow greater
5697 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5698 isa<ConstantInt>(Op1)) {
5699 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5700 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5701 // Convert to unsigned.
5702 Value *N1 = InsertOperandCastBefore(Op0,
5703 Op0->getType()->getUnsignedVersion(), &CI);
5704 // Insert the new shift, which is now unsigned.
5705 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5706 Op1, Src->getName()), CI);
5707 return new CastInst(N1, CI.getType());
5712 case Instruction::SetEQ:
5713 case Instruction::SetNE:
5714 // We if we are just checking for a seteq of a single bit and casting it
5715 // to an integer. If so, shift the bit to the appropriate place then
5716 // cast to integer to avoid the comparison.
5717 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5718 uint64_t Op1CV = Op1C->getZExtValue();
5719 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5720 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5721 // cast (X == 1) to int --> X iff X has only the low bit set.
5722 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5723 // cast (X != 0) to int --> X iff X has only the low bit set.
5724 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5725 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5726 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5727 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5728 // If Op1C some other power of two, convert:
5729 uint64_t KnownZero, KnownOne;
5730 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5731 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5733 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5734 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5735 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5736 // (X&4) == 2 --> false
5737 // (X&4) != 2 --> true
5738 Constant *Res = ConstantBool::get(isSetNE);
5739 Res = ConstantExpr::getCast(Res, CI.getType());
5740 return ReplaceInstUsesWith(CI, Res);
5743 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5746 // Perform an unsigned shr by shiftamt. Convert input to
5747 // unsigned if it is signed.
5748 if (In->getType()->isSigned())
5749 In = InsertNewInstBefore(new CastInst(In,
5750 In->getType()->getUnsignedVersion(), In->getName()),CI);
5751 // Insert the shift to put the result in the low bit.
5752 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
5753 ConstantInt::get(Type::UByteTy, ShiftAmt),
5754 In->getName()+".lobit"), CI);
5757 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5758 Constant *One = ConstantInt::get(In->getType(), 1);
5759 In = BinaryOperator::createXor(In, One, "tmp");
5760 InsertNewInstBefore(cast<Instruction>(In), CI);
5763 if (CI.getType() == In->getType())
5764 return ReplaceInstUsesWith(CI, In);
5766 return new CastInst(In, CI.getType());
5774 if (SrcI->hasOneUse()) {
5775 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5776 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5777 // because the inputs are known to be a vector. Check to see if this is
5778 // a cast to a vector with the same # elts.
5779 if (isa<PackedType>(CI.getType()) &&
5780 cast<PackedType>(CI.getType())->getNumElements() ==
5781 SVI->getType()->getNumElements()) {
5783 // If either of the operands is a cast from CI.getType(), then
5784 // evaluating the shuffle in the casted destination's type will allow
5785 // us to eliminate at least one cast.
5786 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5787 Tmp->getOperand(0)->getType() == CI.getType()) ||
5788 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
5789 Tmp->getOperand(0)->getType() == CI.getType())) {
5790 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5792 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5794 // Return a new shuffle vector. Use the same element ID's, as we
5795 // know the vector types match #elts.
5796 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5806 /// GetSelectFoldableOperands - We want to turn code that looks like this:
5808 /// %D = select %cond, %C, %A
5810 /// %C = select %cond, %B, 0
5813 /// Assuming that the specified instruction is an operand to the select, return
5814 /// a bitmask indicating which operands of this instruction are foldable if they
5815 /// equal the other incoming value of the select.
5817 static unsigned GetSelectFoldableOperands(Instruction *I) {
5818 switch (I->getOpcode()) {
5819 case Instruction::Add:
5820 case Instruction::Mul:
5821 case Instruction::And:
5822 case Instruction::Or:
5823 case Instruction::Xor:
5824 return 3; // Can fold through either operand.
5825 case Instruction::Sub: // Can only fold on the amount subtracted.
5826 case Instruction::Shl: // Can only fold on the shift amount.
5827 case Instruction::Shr:
5830 return 0; // Cannot fold
5834 /// GetSelectFoldableConstant - For the same transformation as the previous
5835 /// function, return the identity constant that goes into the select.
5836 static Constant *GetSelectFoldableConstant(Instruction *I) {
5837 switch (I->getOpcode()) {
5838 default: assert(0 && "This cannot happen!"); abort();
5839 case Instruction::Add:
5840 case Instruction::Sub:
5841 case Instruction::Or:
5842 case Instruction::Xor:
5843 return Constant::getNullValue(I->getType());
5844 case Instruction::Shl:
5845 case Instruction::Shr:
5846 return Constant::getNullValue(Type::UByteTy);
5847 case Instruction::And:
5848 return ConstantInt::getAllOnesValue(I->getType());
5849 case Instruction::Mul:
5850 return ConstantInt::get(I->getType(), 1);
5854 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5855 /// have the same opcode and only one use each. Try to simplify this.
5856 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5858 if (TI->getNumOperands() == 1) {
5859 // If this is a non-volatile load or a cast from the same type,
5861 if (TI->getOpcode() == Instruction::Cast) {
5862 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5865 return 0; // unknown unary op.
5868 // Fold this by inserting a select from the input values.
5869 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5870 FI->getOperand(0), SI.getName()+".v");
5871 InsertNewInstBefore(NewSI, SI);
5872 return new CastInst(NewSI, TI->getType());
5875 // Only handle binary operators here.
5876 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5879 // Figure out if the operations have any operands in common.
5880 Value *MatchOp, *OtherOpT, *OtherOpF;
5882 if (TI->getOperand(0) == FI->getOperand(0)) {
5883 MatchOp = TI->getOperand(0);
5884 OtherOpT = TI->getOperand(1);
5885 OtherOpF = FI->getOperand(1);
5886 MatchIsOpZero = true;
5887 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5888 MatchOp = TI->getOperand(1);
5889 OtherOpT = TI->getOperand(0);
5890 OtherOpF = FI->getOperand(0);
5891 MatchIsOpZero = false;
5892 } else if (!TI->isCommutative()) {
5894 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5895 MatchOp = TI->getOperand(0);
5896 OtherOpT = TI->getOperand(1);
5897 OtherOpF = FI->getOperand(0);
5898 MatchIsOpZero = true;
5899 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5900 MatchOp = TI->getOperand(1);
5901 OtherOpT = TI->getOperand(0);
5902 OtherOpF = FI->getOperand(1);
5903 MatchIsOpZero = true;
5908 // If we reach here, they do have operations in common.
5909 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5910 OtherOpF, SI.getName()+".v");
5911 InsertNewInstBefore(NewSI, SI);
5913 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5915 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5917 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5920 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5922 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5926 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
5927 Value *CondVal = SI.getCondition();
5928 Value *TrueVal = SI.getTrueValue();
5929 Value *FalseVal = SI.getFalseValue();
5931 // select true, X, Y -> X
5932 // select false, X, Y -> Y
5933 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
5934 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
5936 // select C, X, X -> X
5937 if (TrueVal == FalseVal)
5938 return ReplaceInstUsesWith(SI, TrueVal);
5940 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5941 return ReplaceInstUsesWith(SI, FalseVal);
5942 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5943 return ReplaceInstUsesWith(SI, TrueVal);
5944 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5945 if (isa<Constant>(TrueVal))
5946 return ReplaceInstUsesWith(SI, TrueVal);
5948 return ReplaceInstUsesWith(SI, FalseVal);
5951 if (SI.getType() == Type::BoolTy)
5952 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5953 if (C->getValue()) {
5954 // Change: A = select B, true, C --> A = or B, C
5955 return BinaryOperator::createOr(CondVal, FalseVal);
5957 // Change: A = select B, false, C --> A = and !B, C
5959 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5960 "not."+CondVal->getName()), SI);
5961 return BinaryOperator::createAnd(NotCond, FalseVal);
5963 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5964 if (C->getValue() == false) {
5965 // Change: A = select B, C, false --> A = and B, C
5966 return BinaryOperator::createAnd(CondVal, TrueVal);
5968 // Change: A = select B, C, true --> A = or !B, C
5970 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5971 "not."+CondVal->getName()), SI);
5972 return BinaryOperator::createOr(NotCond, TrueVal);
5976 // Selecting between two integer constants?
5977 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5978 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5979 // select C, 1, 0 -> cast C to int
5980 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
5981 return new CastInst(CondVal, SI.getType());
5982 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
5983 // select C, 0, 1 -> cast !C to int
5985 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5986 "not."+CondVal->getName()), SI);
5987 return new CastInst(NotCond, SI.getType());
5990 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
5992 // (x <s 0) ? -1 : 0 -> sra x, 31
5993 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
5994 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
5995 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
5996 bool CanXForm = false;
5997 if (CmpCst->getType()->isSigned())
5998 CanXForm = CmpCst->isNullValue() &&
5999 IC->getOpcode() == Instruction::SetLT;
6001 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6002 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6003 IC->getOpcode() == Instruction::SetGT;
6007 // The comparison constant and the result are not neccessarily the
6008 // same width. In any case, the first step to do is make sure
6009 // that X is signed.
6010 Value *X = IC->getOperand(0);
6011 if (!X->getType()->isSigned())
6012 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6014 // Now that X is signed, we have to make the all ones value. Do
6015 // this by inserting a new SRA.
6016 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6017 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
6018 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
6020 InsertNewInstBefore(SRA, SI);
6022 // Finally, convert to the type of the select RHS. If this is
6023 // smaller than the compare value, it will truncate the ones to
6024 // fit. If it is larger, it will sext the ones to fit.
6025 return new CastInst(SRA, SI.getType());
6030 // If one of the constants is zero (we know they can't both be) and we
6031 // have a setcc instruction with zero, and we have an 'and' with the
6032 // non-constant value, eliminate this whole mess. This corresponds to
6033 // cases like this: ((X & 27) ? 27 : 0)
6034 if (TrueValC->isNullValue() || FalseValC->isNullValue())
6035 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6036 cast<Constant>(IC->getOperand(1))->isNullValue())
6037 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6038 if (ICA->getOpcode() == Instruction::And &&
6039 isa<ConstantInt>(ICA->getOperand(1)) &&
6040 (ICA->getOperand(1) == TrueValC ||
6041 ICA->getOperand(1) == FalseValC) &&
6042 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6043 // Okay, now we know that everything is set up, we just don't
6044 // know whether we have a setne or seteq and whether the true or
6045 // false val is the zero.
6046 bool ShouldNotVal = !TrueValC->isNullValue();
6047 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6050 V = InsertNewInstBefore(BinaryOperator::create(
6051 Instruction::Xor, V, ICA->getOperand(1)), SI);
6052 return ReplaceInstUsesWith(SI, V);
6057 // See if we are selecting two values based on a comparison of the two values.
6058 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6059 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6060 // Transform (X == Y) ? X : Y -> Y
6061 if (SCI->getOpcode() == Instruction::SetEQ)
6062 return ReplaceInstUsesWith(SI, FalseVal);
6063 // Transform (X != Y) ? X : Y -> X
6064 if (SCI->getOpcode() == Instruction::SetNE)
6065 return ReplaceInstUsesWith(SI, TrueVal);
6066 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6068 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6069 // Transform (X == Y) ? Y : X -> X
6070 if (SCI->getOpcode() == Instruction::SetEQ)
6071 return ReplaceInstUsesWith(SI, FalseVal);
6072 // Transform (X != Y) ? Y : X -> Y
6073 if (SCI->getOpcode() == Instruction::SetNE)
6074 return ReplaceInstUsesWith(SI, TrueVal);
6075 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6079 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6080 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6081 if (TI->hasOneUse() && FI->hasOneUse()) {
6082 bool isInverse = false;
6083 Instruction *AddOp = 0, *SubOp = 0;
6085 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6086 if (TI->getOpcode() == FI->getOpcode())
6087 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6090 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6091 // even legal for FP.
6092 if (TI->getOpcode() == Instruction::Sub &&
6093 FI->getOpcode() == Instruction::Add) {
6094 AddOp = FI; SubOp = TI;
6095 } else if (FI->getOpcode() == Instruction::Sub &&
6096 TI->getOpcode() == Instruction::Add) {
6097 AddOp = TI; SubOp = FI;
6101 Value *OtherAddOp = 0;
6102 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6103 OtherAddOp = AddOp->getOperand(1);
6104 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6105 OtherAddOp = AddOp->getOperand(0);
6109 // So at this point we know we have (Y -> OtherAddOp):
6110 // select C, (add X, Y), (sub X, Z)
6111 Value *NegVal; // Compute -Z
6112 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6113 NegVal = ConstantExpr::getNeg(C);
6115 NegVal = InsertNewInstBefore(
6116 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6119 Value *NewTrueOp = OtherAddOp;
6120 Value *NewFalseOp = NegVal;
6122 std::swap(NewTrueOp, NewFalseOp);
6123 Instruction *NewSel =
6124 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6126 NewSel = InsertNewInstBefore(NewSel, SI);
6127 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6132 // See if we can fold the select into one of our operands.
6133 if (SI.getType()->isInteger()) {
6134 // See the comment above GetSelectFoldableOperands for a description of the
6135 // transformation we are doing here.
6136 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6137 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6138 !isa<Constant>(FalseVal))
6139 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6140 unsigned OpToFold = 0;
6141 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6143 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6148 Constant *C = GetSelectFoldableConstant(TVI);
6149 std::string Name = TVI->getName(); TVI->setName("");
6150 Instruction *NewSel =
6151 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6153 InsertNewInstBefore(NewSel, SI);
6154 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6155 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6156 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6157 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6159 assert(0 && "Unknown instruction!!");
6164 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6165 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6166 !isa<Constant>(TrueVal))
6167 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6168 unsigned OpToFold = 0;
6169 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6171 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6176 Constant *C = GetSelectFoldableConstant(FVI);
6177 std::string Name = FVI->getName(); FVI->setName("");
6178 Instruction *NewSel =
6179 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6181 InsertNewInstBefore(NewSel, SI);
6182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6183 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6184 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6185 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6187 assert(0 && "Unknown instruction!!");
6193 if (BinaryOperator::isNot(CondVal)) {
6194 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6195 SI.setOperand(1, FalseVal);
6196 SI.setOperand(2, TrueVal);
6203 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6204 /// determine, return it, otherwise return 0.
6205 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6206 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6207 unsigned Align = GV->getAlignment();
6208 if (Align == 0 && TD)
6209 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6211 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6212 unsigned Align = AI->getAlignment();
6213 if (Align == 0 && TD) {
6214 if (isa<AllocaInst>(AI))
6215 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6216 else if (isa<MallocInst>(AI)) {
6217 // Malloc returns maximally aligned memory.
6218 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6219 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6220 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6224 } else if (isa<CastInst>(V) ||
6225 (isa<ConstantExpr>(V) &&
6226 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6227 User *CI = cast<User>(V);
6228 if (isa<PointerType>(CI->getOperand(0)->getType()))
6229 return GetKnownAlignment(CI->getOperand(0), TD);
6231 } else if (isa<GetElementPtrInst>(V) ||
6232 (isa<ConstantExpr>(V) &&
6233 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6234 User *GEPI = cast<User>(V);
6235 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6236 if (BaseAlignment == 0) return 0;
6238 // If all indexes are zero, it is just the alignment of the base pointer.
6239 bool AllZeroOperands = true;
6240 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6241 if (!isa<Constant>(GEPI->getOperand(i)) ||
6242 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6243 AllZeroOperands = false;
6246 if (AllZeroOperands)
6247 return BaseAlignment;
6249 // Otherwise, if the base alignment is >= the alignment we expect for the
6250 // base pointer type, then we know that the resultant pointer is aligned at
6251 // least as much as its type requires.
6254 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6255 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6257 const Type *GEPTy = GEPI->getType();
6258 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6266 /// visitCallInst - CallInst simplification. This mostly only handles folding
6267 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6268 /// the heavy lifting.
6270 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6271 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6272 if (!II) return visitCallSite(&CI);
6274 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6276 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6277 bool Changed = false;
6279 // memmove/cpy/set of zero bytes is a noop.
6280 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6281 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6283 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6284 if (CI->getZExtValue() == 1) {
6285 // Replace the instruction with just byte operations. We would
6286 // transform other cases to loads/stores, but we don't know if
6287 // alignment is sufficient.
6291 // If we have a memmove and the source operation is a constant global,
6292 // then the source and dest pointers can't alias, so we can change this
6293 // into a call to memcpy.
6294 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6295 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6296 if (GVSrc->isConstant()) {
6297 Module *M = CI.getParent()->getParent()->getParent();
6299 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6301 Name = "llvm.memcpy.i32";
6303 Name = "llvm.memcpy.i64";
6304 Function *MemCpy = M->getOrInsertFunction(Name,
6305 CI.getCalledFunction()->getFunctionType());
6306 CI.setOperand(0, MemCpy);
6311 // If we can determine a pointer alignment that is bigger than currently
6312 // set, update the alignment.
6313 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6314 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6315 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6316 unsigned Align = std::min(Alignment1, Alignment2);
6317 if (MI->getAlignment()->getZExtValue() < Align) {
6318 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
6321 } else if (isa<MemSetInst>(MI)) {
6322 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6323 if (MI->getAlignment()->getZExtValue() < Alignment) {
6324 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
6329 if (Changed) return II;
6331 switch (II->getIntrinsicID()) {
6333 case Intrinsic::ppc_altivec_lvx:
6334 case Intrinsic::ppc_altivec_lvxl:
6335 case Intrinsic::x86_sse_loadu_ps:
6336 case Intrinsic::x86_sse2_loadu_pd:
6337 case Intrinsic::x86_sse2_loadu_dq:
6338 // Turn PPC lvx -> load if the pointer is known aligned.
6339 // Turn X86 loadups -> load if the pointer is known aligned.
6340 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6341 Value *Ptr = InsertCastBefore(II->getOperand(1),
6342 PointerType::get(II->getType()), CI);
6343 return new LoadInst(Ptr);
6346 case Intrinsic::ppc_altivec_stvx:
6347 case Intrinsic::ppc_altivec_stvxl:
6348 // Turn stvx -> store if the pointer is known aligned.
6349 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
6350 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6351 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
6352 return new StoreInst(II->getOperand(1), Ptr);
6355 case Intrinsic::x86_sse_storeu_ps:
6356 case Intrinsic::x86_sse2_storeu_pd:
6357 case Intrinsic::x86_sse2_storeu_dq:
6358 case Intrinsic::x86_sse2_storel_dq:
6359 // Turn X86 storeu -> store if the pointer is known aligned.
6360 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6361 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6362 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6363 return new StoreInst(II->getOperand(2), Ptr);
6367 case Intrinsic::x86_sse_cvttss2si: {
6368 // These intrinsics only demands the 0th element of its input vector. If
6369 // we can simplify the input based on that, do so now.
6371 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6373 II->setOperand(1, V);
6379 case Intrinsic::ppc_altivec_vperm:
6380 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6381 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6382 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6384 // Check that all of the elements are integer constants or undefs.
6385 bool AllEltsOk = true;
6386 for (unsigned i = 0; i != 16; ++i) {
6387 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6388 !isa<UndefValue>(Mask->getOperand(i))) {
6395 // Cast the input vectors to byte vectors.
6396 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6397 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6398 Value *Result = UndefValue::get(Op0->getType());
6400 // Only extract each element once.
6401 Value *ExtractedElts[32];
6402 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6404 for (unsigned i = 0; i != 16; ++i) {
6405 if (isa<UndefValue>(Mask->getOperand(i)))
6407 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
6408 Idx &= 31; // Match the hardware behavior.
6410 if (ExtractedElts[Idx] == 0) {
6412 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
6413 InsertNewInstBefore(Elt, CI);
6414 ExtractedElts[Idx] = Elt;
6417 // Insert this value into the result vector.
6418 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
6419 InsertNewInstBefore(cast<Instruction>(Result), CI);
6421 return new CastInst(Result, CI.getType());
6426 case Intrinsic::stackrestore: {
6427 // If the save is right next to the restore, remove the restore. This can
6428 // happen when variable allocas are DCE'd.
6429 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6430 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6431 BasicBlock::iterator BI = SS;
6433 return EraseInstFromFunction(CI);
6437 // If the stack restore is in a return/unwind block and if there are no
6438 // allocas or calls between the restore and the return, nuke the restore.
6439 TerminatorInst *TI = II->getParent()->getTerminator();
6440 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6441 BasicBlock::iterator BI = II;
6442 bool CannotRemove = false;
6443 for (++BI; &*BI != TI; ++BI) {
6444 if (isa<AllocaInst>(BI) ||
6445 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6446 CannotRemove = true;
6451 return EraseInstFromFunction(CI);
6458 return visitCallSite(II);
6461 // InvokeInst simplification
6463 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6464 return visitCallSite(&II);
6467 // visitCallSite - Improvements for call and invoke instructions.
6469 Instruction *InstCombiner::visitCallSite(CallSite CS) {
6470 bool Changed = false;
6472 // If the callee is a constexpr cast of a function, attempt to move the cast
6473 // to the arguments of the call/invoke.
6474 if (transformConstExprCastCall(CS)) return 0;
6476 Value *Callee = CS.getCalledValue();
6478 if (Function *CalleeF = dyn_cast<Function>(Callee))
6479 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6480 Instruction *OldCall = CS.getInstruction();
6481 // If the call and callee calling conventions don't match, this call must
6482 // be unreachable, as the call is undefined.
6483 new StoreInst(ConstantBool::getTrue(),
6484 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6485 if (!OldCall->use_empty())
6486 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6487 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6488 return EraseInstFromFunction(*OldCall);
6492 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6493 // This instruction is not reachable, just remove it. We insert a store to
6494 // undef so that we know that this code is not reachable, despite the fact
6495 // that we can't modify the CFG here.
6496 new StoreInst(ConstantBool::getTrue(),
6497 UndefValue::get(PointerType::get(Type::BoolTy)),
6498 CS.getInstruction());
6500 if (!CS.getInstruction()->use_empty())
6501 CS.getInstruction()->
6502 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6504 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6505 // Don't break the CFG, insert a dummy cond branch.
6506 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6507 ConstantBool::getTrue(), II);
6509 return EraseInstFromFunction(*CS.getInstruction());
6512 const PointerType *PTy = cast<PointerType>(Callee->getType());
6513 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6514 if (FTy->isVarArg()) {
6515 // See if we can optimize any arguments passed through the varargs area of
6517 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6518 E = CS.arg_end(); I != E; ++I)
6519 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6520 // If this cast does not effect the value passed through the varargs
6521 // area, we can eliminate the use of the cast.
6522 Value *Op = CI->getOperand(0);
6523 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6530 return Changed ? CS.getInstruction() : 0;
6533 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6534 // attempt to move the cast to the arguments of the call/invoke.
6536 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6537 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6538 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6539 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
6541 Function *Callee = cast<Function>(CE->getOperand(0));
6542 Instruction *Caller = CS.getInstruction();
6544 // Okay, this is a cast from a function to a different type. Unless doing so
6545 // would cause a type conversion of one of our arguments, change this call to
6546 // be a direct call with arguments casted to the appropriate types.
6548 const FunctionType *FT = Callee->getFunctionType();
6549 const Type *OldRetTy = Caller->getType();
6551 // Check to see if we are changing the return type...
6552 if (OldRetTy != FT->getReturnType()) {
6553 if (Callee->isExternal() &&
6554 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6555 (isa<PointerType>(FT->getReturnType()) &&
6556 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
6557 && !Caller->use_empty())
6558 return false; // Cannot transform this return value...
6560 // If the callsite is an invoke instruction, and the return value is used by
6561 // a PHI node in a successor, we cannot change the return type of the call
6562 // because there is no place to put the cast instruction (without breaking
6563 // the critical edge). Bail out in this case.
6564 if (!Caller->use_empty())
6565 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6566 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6568 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6569 if (PN->getParent() == II->getNormalDest() ||
6570 PN->getParent() == II->getUnwindDest())
6574 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6575 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6577 CallSite::arg_iterator AI = CS.arg_begin();
6578 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6579 const Type *ParamTy = FT->getParamType(i);
6580 const Type *ActTy = (*AI)->getType();
6581 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
6582 //Either we can cast directly, or we can upconvert the argument
6583 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6584 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6585 ParamTy->isSigned() == ActTy->isSigned() &&
6586 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6587 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6588 c->getSExtValue() > 0);
6589 if (Callee->isExternal() && !isConvertible) return false;
6592 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6593 Callee->isExternal())
6594 return false; // Do not delete arguments unless we have a function body...
6596 // Okay, we decided that this is a safe thing to do: go ahead and start
6597 // inserting cast instructions as necessary...
6598 std::vector<Value*> Args;
6599 Args.reserve(NumActualArgs);
6601 AI = CS.arg_begin();
6602 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6603 const Type *ParamTy = FT->getParamType(i);
6604 if ((*AI)->getType() == ParamTy) {
6605 Args.push_back(*AI);
6607 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6612 // If the function takes more arguments than the call was taking, add them
6614 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6615 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6617 // If we are removing arguments to the function, emit an obnoxious warning...
6618 if (FT->getNumParams() < NumActualArgs)
6619 if (!FT->isVarArg()) {
6620 std::cerr << "WARNING: While resolving call to function '"
6621 << Callee->getName() << "' arguments were dropped!\n";
6623 // Add all of the arguments in their promoted form to the arg list...
6624 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6625 const Type *PTy = getPromotedType((*AI)->getType());
6626 if (PTy != (*AI)->getType()) {
6627 // Must promote to pass through va_arg area!
6628 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6629 InsertNewInstBefore(Cast, *Caller);
6630 Args.push_back(Cast);
6632 Args.push_back(*AI);
6637 if (FT->getReturnType() == Type::VoidTy)
6638 Caller->setName(""); // Void type should not have a name...
6641 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6642 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
6643 Args, Caller->getName(), Caller);
6644 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
6646 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
6647 if (cast<CallInst>(Caller)->isTailCall())
6648 cast<CallInst>(NC)->setTailCall();
6649 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
6652 // Insert a cast of the return type as necessary...
6654 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6655 if (NV->getType() != Type::VoidTy) {
6656 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
6658 // If this is an invoke instruction, we should insert it after the first
6659 // non-phi, instruction in the normal successor block.
6660 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6661 BasicBlock::iterator I = II->getNormalDest()->begin();
6662 while (isa<PHINode>(I)) ++I;
6663 InsertNewInstBefore(NC, *I);
6665 // Otherwise, it's a call, just insert cast right after the call instr
6666 InsertNewInstBefore(NC, *Caller);
6668 AddUsersToWorkList(*Caller);
6670 NV = UndefValue::get(Caller->getType());
6674 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6675 Caller->replaceAllUsesWith(NV);
6676 Caller->getParent()->getInstList().erase(Caller);
6677 removeFromWorkList(Caller);
6682 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6683 // operator and they all are only used by the PHI, PHI together their
6684 // inputs, and do the operation once, to the result of the PHI.
6685 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6686 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6688 // Scan the instruction, looking for input operations that can be folded away.
6689 // If all input operands to the phi are the same instruction (e.g. a cast from
6690 // the same type or "+42") we can pull the operation through the PHI, reducing
6691 // code size and simplifying code.
6692 Constant *ConstantOp = 0;
6693 const Type *CastSrcTy = 0;
6694 if (isa<CastInst>(FirstInst)) {
6695 CastSrcTy = FirstInst->getOperand(0)->getType();
6696 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6697 // Can fold binop or shift if the RHS is a constant.
6698 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6699 if (ConstantOp == 0) return 0;
6701 return 0; // Cannot fold this operation.
6704 // Check to see if all arguments are the same operation.
6705 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6706 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6707 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6708 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6711 if (I->getOperand(0)->getType() != CastSrcTy)
6712 return 0; // Cast operation must match.
6713 } else if (I->getOperand(1) != ConstantOp) {
6718 // Okay, they are all the same operation. Create a new PHI node of the
6719 // correct type, and PHI together all of the LHS's of the instructions.
6720 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6721 PN.getName()+".in");
6722 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
6724 Value *InVal = FirstInst->getOperand(0);
6725 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
6727 // Add all operands to the new PHI.
6728 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6729 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6730 if (NewInVal != InVal)
6732 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6737 // The new PHI unions all of the same values together. This is really
6738 // common, so we handle it intelligently here for compile-time speed.
6742 InsertNewInstBefore(NewPN, PN);
6746 // Insert and return the new operation.
6747 if (isa<CastInst>(FirstInst))
6748 return new CastInst(PhiVal, PN.getType());
6749 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
6750 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
6752 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
6753 PhiVal, ConstantOp);
6756 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6758 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6759 if (PN->use_empty()) return true;
6760 if (!PN->hasOneUse()) return false;
6762 // Remember this node, and if we find the cycle, return.
6763 if (!PotentiallyDeadPHIs.insert(PN).second)
6766 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6767 return DeadPHICycle(PU, PotentiallyDeadPHIs);
6772 // PHINode simplification
6774 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
6775 // If LCSSA is around, don't mess with Phi nodes
6776 if (mustPreserveAnalysisID(LCSSAID)) return 0;
6778 if (Value *V = PN.hasConstantValue())
6779 return ReplaceInstUsesWith(PN, V);
6781 // If the only user of this instruction is a cast instruction, and all of the
6782 // incoming values are constants, change this PHI to merge together the casted
6785 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6786 if (CI->getType() != PN.getType()) { // noop casts will be folded
6787 bool AllConstant = true;
6788 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6789 if (!isa<Constant>(PN.getIncomingValue(i))) {
6790 AllConstant = false;
6794 // Make a new PHI with all casted values.
6795 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6796 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6797 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6798 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6799 PN.getIncomingBlock(i));
6802 // Update the cast instruction.
6803 CI->setOperand(0, New);
6804 WorkList.push_back(CI); // revisit the cast instruction to fold.
6805 WorkList.push_back(New); // Make sure to revisit the new Phi
6806 return &PN; // PN is now dead!
6810 // If all PHI operands are the same operation, pull them through the PHI,
6811 // reducing code size.
6812 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6813 PN.getIncomingValue(0)->hasOneUse())
6814 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6817 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6818 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6819 // PHI)... break the cycle.
6821 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6822 std::set<PHINode*> PotentiallyDeadPHIs;
6823 PotentiallyDeadPHIs.insert(&PN);
6824 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6825 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6831 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6832 Instruction *InsertPoint,
6834 unsigned PS = IC->getTargetData().getPointerSize();
6835 const Type *VTy = V->getType();
6836 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6837 // We must insert a cast to ensure we sign-extend.
6838 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6839 V->getName()), *InsertPoint);
6840 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6845 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
6846 Value *PtrOp = GEP.getOperand(0);
6847 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
6848 // If so, eliminate the noop.
6849 if (GEP.getNumOperands() == 1)
6850 return ReplaceInstUsesWith(GEP, PtrOp);
6852 if (isa<UndefValue>(GEP.getOperand(0)))
6853 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6855 bool HasZeroPointerIndex = false;
6856 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6857 HasZeroPointerIndex = C->isNullValue();
6859 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
6860 return ReplaceInstUsesWith(GEP, PtrOp);
6862 // Eliminate unneeded casts for indices.
6863 bool MadeChange = false;
6864 gep_type_iterator GTI = gep_type_begin(GEP);
6865 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6866 if (isa<SequentialType>(*GTI)) {
6867 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6868 Value *Src = CI->getOperand(0);
6869 const Type *SrcTy = Src->getType();
6870 const Type *DestTy = CI->getType();
6871 if (Src->getType()->isInteger()) {
6872 if (SrcTy->getPrimitiveSizeInBits() ==
6873 DestTy->getPrimitiveSizeInBits()) {
6874 // We can always eliminate a cast from ulong or long to the other.
6875 // We can always eliminate a cast from uint to int or the other on
6876 // 32-bit pointer platforms.
6877 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
6879 GEP.setOperand(i, Src);
6881 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6882 SrcTy->getPrimitiveSize() == 4) {
6883 // We can always eliminate a cast from int to [u]long. We can
6884 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6886 if (SrcTy->isSigned() ||
6887 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
6889 GEP.setOperand(i, Src);
6894 // If we are using a wider index than needed for this platform, shrink it
6895 // to what we need. If the incoming value needs a cast instruction,
6896 // insert it. This explicit cast can make subsequent optimizations more
6898 Value *Op = GEP.getOperand(i);
6899 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
6900 if (Constant *C = dyn_cast<Constant>(Op)) {
6901 GEP.setOperand(i, ConstantExpr::getCast(C,
6902 TD->getIntPtrType()->getSignedVersion()));
6905 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6906 Op->getName()), GEP);
6907 GEP.setOperand(i, Op);
6911 // If this is a constant idx, make sure to canonicalize it to be a signed
6912 // operand, otherwise CSE and other optimizations are pessimized.
6913 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
6914 if (CUI->getType()->isUnsigned()) {
6916 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
6920 if (MadeChange) return &GEP;
6922 // Combine Indices - If the source pointer to this getelementptr instruction
6923 // is a getelementptr instruction, combine the indices of the two
6924 // getelementptr instructions into a single instruction.
6926 std::vector<Value*> SrcGEPOperands;
6927 if (User *Src = dyn_castGetElementPtr(PtrOp))
6928 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
6930 if (!SrcGEPOperands.empty()) {
6931 // Note that if our source is a gep chain itself that we wait for that
6932 // chain to be resolved before we perform this transformation. This
6933 // avoids us creating a TON of code in some cases.
6935 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6936 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6937 return 0; // Wait until our source is folded to completion.
6939 std::vector<Value *> Indices;
6941 // Find out whether the last index in the source GEP is a sequential idx.
6942 bool EndsWithSequential = false;
6943 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6944 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
6945 EndsWithSequential = !isa<StructType>(*I);
6947 // Can we combine the two pointer arithmetics offsets?
6948 if (EndsWithSequential) {
6949 // Replace: gep (gep %P, long B), long A, ...
6950 // With: T = long A+B; gep %P, T, ...
6952 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
6953 if (SO1 == Constant::getNullValue(SO1->getType())) {
6955 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6958 // If they aren't the same type, convert both to an integer of the
6959 // target's pointer size.
6960 if (SO1->getType() != GO1->getType()) {
6961 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6962 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6963 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6964 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6966 unsigned PS = TD->getPointerSize();
6967 if (SO1->getType()->getPrimitiveSize() == PS) {
6968 // Convert GO1 to SO1's type.
6969 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6971 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6972 // Convert SO1 to GO1's type.
6973 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6975 const Type *PT = TD->getIntPtrType();
6976 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6977 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6981 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6982 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6984 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6985 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
6989 // Recycle the GEP we already have if possible.
6990 if (SrcGEPOperands.size() == 2) {
6991 GEP.setOperand(0, SrcGEPOperands[0]);
6992 GEP.setOperand(1, Sum);
6995 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6996 SrcGEPOperands.end()-1);
6997 Indices.push_back(Sum);
6998 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7000 } else if (isa<Constant>(*GEP.idx_begin()) &&
7001 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7002 SrcGEPOperands.size() != 1) {
7003 // Otherwise we can do the fold if the first index of the GEP is a zero
7004 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7005 SrcGEPOperands.end());
7006 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7009 if (!Indices.empty())
7010 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7012 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7013 // GEP of global variable. If all of the indices for this GEP are
7014 // constants, we can promote this to a constexpr instead of an instruction.
7016 // Scan for nonconstants...
7017 std::vector<Constant*> Indices;
7018 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7019 for (; I != E && isa<Constant>(*I); ++I)
7020 Indices.push_back(cast<Constant>(*I));
7022 if (I == E) { // If they are all constants...
7023 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7025 // Replace all uses of the GEP with the new constexpr...
7026 return ReplaceInstUsesWith(GEP, CE);
7028 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7029 if (!isa<PointerType>(X->getType())) {
7030 // Not interesting. Source pointer must be a cast from pointer.
7031 } else if (HasZeroPointerIndex) {
7032 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7033 // into : GEP [10 x ubyte]* X, long 0, ...
7035 // This occurs when the program declares an array extern like "int X[];"
7037 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7038 const PointerType *XTy = cast<PointerType>(X->getType());
7039 if (const ArrayType *XATy =
7040 dyn_cast<ArrayType>(XTy->getElementType()))
7041 if (const ArrayType *CATy =
7042 dyn_cast<ArrayType>(CPTy->getElementType()))
7043 if (CATy->getElementType() == XATy->getElementType()) {
7044 // At this point, we know that the cast source type is a pointer
7045 // to an array of the same type as the destination pointer
7046 // array. Because the array type is never stepped over (there
7047 // is a leading zero) we can fold the cast into this GEP.
7048 GEP.setOperand(0, X);
7051 } else if (GEP.getNumOperands() == 2) {
7052 // Transform things like:
7053 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7054 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7055 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7056 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7057 if (isa<ArrayType>(SrcElTy) &&
7058 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7059 TD->getTypeSize(ResElTy)) {
7060 Value *V = InsertNewInstBefore(
7061 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7062 GEP.getOperand(1), GEP.getName()), GEP);
7063 return new CastInst(V, GEP.getType());
7066 // Transform things like:
7067 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7068 // (where tmp = 8*tmp2) into:
7069 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7071 if (isa<ArrayType>(SrcElTy) &&
7072 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7073 uint64_t ArrayEltSize =
7074 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7076 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7077 // allow either a mul, shift, or constant here.
7079 ConstantInt *Scale = 0;
7080 if (ArrayEltSize == 1) {
7081 NewIdx = GEP.getOperand(1);
7082 Scale = ConstantInt::get(NewIdx->getType(), 1);
7083 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7084 NewIdx = ConstantInt::get(CI->getType(), 1);
7086 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7087 if (Inst->getOpcode() == Instruction::Shl &&
7088 isa<ConstantInt>(Inst->getOperand(1))) {
7090 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7091 if (Inst->getType()->isSigned())
7092 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7094 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7095 NewIdx = Inst->getOperand(0);
7096 } else if (Inst->getOpcode() == Instruction::Mul &&
7097 isa<ConstantInt>(Inst->getOperand(1))) {
7098 Scale = cast<ConstantInt>(Inst->getOperand(1));
7099 NewIdx = Inst->getOperand(0);
7103 // If the index will be to exactly the right offset with the scale taken
7104 // out, perform the transformation.
7105 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7106 if (ConstantInt *C = dyn_cast<ConstantInt>(Scale))
7107 Scale = ConstantInt::get(Scale->getType(),
7108 Scale->getZExtValue() / ArrayEltSize);
7109 if (Scale->getZExtValue() != 1) {
7110 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7111 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7112 NewIdx = InsertNewInstBefore(Sc, GEP);
7115 // Insert the new GEP instruction.
7117 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7118 NewIdx, GEP.getName());
7119 Idx = InsertNewInstBefore(Idx, GEP);
7120 return new CastInst(Idx, GEP.getType());
7129 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7130 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7131 if (AI.isArrayAllocation()) // Check C != 1
7132 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7134 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7135 AllocationInst *New = 0;
7137 // Create and insert the replacement instruction...
7138 if (isa<MallocInst>(AI))
7139 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7141 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7142 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7145 InsertNewInstBefore(New, AI);
7147 // Scan to the end of the allocation instructions, to skip over a block of
7148 // allocas if possible...
7150 BasicBlock::iterator It = New;
7151 while (isa<AllocationInst>(*It)) ++It;
7153 // Now that I is pointing to the first non-allocation-inst in the block,
7154 // insert our getelementptr instruction...
7156 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7157 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7158 New->getName()+".sub", It);
7160 // Now make everything use the getelementptr instead of the original
7162 return ReplaceInstUsesWith(AI, V);
7163 } else if (isa<UndefValue>(AI.getArraySize())) {
7164 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7167 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7168 // Note that we only do this for alloca's, because malloc should allocate and
7169 // return a unique pointer, even for a zero byte allocation.
7170 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7171 TD->getTypeSize(AI.getAllocatedType()) == 0)
7172 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7177 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7178 Value *Op = FI.getOperand(0);
7180 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7181 if (CastInst *CI = dyn_cast<CastInst>(Op))
7182 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7183 FI.setOperand(0, CI->getOperand(0));
7187 // free undef -> unreachable.
7188 if (isa<UndefValue>(Op)) {
7189 // Insert a new store to null because we cannot modify the CFG here.
7190 new StoreInst(ConstantBool::getTrue(),
7191 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7192 return EraseInstFromFunction(FI);
7195 // If we have 'free null' delete the instruction. This can happen in stl code
7196 // when lots of inlining happens.
7197 if (isa<ConstantPointerNull>(Op))
7198 return EraseInstFromFunction(FI);
7204 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7205 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7206 User *CI = cast<User>(LI.getOperand(0));
7207 Value *CastOp = CI->getOperand(0);
7209 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7210 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7211 const Type *SrcPTy = SrcTy->getElementType();
7213 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7214 isa<PackedType>(DestPTy)) {
7215 // If the source is an array, the code below will not succeed. Check to
7216 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7218 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7219 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7220 if (ASrcTy->getNumElements() != 0) {
7221 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7222 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7223 SrcTy = cast<PointerType>(CastOp->getType());
7224 SrcPTy = SrcTy->getElementType();
7227 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7228 isa<PackedType>(SrcPTy)) &&
7229 // Do not allow turning this into a load of an integer, which is then
7230 // casted to a pointer, this pessimizes pointer analysis a lot.
7231 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7232 IC.getTargetData().getTypeSize(SrcPTy) ==
7233 IC.getTargetData().getTypeSize(DestPTy)) {
7235 // Okay, we are casting from one integer or pointer type to another of
7236 // the same size. Instead of casting the pointer before the load, cast
7237 // the result of the loaded value.
7238 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7240 LI.isVolatile()),LI);
7241 // Now cast the result of the load.
7242 return new CastInst(NewLoad, LI.getType());
7249 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
7250 /// from this value cannot trap. If it is not obviously safe to load from the
7251 /// specified pointer, we do a quick local scan of the basic block containing
7252 /// ScanFrom, to determine if the address is already accessed.
7253 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7254 // If it is an alloca or global variable, it is always safe to load from.
7255 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7257 // Otherwise, be a little bit agressive by scanning the local block where we
7258 // want to check to see if the pointer is already being loaded or stored
7259 // from/to. If so, the previous load or store would have already trapped,
7260 // so there is no harm doing an extra load (also, CSE will later eliminate
7261 // the load entirely).
7262 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7267 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7268 if (LI->getOperand(0) == V) return true;
7269 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7270 if (SI->getOperand(1) == V) return true;
7276 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7277 Value *Op = LI.getOperand(0);
7279 // load (cast X) --> cast (load X) iff safe
7280 if (CastInst *CI = dyn_cast<CastInst>(Op))
7281 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7284 // None of the following transforms are legal for volatile loads.
7285 if (LI.isVolatile()) return 0;
7287 if (&LI.getParent()->front() != &LI) {
7288 BasicBlock::iterator BBI = &LI; --BBI;
7289 // If the instruction immediately before this is a store to the same
7290 // address, do a simple form of store->load forwarding.
7291 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7292 if (SI->getOperand(1) == LI.getOperand(0))
7293 return ReplaceInstUsesWith(LI, SI->getOperand(0));
7294 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7295 if (LIB->getOperand(0) == LI.getOperand(0))
7296 return ReplaceInstUsesWith(LI, LIB);
7299 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7300 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7301 isa<UndefValue>(GEPI->getOperand(0))) {
7302 // Insert a new store to null instruction before the load to indicate
7303 // that this code is not reachable. We do this instead of inserting
7304 // an unreachable instruction directly because we cannot modify the
7306 new StoreInst(UndefValue::get(LI.getType()),
7307 Constant::getNullValue(Op->getType()), &LI);
7308 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7311 if (Constant *C = dyn_cast<Constant>(Op)) {
7312 // load null/undef -> undef
7313 if ((C->isNullValue() || isa<UndefValue>(C))) {
7314 // Insert a new store to null instruction before the load to indicate that
7315 // this code is not reachable. We do this instead of inserting an
7316 // unreachable instruction directly because we cannot modify the CFG.
7317 new StoreInst(UndefValue::get(LI.getType()),
7318 Constant::getNullValue(Op->getType()), &LI);
7319 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7322 // Instcombine load (constant global) into the value loaded.
7323 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7324 if (GV->isConstant() && !GV->isExternal())
7325 return ReplaceInstUsesWith(LI, GV->getInitializer());
7327 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7328 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7329 if (CE->getOpcode() == Instruction::GetElementPtr) {
7330 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7331 if (GV->isConstant() && !GV->isExternal())
7333 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
7334 return ReplaceInstUsesWith(LI, V);
7335 if (CE->getOperand(0)->isNullValue()) {
7336 // Insert a new store to null instruction before the load to indicate
7337 // that this code is not reachable. We do this instead of inserting
7338 // an unreachable instruction directly because we cannot modify the
7340 new StoreInst(UndefValue::get(LI.getType()),
7341 Constant::getNullValue(Op->getType()), &LI);
7342 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7345 } else if (CE->getOpcode() == Instruction::Cast) {
7346 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7351 if (Op->hasOneUse()) {
7352 // Change select and PHI nodes to select values instead of addresses: this
7353 // helps alias analysis out a lot, allows many others simplifications, and
7354 // exposes redundancy in the code.
7356 // Note that we cannot do the transformation unless we know that the
7357 // introduced loads cannot trap! Something like this is valid as long as
7358 // the condition is always false: load (select bool %C, int* null, int* %G),
7359 // but it would not be valid if we transformed it to load from null
7362 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7363 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
7364 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7365 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
7366 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
7367 SI->getOperand(1)->getName()+".val"), LI);
7368 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
7369 SI->getOperand(2)->getName()+".val"), LI);
7370 return new SelectInst(SI->getCondition(), V1, V2);
7373 // load (select (cond, null, P)) -> load P
7374 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7375 if (C->isNullValue()) {
7376 LI.setOperand(0, SI->getOperand(2));
7380 // load (select (cond, P, null)) -> load P
7381 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7382 if (C->isNullValue()) {
7383 LI.setOperand(0, SI->getOperand(1));
7387 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7388 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
7389 bool Safe = PN->getParent() == LI.getParent();
7391 // Scan all of the instructions between the PHI and the load to make
7392 // sure there are no instructions that might possibly alter the value
7393 // loaded from the PHI.
7395 BasicBlock::iterator I = &LI;
7396 for (--I; !isa<PHINode>(I); --I)
7397 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7403 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
7404 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
7405 PN->getIncomingBlock(i)->getTerminator()))
7410 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7411 InsertNewInstBefore(NewPN, *PN);
7412 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7414 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7415 BasicBlock *BB = PN->getIncomingBlock(i);
7416 Value *&TheLoad = LoadMap[BB];
7418 Value *InVal = PN->getIncomingValue(i);
7419 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7420 InVal->getName()+".val"),
7421 *BB->getTerminator());
7423 NewPN->addIncoming(TheLoad, BB);
7425 return ReplaceInstUsesWith(LI, NewPN);
7432 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7434 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7435 User *CI = cast<User>(SI.getOperand(1));
7436 Value *CastOp = CI->getOperand(0);
7438 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7439 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7440 const Type *SrcPTy = SrcTy->getElementType();
7442 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7443 // If the source is an array, the code below will not succeed. Check to
7444 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7446 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7447 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7448 if (ASrcTy->getNumElements() != 0) {
7449 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7450 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7451 SrcTy = cast<PointerType>(CastOp->getType());
7452 SrcPTy = SrcTy->getElementType();
7455 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
7456 IC.getTargetData().getTypeSize(SrcPTy) ==
7457 IC.getTargetData().getTypeSize(DestPTy)) {
7459 // Okay, we are casting from one integer or pointer type to another of
7460 // the same size. Instead of casting the pointer before the store, cast
7461 // the value to be stored.
7463 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7464 NewCast = ConstantExpr::getCast(C, SrcPTy);
7466 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7468 SI.getOperand(0)->getName()+".c"), SI);
7470 return new StoreInst(NewCast, CastOp);
7477 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7478 Value *Val = SI.getOperand(0);
7479 Value *Ptr = SI.getOperand(1);
7481 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
7482 EraseInstFromFunction(SI);
7487 // Do really simple DSE, to catch cases where there are several consequtive
7488 // stores to the same location, separated by a few arithmetic operations. This
7489 // situation often occurs with bitfield accesses.
7490 BasicBlock::iterator BBI = &SI;
7491 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7495 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7496 // Prev store isn't volatile, and stores to the same location?
7497 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7500 EraseInstFromFunction(*PrevSI);
7506 // If this is a load, we have to stop. However, if the loaded value is from
7507 // the pointer we're loading and is producing the pointer we're storing,
7508 // then *this* store is dead (X = load P; store X -> P).
7509 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7510 if (LI == Val && LI->getOperand(0) == Ptr) {
7511 EraseInstFromFunction(SI);
7515 // Otherwise, this is a load from some other location. Stores before it
7520 // Don't skip over loads or things that can modify memory.
7521 if (BBI->mayWriteToMemory())
7526 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
7528 // store X, null -> turns into 'unreachable' in SimplifyCFG
7529 if (isa<ConstantPointerNull>(Ptr)) {
7530 if (!isa<UndefValue>(Val)) {
7531 SI.setOperand(0, UndefValue::get(Val->getType()));
7532 if (Instruction *U = dyn_cast<Instruction>(Val))
7533 WorkList.push_back(U); // Dropped a use.
7536 return 0; // Do not modify these!
7539 // store undef, Ptr -> noop
7540 if (isa<UndefValue>(Val)) {
7541 EraseInstFromFunction(SI);
7546 // If the pointer destination is a cast, see if we can fold the cast into the
7548 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7549 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7551 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7552 if (CE->getOpcode() == Instruction::Cast)
7553 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7557 // If this store is the last instruction in the basic block, and if the block
7558 // ends with an unconditional branch, try to move it to the successor block.
7560 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7561 if (BI->isUnconditional()) {
7562 // Check to see if the successor block has exactly two incoming edges. If
7563 // so, see if the other predecessor contains a store to the same location.
7564 // if so, insert a PHI node (if needed) and move the stores down.
7565 BasicBlock *Dest = BI->getSuccessor(0);
7567 pred_iterator PI = pred_begin(Dest);
7568 BasicBlock *Other = 0;
7569 if (*PI != BI->getParent())
7572 if (PI != pred_end(Dest)) {
7573 if (*PI != BI->getParent())
7578 if (++PI != pred_end(Dest))
7581 if (Other) { // If only one other pred...
7582 BBI = Other->getTerminator();
7583 // Make sure this other block ends in an unconditional branch and that
7584 // there is an instruction before the branch.
7585 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7586 BBI != Other->begin()) {
7588 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7590 // If this instruction is a store to the same location.
7591 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7592 // Okay, we know we can perform this transformation. Insert a PHI
7593 // node now if we need it.
7594 Value *MergedVal = OtherStore->getOperand(0);
7595 if (MergedVal != SI.getOperand(0)) {
7596 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7597 PN->reserveOperandSpace(2);
7598 PN->addIncoming(SI.getOperand(0), SI.getParent());
7599 PN->addIncoming(OtherStore->getOperand(0), Other);
7600 MergedVal = InsertNewInstBefore(PN, Dest->front());
7603 // Advance to a place where it is safe to insert the new store and
7605 BBI = Dest->begin();
7606 while (isa<PHINode>(BBI)) ++BBI;
7607 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7608 OtherStore->isVolatile()), *BBI);
7610 // Nuke the old stores.
7611 EraseInstFromFunction(SI);
7612 EraseInstFromFunction(*OtherStore);
7624 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7625 // Change br (not X), label True, label False to: br X, label False, True
7627 BasicBlock *TrueDest;
7628 BasicBlock *FalseDest;
7629 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7630 !isa<Constant>(X)) {
7631 // Swap Destinations and condition...
7633 BI.setSuccessor(0, FalseDest);
7634 BI.setSuccessor(1, TrueDest);
7638 // Cannonicalize setne -> seteq
7639 Instruction::BinaryOps Op; Value *Y;
7640 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7641 TrueDest, FalseDest)))
7642 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7643 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7644 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7645 std::string Name = I->getName(); I->setName("");
7646 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7647 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
7648 // Swap Destinations and condition...
7649 BI.setCondition(NewSCC);
7650 BI.setSuccessor(0, FalseDest);
7651 BI.setSuccessor(1, TrueDest);
7652 removeFromWorkList(I);
7653 I->getParent()->getInstList().erase(I);
7654 WorkList.push_back(cast<Instruction>(NewSCC));
7661 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7662 Value *Cond = SI.getCondition();
7663 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7664 if (I->getOpcode() == Instruction::Add)
7665 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7666 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7667 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
7668 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
7670 SI.setOperand(0, I->getOperand(0));
7671 WorkList.push_back(I);
7678 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7679 /// is to leave as a vector operation.
7680 static bool CheapToScalarize(Value *V, bool isConstant) {
7681 if (isa<ConstantAggregateZero>(V))
7683 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7684 if (isConstant) return true;
7685 // If all elts are the same, we can extract.
7686 Constant *Op0 = C->getOperand(0);
7687 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7688 if (C->getOperand(i) != Op0)
7692 Instruction *I = dyn_cast<Instruction>(V);
7693 if (!I) return false;
7695 // Insert element gets simplified to the inserted element or is deleted if
7696 // this is constant idx extract element and its a constant idx insertelt.
7697 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7698 isa<ConstantInt>(I->getOperand(2)))
7700 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7702 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7703 if (BO->hasOneUse() &&
7704 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7705 CheapToScalarize(BO->getOperand(1), isConstant)))
7711 /// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7712 /// elements into values that are larger than the #elts in the input.
7713 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7714 unsigned NElts = SVI->getType()->getNumElements();
7715 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7716 return std::vector<unsigned>(NElts, 0);
7717 if (isa<UndefValue>(SVI->getOperand(2)))
7718 return std::vector<unsigned>(NElts, 2*NElts);
7720 std::vector<unsigned> Result;
7721 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7722 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7723 if (isa<UndefValue>(CP->getOperand(i)))
7724 Result.push_back(NElts*2); // undef -> 8
7726 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
7730 /// FindScalarElement - Given a vector and an element number, see if the scalar
7731 /// value is already around as a register, for example if it were inserted then
7732 /// extracted from the vector.
7733 static Value *FindScalarElement(Value *V, unsigned EltNo) {
7734 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7735 const PackedType *PTy = cast<PackedType>(V->getType());
7736 unsigned Width = PTy->getNumElements();
7737 if (EltNo >= Width) // Out of range access.
7738 return UndefValue::get(PTy->getElementType());
7740 if (isa<UndefValue>(V))
7741 return UndefValue::get(PTy->getElementType());
7742 else if (isa<ConstantAggregateZero>(V))
7743 return Constant::getNullValue(PTy->getElementType());
7744 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7745 return CP->getOperand(EltNo);
7746 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7747 // If this is an insert to a variable element, we don't know what it is.
7748 if (!isa<ConstantInt>(III->getOperand(2)))
7750 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
7752 // If this is an insert to the element we are looking for, return the
7755 return III->getOperand(1);
7757 // Otherwise, the insertelement doesn't modify the value, recurse on its
7759 return FindScalarElement(III->getOperand(0), EltNo);
7760 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
7761 unsigned InEl = getShuffleMask(SVI)[EltNo];
7763 return FindScalarElement(SVI->getOperand(0), InEl);
7764 else if (InEl < Width*2)
7765 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7767 return UndefValue::get(PTy->getElementType());
7770 // Otherwise, we don't know.
7774 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
7776 // If packed val is undef, replace extract with scalar undef.
7777 if (isa<UndefValue>(EI.getOperand(0)))
7778 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7780 // If packed val is constant 0, replace extract with scalar 0.
7781 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7782 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7784 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7785 // If packed val is constant with uniform operands, replace EI
7786 // with that operand
7787 Constant *op0 = C->getOperand(0);
7788 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7789 if (C->getOperand(i) != op0) {
7794 return ReplaceInstUsesWith(EI, op0);
7797 // If extracting a specified index from the vector, see if we can recursively
7798 // find a previously computed scalar that was inserted into the vector.
7799 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
7800 // This instruction only demands the single element from the input vector.
7801 // If the input vector has a single use, simplify it based on this use
7803 uint64_t IndexVal = IdxC->getZExtValue();
7804 if (EI.getOperand(0)->hasOneUse()) {
7806 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
7809 EI.setOperand(0, V);
7814 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
7815 return ReplaceInstUsesWith(EI, Elt);
7818 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
7819 if (I->hasOneUse()) {
7820 // Push extractelement into predecessor operation if legal and
7821 // profitable to do so
7822 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
7823 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7824 if (CheapToScalarize(BO, isConstantElt)) {
7825 ExtractElementInst *newEI0 =
7826 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7827 EI.getName()+".lhs");
7828 ExtractElementInst *newEI1 =
7829 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7830 EI.getName()+".rhs");
7831 InsertNewInstBefore(newEI0, EI);
7832 InsertNewInstBefore(newEI1, EI);
7833 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7835 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7836 Value *Ptr = InsertCastBefore(I->getOperand(0),
7837 PointerType::get(EI.getType()), EI);
7838 GetElementPtrInst *GEP =
7839 new GetElementPtrInst(Ptr, EI.getOperand(1),
7840 I->getName() + ".gep");
7841 InsertNewInstBefore(GEP, EI);
7842 return new LoadInst(GEP);
7845 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7846 // Extracting the inserted element?
7847 if (IE->getOperand(2) == EI.getOperand(1))
7848 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7849 // If the inserted and extracted elements are constants, they must not
7850 // be the same value, extract from the pre-inserted value instead.
7851 if (isa<Constant>(IE->getOperand(2)) &&
7852 isa<Constant>(EI.getOperand(1))) {
7853 AddUsesToWorkList(EI);
7854 EI.setOperand(0, IE->getOperand(0));
7857 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7858 // If this is extracting an element from a shufflevector, figure out where
7859 // it came from and extract from the appropriate input element instead.
7860 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
7861 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
7863 if (SrcIdx < SVI->getType()->getNumElements())
7864 Src = SVI->getOperand(0);
7865 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7866 SrcIdx -= SVI->getType()->getNumElements();
7867 Src = SVI->getOperand(1);
7869 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7871 return new ExtractElementInst(Src, SrcIdx);
7878 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7879 /// elements from either LHS or RHS, return the shuffle mask and true.
7880 /// Otherwise, return false.
7881 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7882 std::vector<Constant*> &Mask) {
7883 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7884 "Invalid CollectSingleShuffleElements");
7885 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7887 if (isa<UndefValue>(V)) {
7888 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7890 } else if (V == LHS) {
7891 for (unsigned i = 0; i != NumElts; ++i)
7892 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
7894 } else if (V == RHS) {
7895 for (unsigned i = 0; i != NumElts; ++i)
7896 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
7898 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7899 // If this is an insert of an extract from some other vector, include it.
7900 Value *VecOp = IEI->getOperand(0);
7901 Value *ScalarOp = IEI->getOperand(1);
7902 Value *IdxOp = IEI->getOperand(2);
7904 if (!isa<ConstantInt>(IdxOp))
7906 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
7908 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7909 // Okay, we can handle this if the vector we are insertinting into is
7911 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7912 // If so, update the mask to reflect the inserted undef.
7913 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7916 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7917 if (isa<ConstantInt>(EI->getOperand(1)) &&
7918 EI->getOperand(0)->getType() == V->getType()) {
7919 unsigned ExtractedIdx =
7920 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
7922 // This must be extracting from either LHS or RHS.
7923 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7924 // Okay, we can handle this if the vector we are insertinting into is
7926 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7927 // If so, update the mask to reflect the inserted value.
7928 if (EI->getOperand(0) == LHS) {
7929 Mask[InsertedIdx & (NumElts-1)] =
7930 ConstantInt::get(Type::UIntTy, ExtractedIdx);
7932 assert(EI->getOperand(0) == RHS);
7933 Mask[InsertedIdx & (NumElts-1)] =
7934 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7943 // TODO: Handle shufflevector here!
7948 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7949 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7950 /// that computes V and the LHS value of the shuffle.
7951 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
7953 assert(isa<PackedType>(V->getType()) &&
7954 (RHS == 0 || V->getType() == RHS->getType()) &&
7955 "Invalid shuffle!");
7956 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7958 if (isa<UndefValue>(V)) {
7959 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7961 } else if (isa<ConstantAggregateZero>(V)) {
7962 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
7964 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7965 // If this is an insert of an extract from some other vector, include it.
7966 Value *VecOp = IEI->getOperand(0);
7967 Value *ScalarOp = IEI->getOperand(1);
7968 Value *IdxOp = IEI->getOperand(2);
7970 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7971 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7972 EI->getOperand(0)->getType() == V->getType()) {
7973 unsigned ExtractedIdx =
7974 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
7975 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
7977 // Either the extracted from or inserted into vector must be RHSVec,
7978 // otherwise we'd end up with a shuffle of three inputs.
7979 if (EI->getOperand(0) == RHS || RHS == 0) {
7980 RHS = EI->getOperand(0);
7981 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
7982 Mask[InsertedIdx & (NumElts-1)] =
7983 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7988 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
7989 // Everything but the extracted element is replaced with the RHS.
7990 for (unsigned i = 0; i != NumElts; ++i) {
7991 if (i != InsertedIdx)
7992 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
7997 // If this insertelement is a chain that comes from exactly these two
7998 // vectors, return the vector and the effective shuffle.
7999 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8000 return EI->getOperand(0);
8005 // TODO: Handle shufflevector here!
8007 // Otherwise, can't do anything fancy. Return an identity vector.
8008 for (unsigned i = 0; i != NumElts; ++i)
8009 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8013 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8014 Value *VecOp = IE.getOperand(0);
8015 Value *ScalarOp = IE.getOperand(1);
8016 Value *IdxOp = IE.getOperand(2);
8018 // If the inserted element was extracted from some other vector, and if the
8019 // indexes are constant, try to turn this into a shufflevector operation.
8020 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8021 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8022 EI->getOperand(0)->getType() == IE.getType()) {
8023 unsigned NumVectorElts = IE.getType()->getNumElements();
8024 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8025 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8027 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8028 return ReplaceInstUsesWith(IE, VecOp);
8030 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8031 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8033 // If we are extracting a value from a vector, then inserting it right
8034 // back into the same place, just use the input vector.
8035 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8036 return ReplaceInstUsesWith(IE, VecOp);
8038 // We could theoretically do this for ANY input. However, doing so could
8039 // turn chains of insertelement instructions into a chain of shufflevector
8040 // instructions, and right now we do not merge shufflevectors. As such,
8041 // only do this in a situation where it is clear that there is benefit.
8042 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8043 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8044 // the values of VecOp, except then one read from EIOp0.
8045 // Build a new shuffle mask.
8046 std::vector<Constant*> Mask;
8047 if (isa<UndefValue>(VecOp))
8048 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8050 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8051 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
8054 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
8055 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8056 ConstantPacked::get(Mask));
8059 // If this insertelement isn't used by some other insertelement, turn it
8060 // (and any insertelements it points to), into one big shuffle.
8061 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8062 std::vector<Constant*> Mask;
8064 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8065 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8066 // We now have a shuffle of LHS, RHS, Mask.
8067 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8076 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8077 Value *LHS = SVI.getOperand(0);
8078 Value *RHS = SVI.getOperand(1);
8079 std::vector<unsigned> Mask = getShuffleMask(&SVI);
8081 bool MadeChange = false;
8083 // Undefined shuffle mask -> undefined value.
8084 if (isa<UndefValue>(SVI.getOperand(2)))
8085 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8087 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8088 // the undef, change them to undefs.
8090 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8091 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8092 if (LHS == RHS || isa<UndefValue>(LHS)) {
8093 if (isa<UndefValue>(LHS) && LHS == RHS) {
8094 // shuffle(undef,undef,mask) -> undef.
8095 return ReplaceInstUsesWith(SVI, LHS);
8098 // Remap any references to RHS to use LHS.
8099 std::vector<Constant*> Elts;
8100 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8102 Elts.push_back(UndefValue::get(Type::UIntTy));
8104 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8105 (Mask[i] < e && isa<UndefValue>(LHS)))
8106 Mask[i] = 2*e; // Turn into undef.
8108 Mask[i] &= (e-1); // Force to LHS.
8109 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
8112 SVI.setOperand(0, SVI.getOperand(1));
8113 SVI.setOperand(1, UndefValue::get(RHS->getType()));
8114 SVI.setOperand(2, ConstantPacked::get(Elts));
8115 LHS = SVI.getOperand(0);
8116 RHS = SVI.getOperand(1);
8120 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8121 bool isLHSID = true, isRHSID = true;
8123 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8124 if (Mask[i] >= e*2) continue; // Ignore undef values.
8125 // Is this an identity shuffle of the LHS value?
8126 isLHSID &= (Mask[i] == i);
8128 // Is this an identity shuffle of the RHS value?
8129 isRHSID &= (Mask[i]-e == i);
8132 // Eliminate identity shuffles.
8133 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8134 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8136 // If the LHS is a shufflevector itself, see if we can combine it with this
8137 // one without producing an unusual shuffle. Here we are really conservative:
8138 // we are absolutely afraid of producing a shuffle mask not in the input
8139 // program, because the code gen may not be smart enough to turn a merged
8140 // shuffle into two specific shuffles: it may produce worse code. As such,
8141 // we only merge two shuffles if the result is one of the two input shuffle
8142 // masks. In this case, merging the shuffles just removes one instruction,
8143 // which we know is safe. This is good for things like turning:
8144 // (splat(splat)) -> splat.
8145 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8146 if (isa<UndefValue>(RHS)) {
8147 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8149 std::vector<unsigned> NewMask;
8150 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8152 NewMask.push_back(2*e);
8154 NewMask.push_back(LHSMask[Mask[i]]);
8156 // If the result mask is equal to the src shuffle or this shuffle mask, do
8158 if (NewMask == LHSMask || NewMask == Mask) {
8159 std::vector<Constant*> Elts;
8160 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8161 if (NewMask[i] >= e*2) {
8162 Elts.push_back(UndefValue::get(Type::UIntTy));
8164 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
8167 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8168 LHSSVI->getOperand(1),
8169 ConstantPacked::get(Elts));
8174 return MadeChange ? &SVI : 0;
8179 void InstCombiner::removeFromWorkList(Instruction *I) {
8180 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8185 /// TryToSinkInstruction - Try to move the specified instruction from its
8186 /// current block into the beginning of DestBlock, which can only happen if it's
8187 /// safe to move the instruction past all of the instructions between it and the
8188 /// end of its block.
8189 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8190 assert(I->hasOneUse() && "Invariants didn't hold!");
8192 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8193 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8195 // Do not sink alloca instructions out of the entry block.
8196 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8199 // We can only sink load instructions if there is nothing between the load and
8200 // the end of block that could change the value.
8201 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8202 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8204 if (Scan->mayWriteToMemory())
8208 BasicBlock::iterator InsertPos = DestBlock->begin();
8209 while (isa<PHINode>(InsertPos)) ++InsertPos;
8211 I->moveBefore(InsertPos);
8216 /// OptimizeConstantExpr - Given a constant expression and target data layout
8217 /// information, symbolically evaluation the constant expr to something simpler
8219 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8222 Constant *Ptr = CE->getOperand(0);
8223 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8224 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8225 // If this is a constant expr gep that is effectively computing an
8226 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8227 bool isFoldableGEP = true;
8228 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8229 if (!isa<ConstantInt>(CE->getOperand(i)))
8230 isFoldableGEP = false;
8231 if (isFoldableGEP) {
8232 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8233 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8234 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
8235 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8236 return ConstantExpr::getCast(C, CE->getType());
8244 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8245 /// all reachable code to the worklist.
8247 /// This has a couple of tricks to make the code faster and more powerful. In
8248 /// particular, we constant fold and DCE instructions as we go, to avoid adding
8249 /// them to the worklist (this significantly speeds up instcombine on code where
8250 /// many instructions are dead or constant). Additionally, if we find a branch
8251 /// whose condition is a known constant, we only visit the reachable successors.
8253 static void AddReachableCodeToWorklist(BasicBlock *BB,
8254 std::set<BasicBlock*> &Visited,
8255 std::vector<Instruction*> &WorkList,
8256 const TargetData *TD) {
8257 // We have now visited this block! If we've already been here, bail out.
8258 if (!Visited.insert(BB).second) return;
8260 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8261 Instruction *Inst = BBI++;
8263 // DCE instruction if trivially dead.
8264 if (isInstructionTriviallyDead(Inst)) {
8266 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8267 Inst->eraseFromParent();
8271 // ConstantProp instruction if trivially constant.
8272 if (Constant *C = ConstantFoldInstruction(Inst)) {
8273 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8274 C = OptimizeConstantExpr(CE, TD);
8275 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8276 Inst->replaceAllUsesWith(C);
8278 Inst->eraseFromParent();
8282 WorkList.push_back(Inst);
8285 // Recursively visit successors. If this is a branch or switch on a constant,
8286 // only visit the reachable successor.
8287 TerminatorInst *TI = BB->getTerminator();
8288 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8289 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8290 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
8291 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8295 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8296 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8297 // See if this is an explicit destination.
8298 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8299 if (SI->getCaseValue(i) == Cond) {
8300 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
8304 // Otherwise it is the default destination.
8305 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
8310 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
8311 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
8314 bool InstCombiner::runOnFunction(Function &F) {
8315 bool Changed = false;
8316 TD = &getAnalysis<TargetData>();
8319 // Do a depth-first traversal of the function, populate the worklist with
8320 // the reachable instructions. Ignore blocks that are not reachable. Keep
8321 // track of which blocks we visit.
8322 std::set<BasicBlock*> Visited;
8323 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
8325 // Do a quick scan over the function. If we find any blocks that are
8326 // unreachable, remove any instructions inside of them. This prevents
8327 // the instcombine code from having to deal with some bad special cases.
8328 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8329 if (!Visited.count(BB)) {
8330 Instruction *Term = BB->getTerminator();
8331 while (Term != BB->begin()) { // Remove instrs bottom-up
8332 BasicBlock::iterator I = Term; --I;
8334 DEBUG(std::cerr << "IC: DCE: " << *I);
8337 if (!I->use_empty())
8338 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8339 I->eraseFromParent();
8344 while (!WorkList.empty()) {
8345 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8346 WorkList.pop_back();
8348 // Check to see if we can DCE the instruction.
8349 if (isInstructionTriviallyDead(I)) {
8350 // Add operands to the worklist.
8351 if (I->getNumOperands() < 4)
8352 AddUsesToWorkList(*I);
8355 DEBUG(std::cerr << "IC: DCE: " << *I);
8357 I->eraseFromParent();
8358 removeFromWorkList(I);
8362 // Instruction isn't dead, see if we can constant propagate it.
8363 if (Constant *C = ConstantFoldInstruction(I)) {
8364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8365 C = OptimizeConstantExpr(CE, TD);
8366 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8368 // Add operands to the worklist.
8369 AddUsesToWorkList(*I);
8370 ReplaceInstUsesWith(*I, C);
8373 I->eraseFromParent();
8374 removeFromWorkList(I);
8378 // See if we can trivially sink this instruction to a successor basic block.
8379 if (I->hasOneUse()) {
8380 BasicBlock *BB = I->getParent();
8381 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8382 if (UserParent != BB) {
8383 bool UserIsSuccessor = false;
8384 // See if the user is one of our successors.
8385 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8386 if (*SI == UserParent) {
8387 UserIsSuccessor = true;
8391 // If the user is one of our immediate successors, and if that successor
8392 // only has us as a predecessors (we'd have to split the critical edge
8393 // otherwise), we can keep going.
8394 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8395 next(pred_begin(UserParent)) == pred_end(UserParent))
8396 // Okay, the CFG is simple enough, try to sink this instruction.
8397 Changed |= TryToSinkInstruction(I, UserParent);
8401 // Now that we have an instruction, try combining it to simplify it...
8402 if (Instruction *Result = visit(*I)) {
8404 // Should we replace the old instruction with a new one?
8406 DEBUG(std::cerr << "IC: Old = " << *I
8407 << " New = " << *Result);
8409 // Everything uses the new instruction now.
8410 I->replaceAllUsesWith(Result);
8412 // Push the new instruction and any users onto the worklist.
8413 WorkList.push_back(Result);
8414 AddUsersToWorkList(*Result);
8416 // Move the name to the new instruction first...
8417 std::string OldName = I->getName(); I->setName("");
8418 Result->setName(OldName);
8420 // Insert the new instruction into the basic block...
8421 BasicBlock *InstParent = I->getParent();
8422 BasicBlock::iterator InsertPos = I;
8424 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8425 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8428 InstParent->getInstList().insert(InsertPos, Result);
8430 // Make sure that we reprocess all operands now that we reduced their
8432 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8433 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8434 WorkList.push_back(OpI);
8436 // Instructions can end up on the worklist more than once. Make sure
8437 // we do not process an instruction that has been deleted.
8438 removeFromWorkList(I);
8440 // Erase the old instruction.
8441 InstParent->getInstList().erase(I);
8443 DEBUG(std::cerr << "IC: MOD = " << *I);
8445 // If the instruction was modified, it's possible that it is now dead.
8446 // if so, remove it.
8447 if (isInstructionTriviallyDead(I)) {
8448 // Make sure we process all operands now that we are reducing their
8450 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8451 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8452 WorkList.push_back(OpI);
8454 // Instructions may end up in the worklist more than once. Erase all
8455 // occurrences of this instruction.
8456 removeFromWorkList(I);
8457 I->eraseFromParent();
8459 WorkList.push_back(Result);
8460 AddUsersToWorkList(*Result);
8470 FunctionPass *llvm::createInstructionCombiningPass() {
8471 return new InstCombiner();