1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All SetCC instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
56 using namespace llvm::PatternMatch;
59 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
63 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
65 class VISIBILITY_HIDDEN InstCombiner
66 : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(Value &I) {
77 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
79 WorkList.push_back(cast<Instruction>(*UI));
82 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
91 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92 /// dead. Add all of its operands to the worklist, turning them into
93 /// undef's to reduce the number of uses of those instructions.
95 /// Return the specified operand before it is turned into an undef.
97 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98 Value *R = I.getOperand(op);
100 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102 WorkList.push_back(Op);
103 // Set the operand to undef to drop the use.
104 I.setOperand(i, UndefValue::get(Op->getType()));
110 // removeFromWorkList - remove all instances of I from the worklist.
111 void removeFromWorkList(Instruction *I);
113 virtual bool runOnFunction(Function &F);
115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116 AU.addRequired<TargetData>();
117 AU.addPreservedID(LCSSAID);
118 AU.setPreservesCFG();
121 TargetData &getTargetData() const { return *TD; }
123 // Visitation implementation - Implement instruction combining for different
124 // instruction types. The semantics are as follows:
126 // null - No change was made
127 // I - Change was made, I is still valid, I may be dead though
128 // otherwise - Change was made, replace I with returned instruction
130 Instruction *visitAdd(BinaryOperator &I);
131 Instruction *visitSub(BinaryOperator &I);
132 Instruction *visitMul(BinaryOperator &I);
133 Instruction *visitURem(BinaryOperator &I);
134 Instruction *visitSRem(BinaryOperator &I);
135 Instruction *visitFRem(BinaryOperator &I);
136 Instruction *commonRemTransforms(BinaryOperator &I);
137 Instruction *commonIRemTransforms(BinaryOperator &I);
138 Instruction *commonDivTransforms(BinaryOperator &I);
139 Instruction *commonIDivTransforms(BinaryOperator &I);
140 Instruction *visitUDiv(BinaryOperator &I);
141 Instruction *visitSDiv(BinaryOperator &I);
142 Instruction *visitFDiv(BinaryOperator &I);
143 Instruction *visitAnd(BinaryOperator &I);
144 Instruction *visitOr (BinaryOperator &I);
145 Instruction *visitXor(BinaryOperator &I);
146 Instruction *visitSetCondInst(SetCondInst &I);
147 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
149 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
150 Instruction::BinaryOps Cond, Instruction &I);
151 Instruction *visitShiftInst(ShiftInst &I);
152 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
154 Instruction *visitCastInst(CastInst &CI);
155 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
157 Instruction *visitSelectInst(SelectInst &CI);
158 Instruction *visitCallInst(CallInst &CI);
159 Instruction *visitInvokeInst(InvokeInst &II);
160 Instruction *visitPHINode(PHINode &PN);
161 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
162 Instruction *visitAllocationInst(AllocationInst &AI);
163 Instruction *visitFreeInst(FreeInst &FI);
164 Instruction *visitLoadInst(LoadInst &LI);
165 Instruction *visitStoreInst(StoreInst &SI);
166 Instruction *visitBranchInst(BranchInst &BI);
167 Instruction *visitSwitchInst(SwitchInst &SI);
168 Instruction *visitInsertElementInst(InsertElementInst &IE);
169 Instruction *visitExtractElementInst(ExtractElementInst &EI);
170 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
172 // visitInstruction - Specify what to return for unhandled instructions...
173 Instruction *visitInstruction(Instruction &I) { return 0; }
176 Instruction *visitCallSite(CallSite CS);
177 bool transformConstExprCastCall(CallSite CS);
180 // InsertNewInstBefore - insert an instruction New before instruction Old
181 // in the program. Add the new instruction to the worklist.
183 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
184 assert(New && New->getParent() == 0 &&
185 "New instruction already inserted into a basic block!");
186 BasicBlock *BB = Old.getParent();
187 BB->getInstList().insert(&Old, New); // Insert inst
188 WorkList.push_back(New); // Add to worklist
192 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
193 /// This also adds the cast to the worklist. Finally, this returns the
195 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
196 if (V->getType() == Ty) return V;
198 if (Constant *CV = dyn_cast<Constant>(V))
199 return ConstantExpr::getCast(CV, Ty);
201 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
202 WorkList.push_back(C);
206 // ReplaceInstUsesWith - This method is to be used when an instruction is
207 // found to be dead, replacable with another preexisting expression. Here
208 // we add all uses of I to the worklist, replace all uses of I with the new
209 // value, then return I, so that the inst combiner will know that I was
212 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
213 AddUsersToWorkList(I); // Add all modified instrs to worklist
215 I.replaceAllUsesWith(V);
218 // If we are replacing the instruction with itself, this must be in a
219 // segment of unreachable code, so just clobber the instruction.
220 I.replaceAllUsesWith(UndefValue::get(I.getType()));
225 // UpdateValueUsesWith - This method is to be used when an value is
226 // found to be replacable with another preexisting expression or was
227 // updated. Here we add all uses of I to the worklist, replace all uses of
228 // I with the new value (unless the instruction was just updated), then
229 // return true, so that the inst combiner will know that I was modified.
231 bool UpdateValueUsesWith(Value *Old, Value *New) {
232 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
234 Old->replaceAllUsesWith(New);
235 if (Instruction *I = dyn_cast<Instruction>(Old))
236 WorkList.push_back(I);
237 if (Instruction *I = dyn_cast<Instruction>(New))
238 WorkList.push_back(I);
242 // EraseInstFromFunction - When dealing with an instruction that has side
243 // effects or produces a void value, we can't rely on DCE to delete the
244 // instruction. Instead, visit methods should return the value returned by
246 Instruction *EraseInstFromFunction(Instruction &I) {
247 assert(I.use_empty() && "Cannot erase instruction that is used!");
248 AddUsesToWorkList(I);
249 removeFromWorkList(&I);
251 return 0; // Don't do anything with FI
255 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
256 /// InsertBefore instruction. This is specialized a bit to avoid inserting
257 /// casts that are known to not do anything...
259 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
260 Instruction *InsertBefore);
262 // SimplifyCommutative - This performs a few simplifications for commutative
264 bool SimplifyCommutative(BinaryOperator &I);
266 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
267 uint64_t &KnownZero, uint64_t &KnownOne,
270 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
271 uint64_t &UndefElts, unsigned Depth = 0);
273 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
274 // PHI node as operand #0, see if we can fold the instruction into the PHI
275 // (which is only possible if all operands to the PHI are constants).
276 Instruction *FoldOpIntoPhi(Instruction &I);
278 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
279 // operator and they all are only used by the PHI, PHI together their
280 // inputs, and do the operation once, to the result of the PHI.
281 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
282 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
285 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
286 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
288 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
289 bool isSub, Instruction &I);
290 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
291 bool Inside, Instruction &IB);
292 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
293 Instruction *MatchBSwap(BinaryOperator &I);
295 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
298 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
301 // getComplexity: Assign a complexity or rank value to LLVM Values...
302 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
303 static unsigned getComplexity(Value *V) {
304 if (isa<Instruction>(V)) {
305 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
309 if (isa<Argument>(V)) return 3;
310 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
313 // isOnlyUse - Return true if this instruction will be deleted if we stop using
315 static bool isOnlyUse(Value *V) {
316 return V->hasOneUse() || isa<Constant>(V);
319 // getPromotedType - Return the specified type promoted as it would be to pass
320 // though a va_arg area...
321 static const Type *getPromotedType(const Type *Ty) {
322 switch (Ty->getTypeID()) {
323 case Type::SByteTyID:
324 case Type::ShortTyID: return Type::IntTy;
325 case Type::UByteTyID:
326 case Type::UShortTyID: return Type::UIntTy;
327 case Type::FloatTyID: return Type::DoubleTy;
332 /// isCast - If the specified operand is a CastInst or a constant expr cast,
333 /// return the operand value, otherwise return null.
334 static Value *isCast(Value *V) {
335 if (CastInst *I = dyn_cast<CastInst>(V))
336 return I->getOperand(0);
337 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
338 if (CE->getOpcode() == Instruction::Cast)
339 return CE->getOperand(0);
350 /// getCastType - In the future, we will split the cast instruction into these
351 /// various types. Until then, we have to do the analysis here.
352 static CastType getCastType(const Type *Src, const Type *Dest) {
353 assert(Src->isIntegral() && Dest->isIntegral() &&
354 "Only works on integral types!");
355 unsigned SrcSize = Src->getPrimitiveSizeInBits();
356 unsigned DestSize = Dest->getPrimitiveSizeInBits();
358 if (SrcSize == DestSize) return Noop;
359 if (SrcSize > DestSize) return Truncate;
360 if (Src->isSigned()) return Signext;
365 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
368 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
369 const Type *DstTy, TargetData *TD) {
371 // It is legal to eliminate the instruction if casting A->B->A if the sizes
372 // are identical and the bits don't get reinterpreted (for example
373 // int->float->int would not be allowed).
374 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
377 // If we are casting between pointer and integer types, treat pointers as
378 // integers of the appropriate size for the code below.
379 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
380 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
381 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
383 // Allow free casting and conversion of sizes as long as the sign doesn't
385 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
386 CastType FirstCast = getCastType(SrcTy, MidTy);
387 CastType SecondCast = getCastType(MidTy, DstTy);
389 // Capture the effect of these two casts. If the result is a legal cast,
390 // the CastType is stored here, otherwise a special code is used.
391 static const unsigned CastResult[] = {
392 // First cast is noop
394 // First cast is a truncate
395 1, 1, 4, 4, // trunc->extend is not safe to eliminate
396 // First cast is a sign ext
397 2, 5, 2, 4, // signext->zeroext never ok
398 // First cast is a zero ext
402 unsigned Result = CastResult[FirstCast*4+SecondCast];
404 default: assert(0 && "Illegal table value!");
409 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
410 // truncates, we could eliminate more casts.
411 return (unsigned)getCastType(SrcTy, DstTy) == Result;
413 return false; // Not possible to eliminate this here.
415 // Sign or zero extend followed by truncate is always ok if the result
416 // is a truncate or noop.
417 CastType ResultCast = getCastType(SrcTy, DstTy);
418 if (ResultCast == Noop || ResultCast == Truncate)
420 // Otherwise we are still growing the value, we are only safe if the
421 // result will match the sign/zeroextendness of the result.
422 return ResultCast == FirstCast;
426 // If this is a cast from 'float -> double -> integer', cast from
427 // 'float -> integer' directly, as the value isn't changed by the
428 // float->double conversion.
429 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
430 DstTy->isIntegral() &&
431 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
434 // Packed type conversions don't modify bits.
435 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
441 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
442 /// in any code being generated. It does not require codegen if V is simple
443 /// enough or if the cast can be folded into other casts.
444 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
445 if (V->getType() == Ty || isa<Constant>(V)) return false;
447 // If this is a noop cast, it isn't real codegen.
448 if (V->getType()->isLosslesslyConvertibleTo(Ty))
451 // If this is another cast that can be eliminated, it isn't codegen either.
452 if (const CastInst *CI = dyn_cast<CastInst>(V))
453 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
459 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
460 /// InsertBefore instruction. This is specialized a bit to avoid inserting
461 /// casts that are known to not do anything...
463 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
464 Instruction *InsertBefore) {
465 if (V->getType() == DestTy) return V;
466 if (Constant *C = dyn_cast<Constant>(V))
467 return ConstantExpr::getCast(C, DestTy);
469 return InsertCastBefore(V, DestTy, *InsertBefore);
472 // SimplifyCommutative - This performs a few simplifications for commutative
475 // 1. Order operands such that they are listed from right (least complex) to
476 // left (most complex). This puts constants before unary operators before
479 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
480 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
482 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
483 bool Changed = false;
484 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
485 Changed = !I.swapOperands();
487 if (!I.isAssociative()) return Changed;
488 Instruction::BinaryOps Opcode = I.getOpcode();
489 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
490 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
491 if (isa<Constant>(I.getOperand(1))) {
492 Constant *Folded = ConstantExpr::get(I.getOpcode(),
493 cast<Constant>(I.getOperand(1)),
494 cast<Constant>(Op->getOperand(1)));
495 I.setOperand(0, Op->getOperand(0));
496 I.setOperand(1, Folded);
498 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
499 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
500 isOnlyUse(Op) && isOnlyUse(Op1)) {
501 Constant *C1 = cast<Constant>(Op->getOperand(1));
502 Constant *C2 = cast<Constant>(Op1->getOperand(1));
504 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
505 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
506 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
509 WorkList.push_back(New);
510 I.setOperand(0, New);
511 I.setOperand(1, Folded);
518 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
519 // if the LHS is a constant zero (which is the 'negate' form).
521 static inline Value *dyn_castNegVal(Value *V) {
522 if (BinaryOperator::isNeg(V))
523 return BinaryOperator::getNegArgument(V);
525 // Constants can be considered to be negated values if they can be folded.
526 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
527 return ConstantExpr::getNeg(C);
531 static inline Value *dyn_castNotVal(Value *V) {
532 if (BinaryOperator::isNot(V))
533 return BinaryOperator::getNotArgument(V);
535 // Constants can be considered to be not'ed values...
536 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
537 return ConstantExpr::getNot(C);
541 // dyn_castFoldableMul - If this value is a multiply that can be folded into
542 // other computations (because it has a constant operand), return the
543 // non-constant operand of the multiply, and set CST to point to the multiplier.
544 // Otherwise, return null.
546 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
547 if (V->hasOneUse() && V->getType()->isInteger())
548 if (Instruction *I = dyn_cast<Instruction>(V)) {
549 if (I->getOpcode() == Instruction::Mul)
550 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
551 return I->getOperand(0);
552 if (I->getOpcode() == Instruction::Shl)
553 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
554 // The multiplier is really 1 << CST.
555 Constant *One = ConstantInt::get(V->getType(), 1);
556 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
557 return I->getOperand(0);
563 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
564 /// expression, return it.
565 static User *dyn_castGetElementPtr(Value *V) {
566 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
567 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
568 if (CE->getOpcode() == Instruction::GetElementPtr)
569 return cast<User>(V);
573 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
574 static ConstantInt *AddOne(ConstantInt *C) {
575 return cast<ConstantInt>(ConstantExpr::getAdd(C,
576 ConstantInt::get(C->getType(), 1)));
578 static ConstantInt *SubOne(ConstantInt *C) {
579 return cast<ConstantInt>(ConstantExpr::getSub(C,
580 ConstantInt::get(C->getType(), 1)));
583 /// GetConstantInType - Return a ConstantInt with the specified type and value.
585 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
586 if (Ty->isUnsigned())
587 return ConstantInt::get(Ty, Val);
588 else if (Ty->getTypeID() == Type::BoolTyID)
589 return ConstantBool::get(Val);
591 SVal <<= 64-Ty->getPrimitiveSizeInBits();
592 SVal >>= 64-Ty->getPrimitiveSizeInBits();
593 return ConstantInt::get(Ty, SVal);
597 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
598 /// known to be either zero or one and return them in the KnownZero/KnownOne
599 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
601 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
602 uint64_t &KnownOne, unsigned Depth = 0) {
603 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
604 // we cannot optimize based on the assumption that it is zero without changing
605 // it to be an explicit zero. If we don't change it to zero, other code could
606 // optimized based on the contradictory assumption that it is non-zero.
607 // Because instcombine aggressively folds operations with undef args anyway,
608 // this won't lose us code quality.
609 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
610 // We know all of the bits for a constant!
611 KnownOne = CI->getZExtValue() & Mask;
612 KnownZero = ~KnownOne & Mask;
616 KnownZero = KnownOne = 0; // Don't know anything.
617 if (Depth == 6 || Mask == 0)
618 return; // Limit search depth.
620 uint64_t KnownZero2, KnownOne2;
621 Instruction *I = dyn_cast<Instruction>(V);
624 Mask &= V->getType()->getIntegralTypeMask();
626 switch (I->getOpcode()) {
627 case Instruction::And:
628 // If either the LHS or the RHS are Zero, the result is zero.
629 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
631 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
632 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
633 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
635 // Output known-1 bits are only known if set in both the LHS & RHS.
636 KnownOne &= KnownOne2;
637 // Output known-0 are known to be clear if zero in either the LHS | RHS.
638 KnownZero |= KnownZero2;
640 case Instruction::Or:
641 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
643 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
644 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
645 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
647 // Output known-0 bits are only known if clear in both the LHS & RHS.
648 KnownZero &= KnownZero2;
649 // Output known-1 are known to be set if set in either the LHS | RHS.
650 KnownOne |= KnownOne2;
652 case Instruction::Xor: {
653 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
654 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
655 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
656 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
658 // Output known-0 bits are known if clear or set in both the LHS & RHS.
659 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
660 // Output known-1 are known to be set if set in only one of the LHS, RHS.
661 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
662 KnownZero = KnownZeroOut;
665 case Instruction::Select:
666 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
667 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
668 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
669 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
671 // Only known if known in both the LHS and RHS.
672 KnownOne &= KnownOne2;
673 KnownZero &= KnownZero2;
675 case Instruction::Cast: {
676 const Type *SrcTy = I->getOperand(0)->getType();
677 if (!SrcTy->isIntegral()) return;
679 // If this is an integer truncate or noop, just look in the input.
680 if (SrcTy->getPrimitiveSizeInBits() >=
681 I->getType()->getPrimitiveSizeInBits()) {
682 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
686 // Sign or Zero extension. Compute the bits in the result that are not
687 // present in the input.
688 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
689 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
691 // Handle zero extension.
692 if (!SrcTy->isSigned()) {
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?");
696 // The top bits are known to be zero.
697 KnownZero |= NewBits;
700 Mask &= SrcTy->getIntegralTypeMask();
701 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
702 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
704 // If the sign bit of the input is known set or clear, then we know the
705 // top bits of the result.
706 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
707 if (KnownZero & InSignBit) { // Input sign bit known zero
708 KnownZero |= NewBits;
709 KnownOne &= ~NewBits;
710 } else if (KnownOne & InSignBit) { // Input sign bit known set
712 KnownZero &= ~NewBits;
713 } else { // Input sign bit unknown
714 KnownZero &= ~NewBits;
715 KnownOne &= ~NewBits;
720 case Instruction::Shl:
721 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
722 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
723 uint64_t ShiftAmt = SA->getZExtValue();
725 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
726 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
727 KnownZero <<= ShiftAmt;
728 KnownOne <<= ShiftAmt;
729 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
733 case Instruction::LShr:
734 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
735 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
736 // Compute the new bits that are at the top now.
737 uint64_t ShiftAmt = SA->getZExtValue();
738 uint64_t HighBits = (1ULL << ShiftAmt)-1;
739 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
741 // Unsigned shift right.
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;
747 KnownZero |= HighBits; // high bits known zero.
751 case Instruction::AShr:
752 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
753 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
754 // Compute the new bits that are at the top now.
755 uint64_t ShiftAmt = SA->getZExtValue();
756 uint64_t HighBits = (1ULL << ShiftAmt)-1;
757 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
759 // Signed shift right.
761 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
762 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
763 KnownZero >>= ShiftAmt;
764 KnownOne >>= ShiftAmt;
766 // Handle the sign bits.
767 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
768 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
770 if (KnownZero & SignBit) { // New bits are known zero.
771 KnownZero |= HighBits;
772 } else if (KnownOne & SignBit) { // New bits are known one.
773 KnownOne |= HighBits;
781 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
782 /// this predicate to simplify operations downstream. Mask is known to be zero
783 /// for bits that V cannot have.
784 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
785 uint64_t KnownZero, KnownOne;
786 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
787 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
788 return (KnownZero & Mask) == Mask;
791 /// ShrinkDemandedConstant - Check to see if the specified operand of the
792 /// specified instruction is a constant integer. If so, check to see if there
793 /// are any bits set in the constant that are not demanded. If so, shrink the
794 /// constant and return true.
795 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
797 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
798 if (!OpC) return false;
800 // If there are no bits set that aren't demanded, nothing to do.
801 if ((~Demanded & OpC->getZExtValue()) == 0)
804 // This is producing any bits that are not needed, shrink the RHS.
805 uint64_t Val = Demanded & OpC->getZExtValue();
806 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
810 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
811 // set of known zero and one bits, compute the maximum and minimum values that
812 // could have the specified known zero and known one bits, returning them in
814 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
817 int64_t &Min, int64_t &Max) {
818 uint64_t TypeBits = Ty->getIntegralTypeMask();
819 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
821 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
823 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
824 // bit if it is unknown.
826 Max = KnownOne|UnknownBits;
828 if (SignBit & UnknownBits) { // Sign bit is unknown
833 // Sign extend the min/max values.
834 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
835 Min = (Min << ShAmt) >> ShAmt;
836 Max = (Max << ShAmt) >> ShAmt;
839 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
840 // a set of known zero and one bits, compute the maximum and minimum values that
841 // could have the specified known zero and known one bits, returning them in
843 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
848 uint64_t TypeBits = Ty->getIntegralTypeMask();
849 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
851 // The minimum value is when the unknown bits are all zeros.
853 // The maximum value is when the unknown bits are all ones.
854 Max = KnownOne|UnknownBits;
858 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
859 /// DemandedMask bits of the result of V are ever used downstream. If we can
860 /// use this information to simplify V, do so and return true. Otherwise,
861 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
862 /// the expression (used to simplify the caller). The KnownZero/One bits may
863 /// only be accurate for those bits in the DemandedMask.
864 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
865 uint64_t &KnownZero, uint64_t &KnownOne,
867 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
868 // We know all of the bits for a constant!
869 KnownOne = CI->getZExtValue() & DemandedMask;
870 KnownZero = ~KnownOne & DemandedMask;
874 KnownZero = KnownOne = 0;
875 if (!V->hasOneUse()) { // Other users may use these bits.
876 if (Depth != 0) { // Not at the root.
877 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
878 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
881 // If this is the root being simplified, allow it to have multiple uses,
882 // just set the DemandedMask to all bits.
883 DemandedMask = V->getType()->getIntegralTypeMask();
884 } else if (DemandedMask == 0) { // Not demanding any bits from V.
885 if (V != UndefValue::get(V->getType()))
886 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
888 } else if (Depth == 6) { // Limit search depth.
892 Instruction *I = dyn_cast<Instruction>(V);
893 if (!I) return false; // Only analyze instructions.
895 DemandedMask &= V->getType()->getIntegralTypeMask();
897 uint64_t KnownZero2, KnownOne2;
898 switch (I->getOpcode()) {
900 case Instruction::And:
901 // If either the LHS or the RHS are Zero, the result is zero.
902 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
903 KnownZero, KnownOne, Depth+1))
905 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
907 // If something is known zero on the RHS, the bits aren't demanded on the
909 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
910 KnownZero2, KnownOne2, Depth+1))
912 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
914 // If all of the demanded bits are known one on one side, return the other.
915 // These bits cannot contribute to the result of the 'and'.
916 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
917 return UpdateValueUsesWith(I, I->getOperand(0));
918 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
919 return UpdateValueUsesWith(I, I->getOperand(1));
921 // If all of the demanded bits in the inputs are known zeros, return zero.
922 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
923 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
925 // If the RHS is a constant, see if we can simplify it.
926 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
927 return UpdateValueUsesWith(I, I);
929 // Output known-1 bits are only known if set in both the LHS & RHS.
930 KnownOne &= KnownOne2;
931 // Output known-0 are known to be clear if zero in either the LHS | RHS.
932 KnownZero |= KnownZero2;
934 case Instruction::Or:
935 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
936 KnownZero, KnownOne, Depth+1))
938 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
939 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
940 KnownZero2, KnownOne2, Depth+1))
942 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
944 // If all of the demanded bits are known zero on one side, return the other.
945 // These bits cannot contribute to the result of the 'or'.
946 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
947 return UpdateValueUsesWith(I, I->getOperand(0));
948 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
949 return UpdateValueUsesWith(I, I->getOperand(1));
951 // If all of the potentially set bits on one side are known to be set on
952 // the other side, just use the 'other' side.
953 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
954 (DemandedMask & (~KnownZero)))
955 return UpdateValueUsesWith(I, I->getOperand(0));
956 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
957 (DemandedMask & (~KnownZero2)))
958 return UpdateValueUsesWith(I, I->getOperand(1));
960 // If the RHS is a constant, see if we can simplify it.
961 if (ShrinkDemandedConstant(I, 1, DemandedMask))
962 return UpdateValueUsesWith(I, I);
964 // Output known-0 bits are only known if clear in both the LHS & RHS.
965 KnownZero &= KnownZero2;
966 // Output known-1 are known to be set if set in either the LHS | RHS.
967 KnownOne |= KnownOne2;
969 case Instruction::Xor: {
970 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
971 KnownZero, KnownOne, Depth+1))
973 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
974 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
975 KnownZero2, KnownOne2, Depth+1))
977 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
979 // If all of the demanded bits are known zero on one side, return the other.
980 // These bits cannot contribute to the result of the 'xor'.
981 if ((DemandedMask & KnownZero) == DemandedMask)
982 return UpdateValueUsesWith(I, I->getOperand(0));
983 if ((DemandedMask & KnownZero2) == DemandedMask)
984 return UpdateValueUsesWith(I, I->getOperand(1));
986 // Output known-0 bits are known if clear or set in both the LHS & RHS.
987 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
988 // Output known-1 are known to be set if set in only one of the LHS, RHS.
989 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
991 // If all of the unknown bits are known to be zero on one side or the other
992 // (but not both) turn this into an *inclusive* or.
993 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
994 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
995 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
997 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
999 InsertNewInstBefore(Or, *I);
1000 return UpdateValueUsesWith(I, Or);
1004 // If all of the demanded bits on one side are known, and all of the set
1005 // bits on that side are also known to be set on the other side, turn this
1006 // into an AND, as we know the bits will be cleared.
1007 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1008 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1009 if ((KnownOne & KnownOne2) == KnownOne) {
1010 Constant *AndC = GetConstantInType(I->getType(),
1011 ~KnownOne & DemandedMask);
1013 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1014 InsertNewInstBefore(And, *I);
1015 return UpdateValueUsesWith(I, And);
1019 // If the RHS is a constant, see if we can simplify it.
1020 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1021 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1022 return UpdateValueUsesWith(I, I);
1024 KnownZero = KnownZeroOut;
1025 KnownOne = KnownOneOut;
1028 case Instruction::Select:
1029 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1030 KnownZero, KnownOne, Depth+1))
1032 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1033 KnownZero2, KnownOne2, Depth+1))
1035 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1036 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1038 // If the operands are constants, see if we can simplify them.
1039 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1040 return UpdateValueUsesWith(I, I);
1041 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1042 return UpdateValueUsesWith(I, I);
1044 // Only known if known in both the LHS and RHS.
1045 KnownOne &= KnownOne2;
1046 KnownZero &= KnownZero2;
1048 case Instruction::Cast: {
1049 const Type *SrcTy = I->getOperand(0)->getType();
1050 if (!SrcTy->isIntegral()) return false;
1052 // If this is an integer truncate or noop, just look in the input.
1053 if (SrcTy->getPrimitiveSizeInBits() >=
1054 I->getType()->getPrimitiveSizeInBits()) {
1055 // Cast to bool is a comparison against 0, which demands all bits. We
1056 // can't propagate anything useful up.
1057 if (I->getType() == Type::BoolTy)
1060 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1061 KnownZero, KnownOne, Depth+1))
1063 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1067 // Sign or Zero extension. Compute the bits in the result that are not
1068 // present in the input.
1069 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1070 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1072 // Handle zero extension.
1073 if (!SrcTy->isSigned()) {
1074 DemandedMask &= SrcTy->getIntegralTypeMask();
1075 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1076 KnownZero, KnownOne, Depth+1))
1078 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1079 // The top bits are known to be zero.
1080 KnownZero |= NewBits;
1083 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1084 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1086 // If any of the sign extended bits are demanded, we know that the sign
1088 if (NewBits & DemandedMask)
1089 InputDemandedBits |= InSignBit;
1091 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1092 KnownZero, KnownOne, Depth+1))
1094 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1096 // If the sign bit of the input is known set or clear, then we know the
1097 // top bits of the result.
1099 // If the input sign bit is known zero, or if the NewBits are not demanded
1100 // convert this into a zero extension.
1101 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1102 // Convert to unsigned first.
1104 InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
1105 // Then cast that to the destination type.
1106 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1107 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1108 return UpdateValueUsesWith(I, NewVal);
1109 } else if (KnownOne & InSignBit) { // Input sign bit known set
1110 KnownOne |= NewBits;
1111 KnownZero &= ~NewBits;
1112 } else { // Input sign bit unknown
1113 KnownZero &= ~NewBits;
1114 KnownOne &= ~NewBits;
1119 case Instruction::Add:
1120 // If there is a constant on the RHS, there are a variety of xformations
1122 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1123 // If null, this should be simplified elsewhere. Some of the xforms here
1124 // won't work if the RHS is zero.
1125 if (RHS->isNullValue())
1128 // Figure out what the input bits are. If the top bits of the and result
1129 // are not demanded, then the add doesn't demand them from its input
1132 // Shift the demanded mask up so that it's at the top of the uint64_t.
1133 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1134 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1136 // If the top bit of the output is demanded, demand everything from the
1137 // input. Otherwise, we demand all the input bits except NLZ top bits.
1138 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1140 // Find information about known zero/one bits in the input.
1141 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1142 KnownZero2, KnownOne2, Depth+1))
1145 // If the RHS of the add has bits set that can't affect the input, reduce
1147 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1148 return UpdateValueUsesWith(I, I);
1150 // Avoid excess work.
1151 if (KnownZero2 == 0 && KnownOne2 == 0)
1154 // Turn it into OR if input bits are zero.
1155 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1157 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1159 InsertNewInstBefore(Or, *I);
1160 return UpdateValueUsesWith(I, Or);
1163 // We can say something about the output known-zero and known-one bits,
1164 // depending on potential carries from the input constant and the
1165 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1166 // bits set and the RHS constant is 0x01001, then we know we have a known
1167 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1169 // To compute this, we first compute the potential carry bits. These are
1170 // the bits which may be modified. I'm not aware of a better way to do
1172 uint64_t RHSVal = RHS->getZExtValue();
1174 bool CarryIn = false;
1175 uint64_t CarryBits = 0;
1176 uint64_t CurBit = 1;
1177 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1178 // Record the current carry in.
1179 if (CarryIn) CarryBits |= CurBit;
1183 // This bit has a carry out unless it is "zero + zero" or
1184 // "zero + anything" with no carry in.
1185 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1186 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1187 } else if (!CarryIn &&
1188 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1189 CarryOut = false; // 0 + anything has no carry out if no carry in.
1191 // Otherwise, we have to assume we have a carry out.
1195 // This stage's carry out becomes the next stage's carry-in.
1199 // Now that we know which bits have carries, compute the known-1/0 sets.
1201 // Bits are known one if they are known zero in one operand and one in the
1202 // other, and there is no input carry.
1203 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1205 // Bits are known zero if they are known zero in both operands and there
1206 // is no input carry.
1207 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1210 case Instruction::Shl:
1211 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1212 uint64_t ShiftAmt = SA->getZExtValue();
1213 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
1214 KnownZero, KnownOne, Depth+1))
1216 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1217 KnownZero <<= ShiftAmt;
1218 KnownOne <<= ShiftAmt;
1219 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
1222 case Instruction::LShr:
1223 // For a logical shift right
1224 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1225 unsigned ShiftAmt = SA->getZExtValue();
1227 // Compute the new bits that are at the top now.
1228 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1229 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1230 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1231 // Unsigned shift right.
1232 if (SimplifyDemandedBits(I->getOperand(0),
1233 (DemandedMask << ShiftAmt) & TypeMask,
1234 KnownZero, KnownOne, Depth+1))
1236 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1237 KnownZero &= TypeMask;
1238 KnownOne &= TypeMask;
1239 KnownZero >>= ShiftAmt;
1240 KnownOne >>= ShiftAmt;
1241 KnownZero |= HighBits; // high bits known zero.
1244 case Instruction::AShr:
1245 // If this is an arithmetic shift right and only the low-bit is set, we can
1246 // always convert this into a logical shr, even if the shift amount is
1247 // variable. The low bit of the shift cannot be an input sign bit unless
1248 // the shift amount is >= the size of the datatype, which is undefined.
1249 if (DemandedMask == 1) {
1250 // Perform the logical shift right.
1251 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1252 I->getOperand(1), I->getName());
1253 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1254 return UpdateValueUsesWith(I, NewVal);
1257 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258 unsigned ShiftAmt = SA->getZExtValue();
1260 // Compute the new bits that are at the top now.
1261 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1262 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1263 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1264 // Signed shift right.
1265 if (SimplifyDemandedBits(I->getOperand(0),
1266 (DemandedMask << ShiftAmt) & TypeMask,
1267 KnownZero, KnownOne, Depth+1))
1269 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1270 KnownZero &= TypeMask;
1271 KnownOne &= TypeMask;
1272 KnownZero >>= ShiftAmt;
1273 KnownOne >>= ShiftAmt;
1275 // Handle the sign bits.
1276 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1277 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
1279 // If the input sign bit is known to be zero, or if none of the top bits
1280 // are demanded, turn this into an unsigned shift right.
1281 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1282 // Perform the logical shift right.
1283 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1285 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1286 return UpdateValueUsesWith(I, NewVal);
1287 } else if (KnownOne & SignBit) { // New bits are known one.
1288 KnownOne |= HighBits;
1294 // If the client is only demanding bits that we know, return the known
1296 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1297 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1302 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1303 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1304 /// actually used by the caller. This method analyzes which elements of the
1305 /// operand are undef and returns that information in UndefElts.
1307 /// If the information about demanded elements can be used to simplify the
1308 /// operation, the operation is simplified, then the resultant value is
1309 /// returned. This returns null if no change was made.
1310 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1311 uint64_t &UndefElts,
1313 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1314 assert(VWidth <= 64 && "Vector too wide to analyze!");
1315 uint64_t EltMask = ~0ULL >> (64-VWidth);
1316 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1317 "Invalid DemandedElts!");
1319 if (isa<UndefValue>(V)) {
1320 // If the entire vector is undefined, just return this info.
1321 UndefElts = EltMask;
1323 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1324 UndefElts = EltMask;
1325 return UndefValue::get(V->getType());
1329 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1330 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1331 Constant *Undef = UndefValue::get(EltTy);
1333 std::vector<Constant*> Elts;
1334 for (unsigned i = 0; i != VWidth; ++i)
1335 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1336 Elts.push_back(Undef);
1337 UndefElts |= (1ULL << i);
1338 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1339 Elts.push_back(Undef);
1340 UndefElts |= (1ULL << i);
1341 } else { // Otherwise, defined.
1342 Elts.push_back(CP->getOperand(i));
1345 // If we changed the constant, return it.
1346 Constant *NewCP = ConstantPacked::get(Elts);
1347 return NewCP != CP ? NewCP : 0;
1348 } else if (isa<ConstantAggregateZero>(V)) {
1349 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1351 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1352 Constant *Zero = Constant::getNullValue(EltTy);
1353 Constant *Undef = UndefValue::get(EltTy);
1354 std::vector<Constant*> Elts;
1355 for (unsigned i = 0; i != VWidth; ++i)
1356 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1357 UndefElts = DemandedElts ^ EltMask;
1358 return ConstantPacked::get(Elts);
1361 if (!V->hasOneUse()) { // Other users may use these bits.
1362 if (Depth != 0) { // Not at the root.
1363 // TODO: Just compute the UndefElts information recursively.
1367 } else if (Depth == 10) { // Limit search depth.
1371 Instruction *I = dyn_cast<Instruction>(V);
1372 if (!I) return false; // Only analyze instructions.
1374 bool MadeChange = false;
1375 uint64_t UndefElts2;
1377 switch (I->getOpcode()) {
1380 case Instruction::InsertElement: {
1381 // If this is a variable index, we don't know which element it overwrites.
1382 // demand exactly the same input as we produce.
1383 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1385 // Note that we can't propagate undef elt info, because we don't know
1386 // which elt is getting updated.
1387 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1388 UndefElts2, Depth+1);
1389 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1393 // If this is inserting an element that isn't demanded, remove this
1395 unsigned IdxNo = Idx->getZExtValue();
1396 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1397 return AddSoonDeadInstToWorklist(*I, 0);
1399 // Otherwise, the element inserted overwrites whatever was there, so the
1400 // input demanded set is simpler than the output set.
1401 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1402 DemandedElts & ~(1ULL << IdxNo),
1403 UndefElts, Depth+1);
1404 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1406 // The inserted element is defined.
1407 UndefElts |= 1ULL << IdxNo;
1411 case Instruction::And:
1412 case Instruction::Or:
1413 case Instruction::Xor:
1414 case Instruction::Add:
1415 case Instruction::Sub:
1416 case Instruction::Mul:
1417 // div/rem demand all inputs, because they don't want divide by zero.
1418 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1419 UndefElts, Depth+1);
1420 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1421 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1422 UndefElts2, Depth+1);
1423 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1425 // Output elements are undefined if both are undefined. Consider things
1426 // like undef&0. The result is known zero, not undef.
1427 UndefElts &= UndefElts2;
1430 case Instruction::Call: {
1431 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1433 switch (II->getIntrinsicID()) {
1436 // Binary vector operations that work column-wise. A dest element is a
1437 // function of the corresponding input elements from the two inputs.
1438 case Intrinsic::x86_sse_sub_ss:
1439 case Intrinsic::x86_sse_mul_ss:
1440 case Intrinsic::x86_sse_min_ss:
1441 case Intrinsic::x86_sse_max_ss:
1442 case Intrinsic::x86_sse2_sub_sd:
1443 case Intrinsic::x86_sse2_mul_sd:
1444 case Intrinsic::x86_sse2_min_sd:
1445 case Intrinsic::x86_sse2_max_sd:
1446 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1447 UndefElts, Depth+1);
1448 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1449 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1450 UndefElts2, Depth+1);
1451 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1453 // If only the low elt is demanded and this is a scalarizable intrinsic,
1454 // scalarize it now.
1455 if (DemandedElts == 1) {
1456 switch (II->getIntrinsicID()) {
1458 case Intrinsic::x86_sse_sub_ss:
1459 case Intrinsic::x86_sse_mul_ss:
1460 case Intrinsic::x86_sse2_sub_sd:
1461 case Intrinsic::x86_sse2_mul_sd:
1462 // TODO: Lower MIN/MAX/ABS/etc
1463 Value *LHS = II->getOperand(1);
1464 Value *RHS = II->getOperand(2);
1465 // Extract the element as scalars.
1466 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1467 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1469 switch (II->getIntrinsicID()) {
1470 default: assert(0 && "Case stmts out of sync!");
1471 case Intrinsic::x86_sse_sub_ss:
1472 case Intrinsic::x86_sse2_sub_sd:
1473 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1474 II->getName()), *II);
1476 case Intrinsic::x86_sse_mul_ss:
1477 case Intrinsic::x86_sse2_mul_sd:
1478 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1479 II->getName()), *II);
1484 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1486 InsertNewInstBefore(New, *II);
1487 AddSoonDeadInstToWorklist(*II, 0);
1492 // Output elements are undefined if both are undefined. Consider things
1493 // like undef&0. The result is known zero, not undef.
1494 UndefElts &= UndefElts2;
1500 return MadeChange ? I : 0;
1503 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1504 // true when both operands are equal...
1506 static bool isTrueWhenEqual(Instruction &I) {
1507 return I.getOpcode() == Instruction::SetEQ ||
1508 I.getOpcode() == Instruction::SetGE ||
1509 I.getOpcode() == Instruction::SetLE;
1512 /// AssociativeOpt - Perform an optimization on an associative operator. This
1513 /// function is designed to check a chain of associative operators for a
1514 /// potential to apply a certain optimization. Since the optimization may be
1515 /// applicable if the expression was reassociated, this checks the chain, then
1516 /// reassociates the expression as necessary to expose the optimization
1517 /// opportunity. This makes use of a special Functor, which must define
1518 /// 'shouldApply' and 'apply' methods.
1520 template<typename Functor>
1521 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1522 unsigned Opcode = Root.getOpcode();
1523 Value *LHS = Root.getOperand(0);
1525 // Quick check, see if the immediate LHS matches...
1526 if (F.shouldApply(LHS))
1527 return F.apply(Root);
1529 // Otherwise, if the LHS is not of the same opcode as the root, return.
1530 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1531 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1532 // Should we apply this transform to the RHS?
1533 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1535 // If not to the RHS, check to see if we should apply to the LHS...
1536 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1537 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1541 // If the functor wants to apply the optimization to the RHS of LHSI,
1542 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1544 BasicBlock *BB = Root.getParent();
1546 // Now all of the instructions are in the current basic block, go ahead
1547 // and perform the reassociation.
1548 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1550 // First move the selected RHS to the LHS of the root...
1551 Root.setOperand(0, LHSI->getOperand(1));
1553 // Make what used to be the LHS of the root be the user of the root...
1554 Value *ExtraOperand = TmpLHSI->getOperand(1);
1555 if (&Root == TmpLHSI) {
1556 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1559 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1560 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1561 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1562 BasicBlock::iterator ARI = &Root; ++ARI;
1563 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1566 // Now propagate the ExtraOperand down the chain of instructions until we
1568 while (TmpLHSI != LHSI) {
1569 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1570 // Move the instruction to immediately before the chain we are
1571 // constructing to avoid breaking dominance properties.
1572 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1573 BB->getInstList().insert(ARI, NextLHSI);
1576 Value *NextOp = NextLHSI->getOperand(1);
1577 NextLHSI->setOperand(1, ExtraOperand);
1579 ExtraOperand = NextOp;
1582 // Now that the instructions are reassociated, have the functor perform
1583 // the transformation...
1584 return F.apply(Root);
1587 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1593 // AddRHS - Implements: X + X --> X << 1
1596 AddRHS(Value *rhs) : RHS(rhs) {}
1597 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1598 Instruction *apply(BinaryOperator &Add) const {
1599 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1600 ConstantInt::get(Type::UByteTy, 1));
1604 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1606 struct AddMaskingAnd {
1608 AddMaskingAnd(Constant *c) : C2(c) {}
1609 bool shouldApply(Value *LHS) const {
1611 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1612 ConstantExpr::getAnd(C1, C2)->isNullValue();
1614 Instruction *apply(BinaryOperator &Add) const {
1615 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1619 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1621 if (isa<CastInst>(I)) {
1622 if (Constant *SOC = dyn_cast<Constant>(SO))
1623 return ConstantExpr::getCast(SOC, I.getType());
1625 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1626 SO->getName() + ".cast"), I);
1629 // Figure out if the constant is the left or the right argument.
1630 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1631 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1633 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1635 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1636 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1639 Value *Op0 = SO, *Op1 = ConstOperand;
1641 std::swap(Op0, Op1);
1643 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1644 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1645 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1646 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1648 assert(0 && "Unknown binary instruction type!");
1651 return IC->InsertNewInstBefore(New, I);
1654 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1655 // constant as the other operand, try to fold the binary operator into the
1656 // select arguments. This also works for Cast instructions, which obviously do
1657 // not have a second operand.
1658 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1660 // Don't modify shared select instructions
1661 if (!SI->hasOneUse()) return 0;
1662 Value *TV = SI->getOperand(1);
1663 Value *FV = SI->getOperand(2);
1665 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1666 // Bool selects with constant operands can be folded to logical ops.
1667 if (SI->getType() == Type::BoolTy) return 0;
1669 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1670 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1672 return new SelectInst(SI->getCondition(), SelectTrueVal,
1679 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1680 /// node as operand #0, see if we can fold the instruction into the PHI (which
1681 /// is only possible if all operands to the PHI are constants).
1682 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1683 PHINode *PN = cast<PHINode>(I.getOperand(0));
1684 unsigned NumPHIValues = PN->getNumIncomingValues();
1685 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1687 // Check to see if all of the operands of the PHI are constants. If there is
1688 // one non-constant value, remember the BB it is. If there is more than one
1690 BasicBlock *NonConstBB = 0;
1691 for (unsigned i = 0; i != NumPHIValues; ++i)
1692 if (!isa<Constant>(PN->getIncomingValue(i))) {
1693 if (NonConstBB) return 0; // More than one non-const value.
1694 NonConstBB = PN->getIncomingBlock(i);
1696 // If the incoming non-constant value is in I's block, we have an infinite
1698 if (NonConstBB == I.getParent())
1702 // If there is exactly one non-constant value, we can insert a copy of the
1703 // operation in that block. However, if this is a critical edge, we would be
1704 // inserting the computation one some other paths (e.g. inside a loop). Only
1705 // do this if the pred block is unconditionally branching into the phi block.
1707 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1708 if (!BI || !BI->isUnconditional()) return 0;
1711 // Okay, we can do the transformation: create the new PHI node.
1712 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1714 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1715 InsertNewInstBefore(NewPN, *PN);
1717 // Next, add all of the operands to the PHI.
1718 if (I.getNumOperands() == 2) {
1719 Constant *C = cast<Constant>(I.getOperand(1));
1720 for (unsigned i = 0; i != NumPHIValues; ++i) {
1722 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1723 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1725 assert(PN->getIncomingBlock(i) == NonConstBB);
1726 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1727 InV = BinaryOperator::create(BO->getOpcode(),
1728 PN->getIncomingValue(i), C, "phitmp",
1729 NonConstBB->getTerminator());
1730 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1731 InV = new ShiftInst(SI->getOpcode(),
1732 PN->getIncomingValue(i), C, "phitmp",
1733 NonConstBB->getTerminator());
1735 assert(0 && "Unknown binop!");
1737 WorkList.push_back(cast<Instruction>(InV));
1739 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1742 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1743 const Type *RetTy = I.getType();
1744 for (unsigned i = 0; i != NumPHIValues; ++i) {
1746 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1747 InV = ConstantExpr::getCast(InC, RetTy);
1749 assert(PN->getIncomingBlock(i) == NonConstBB);
1750 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1751 NonConstBB->getTerminator());
1752 WorkList.push_back(cast<Instruction>(InV));
1754 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1757 return ReplaceInstUsesWith(I, NewPN);
1760 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1761 bool Changed = SimplifyCommutative(I);
1762 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1764 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1765 // X + undef -> undef
1766 if (isa<UndefValue>(RHS))
1767 return ReplaceInstUsesWith(I, RHS);
1770 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1771 if (RHSC->isNullValue())
1772 return ReplaceInstUsesWith(I, LHS);
1773 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1774 if (CFP->isExactlyValue(-0.0))
1775 return ReplaceInstUsesWith(I, LHS);
1778 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1779 // X + (signbit) --> X ^ signbit
1780 uint64_t Val = CI->getZExtValue();
1781 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1782 return BinaryOperator::createXor(LHS, RHS);
1784 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1785 // (X & 254)+1 -> (X&254)|1
1786 uint64_t KnownZero, KnownOne;
1787 if (!isa<PackedType>(I.getType()) &&
1788 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1789 KnownZero, KnownOne))
1793 if (isa<PHINode>(LHS))
1794 if (Instruction *NV = FoldOpIntoPhi(I))
1797 ConstantInt *XorRHS = 0;
1799 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1800 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1801 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1802 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1804 uint64_t C0080Val = 1ULL << 31;
1805 int64_t CFF80Val = -C0080Val;
1808 if (TySizeBits > Size) {
1810 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1811 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1812 if (RHSSExt == CFF80Val) {
1813 if (XorRHS->getZExtValue() == C0080Val)
1815 } else if (RHSZExt == C0080Val) {
1816 if (XorRHS->getSExtValue() == CFF80Val)
1820 // This is a sign extend if the top bits are known zero.
1821 uint64_t Mask = ~0ULL;
1822 Mask <<= 64-(TySizeBits-Size);
1823 Mask &= XorLHS->getType()->getIntegralTypeMask();
1824 if (!MaskedValueIsZero(XorLHS, Mask))
1825 Size = 0; // Not a sign ext, but can't be any others either.
1832 } while (Size >= 8);
1835 const Type *MiddleType = 0;
1838 case 32: MiddleType = Type::IntTy; break;
1839 case 16: MiddleType = Type::ShortTy; break;
1840 case 8: MiddleType = Type::SByteTy; break;
1843 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1844 InsertNewInstBefore(NewTrunc, I);
1845 return new CastInst(NewTrunc, I.getType());
1851 if (I.getType()->isInteger()) {
1852 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1854 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1855 if (RHSI->getOpcode() == Instruction::Sub)
1856 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1857 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1859 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1860 if (LHSI->getOpcode() == Instruction::Sub)
1861 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1862 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1867 if (Value *V = dyn_castNegVal(LHS))
1868 return BinaryOperator::createSub(RHS, V);
1871 if (!isa<Constant>(RHS))
1872 if (Value *V = dyn_castNegVal(RHS))
1873 return BinaryOperator::createSub(LHS, V);
1877 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1878 if (X == RHS) // X*C + X --> X * (C+1)
1879 return BinaryOperator::createMul(RHS, AddOne(C2));
1881 // X*C1 + X*C2 --> X * (C1+C2)
1883 if (X == dyn_castFoldableMul(RHS, C1))
1884 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1887 // X + X*C --> X * (C+1)
1888 if (dyn_castFoldableMul(RHS, C2) == LHS)
1889 return BinaryOperator::createMul(LHS, AddOne(C2));
1892 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1893 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1894 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1896 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1898 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1899 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1900 return BinaryOperator::createSub(C, X);
1903 // (X & FF00) + xx00 -> (X+xx00) & FF00
1904 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1905 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1906 if (Anded == CRHS) {
1907 // See if all bits from the first bit set in the Add RHS up are included
1908 // in the mask. First, get the rightmost bit.
1909 uint64_t AddRHSV = CRHS->getZExtValue();
1911 // Form a mask of all bits from the lowest bit added through the top.
1912 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1913 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1915 // See if the and mask includes all of these bits.
1916 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1918 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1919 // Okay, the xform is safe. Insert the new add pronto.
1920 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1921 LHS->getName()), I);
1922 return BinaryOperator::createAnd(NewAdd, C2);
1927 // Try to fold constant add into select arguments.
1928 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1929 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1933 // add (cast *A to intptrtype) B ->
1934 // cast (GEP (cast *A to sbyte*) B) ->
1937 CastInst* CI = dyn_cast<CastInst>(LHS);
1940 CI = dyn_cast<CastInst>(RHS);
1943 if (CI && CI->getType()->isSized() &&
1944 (CI->getType()->getPrimitiveSize() ==
1945 TD->getIntPtrType()->getPrimitiveSize())
1946 && isa<PointerType>(CI->getOperand(0)->getType())) {
1947 Value* I2 = InsertCastBefore(CI->getOperand(0),
1948 PointerType::get(Type::SByteTy), I);
1949 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1950 return new CastInst(I2, CI->getType());
1954 return Changed ? &I : 0;
1957 // isSignBit - Return true if the value represented by the constant only has the
1958 // highest order bit set.
1959 static bool isSignBit(ConstantInt *CI) {
1960 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1961 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1964 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1966 static Value *RemoveNoopCast(Value *V) {
1967 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1968 const Type *CTy = CI->getType();
1969 const Type *OpTy = CI->getOperand(0)->getType();
1970 if (CTy->isInteger() && OpTy->isInteger()) {
1971 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1972 return RemoveNoopCast(CI->getOperand(0));
1973 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1974 return RemoveNoopCast(CI->getOperand(0));
1979 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1980 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1982 if (Op0 == Op1) // sub X, X -> 0
1983 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1985 // If this is a 'B = x-(-A)', change to B = x+A...
1986 if (Value *V = dyn_castNegVal(Op1))
1987 return BinaryOperator::createAdd(Op0, V);
1989 if (isa<UndefValue>(Op0))
1990 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1991 if (isa<UndefValue>(Op1))
1992 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1994 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1995 // Replace (-1 - A) with (~A)...
1996 if (C->isAllOnesValue())
1997 return BinaryOperator::createNot(Op1);
1999 // C - ~X == X + (1+C)
2001 if (match(Op1, m_Not(m_Value(X))))
2002 return BinaryOperator::createAdd(X,
2003 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
2004 // -((uint)X >> 31) -> ((int)X >> 31)
2005 // -((int)X >> 31) -> ((uint)X >> 31)
2006 if (C->isNullValue()) {
2007 Value *NoopCastedRHS = RemoveNoopCast(Op1);
2008 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
2009 if (SI->getOpcode() == Instruction::LShr) {
2010 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2011 // Check to see if we are shifting out everything but the sign bit.
2012 if (CU->getZExtValue() ==
2013 SI->getType()->getPrimitiveSizeInBits()-1) {
2014 // Ok, the transformation is safe. Insert AShr.
2015 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
2020 else if (SI->getOpcode() == Instruction::AShr) {
2021 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2022 // Check to see if we are shifting out everything but the sign bit.
2023 if (CU->getZExtValue() ==
2024 SI->getType()->getPrimitiveSizeInBits()-1) {
2025 // Ok, the transformation is safe. Insert LShr.
2026 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
2033 // Try to fold constant sub into select arguments.
2034 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2035 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2038 if (isa<PHINode>(Op0))
2039 if (Instruction *NV = FoldOpIntoPhi(I))
2043 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2044 if (Op1I->getOpcode() == Instruction::Add &&
2045 !Op0->getType()->isFloatingPoint()) {
2046 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2047 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2048 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2049 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2050 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2051 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2052 // C1-(X+C2) --> (C1-C2)-X
2053 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2054 Op1I->getOperand(0));
2058 if (Op1I->hasOneUse()) {
2059 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2060 // is not used by anyone else...
2062 if (Op1I->getOpcode() == Instruction::Sub &&
2063 !Op1I->getType()->isFloatingPoint()) {
2064 // Swap the two operands of the subexpr...
2065 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2066 Op1I->setOperand(0, IIOp1);
2067 Op1I->setOperand(1, IIOp0);
2069 // Create the new top level add instruction...
2070 return BinaryOperator::createAdd(Op0, Op1);
2073 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2075 if (Op1I->getOpcode() == Instruction::And &&
2076 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2077 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2080 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2081 return BinaryOperator::createAnd(Op0, NewNot);
2084 // 0 - (X sdiv C) -> (X sdiv -C)
2085 if (Op1I->getOpcode() == Instruction::SDiv)
2086 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2087 if (CSI->isNullValue())
2088 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2089 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2090 ConstantExpr::getNeg(DivRHS));
2092 // X - X*C --> X * (1-C)
2093 ConstantInt *C2 = 0;
2094 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2096 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2097 return BinaryOperator::createMul(Op0, CP1);
2102 if (!Op0->getType()->isFloatingPoint())
2103 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2104 if (Op0I->getOpcode() == Instruction::Add) {
2105 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2106 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2107 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2108 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2109 } else if (Op0I->getOpcode() == Instruction::Sub) {
2110 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2111 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2115 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2116 if (X == Op1) { // X*C - X --> X * (C-1)
2117 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2118 return BinaryOperator::createMul(Op1, CP1);
2121 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2122 if (X == dyn_castFoldableMul(Op1, C2))
2123 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2128 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2129 /// really just returns true if the most significant (sign) bit is set.
2130 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2131 if (RHS->getType()->isSigned()) {
2132 // True if source is LHS < 0 or LHS <= -1
2133 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2134 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2136 ConstantInt *RHSC = cast<ConstantInt>(RHS);
2137 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2138 // the size of the integer type.
2139 if (Opcode == Instruction::SetGE)
2140 return RHSC->getZExtValue() ==
2141 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
2142 if (Opcode == Instruction::SetGT)
2143 return RHSC->getZExtValue() ==
2144 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2149 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2150 bool Changed = SimplifyCommutative(I);
2151 Value *Op0 = I.getOperand(0);
2153 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2154 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2156 // Simplify mul instructions with a constant RHS...
2157 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2158 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2160 // ((X << C1)*C2) == (X * (C2 << C1))
2161 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2162 if (SI->getOpcode() == Instruction::Shl)
2163 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2164 return BinaryOperator::createMul(SI->getOperand(0),
2165 ConstantExpr::getShl(CI, ShOp));
2167 if (CI->isNullValue())
2168 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2169 if (CI->equalsInt(1)) // X * 1 == X
2170 return ReplaceInstUsesWith(I, Op0);
2171 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2172 return BinaryOperator::createNeg(Op0, I.getName());
2174 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2175 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2176 uint64_t C = Log2_64(Val);
2177 return new ShiftInst(Instruction::Shl, Op0,
2178 ConstantInt::get(Type::UByteTy, C));
2180 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2181 if (Op1F->isNullValue())
2182 return ReplaceInstUsesWith(I, Op1);
2184 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2185 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2186 if (Op1F->getValue() == 1.0)
2187 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2190 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2191 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2192 isa<ConstantInt>(Op0I->getOperand(1))) {
2193 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2194 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2196 InsertNewInstBefore(Add, I);
2197 Value *C1C2 = ConstantExpr::getMul(Op1,
2198 cast<Constant>(Op0I->getOperand(1)));
2199 return BinaryOperator::createAdd(Add, C1C2);
2203 // Try to fold constant mul into select arguments.
2204 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2205 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2208 if (isa<PHINode>(Op0))
2209 if (Instruction *NV = FoldOpIntoPhi(I))
2213 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2214 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2215 return BinaryOperator::createMul(Op0v, Op1v);
2217 // If one of the operands of the multiply is a cast from a boolean value, then
2218 // we know the bool is either zero or one, so this is a 'masking' multiply.
2219 // See if we can simplify things based on how the boolean was originally
2221 CastInst *BoolCast = 0;
2222 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2223 if (CI->getOperand(0)->getType() == Type::BoolTy)
2226 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2227 if (CI->getOperand(0)->getType() == Type::BoolTy)
2230 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2231 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2232 const Type *SCOpTy = SCIOp0->getType();
2234 // If the setcc is true iff the sign bit of X is set, then convert this
2235 // multiply into a shift/and combination.
2236 if (isa<ConstantInt>(SCIOp1) &&
2237 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
2238 // Shift the X value right to turn it into "all signbits".
2239 Constant *Amt = ConstantInt::get(Type::UByteTy,
2240 SCOpTy->getPrimitiveSizeInBits()-1);
2241 if (SCIOp0->getType()->isUnsigned()) {
2242 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
2243 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
2247 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2248 BoolCast->getOperand(0)->getName()+
2251 // If the multiply type is not the same as the source type, sign extend
2252 // or truncate to the multiply type.
2253 if (I.getType() != V->getType())
2254 V = InsertCastBefore(V, I.getType(), I);
2256 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2257 return BinaryOperator::createAnd(V, OtherOp);
2262 return Changed ? &I : 0;
2265 /// This function implements the transforms on div instructions that work
2266 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2267 /// used by the visitors to those instructions.
2268 /// @brief Transforms common to all three div instructions
2269 Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
2270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2273 if (isa<UndefValue>(Op0))
2274 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2276 // X / undef -> undef
2277 if (isa<UndefValue>(Op1))
2278 return ReplaceInstUsesWith(I, Op1);
2280 // Handle cases involving: div X, (select Cond, Y, Z)
2281 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2282 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2283 // same basic block, then we replace the select with Y, and the condition
2284 // of the select with false (if the cond value is in the same BB). If the
2285 // select has uses other than the div, this allows them to be simplified
2286 // also. Note that div X, Y is just as good as div X, 0 (undef)
2287 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2288 if (ST->isNullValue()) {
2289 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2290 if (CondI && CondI->getParent() == I.getParent())
2291 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2292 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2293 I.setOperand(1, SI->getOperand(2));
2295 UpdateValueUsesWith(SI, SI->getOperand(2));
2299 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2300 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2301 if (ST->isNullValue()) {
2302 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2303 if (CondI && CondI->getParent() == I.getParent())
2304 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2305 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2306 I.setOperand(1, SI->getOperand(1));
2308 UpdateValueUsesWith(SI, SI->getOperand(1));
2316 /// This function implements the transforms common to both integer division
2317 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2318 /// division instructions.
2319 /// @brief Common integer divide transforms
2320 Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2321 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2323 if (Instruction *Common = commonDivTransforms(I))
2326 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2328 if (RHS->equalsInt(1))
2329 return ReplaceInstUsesWith(I, Op0);
2331 // (X / C1) / C2 -> X / (C1*C2)
2332 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2333 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2334 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2335 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2336 ConstantExpr::getMul(RHS, LHSRHS));
2339 if (!RHS->isNullValue()) { // avoid X udiv 0
2340 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2341 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2343 if (isa<PHINode>(Op0))
2344 if (Instruction *NV = FoldOpIntoPhi(I))
2349 // 0 / X == 0, we don't need to preserve faults!
2350 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2351 if (LHS->equalsInt(0))
2352 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2357 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2358 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2360 // Handle the integer div common cases
2361 if (Instruction *Common = commonIDivTransforms(I))
2364 // X udiv C^2 -> X >> C
2365 // Check to see if this is an unsigned division with an exact power of 2,
2366 // if so, convert to a right shift.
2367 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2368 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2369 if (isPowerOf2_64(Val)) {
2370 uint64_t ShiftAmt = Log2_64(Val);
2371 return new ShiftInst(Instruction::LShr, Op0,
2372 ConstantInt::get(Type::UByteTy, ShiftAmt));
2376 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2377 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2378 if (RHSI->getOpcode() == Instruction::Shl &&
2379 isa<ConstantInt>(RHSI->getOperand(0))) {
2380 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2381 if (isPowerOf2_64(C1)) {
2382 Value *N = RHSI->getOperand(1);
2383 const Type* NTy = N->getType();
2384 if (uint64_t C2 = Log2_64(C1)) {
2385 Constant *C2V = ConstantInt::get(NTy, C2);
2386 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2388 return new ShiftInst(Instruction::LShr, Op0, N);
2393 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2394 // where C1&C2 are powers of two.
2395 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2396 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2397 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2398 if (!STO->isNullValue() && !STO->isNullValue()) {
2399 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2400 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2401 // Compute the shift amounts
2402 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2403 // Construct the "on true" case of the select
2404 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2406 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2407 TSI = InsertNewInstBefore(TSI, I);
2409 // Construct the "on false" case of the select
2410 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2412 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2413 FSI = InsertNewInstBefore(FSI, I);
2415 // construct the select instruction and return it.
2416 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2423 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2424 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2426 // Handle the integer div common cases
2427 if (Instruction *Common = commonIDivTransforms(I))
2430 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2432 if (RHS->isAllOnesValue())
2433 return BinaryOperator::createNeg(Op0);
2436 if (Value *LHSNeg = dyn_castNegVal(Op0))
2437 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2440 // If the sign bits of both operands are zero (i.e. we can prove they are
2441 // unsigned inputs), turn this into a udiv.
2442 if (I.getType()->isInteger()) {
2443 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2444 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2445 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2452 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2453 return commonDivTransforms(I);
2456 /// GetFactor - If we can prove that the specified value is at least a multiple
2457 /// of some factor, return that factor.
2458 static Constant *GetFactor(Value *V) {
2459 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2462 // Unless we can be tricky, we know this is a multiple of 1.
2463 Constant *Result = ConstantInt::get(V->getType(), 1);
2465 Instruction *I = dyn_cast<Instruction>(V);
2466 if (!I) return Result;
2468 if (I->getOpcode() == Instruction::Mul) {
2469 // Handle multiplies by a constant, etc.
2470 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2471 GetFactor(I->getOperand(1)));
2472 } else if (I->getOpcode() == Instruction::Shl) {
2473 // (X<<C) -> X * (1 << C)
2474 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2475 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2476 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2478 } else if (I->getOpcode() == Instruction::And) {
2479 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2480 // X & 0xFFF0 is known to be a multiple of 16.
2481 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2482 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2483 return ConstantExpr::getShl(Result,
2484 ConstantInt::get(Type::UByteTy, Zeros));
2486 } else if (I->getOpcode() == Instruction::Cast) {
2487 Value *Op = I->getOperand(0);
2488 // Only handle int->int casts.
2489 if (!Op->getType()->isInteger()) return Result;
2490 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2495 /// This function implements the transforms on rem instructions that work
2496 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2497 /// is used by the visitors to those instructions.
2498 /// @brief Transforms common to all three rem instructions
2499 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2500 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2502 // 0 % X == 0, we don't need to preserve faults!
2503 if (Constant *LHS = dyn_cast<Constant>(Op0))
2504 if (LHS->isNullValue())
2505 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2507 if (isa<UndefValue>(Op0)) // undef % X -> 0
2508 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2509 if (isa<UndefValue>(Op1))
2510 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2512 // Handle cases involving: rem X, (select Cond, Y, Z)
2513 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2514 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2515 // the same basic block, then we replace the select with Y, and the
2516 // condition of the select with false (if the cond value is in the same
2517 // BB). If the select has uses other than the div, this allows them to be
2519 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2520 if (ST->isNullValue()) {
2521 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2522 if (CondI && CondI->getParent() == I.getParent())
2523 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2524 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2525 I.setOperand(1, SI->getOperand(2));
2527 UpdateValueUsesWith(SI, SI->getOperand(2));
2530 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2531 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2532 if (ST->isNullValue()) {
2533 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2534 if (CondI && CondI->getParent() == I.getParent())
2535 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2536 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2537 I.setOperand(1, SI->getOperand(1));
2539 UpdateValueUsesWith(SI, SI->getOperand(1));
2547 /// This function implements the transforms common to both integer remainder
2548 /// instructions (urem and srem). It is called by the visitors to those integer
2549 /// remainder instructions.
2550 /// @brief Common integer remainder transforms
2551 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2552 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2554 if (Instruction *common = commonRemTransforms(I))
2557 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2558 // X % 0 == undef, we don't need to preserve faults!
2559 if (RHS->equalsInt(0))
2560 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2562 if (RHS->equalsInt(1)) // X % 1 == 0
2563 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2565 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2566 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2567 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2569 } else if (isa<PHINode>(Op0I)) {
2570 if (Instruction *NV = FoldOpIntoPhi(I))
2573 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2574 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2575 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2582 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2583 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2585 if (Instruction *common = commonIRemTransforms(I))
2588 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2589 // X urem C^2 -> X and C
2590 // Check to see if this is an unsigned remainder with an exact power of 2,
2591 // if so, convert to a bitwise and.
2592 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2593 if (isPowerOf2_64(C->getZExtValue()))
2594 return BinaryOperator::createAnd(Op0, SubOne(C));
2597 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2598 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2599 if (RHSI->getOpcode() == Instruction::Shl &&
2600 isa<ConstantInt>(RHSI->getOperand(0))) {
2601 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2602 if (isPowerOf2_64(C1)) {
2603 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2604 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2606 return BinaryOperator::createAnd(Op0, Add);
2611 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2612 // where C1&C2 are powers of two.
2613 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2614 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2615 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2616 // STO == 0 and SFO == 0 handled above.
2617 if (isPowerOf2_64(STO->getZExtValue()) &&
2618 isPowerOf2_64(SFO->getZExtValue())) {
2619 Value *TrueAnd = InsertNewInstBefore(
2620 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2621 Value *FalseAnd = InsertNewInstBefore(
2622 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2623 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2631 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2632 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2634 if (Instruction *common = commonIRemTransforms(I))
2637 if (Value *RHSNeg = dyn_castNegVal(Op1))
2638 if (!isa<ConstantInt>(RHSNeg) ||
2639 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2641 AddUsesToWorkList(I);
2642 I.setOperand(1, RHSNeg);
2646 // If the top bits of both operands are zero (i.e. we can prove they are
2647 // unsigned inputs), turn this into a urem.
2648 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2649 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2650 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2651 return BinaryOperator::createURem(Op0, Op1, I.getName());
2657 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2658 return commonRemTransforms(I);
2661 // isMaxValueMinusOne - return true if this is Max-1
2662 static bool isMaxValueMinusOne(const ConstantInt *C) {
2663 if (C->getType()->isUnsigned())
2664 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2666 // Calculate 0111111111..11111
2667 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2668 int64_t Val = INT64_MAX; // All ones
2669 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2670 return C->getSExtValue() == Val-1;
2673 // isMinValuePlusOne - return true if this is Min+1
2674 static bool isMinValuePlusOne(const ConstantInt *C) {
2675 if (C->getType()->isUnsigned())
2676 return C->getZExtValue() == 1;
2678 // Calculate 1111111111000000000000
2679 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2680 int64_t Val = -1; // All ones
2681 Val <<= TypeBits-1; // Shift over to the right spot
2682 return C->getSExtValue() == Val+1;
2685 // isOneBitSet - Return true if there is exactly one bit set in the specified
2687 static bool isOneBitSet(const ConstantInt *CI) {
2688 uint64_t V = CI->getZExtValue();
2689 return V && (V & (V-1)) == 0;
2692 #if 0 // Currently unused
2693 // isLowOnes - Return true if the constant is of the form 0+1+.
2694 static bool isLowOnes(const ConstantInt *CI) {
2695 uint64_t V = CI->getZExtValue();
2697 // There won't be bits set in parts that the type doesn't contain.
2698 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2700 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2701 return U && V && (U & V) == 0;
2705 // isHighOnes - Return true if the constant is of the form 1+0+.
2706 // This is the same as lowones(~X).
2707 static bool isHighOnes(const ConstantInt *CI) {
2708 uint64_t V = ~CI->getZExtValue();
2709 if (~V == 0) return false; // 0's does not match "1+"
2711 // There won't be bits set in parts that the type doesn't contain.
2712 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2714 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2715 return U && V && (U & V) == 0;
2719 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2720 /// are carefully arranged to allow folding of expressions such as:
2722 /// (A < B) | (A > B) --> (A != B)
2724 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2725 /// represents that the comparison is true if A == B, and bit value '1' is true
2728 static unsigned getSetCondCode(const SetCondInst *SCI) {
2729 switch (SCI->getOpcode()) {
2731 case Instruction::SetGT: return 1;
2732 case Instruction::SetEQ: return 2;
2733 case Instruction::SetGE: return 3;
2734 case Instruction::SetLT: return 4;
2735 case Instruction::SetNE: return 5;
2736 case Instruction::SetLE: return 6;
2739 assert(0 && "Invalid SetCC opcode!");
2744 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2745 /// opcode and two operands into either a constant true or false, or a brand new
2746 /// SetCC instruction.
2747 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2749 case 0: return ConstantBool::getFalse();
2750 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2751 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2752 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2753 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2754 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2755 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2756 case 7: return ConstantBool::getTrue();
2757 default: assert(0 && "Illegal SetCCCode!"); return 0;
2761 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2763 struct FoldSetCCLogical {
2766 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2767 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2768 bool shouldApply(Value *V) const {
2769 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2770 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2771 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2774 Instruction *apply(BinaryOperator &Log) const {
2775 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2776 if (SCI->getOperand(0) != LHS) {
2777 assert(SCI->getOperand(1) == LHS);
2778 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2781 unsigned LHSCode = getSetCondCode(SCI);
2782 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2784 switch (Log.getOpcode()) {
2785 case Instruction::And: Code = LHSCode & RHSCode; break;
2786 case Instruction::Or: Code = LHSCode | RHSCode; break;
2787 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2788 default: assert(0 && "Illegal logical opcode!"); return 0;
2791 Value *RV = getSetCCValue(Code, LHS, RHS);
2792 if (Instruction *I = dyn_cast<Instruction>(RV))
2794 // Otherwise, it's a constant boolean value...
2795 return IC.ReplaceInstUsesWith(Log, RV);
2798 } // end anonymous namespace
2800 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2801 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2802 // guaranteed to be either a shift instruction or a binary operator.
2803 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2804 ConstantIntegral *OpRHS,
2805 ConstantIntegral *AndRHS,
2806 BinaryOperator &TheAnd) {
2807 Value *X = Op->getOperand(0);
2808 Constant *Together = 0;
2809 if (!isa<ShiftInst>(Op))
2810 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2812 switch (Op->getOpcode()) {
2813 case Instruction::Xor:
2814 if (Op->hasOneUse()) {
2815 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2816 std::string OpName = Op->getName(); Op->setName("");
2817 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2818 InsertNewInstBefore(And, TheAnd);
2819 return BinaryOperator::createXor(And, Together);
2822 case Instruction::Or:
2823 if (Together == AndRHS) // (X | C) & C --> C
2824 return ReplaceInstUsesWith(TheAnd, AndRHS);
2826 if (Op->hasOneUse() && Together != OpRHS) {
2827 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2828 std::string Op0Name = Op->getName(); Op->setName("");
2829 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2830 InsertNewInstBefore(Or, TheAnd);
2831 return BinaryOperator::createAnd(Or, AndRHS);
2834 case Instruction::Add:
2835 if (Op->hasOneUse()) {
2836 // Adding a one to a single bit bit-field should be turned into an XOR
2837 // of the bit. First thing to check is to see if this AND is with a
2838 // single bit constant.
2839 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2841 // Clear bits that are not part of the constant.
2842 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2844 // If there is only one bit set...
2845 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2846 // Ok, at this point, we know that we are masking the result of the
2847 // ADD down to exactly one bit. If the constant we are adding has
2848 // no bits set below this bit, then we can eliminate the ADD.
2849 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2851 // Check to see if any bits below the one bit set in AndRHSV are set.
2852 if ((AddRHS & (AndRHSV-1)) == 0) {
2853 // If not, the only thing that can effect the output of the AND is
2854 // the bit specified by AndRHSV. If that bit is set, the effect of
2855 // the XOR is to toggle the bit. If it is clear, then the ADD has
2857 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2858 TheAnd.setOperand(0, X);
2861 std::string Name = Op->getName(); Op->setName("");
2862 // Pull the XOR out of the AND.
2863 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2864 InsertNewInstBefore(NewAnd, TheAnd);
2865 return BinaryOperator::createXor(NewAnd, AndRHS);
2872 case Instruction::Shl: {
2873 // We know that the AND will not produce any of the bits shifted in, so if
2874 // the anded constant includes them, clear them now!
2876 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2877 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2878 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2880 if (CI == ShlMask) { // Masking out bits that the shift already masks
2881 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2882 } else if (CI != AndRHS) { // Reducing bits set in and.
2883 TheAnd.setOperand(1, CI);
2888 case Instruction::LShr:
2890 // We know that the AND will not produce any of the bits shifted in, so if
2891 // the anded constant includes them, clear them now! This only applies to
2892 // unsigned shifts, because a signed shr may bring in set bits!
2894 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2895 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2896 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2898 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2899 return ReplaceInstUsesWith(TheAnd, Op);
2900 } else if (CI != AndRHS) {
2901 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2906 case Instruction::AShr:
2908 // See if this is shifting in some sign extension, then masking it out
2910 if (Op->hasOneUse()) {
2911 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2912 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2913 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2914 if (CI == AndRHS) { // Masking out bits shifted in.
2915 // Make the argument unsigned.
2916 Value *ShVal = Op->getOperand(0);
2917 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2918 OpRHS, Op->getName()),
2920 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2921 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
2930 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2931 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2932 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2933 /// insert new instructions.
2934 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2935 bool Inside, Instruction &IB) {
2936 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2937 "Lo is not <= Hi in range emission code!");
2939 if (Lo == Hi) // Trivially false.
2940 return new SetCondInst(Instruction::SetNE, V, V);
2941 if (cast<ConstantIntegral>(Lo)->isMinValue())
2942 return new SetCondInst(Instruction::SetLT, V, Hi);
2944 Constant *AddCST = ConstantExpr::getNeg(Lo);
2945 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2946 InsertNewInstBefore(Add, IB);
2947 // Convert to unsigned for the comparison.
2948 const Type *UnsType = Add->getType()->getUnsignedVersion();
2949 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2950 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2951 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2952 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2955 if (Lo == Hi) // Trivially true.
2956 return new SetCondInst(Instruction::SetEQ, V, V);
2958 Hi = SubOne(cast<ConstantInt>(Hi));
2960 // V < 0 || V >= Hi ->'V > Hi-1'
2961 if (cast<ConstantIntegral>(Lo)->isMinValue())
2962 return new SetCondInst(Instruction::SetGT, V, Hi);
2964 // Emit X-Lo > Hi-Lo-1
2965 Constant *AddCST = ConstantExpr::getNeg(Lo);
2966 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2967 InsertNewInstBefore(Add, IB);
2968 // Convert to unsigned for the comparison.
2969 const Type *UnsType = Add->getType()->getUnsignedVersion();
2970 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2971 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2972 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2973 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2976 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2977 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2978 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2979 // not, since all 1s are not contiguous.
2980 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2981 uint64_t V = Val->getZExtValue();
2982 if (!isShiftedMask_64(V)) return false;
2984 // look for the first zero bit after the run of ones
2985 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2986 // look for the first non-zero bit
2987 ME = 64-CountLeadingZeros_64(V);
2993 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2994 /// where isSub determines whether the operator is a sub. If we can fold one of
2995 /// the following xforms:
2997 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2998 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2999 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3001 /// return (A +/- B).
3003 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3004 ConstantIntegral *Mask, bool isSub,
3006 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3007 if (!LHSI || LHSI->getNumOperands() != 2 ||
3008 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3010 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3012 switch (LHSI->getOpcode()) {
3014 case Instruction::And:
3015 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3016 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3017 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3020 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3021 // part, we don't need any explicit masks to take them out of A. If that
3022 // is all N is, ignore it.
3024 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3025 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3027 if (MaskedValueIsZero(RHS, Mask))
3032 case Instruction::Or:
3033 case Instruction::Xor:
3034 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3035 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3036 ConstantExpr::getAnd(N, Mask)->isNullValue())
3043 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3045 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3046 return InsertNewInstBefore(New, I);
3049 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3050 bool Changed = SimplifyCommutative(I);
3051 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3053 if (isa<UndefValue>(Op1)) // X & undef -> 0
3054 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3058 return ReplaceInstUsesWith(I, Op1);
3060 // See if we can simplify any instructions used by the instruction whose sole
3061 // purpose is to compute bits we don't care about.
3062 uint64_t KnownZero, KnownOne;
3063 if (!isa<PackedType>(I.getType()) &&
3064 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3065 KnownZero, KnownOne))
3068 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
3069 uint64_t AndRHSMask = AndRHS->getZExtValue();
3070 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
3071 uint64_t NotAndRHS = AndRHSMask^TypeMask;
3073 // Optimize a variety of ((val OP C1) & C2) combinations...
3074 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3075 Instruction *Op0I = cast<Instruction>(Op0);
3076 Value *Op0LHS = Op0I->getOperand(0);
3077 Value *Op0RHS = Op0I->getOperand(1);
3078 switch (Op0I->getOpcode()) {
3079 case Instruction::Xor:
3080 case Instruction::Or:
3081 // If the mask is only needed on one incoming arm, push it up.
3082 if (Op0I->hasOneUse()) {
3083 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3084 // Not masking anything out for the LHS, move to RHS.
3085 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3086 Op0RHS->getName()+".masked");
3087 InsertNewInstBefore(NewRHS, I);
3088 return BinaryOperator::create(
3089 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3091 if (!isa<Constant>(Op0RHS) &&
3092 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3093 // Not masking anything out for the RHS, move to LHS.
3094 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3095 Op0LHS->getName()+".masked");
3096 InsertNewInstBefore(NewLHS, I);
3097 return BinaryOperator::create(
3098 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3103 case Instruction::Add:
3104 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3105 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3106 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3107 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3108 return BinaryOperator::createAnd(V, AndRHS);
3109 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3110 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3113 case Instruction::Sub:
3114 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3115 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3116 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3117 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3118 return BinaryOperator::createAnd(V, AndRHS);
3122 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3123 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3125 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3126 const Type *SrcTy = CI->getOperand(0)->getType();
3128 // If this is an integer truncation or change from signed-to-unsigned, and
3129 // if the source is an and/or with immediate, transform it. This
3130 // frequently occurs for bitfield accesses.
3131 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3132 if (SrcTy->getPrimitiveSizeInBits() >=
3133 I.getType()->getPrimitiveSizeInBits() &&
3134 CastOp->getNumOperands() == 2)
3135 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3136 if (CastOp->getOpcode() == Instruction::And) {
3137 // Change: and (cast (and X, C1) to T), C2
3138 // into : and (cast X to T), trunc(C1)&C2
3139 // This will folds the two ands together, which may allow other
3141 Instruction *NewCast =
3142 new CastInst(CastOp->getOperand(0), I.getType(),
3143 CastOp->getName()+".shrunk");
3144 NewCast = InsertNewInstBefore(NewCast, I);
3146 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3147 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
3148 return BinaryOperator::createAnd(NewCast, C3);
3149 } else if (CastOp->getOpcode() == Instruction::Or) {
3150 // Change: and (cast (or X, C1) to T), C2
3151 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3152 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3153 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3154 return ReplaceInstUsesWith(I, AndRHS);
3159 // Try to fold constant and into select arguments.
3160 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3161 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3163 if (isa<PHINode>(Op0))
3164 if (Instruction *NV = FoldOpIntoPhi(I))
3168 Value *Op0NotVal = dyn_castNotVal(Op0);
3169 Value *Op1NotVal = dyn_castNotVal(Op1);
3171 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3172 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3174 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3175 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3176 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3177 I.getName()+".demorgan");
3178 InsertNewInstBefore(Or, I);
3179 return BinaryOperator::createNot(Or);
3183 Value *A = 0, *B = 0;
3184 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3185 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3186 return ReplaceInstUsesWith(I, Op1);
3187 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3188 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3189 return ReplaceInstUsesWith(I, Op0);
3191 if (Op0->hasOneUse() &&
3192 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3193 if (A == Op1) { // (A^B)&A -> A&(A^B)
3194 I.swapOperands(); // Simplify below
3195 std::swap(Op0, Op1);
3196 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3197 cast<BinaryOperator>(Op0)->swapOperands();
3198 I.swapOperands(); // Simplify below
3199 std::swap(Op0, Op1);
3202 if (Op1->hasOneUse() &&
3203 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3204 if (B == Op0) { // B&(A^B) -> B&(B^A)
3205 cast<BinaryOperator>(Op1)->swapOperands();
3208 if (A == Op0) { // A&(A^B) -> A & ~B
3209 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3210 InsertNewInstBefore(NotB, I);
3211 return BinaryOperator::createAnd(A, NotB);
3217 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3218 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
3219 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3222 Value *LHSVal, *RHSVal;
3223 ConstantInt *LHSCst, *RHSCst;
3224 Instruction::BinaryOps LHSCC, RHSCC;
3225 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3226 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3227 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3228 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3229 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3230 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3231 // Ensure that the larger constant is on the RHS.
3232 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3233 SetCondInst *LHS = cast<SetCondInst>(Op0);
3234 if (cast<ConstantBool>(Cmp)->getValue()) {
3235 std::swap(LHS, RHS);
3236 std::swap(LHSCst, RHSCst);
3237 std::swap(LHSCC, RHSCC);
3240 // At this point, we know we have have two setcc instructions
3241 // comparing a value against two constants and and'ing the result
3242 // together. Because of the above check, we know that we only have
3243 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3244 // FoldSetCCLogical check above), that the two constants are not
3246 assert(LHSCst != RHSCst && "Compares not folded above?");
3249 default: assert(0 && "Unknown integer condition code!");
3250 case Instruction::SetEQ:
3252 default: assert(0 && "Unknown integer condition code!");
3253 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3254 case Instruction::SetGT: // (X == 13 & X > 15) -> false
3255 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3256 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3257 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3258 return ReplaceInstUsesWith(I, LHS);
3260 case Instruction::SetNE:
3262 default: assert(0 && "Unknown integer condition code!");
3263 case Instruction::SetLT:
3264 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3265 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3266 break; // (X != 13 & X < 15) -> no change
3267 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3268 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3269 return ReplaceInstUsesWith(I, RHS);
3270 case Instruction::SetNE:
3271 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3272 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3273 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3274 LHSVal->getName()+".off");
3275 InsertNewInstBefore(Add, I);
3276 const Type *UnsType = Add->getType()->getUnsignedVersion();
3277 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3278 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3279 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3280 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3282 break; // (X != 13 & X != 15) -> no change
3285 case Instruction::SetLT:
3287 default: assert(0 && "Unknown integer condition code!");
3288 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3289 case Instruction::SetGT: // (X < 13 & X > 15) -> false
3290 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3291 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3292 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3293 return ReplaceInstUsesWith(I, LHS);
3295 case Instruction::SetGT:
3297 default: assert(0 && "Unknown integer condition code!");
3298 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3299 return ReplaceInstUsesWith(I, LHS);
3300 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3301 return ReplaceInstUsesWith(I, RHS);
3302 case Instruction::SetNE:
3303 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3304 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3305 break; // (X > 13 & X != 15) -> no change
3306 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3307 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
3313 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3314 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
3315 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3316 const Type *SrcTy = Op0C->getOperand(0)->getType();
3317 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3318 // Only do this if the casts both really cause code to be generated.
3319 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3320 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3321 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3322 Op1C->getOperand(0),
3324 InsertNewInstBefore(NewOp, I);
3325 return new CastInst(NewOp, I.getType());
3330 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3331 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3332 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3333 if (SI0->getOpcode() == SI1->getOpcode() &&
3334 SI0->getOperand(1) == SI1->getOperand(1) &&
3335 (SI0->hasOneUse() || SI1->hasOneUse())) {
3336 Instruction *NewOp =
3337 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3339 SI0->getName()), I);
3340 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3344 return Changed ? &I : 0;
3347 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3348 /// in the result. If it does, and if the specified byte hasn't been filled in
3349 /// yet, fill it in and return false.
3350 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3351 Instruction *I = dyn_cast<Instruction>(V);
3352 if (I == 0) return true;
3354 // If this is an or instruction, it is an inner node of the bswap.
3355 if (I->getOpcode() == Instruction::Or)
3356 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3357 CollectBSwapParts(I->getOperand(1), ByteValues);
3359 // If this is a shift by a constant int, and it is "24", then its operand
3360 // defines a byte. We only handle unsigned types here.
3361 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3362 // Not shifting the entire input by N-1 bytes?
3363 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3364 8*(ByteValues.size()-1))
3368 if (I->getOpcode() == Instruction::Shl) {
3369 // X << 24 defines the top byte with the lowest of the input bytes.
3370 DestNo = ByteValues.size()-1;
3372 // X >>u 24 defines the low byte with the highest of the input bytes.
3376 // If the destination byte value is already defined, the values are or'd
3377 // together, which isn't a bswap (unless it's an or of the same bits).
3378 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3380 ByteValues[DestNo] = I->getOperand(0);
3384 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3386 Value *Shift = 0, *ShiftLHS = 0;
3387 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3388 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3389 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3391 Instruction *SI = cast<Instruction>(Shift);
3393 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3394 if (ShiftAmt->getZExtValue() & 7 ||
3395 ShiftAmt->getZExtValue() > 8*ByteValues.size())
3398 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3400 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3401 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3403 // Unknown mask for bswap.
3404 if (DestByte == ByteValues.size()) return true;
3406 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3408 if (SI->getOpcode() == Instruction::Shl)
3409 SrcByte = DestByte - ShiftBytes;
3411 SrcByte = DestByte + ShiftBytes;
3413 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3414 if (SrcByte != ByteValues.size()-DestByte-1)
3417 // If the destination byte value is already defined, the values are or'd
3418 // together, which isn't a bswap (unless it's an or of the same bits).
3419 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3421 ByteValues[DestByte] = SI->getOperand(0);
3425 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3426 /// If so, insert the new bswap intrinsic and return it.
3427 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3428 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3429 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3432 /// ByteValues - For each byte of the result, we keep track of which value
3433 /// defines each byte.
3434 std::vector<Value*> ByteValues;
3435 ByteValues.resize(I.getType()->getPrimitiveSize());
3437 // Try to find all the pieces corresponding to the bswap.
3438 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3439 CollectBSwapParts(I.getOperand(1), ByteValues))
3442 // Check to see if all of the bytes come from the same value.
3443 Value *V = ByteValues[0];
3444 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3446 // Check to make sure that all of the bytes come from the same value.
3447 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3448 if (ByteValues[i] != V)
3451 // If they do then *success* we can turn this into a bswap. Figure out what
3452 // bswap to make it into.
3453 Module *M = I.getParent()->getParent()->getParent();
3454 const char *FnName = 0;
3455 if (I.getType() == Type::UShortTy)
3456 FnName = "llvm.bswap.i16";
3457 else if (I.getType() == Type::UIntTy)
3458 FnName = "llvm.bswap.i32";
3459 else if (I.getType() == Type::ULongTy)
3460 FnName = "llvm.bswap.i64";
3462 assert(0 && "Unknown integer type!");
3463 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3465 return new CallInst(F, V);
3469 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3470 bool Changed = SimplifyCommutative(I);
3471 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3473 if (isa<UndefValue>(Op1))
3474 return ReplaceInstUsesWith(I, // X | undef -> -1
3475 ConstantIntegral::getAllOnesValue(I.getType()));
3479 return ReplaceInstUsesWith(I, Op0);
3481 // See if we can simplify any instructions used by the instruction whose sole
3482 // purpose is to compute bits we don't care about.
3483 uint64_t KnownZero, KnownOne;
3484 if (!isa<PackedType>(I.getType()) &&
3485 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3486 KnownZero, KnownOne))
3490 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3491 ConstantInt *C1 = 0; Value *X = 0;
3492 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3493 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3494 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3496 InsertNewInstBefore(Or, I);
3497 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3500 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3501 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3502 std::string Op0Name = Op0->getName(); Op0->setName("");
3503 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3504 InsertNewInstBefore(Or, I);
3505 return BinaryOperator::createXor(Or,
3506 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3509 // Try to fold constant and into select arguments.
3510 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3511 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3513 if (isa<PHINode>(Op0))
3514 if (Instruction *NV = FoldOpIntoPhi(I))
3518 Value *A = 0, *B = 0;
3519 ConstantInt *C1 = 0, *C2 = 0;
3521 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3522 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3523 return ReplaceInstUsesWith(I, Op1);
3524 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3525 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3526 return ReplaceInstUsesWith(I, Op0);
3528 // (A | B) | C and A | (B | C) -> bswap if possible.
3529 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3530 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3531 match(Op1, m_Or(m_Value(), m_Value())) ||
3532 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3533 match(Op1, m_Shift(m_Value(), m_Value())))) {
3534 if (Instruction *BSwap = MatchBSwap(I))
3538 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3539 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3540 MaskedValueIsZero(Op1, C1->getZExtValue())) {
3541 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3543 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3546 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3547 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3548 MaskedValueIsZero(Op0, C1->getZExtValue())) {
3549 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3551 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3554 // (A & C1)|(B & C2)
3555 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3556 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3558 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3559 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3562 // If we have: ((V + N) & C1) | (V & C2)
3563 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3564 // replace with V+N.
3565 if (C1 == ConstantExpr::getNot(C2)) {
3566 Value *V1 = 0, *V2 = 0;
3567 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3568 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3569 // Add commutes, try both ways.
3570 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3571 return ReplaceInstUsesWith(I, A);
3572 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3573 return ReplaceInstUsesWith(I, A);
3575 // Or commutes, try both ways.
3576 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3577 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3578 // Add commutes, try both ways.
3579 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3580 return ReplaceInstUsesWith(I, B);
3581 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3582 return ReplaceInstUsesWith(I, B);
3587 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3588 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3589 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3590 if (SI0->getOpcode() == SI1->getOpcode() &&
3591 SI0->getOperand(1) == SI1->getOperand(1) &&
3592 (SI0->hasOneUse() || SI1->hasOneUse())) {
3593 Instruction *NewOp =
3594 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3596 SI0->getName()), I);
3597 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3601 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3602 if (A == Op1) // ~A | A == -1
3603 return ReplaceInstUsesWith(I,
3604 ConstantIntegral::getAllOnesValue(I.getType()));
3608 // Note, A is still live here!
3609 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3611 return ReplaceInstUsesWith(I,
3612 ConstantIntegral::getAllOnesValue(I.getType()));
3614 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3615 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3616 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3617 I.getName()+".demorgan"), I);
3618 return BinaryOperator::createNot(And);
3622 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3623 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3624 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3627 Value *LHSVal, *RHSVal;
3628 ConstantInt *LHSCst, *RHSCst;
3629 Instruction::BinaryOps LHSCC, RHSCC;
3630 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3631 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3632 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3633 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3634 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3635 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3636 // Ensure that the larger constant is on the RHS.
3637 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3638 SetCondInst *LHS = cast<SetCondInst>(Op0);
3639 if (cast<ConstantBool>(Cmp)->getValue()) {
3640 std::swap(LHS, RHS);
3641 std::swap(LHSCst, RHSCst);
3642 std::swap(LHSCC, RHSCC);
3645 // At this point, we know we have have two setcc instructions
3646 // comparing a value against two constants and or'ing the result
3647 // together. Because of the above check, we know that we only have
3648 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3649 // FoldSetCCLogical check above), that the two constants are not
3651 assert(LHSCst != RHSCst && "Compares not folded above?");
3654 default: assert(0 && "Unknown integer condition code!");
3655 case Instruction::SetEQ:
3657 default: assert(0 && "Unknown integer condition code!");
3658 case Instruction::SetEQ:
3659 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3660 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3661 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3662 LHSVal->getName()+".off");
3663 InsertNewInstBefore(Add, I);
3664 const Type *UnsType = Add->getType()->getUnsignedVersion();
3665 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3666 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3667 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3668 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3670 break; // (X == 13 | X == 15) -> no change
3672 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3674 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3675 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3676 return ReplaceInstUsesWith(I, RHS);
3679 case Instruction::SetNE:
3681 default: assert(0 && "Unknown integer condition code!");
3682 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3683 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3684 return ReplaceInstUsesWith(I, LHS);
3685 case Instruction::SetNE: // (X != 13 | X != 15) -> true
3686 case Instruction::SetLT: // (X != 13 | X < 15) -> true
3687 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3690 case Instruction::SetLT:
3692 default: assert(0 && "Unknown integer condition code!");
3693 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3695 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3696 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3697 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3698 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3699 return ReplaceInstUsesWith(I, RHS);
3702 case Instruction::SetGT:
3704 default: assert(0 && "Unknown integer condition code!");
3705 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3706 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3707 return ReplaceInstUsesWith(I, LHS);
3708 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3709 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3710 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3716 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3717 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3718 const Type *SrcTy = Op0C->getOperand(0)->getType();
3719 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3720 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3721 // Only do this if the casts both really cause code to be generated.
3722 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3723 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3724 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3725 Op1C->getOperand(0),
3727 InsertNewInstBefore(NewOp, I);
3728 return new CastInst(NewOp, I.getType());
3733 return Changed ? &I : 0;
3736 // XorSelf - Implements: X ^ X --> 0
3739 XorSelf(Value *rhs) : RHS(rhs) {}
3740 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3741 Instruction *apply(BinaryOperator &Xor) const {
3747 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3748 bool Changed = SimplifyCommutative(I);
3749 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3751 if (isa<UndefValue>(Op1))
3752 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3754 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3755 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3756 assert(Result == &I && "AssociativeOpt didn't work?");
3757 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3760 // See if we can simplify any instructions used by the instruction whose sole
3761 // purpose is to compute bits we don't care about.
3762 uint64_t KnownZero, KnownOne;
3763 if (!isa<PackedType>(I.getType()) &&
3764 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3765 KnownZero, KnownOne))
3768 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3769 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3770 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3771 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3772 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
3773 return new SetCondInst(SCI->getInverseCondition(),
3774 SCI->getOperand(0), SCI->getOperand(1));
3776 // ~(c-X) == X-c-1 == X+(-c-1)
3777 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3778 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3779 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3780 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3781 ConstantInt::get(I.getType(), 1));
3782 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3785 // ~(~X & Y) --> (X | ~Y)
3786 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3787 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3788 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3790 BinaryOperator::createNot(Op0I->getOperand(1),
3791 Op0I->getOperand(1)->getName()+".not");
3792 InsertNewInstBefore(NotY, I);
3793 return BinaryOperator::createOr(Op0NotVal, NotY);
3797 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3798 if (Op0I->getOpcode() == Instruction::Add) {
3799 // ~(X-c) --> (-c-1)-X
3800 if (RHS->isAllOnesValue()) {
3801 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3802 return BinaryOperator::createSub(
3803 ConstantExpr::getSub(NegOp0CI,
3804 ConstantInt::get(I.getType(), 1)),
3805 Op0I->getOperand(0));
3807 } else if (Op0I->getOpcode() == Instruction::Or) {
3808 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3809 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3810 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3811 // Anything in both C1 and C2 is known to be zero, remove it from
3813 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3814 NewRHS = ConstantExpr::getAnd(NewRHS,
3815 ConstantExpr::getNot(CommonBits));
3816 WorkList.push_back(Op0I);
3817 I.setOperand(0, Op0I->getOperand(0));
3818 I.setOperand(1, NewRHS);
3824 // Try to fold constant and into select arguments.
3825 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3826 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3828 if (isa<PHINode>(Op0))
3829 if (Instruction *NV = FoldOpIntoPhi(I))
3833 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
3835 return ReplaceInstUsesWith(I,
3836 ConstantIntegral::getAllOnesValue(I.getType()));
3838 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
3840 return ReplaceInstUsesWith(I,
3841 ConstantIntegral::getAllOnesValue(I.getType()));
3843 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3844 if (Op1I->getOpcode() == Instruction::Or) {
3845 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
3846 Op1I->swapOperands();
3848 std::swap(Op0, Op1);
3849 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
3850 I.swapOperands(); // Simplified below.
3851 std::swap(Op0, Op1);
3853 } else if (Op1I->getOpcode() == Instruction::Xor) {
3854 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3855 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3856 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3857 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3858 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3859 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3860 Op1I->swapOperands();
3861 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3862 I.swapOperands(); // Simplified below.
3863 std::swap(Op0, Op1);
3867 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3868 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3869 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3870 Op0I->swapOperands();
3871 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3872 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3873 InsertNewInstBefore(NotB, I);
3874 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3876 } else if (Op0I->getOpcode() == Instruction::Xor) {
3877 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3878 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3879 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3880 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3881 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3882 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3883 Op0I->swapOperands();
3884 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3885 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3886 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3887 InsertNewInstBefore(N, I);
3888 return BinaryOperator::createAnd(N, Op1);
3892 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3893 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3894 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3897 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3898 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3899 const Type *SrcTy = Op0C->getOperand(0)->getType();
3900 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3901 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3902 // Only do this if the casts both really cause code to be generated.
3903 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3904 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3905 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3906 Op1C->getOperand(0),
3908 InsertNewInstBefore(NewOp, I);
3909 return new CastInst(NewOp, I.getType());
3913 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3914 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3915 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3916 if (SI0->getOpcode() == SI1->getOpcode() &&
3917 SI0->getOperand(1) == SI1->getOperand(1) &&
3918 (SI0->hasOneUse() || SI1->hasOneUse())) {
3919 Instruction *NewOp =
3920 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3922 SI0->getName()), I);
3923 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3927 return Changed ? &I : 0;
3930 static bool isPositive(ConstantInt *C) {
3931 return C->getSExtValue() >= 0;
3934 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3935 /// overflowed for this type.
3936 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3938 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3940 if (In1->getType()->isUnsigned())
3941 return cast<ConstantInt>(Result)->getZExtValue() <
3942 cast<ConstantInt>(In1)->getZExtValue();
3943 if (isPositive(In1) != isPositive(In2))
3945 if (isPositive(In1))
3946 return cast<ConstantInt>(Result)->getSExtValue() <
3947 cast<ConstantInt>(In1)->getSExtValue();
3948 return cast<ConstantInt>(Result)->getSExtValue() >
3949 cast<ConstantInt>(In1)->getSExtValue();
3952 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3953 /// code necessary to compute the offset from the base pointer (without adding
3954 /// in the base pointer). Return the result as a signed integer of intptr size.
3955 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3956 TargetData &TD = IC.getTargetData();
3957 gep_type_iterator GTI = gep_type_begin(GEP);
3958 const Type *UIntPtrTy = TD.getIntPtrType();
3959 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3960 Value *Result = Constant::getNullValue(SIntPtrTy);
3962 // Build a mask for high order bits.
3963 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3965 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3966 Value *Op = GEP->getOperand(i);
3967 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3968 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
3970 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3971 if (!OpC->isNullValue()) {
3972 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3973 Scale = ConstantExpr::getMul(OpC, Scale);
3974 if (Constant *RC = dyn_cast<Constant>(Result))
3975 Result = ConstantExpr::getAdd(RC, Scale);
3977 // Emit an add instruction.
3978 Result = IC.InsertNewInstBefore(
3979 BinaryOperator::createAdd(Result, Scale,
3980 GEP->getName()+".offs"), I);
3984 // Convert to correct type.
3985 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3986 Op->getName()+".c"), I);
3988 // We'll let instcombine(mul) convert this to a shl if possible.
3989 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3990 GEP->getName()+".idx"), I);
3992 // Emit an add instruction.
3993 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3994 GEP->getName()+".offs"), I);
4000 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
4001 /// else. At this point we know that the GEP is on the LHS of the comparison.
4002 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
4003 Instruction::BinaryOps Cond,
4005 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4007 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4008 if (isa<PointerType>(CI->getOperand(0)->getType()))
4009 RHS = CI->getOperand(0);
4011 Value *PtrBase = GEPLHS->getOperand(0);
4012 if (PtrBase == RHS) {
4013 // As an optimization, we don't actually have to compute the actual value of
4014 // OFFSET if this is a seteq or setne comparison, just return whether each
4015 // index is zero or not.
4016 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
4017 Instruction *InVal = 0;
4018 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4019 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4021 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4022 if (isa<UndefValue>(C)) // undef index -> undef.
4023 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4024 if (C->isNullValue())
4026 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4027 EmitIt = false; // This is indexing into a zero sized array?
4028 } else if (isa<ConstantInt>(C))
4029 return ReplaceInstUsesWith(I, // No comparison is needed here.
4030 ConstantBool::get(Cond == Instruction::SetNE));
4035 new SetCondInst(Cond, GEPLHS->getOperand(i),
4036 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4040 InVal = InsertNewInstBefore(InVal, I);
4041 InsertNewInstBefore(Comp, I);
4042 if (Cond == Instruction::SetNE) // True if any are unequal
4043 InVal = BinaryOperator::createOr(InVal, Comp);
4044 else // True if all are equal
4045 InVal = BinaryOperator::createAnd(InVal, Comp);
4053 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4054 ConstantBool::get(Cond == Instruction::SetEQ));
4057 // Only lower this if the setcc is the only user of the GEP or if we expect
4058 // the result to fold to a constant!
4059 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4060 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4061 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4062 return new SetCondInst(Cond, Offset,
4063 Constant::getNullValue(Offset->getType()));
4065 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4066 // If the base pointers are different, but the indices are the same, just
4067 // compare the base pointer.
4068 if (PtrBase != GEPRHS->getOperand(0)) {
4069 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4070 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4071 GEPRHS->getOperand(0)->getType();
4073 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4074 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4075 IndicesTheSame = false;
4079 // If all indices are the same, just compare the base pointers.
4081 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4082 GEPRHS->getOperand(0));
4084 // Otherwise, the base pointers are different and the indices are
4085 // different, bail out.
4089 // If one of the GEPs has all zero indices, recurse.
4090 bool AllZeros = true;
4091 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4092 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4093 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4098 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4099 SetCondInst::getSwappedCondition(Cond), I);
4101 // If the other GEP has all zero indices, recurse.
4103 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4104 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4105 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4110 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4112 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4113 // If the GEPs only differ by one index, compare it.
4114 unsigned NumDifferences = 0; // Keep track of # differences.
4115 unsigned DiffOperand = 0; // The operand that differs.
4116 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4117 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4118 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4119 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4120 // Irreconcilable differences.
4124 if (NumDifferences++) break;
4129 if (NumDifferences == 0) // SAME GEP?
4130 return ReplaceInstUsesWith(I, // No comparison is needed here.
4131 ConstantBool::get(Cond == Instruction::SetEQ));
4132 else if (NumDifferences == 1) {
4133 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4134 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4136 // Convert the operands to signed values to make sure to perform a
4137 // signed comparison.
4138 const Type *NewTy = LHSV->getType()->getSignedVersion();
4139 if (LHSV->getType() != NewTy)
4140 LHSV = InsertCastBefore(LHSV, NewTy, I);
4141 if (RHSV->getType() != NewTy)
4142 RHSV = InsertCastBefore(RHSV, NewTy, I);
4143 return new SetCondInst(Cond, LHSV, RHSV);
4147 // Only lower this if the setcc is the only user of the GEP or if we expect
4148 // the result to fold to a constant!
4149 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4150 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4151 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4152 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4153 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4154 return new SetCondInst(Cond, L, R);
4161 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
4162 bool Changed = SimplifyCommutative(I);
4163 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4164 const Type *Ty = Op0->getType();
4168 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4170 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4171 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4173 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4174 // addresses never equal each other! We already know that Op0 != Op1.
4175 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4176 isa<ConstantPointerNull>(Op0)) &&
4177 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4178 isa<ConstantPointerNull>(Op1)))
4179 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4181 // setcc's with boolean values can always be turned into bitwise operations
4182 if (Ty == Type::BoolTy) {
4183 switch (I.getOpcode()) {
4184 default: assert(0 && "Invalid setcc instruction!");
4185 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
4186 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4187 InsertNewInstBefore(Xor, I);
4188 return BinaryOperator::createNot(Xor);
4190 case Instruction::SetNE:
4191 return BinaryOperator::createXor(Op0, Op1);
4193 case Instruction::SetGT:
4194 std::swap(Op0, Op1); // Change setgt -> setlt
4196 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4197 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4198 InsertNewInstBefore(Not, I);
4199 return BinaryOperator::createAnd(Not, Op1);
4201 case Instruction::SetGE:
4202 std::swap(Op0, Op1); // Change setge -> setle
4204 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4205 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4206 InsertNewInstBefore(Not, I);
4207 return BinaryOperator::createOr(Not, Op1);
4212 // See if we are doing a comparison between a constant and an instruction that
4213 // can be folded into the comparison.
4214 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4215 // Check to see if we are comparing against the minimum or maximum value...
4216 if (CI->isMinValue()) {
4217 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
4218 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4219 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
4220 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4221 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4222 return BinaryOperator::createSetEQ(Op0, Op1);
4223 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4224 return BinaryOperator::createSetNE(Op0, Op1);
4226 } else if (CI->isMaxValue()) {
4227 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
4228 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4229 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
4230 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4231 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4232 return BinaryOperator::createSetEQ(Op0, Op1);
4233 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4234 return BinaryOperator::createSetNE(Op0, Op1);
4236 // Comparing against a value really close to min or max?
4237 } else if (isMinValuePlusOne(CI)) {
4238 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4239 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4240 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4241 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4243 } else if (isMaxValueMinusOne(CI)) {
4244 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4245 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4246 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4247 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4250 // If we still have a setle or setge instruction, turn it into the
4251 // appropriate setlt or setgt instruction. Since the border cases have
4252 // already been handled above, this requires little checking.
4254 if (I.getOpcode() == Instruction::SetLE)
4255 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4256 if (I.getOpcode() == Instruction::SetGE)
4257 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4260 // See if we can fold the comparison based on bits known to be zero or one
4262 uint64_t KnownZero, KnownOne;
4263 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4264 KnownZero, KnownOne, 0))
4267 // Given the known and unknown bits, compute a range that the LHS could be
4269 if (KnownOne | KnownZero) {
4270 if (Ty->isUnsigned()) { // Unsigned comparison.
4272 uint64_t RHSVal = CI->getZExtValue();
4273 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4275 switch (I.getOpcode()) { // LE/GE have been folded already.
4276 default: assert(0 && "Unknown setcc opcode!");
4277 case Instruction::SetEQ:
4278 if (Max < RHSVal || Min > RHSVal)
4279 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4281 case Instruction::SetNE:
4282 if (Max < RHSVal || Min > RHSVal)
4283 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4285 case Instruction::SetLT:
4287 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4289 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4291 case Instruction::SetGT:
4293 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4295 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4298 } else { // Signed comparison.
4300 int64_t RHSVal = CI->getSExtValue();
4301 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4303 switch (I.getOpcode()) { // LE/GE have been folded already.
4304 default: assert(0 && "Unknown setcc opcode!");
4305 case Instruction::SetEQ:
4306 if (Max < RHSVal || Min > RHSVal)
4307 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4309 case Instruction::SetNE:
4310 if (Max < RHSVal || Min > RHSVal)
4311 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4313 case Instruction::SetLT:
4315 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4317 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4319 case Instruction::SetGT:
4321 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4323 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4329 // Since the RHS is a constantInt (CI), if the left hand side is an
4330 // instruction, see if that instruction also has constants so that the
4331 // instruction can be folded into the setcc
4332 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4333 switch (LHSI->getOpcode()) {
4334 case Instruction::And:
4335 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4336 LHSI->getOperand(0)->hasOneUse()) {
4337 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4339 // If an operand is an AND of a truncating cast, we can widen the
4340 // and/compare to be the input width without changing the value
4341 // produced, eliminating a cast.
4342 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4343 // We can do this transformation if either the AND constant does not
4344 // have its sign bit set or if it is an equality comparison.
4345 // Extending a relational comparison when we're checking the sign
4346 // bit would not work.
4347 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4349 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4350 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4351 ConstantInt *NewCST;
4353 if (Cast->getOperand(0)->getType()->isSigned()) {
4354 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4355 AndCST->getZExtValue());
4356 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4357 CI->getZExtValue());
4359 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4360 AndCST->getZExtValue());
4361 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4362 CI->getZExtValue());
4364 Instruction *NewAnd =
4365 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4367 InsertNewInstBefore(NewAnd, I);
4368 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4372 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4373 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4374 // happens a LOT in code produced by the C front-end, for bitfield
4376 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4378 // Check to see if there is a noop-cast between the shift and the and.
4380 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4381 if (CI->getOperand(0)->getType()->isIntegral() &&
4382 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4383 CI->getType()->getPrimitiveSizeInBits())
4384 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4388 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4389 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4390 const Type *AndTy = AndCST->getType(); // Type of the and.
4392 // We can fold this as long as we can't shift unknown bits
4393 // into the mask. This can only happen with signed shift
4394 // rights, as they sign-extend.
4396 bool CanFold = Shift->isLogicalShift();
4398 // To test for the bad case of the signed shr, see if any
4399 // of the bits shifted in could be tested after the mask.
4400 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4401 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4403 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
4405 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4407 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4413 if (Shift->getOpcode() == Instruction::Shl)
4414 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4416 NewCst = ConstantExpr::getShl(CI, ShAmt);
4418 // Check to see if we are shifting out any of the bits being
4420 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4421 // If we shifted bits out, the fold is not going to work out.
4422 // As a special case, check to see if this means that the
4423 // result is always true or false now.
4424 if (I.getOpcode() == Instruction::SetEQ)
4425 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4426 if (I.getOpcode() == Instruction::SetNE)
4427 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4429 I.setOperand(1, NewCst);
4430 Constant *NewAndCST;
4431 if (Shift->getOpcode() == Instruction::Shl)
4432 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4434 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4435 LHSI->setOperand(1, NewAndCST);
4437 LHSI->setOperand(0, Shift->getOperand(0));
4439 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4441 LHSI->setOperand(0, NewCast);
4443 WorkList.push_back(Shift); // Shift is dead.
4444 AddUsesToWorkList(I);
4450 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4451 // preferable because it allows the C<<Y expression to be hoisted out
4452 // of a loop if Y is invariant and X is not.
4453 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4454 I.isEquality() && !Shift->isArithmeticShift() &&
4455 isa<Instruction>(Shift->getOperand(0))) {
4458 if (Shift->getOpcode() == Instruction::LShr) {
4459 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4462 // Make sure we insert a logical shift.
4463 Constant *NewAndCST = AndCST;
4464 if (AndCST->getType()->isSigned())
4465 NewAndCST = ConstantExpr::getCast(AndCST,
4466 AndCST->getType()->getUnsignedVersion());
4467 NS = new ShiftInst(Instruction::LShr, NewAndCST,
4468 Shift->getOperand(1), "tmp");
4470 InsertNewInstBefore(cast<Instruction>(NS), I);
4472 // If C's sign doesn't agree with the and, insert a cast now.
4473 if (NS->getType() != LHSI->getType())
4474 NS = InsertCastBefore(NS, LHSI->getType(), I);
4476 Value *ShiftOp = Shift->getOperand(0);
4477 if (ShiftOp->getType() != LHSI->getType())
4478 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4480 // Compute X & (C << Y).
4481 Instruction *NewAnd =
4482 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4483 InsertNewInstBefore(NewAnd, I);
4485 I.setOperand(0, NewAnd);
4491 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
4492 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4493 if (I.isEquality()) {
4494 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4496 // Check that the shift amount is in range. If not, don't perform
4497 // undefined shifts. When the shift is visited it will be
4499 if (ShAmt->getZExtValue() >= TypeBits)
4502 // If we are comparing against bits always shifted out, the
4503 // comparison cannot succeed.
4505 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4506 if (Comp != CI) {// Comparing against a bit that we know is zero.
4507 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4508 Constant *Cst = ConstantBool::get(IsSetNE);
4509 return ReplaceInstUsesWith(I, Cst);
4512 if (LHSI->hasOneUse()) {
4513 // Otherwise strength reduce the shift into an and.
4514 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4515 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4518 if (CI->getType()->isUnsigned()) {
4519 Mask = ConstantInt::get(CI->getType(), Val);
4520 } else if (ShAmtVal != 0) {
4521 Mask = ConstantInt::get(CI->getType(), Val);
4523 Mask = ConstantInt::getAllOnesValue(CI->getType());
4527 BinaryOperator::createAnd(LHSI->getOperand(0),
4528 Mask, LHSI->getName()+".mask");
4529 Value *And = InsertNewInstBefore(AndI, I);
4530 return new SetCondInst(I.getOpcode(), And,
4531 ConstantExpr::getLShr(CI, ShAmt));
4537 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4538 case Instruction::AShr:
4539 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4540 if (I.isEquality()) {
4541 // Check that the shift amount is in range. If not, don't perform
4542 // undefined shifts. When the shift is visited it will be
4544 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4545 if (ShAmt->getZExtValue() >= TypeBits)
4548 // If we are comparing against bits always shifted out, the
4549 // comparison cannot succeed.
4551 if (CI->getType()->isUnsigned())
4552 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4555 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4558 if (Comp != CI) {// Comparing against a bit that we know is zero.
4559 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4560 Constant *Cst = ConstantBool::get(IsSetNE);
4561 return ReplaceInstUsesWith(I, Cst);
4564 if (LHSI->hasOneUse() || CI->isNullValue()) {
4565 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4567 // Otherwise strength reduce the shift into an and.
4568 uint64_t Val = ~0ULL; // All ones.
4569 Val <<= ShAmtVal; // Shift over to the right spot.
4572 if (CI->getType()->isUnsigned()) {
4573 Val &= ~0ULL >> (64-TypeBits);
4574 Mask = ConstantInt::get(CI->getType(), Val);
4576 Mask = ConstantInt::get(CI->getType(), Val);
4580 BinaryOperator::createAnd(LHSI->getOperand(0),
4581 Mask, LHSI->getName()+".mask");
4582 Value *And = InsertNewInstBefore(AndI, I);
4583 return new SetCondInst(I.getOpcode(), And,
4584 ConstantExpr::getShl(CI, ShAmt));
4590 case Instruction::SDiv:
4591 case Instruction::UDiv:
4592 // Fold: setcc ([us]div X, C1), C2 -> range test
4593 // Fold this div into the comparison, producing a range check.
4594 // Determine, based on the divide type, what the range is being
4595 // checked. If there is an overflow on the low or high side, remember
4596 // it, otherwise compute the range [low, hi) bounding the new value.
4597 // See: InsertRangeTest above for the kinds of replacements possible.
4598 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4599 // FIXME: If the operand types don't match the type of the divide
4600 // then don't attempt this transform. The code below doesn't have the
4601 // logic to deal with a signed divide and an unsigned compare (and
4602 // vice versa). This is because (x /s C1) <s C2 produces different
4603 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4604 // (x /u C1) <u C2. Simply casting the operands and result won't
4605 // work. :( The if statement below tests that condition and bails
4607 const Type* DivRHSTy = DivRHS->getType();
4608 unsigned DivOpCode = LHSI->getOpcode();
4609 if (I.isEquality() &&
4610 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4611 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4614 // Initialize the variables that will indicate the nature of the
4616 bool LoOverflow = false, HiOverflow = false;
4617 ConstantInt *LoBound = 0, *HiBound = 0;
4619 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4620 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4621 // C2 (CI). By solving for X we can turn this into a range check
4622 // instead of computing a divide.
4624 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4626 // Determine if the product overflows by seeing if the product is
4627 // not equal to the divide. Make sure we do the same kind of divide
4628 // as in the LHS instruction that we're folding.
4629 bool ProdOV = !DivRHS->isNullValue() &&
4630 (DivOpCode == Instruction::SDiv ?
4631 ConstantExpr::getSDiv(Prod, DivRHS) :
4632 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4634 // Get the SetCC opcode
4635 Instruction::BinaryOps Opcode = I.getOpcode();
4637 if (DivRHS->isNullValue()) {
4638 // Don't hack on divide by zeros!
4639 } else if (DivOpCode == Instruction::UDiv) { // udiv
4641 LoOverflow = ProdOV;
4642 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4643 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4644 if (CI->isNullValue()) { // (X / pos) op 0
4646 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4648 } else if (isPositive(CI)) { // (X / pos) op pos
4650 LoOverflow = ProdOV;
4651 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4652 } else { // (X / pos) op neg
4653 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4654 LoOverflow = AddWithOverflow(LoBound, Prod,
4655 cast<ConstantInt>(DivRHSH));
4657 HiOverflow = ProdOV;
4659 } else { // Divisor is < 0.
4660 if (CI->isNullValue()) { // (X / neg) op 0
4661 LoBound = AddOne(DivRHS);
4662 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4663 if (HiBound == DivRHS)
4664 LoBound = 0; // - INTMIN = INTMIN
4665 } else if (isPositive(CI)) { // (X / neg) op pos
4666 HiOverflow = LoOverflow = ProdOV;
4668 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4669 HiBound = AddOne(Prod);
4670 } else { // (X / neg) op neg
4672 LoOverflow = HiOverflow = ProdOV;
4673 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4676 // Dividing by a negate swaps the condition.
4677 Opcode = SetCondInst::getSwappedCondition(Opcode);
4681 Value *X = LHSI->getOperand(0);
4683 default: assert(0 && "Unhandled setcc opcode!");
4684 case Instruction::SetEQ:
4685 if (LoOverflow && HiOverflow)
4686 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4687 else if (HiOverflow)
4688 return new SetCondInst(Instruction::SetGE, X, LoBound);
4689 else if (LoOverflow)
4690 return new SetCondInst(Instruction::SetLT, X, HiBound);
4692 return InsertRangeTest(X, LoBound, HiBound, true, I);
4693 case Instruction::SetNE:
4694 if (LoOverflow && HiOverflow)
4695 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4696 else if (HiOverflow)
4697 return new SetCondInst(Instruction::SetLT, X, LoBound);
4698 else if (LoOverflow)
4699 return new SetCondInst(Instruction::SetGE, X, HiBound);
4701 return InsertRangeTest(X, LoBound, HiBound, false, I);
4702 case Instruction::SetLT:
4704 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4705 return new SetCondInst(Instruction::SetLT, X, LoBound);
4706 case Instruction::SetGT:
4708 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4709 return new SetCondInst(Instruction::SetGE, X, HiBound);
4716 // Simplify seteq and setne instructions...
4717 if (I.isEquality()) {
4718 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4720 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4721 // the second operand is a constant, simplify a bit.
4722 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4723 switch (BO->getOpcode()) {
4724 case Instruction::SRem:
4725 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4726 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4728 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4729 if (V > 1 && isPowerOf2_64(V)) {
4730 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4731 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4732 return BinaryOperator::create(I.getOpcode(), NewRem,
4733 Constant::getNullValue(BO->getType()));
4737 case Instruction::Add:
4738 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4739 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4740 if (BO->hasOneUse())
4741 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4742 ConstantExpr::getSub(CI, BOp1C));
4743 } else if (CI->isNullValue()) {
4744 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4745 // efficiently invertible, or if the add has just this one use.
4746 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4748 if (Value *NegVal = dyn_castNegVal(BOp1))
4749 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4750 else if (Value *NegVal = dyn_castNegVal(BOp0))
4751 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4752 else if (BO->hasOneUse()) {
4753 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4755 InsertNewInstBefore(Neg, I);
4756 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4760 case Instruction::Xor:
4761 // For the xor case, we can xor two constants together, eliminating
4762 // the explicit xor.
4763 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4764 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4765 ConstantExpr::getXor(CI, BOC));
4768 case Instruction::Sub:
4769 // Replace (([sub|xor] A, B) != 0) with (A != B)
4770 if (CI->isNullValue())
4771 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4775 case Instruction::Or:
4776 // If bits are being or'd in that are not present in the constant we
4777 // are comparing against, then the comparison could never succeed!
4778 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4779 Constant *NotCI = ConstantExpr::getNot(CI);
4780 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4781 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4785 case Instruction::And:
4786 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4787 // If bits are being compared against that are and'd out, then the
4788 // comparison can never succeed!
4789 if (!ConstantExpr::getAnd(CI,
4790 ConstantExpr::getNot(BOC))->isNullValue())
4791 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4793 // If we have ((X & C) == C), turn it into ((X & C) != 0).
4794 if (CI == BOC && isOneBitSet(CI))
4795 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4796 Instruction::SetNE, Op0,
4797 Constant::getNullValue(CI->getType()));
4799 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4800 // to be a signed value as appropriate.
4801 if (isSignBit(BOC)) {
4802 Value *X = BO->getOperand(0);
4803 // If 'X' is not signed, insert a cast now...
4804 if (!BOC->getType()->isSigned()) {
4805 const Type *DestTy = BOC->getType()->getSignedVersion();
4806 X = InsertCastBefore(X, DestTy, I);
4808 return new SetCondInst(isSetNE ? Instruction::SetLT :
4809 Instruction::SetGE, X,
4810 Constant::getNullValue(X->getType()));
4813 // ((X & ~7) == 0) --> X < 8
4814 if (CI->isNullValue() && isHighOnes(BOC)) {
4815 Value *X = BO->getOperand(0);
4816 Constant *NegX = ConstantExpr::getNeg(BOC);
4818 // If 'X' is signed, insert a cast now.
4819 if (NegX->getType()->isSigned()) {
4820 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4821 X = InsertCastBefore(X, DestTy, I);
4822 NegX = ConstantExpr::getCast(NegX, DestTy);
4825 return new SetCondInst(isSetNE ? Instruction::SetGE :
4826 Instruction::SetLT, X, NegX);
4833 } else { // Not a SetEQ/SetNE
4834 // If the LHS is a cast from an integral value of the same size,
4835 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4836 Value *CastOp = Cast->getOperand(0);
4837 const Type *SrcTy = CastOp->getType();
4838 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4839 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4840 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4841 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4842 "Source and destination signednesses should differ!");
4843 if (Cast->getType()->isSigned()) {
4844 // If this is a signed comparison, check for comparisons in the
4845 // vicinity of zero.
4846 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4848 return BinaryOperator::createSetGT(CastOp,
4849 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4850 else if (I.getOpcode() == Instruction::SetGT &&
4851 cast<ConstantInt>(CI)->getSExtValue() == -1)
4852 // X > -1 => x < 128
4853 return BinaryOperator::createSetLT(CastOp,
4854 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4856 ConstantInt *CUI = cast<ConstantInt>(CI);
4857 if (I.getOpcode() == Instruction::SetLT &&
4858 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
4859 // X < 128 => X > -1
4860 return BinaryOperator::createSetGT(CastOp,
4861 ConstantInt::get(SrcTy, -1));
4862 else if (I.getOpcode() == Instruction::SetGT &&
4863 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
4865 return BinaryOperator::createSetLT(CastOp,
4866 Constant::getNullValue(SrcTy));
4873 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4874 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4875 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4876 switch (LHSI->getOpcode()) {
4877 case Instruction::GetElementPtr:
4878 if (RHSC->isNullValue()) {
4879 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4880 bool isAllZeros = true;
4881 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4882 if (!isa<Constant>(LHSI->getOperand(i)) ||
4883 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4888 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4889 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4893 case Instruction::PHI:
4894 if (Instruction *NV = FoldOpIntoPhi(I))
4897 case Instruction::Select:
4898 // If either operand of the select is a constant, we can fold the
4899 // comparison into the select arms, which will cause one to be
4900 // constant folded and the select turned into a bitwise or.
4901 Value *Op1 = 0, *Op2 = 0;
4902 if (LHSI->hasOneUse()) {
4903 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4904 // Fold the known value into the constant operand.
4905 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4906 // Insert a new SetCC of the other select operand.
4907 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4908 LHSI->getOperand(2), RHSC,
4910 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4911 // Fold the known value into the constant operand.
4912 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4913 // Insert a new SetCC of the other select operand.
4914 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4915 LHSI->getOperand(1), RHSC,
4921 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4926 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4927 if (User *GEP = dyn_castGetElementPtr(Op0))
4928 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4930 if (User *GEP = dyn_castGetElementPtr(Op1))
4931 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4932 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4935 // Test to see if the operands of the setcc are casted versions of other
4936 // values. If the cast can be stripped off both arguments, we do so now.
4937 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4938 Value *CastOp0 = CI->getOperand(0);
4939 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
4940 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
4941 // We keep moving the cast from the left operand over to the right
4942 // operand, where it can often be eliminated completely.
4945 // If operand #1 is a cast instruction, see if we can eliminate it as
4947 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4948 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
4950 Op1 = CI2->getOperand(0);
4952 // If Op1 is a constant, we can fold the cast into the constant.
4953 if (Op1->getType() != Op0->getType())
4954 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4955 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4957 // Otherwise, cast the RHS right before the setcc
4958 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
4960 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4963 // Handle the special case of: setcc (cast bool to X), <cst>
4964 // This comes up when you have code like
4967 // For generality, we handle any zero-extension of any operand comparison
4968 // with a constant or another cast from the same type.
4969 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4970 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4974 if (I.isEquality()) {
4976 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4977 (A == Op1 || B == Op1)) {
4978 // (A^B) == A -> B == 0
4979 Value *OtherVal = A == Op1 ? B : A;
4980 return BinaryOperator::create(I.getOpcode(), OtherVal,
4981 Constant::getNullValue(A->getType()));
4982 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4983 (A == Op0 || B == Op0)) {
4984 // A == (A^B) -> B == 0
4985 Value *OtherVal = A == Op0 ? B : A;
4986 return BinaryOperator::create(I.getOpcode(), OtherVal,
4987 Constant::getNullValue(A->getType()));
4988 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4989 // (A-B) == A -> B == 0
4990 return BinaryOperator::create(I.getOpcode(), B,
4991 Constant::getNullValue(B->getType()));
4992 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4993 // A == (A-B) -> B == 0
4994 return BinaryOperator::create(I.getOpcode(), B,
4995 Constant::getNullValue(B->getType()));
4999 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5000 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5001 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5002 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5003 Value *X = 0, *Y = 0, *Z = 0;
5006 X = B; Y = D; Z = A;
5007 } else if (A == D) {
5008 X = B; Y = C; Z = A;
5009 } else if (B == C) {
5010 X = A; Y = D; Z = B;
5011 } else if (B == D) {
5012 X = A; Y = C; Z = B;
5015 if (X) { // Build (X^Y) & Z
5016 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5017 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5018 I.setOperand(0, Op1);
5019 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5024 return Changed ? &I : 0;
5027 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
5028 // We only handle extending casts so far.
5030 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
5031 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
5032 const Type *SrcTy = LHSCIOp->getType();
5033 const Type *DestTy = SCI.getOperand(0)->getType();
5036 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
5039 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
5040 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
5041 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
5043 // Is this a sign or zero extension?
5044 bool isSignSrc = SrcTy->isSigned();
5045 bool isSignDest = DestTy->isSigned();
5047 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5048 // Not an extension from the same type?
5049 RHSCIOp = CI->getOperand(0);
5050 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5051 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5052 // Compute the constant that would happen if we truncated to SrcTy then
5053 // reextended to DestTy.
5054 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
5056 if (ConstantExpr::getCast(Res, DestTy) == CI) {
5057 // Make sure that src sign and dest sign match. For example,
5059 // %A = cast short %X to uint
5060 // %B = setgt uint %A, 1330
5062 // It is incorrect to transform this into
5064 // %B = setgt short %X, 1330
5066 // because %A may have negative value.
5067 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5068 // OR operation is EQ/NE.
5069 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
5074 // If the value cannot be represented in the shorter type, we cannot emit
5075 // a simple comparison.
5076 if (SCI.getOpcode() == Instruction::SetEQ)
5077 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
5078 if (SCI.getOpcode() == Instruction::SetNE)
5079 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
5081 // Evaluate the comparison for LT.
5083 if (DestTy->isSigned()) {
5084 // We're performing a signed comparison.
5086 // Signed extend and signed comparison.
5087 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
5088 Result = ConstantBool::getFalse();
5090 Result = ConstantBool::getTrue(); // X < (large) --> true
5092 // Unsigned extend and signed comparison.
5093 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5094 Result = ConstantBool::getFalse();
5096 Result = ConstantBool::getTrue();
5099 // We're performing an unsigned comparison.
5101 // Unsigned extend & compare -> always true.
5102 Result = ConstantBool::getTrue();
5104 // We're performing an unsigned comp with a sign extended value.
5105 // This is true if the input is >= 0. [aka >s -1]
5106 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5107 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5108 NegOne, SCI.getName()), SCI);
5112 // Finally, return the value computed.
5113 if (SCI.getOpcode() == Instruction::SetLT) {
5114 return ReplaceInstUsesWith(SCI, Result);
5116 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5117 if (Constant *CI = dyn_cast<Constant>(Result))
5118 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5120 return BinaryOperator::createNot(Result);
5127 // Okay, just insert a compare of the reduced operands now!
5128 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5131 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5132 assert(I.getOperand(1)->getType() == Type::UByteTy);
5133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5134 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5136 // shl X, 0 == X and shr X, 0 == X
5137 // shl 0, X == 0 and shr 0, X == 0
5138 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
5139 Op0 == Constant::getNullValue(Op0->getType()))
5140 return ReplaceInstUsesWith(I, Op0);
5142 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5143 if (!isLeftShift && I.getType()->isSigned())
5144 return ReplaceInstUsesWith(I, Op0);
5145 else // undef << X -> 0 AND undef >>u X -> 0
5146 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5148 if (isa<UndefValue>(Op1)) {
5149 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
5150 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5152 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5155 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5156 if (I.getOpcode() == Instruction::AShr)
5157 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5158 if (CSI->isAllOnesValue())
5159 return ReplaceInstUsesWith(I, CSI);
5161 // Try to fold constant and into select arguments.
5162 if (isa<Constant>(Op0))
5163 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5164 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5167 // See if we can turn a signed shr into an unsigned shr.
5168 if (I.isArithmeticShift()) {
5169 if (MaskedValueIsZero(Op0,
5170 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5171 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5175 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5176 if (CUI->getType()->isUnsigned())
5177 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5182 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5184 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5185 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5186 I.getOpcode() == Instruction::AShr;
5187 bool isUnsignedShift = !isSignedShift;
5189 // See if we can simplify any instructions used by the instruction whose sole
5190 // purpose is to compute bits we don't care about.
5191 uint64_t KnownZero, KnownOne;
5192 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5193 KnownZero, KnownOne))
5196 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5197 // of a signed value.
5199 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5200 if (Op1->getZExtValue() >= TypeBits) {
5201 if (isUnsignedShift || isLeftShift)
5202 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5204 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
5209 // ((X*C1) << C2) == (X * (C1 << C2))
5210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5211 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5212 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5213 return BinaryOperator::createMul(BO->getOperand(0),
5214 ConstantExpr::getShl(BOOp, Op1));
5216 // Try to fold constant and into select arguments.
5217 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5218 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5220 if (isa<PHINode>(Op0))
5221 if (Instruction *NV = FoldOpIntoPhi(I))
5224 if (Op0->hasOneUse()) {
5225 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5226 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5229 switch (Op0BO->getOpcode()) {
5231 case Instruction::Add:
5232 case Instruction::And:
5233 case Instruction::Or:
5234 case Instruction::Xor:
5235 // These operators commute.
5236 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
5237 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5238 match(Op0BO->getOperand(1),
5239 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5240 Instruction *YS = new ShiftInst(Instruction::Shl,
5241 Op0BO->getOperand(0), Op1,
5243 InsertNewInstBefore(YS, I); // (Y << C)
5245 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5246 Op0BO->getOperand(1)->getName());
5247 InsertNewInstBefore(X, I); // (X + (Y << C))
5248 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5249 C2 = ConstantExpr::getShl(C2, Op1);
5250 return BinaryOperator::createAnd(X, C2);
5253 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5254 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5255 match(Op0BO->getOperand(1),
5256 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5257 m_ConstantInt(CC))) && V2 == Op1 &&
5258 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5259 Instruction *YS = new ShiftInst(Instruction::Shl,
5260 Op0BO->getOperand(0), Op1,
5262 InsertNewInstBefore(YS, I); // (Y << C)
5264 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5265 V1->getName()+".mask");
5266 InsertNewInstBefore(XM, I); // X & (CC << C)
5268 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5272 case Instruction::Sub:
5273 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5274 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5275 match(Op0BO->getOperand(0),
5276 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5277 Instruction *YS = new ShiftInst(Instruction::Shl,
5278 Op0BO->getOperand(1), Op1,
5280 InsertNewInstBefore(YS, I); // (Y << C)
5282 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5283 Op0BO->getOperand(0)->getName());
5284 InsertNewInstBefore(X, I); // (X + (Y << C))
5285 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5286 C2 = ConstantExpr::getShl(C2, Op1);
5287 return BinaryOperator::createAnd(X, C2);
5290 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
5291 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5292 match(Op0BO->getOperand(0),
5293 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5294 m_ConstantInt(CC))) && V2 == Op1 &&
5295 cast<BinaryOperator>(Op0BO->getOperand(0))
5296 ->getOperand(0)->hasOneUse()) {
5297 Instruction *YS = new ShiftInst(Instruction::Shl,
5298 Op0BO->getOperand(1), Op1,
5300 InsertNewInstBefore(YS, I); // (Y << C)
5302 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5303 V1->getName()+".mask");
5304 InsertNewInstBefore(XM, I); // X & (CC << C)
5306 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5313 // If the operand is an bitwise operator with a constant RHS, and the
5314 // shift is the only use, we can pull it out of the shift.
5315 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5316 bool isValid = true; // Valid only for And, Or, Xor
5317 bool highBitSet = false; // Transform if high bit of constant set?
5319 switch (Op0BO->getOpcode()) {
5320 default: isValid = false; break; // Do not perform transform!
5321 case Instruction::Add:
5322 isValid = isLeftShift;
5324 case Instruction::Or:
5325 case Instruction::Xor:
5328 case Instruction::And:
5333 // If this is a signed shift right, and the high bit is modified
5334 // by the logical operation, do not perform the transformation.
5335 // The highBitSet boolean indicates the value of the high bit of
5336 // the constant which would cause it to be modified for this
5339 if (isValid && !isLeftShift && isSignedShift) {
5340 uint64_t Val = Op0C->getZExtValue();
5341 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5345 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5347 Instruction *NewShift =
5348 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5351 InsertNewInstBefore(NewShift, I);
5353 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5360 // Find out if this is a shift of a shift by a constant.
5361 ShiftInst *ShiftOp = 0;
5362 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5364 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5365 // If this is a noop-integer case of a shift instruction, use the shift.
5366 if (CI->getOperand(0)->getType()->isInteger() &&
5367 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5368 CI->getType()->getPrimitiveSizeInBits() &&
5369 isa<ShiftInst>(CI->getOperand(0))) {
5370 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5374 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5375 // Find the operands and properties of the input shift. Note that the
5376 // signedness of the input shift may differ from the current shift if there
5377 // is a noop cast between the two.
5378 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5379 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5380 ShiftOp->getType()->isSigned() :
5381 ShiftOp->getOpcode() == Instruction::AShr;
5382 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5384 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5386 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5387 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5389 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5390 if (isLeftShift == isShiftOfLeftShift) {
5391 // Do not fold these shifts if the first one is signed and the second one
5392 // is unsigned and this is a right shift. Further, don't do any folding
5394 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5397 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5398 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5399 Amt = Op0->getType()->getPrimitiveSizeInBits();
5401 Value *Op = ShiftOp->getOperand(0);
5402 if (isShiftOfSignedShift != isSignedShift)
5403 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5404 ShiftInst* ShiftResult = new ShiftInst(I.getOpcode(), Op,
5405 ConstantInt::get(Type::UByteTy, Amt));
5406 if (I.getType() == ShiftResult->getType())
5408 InsertNewInstBefore(ShiftResult, I);
5409 return new CastInst(ShiftResult, I.getType());
5412 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5413 // signed types, we can only support the (A >> c1) << c2 configuration,
5414 // because it can not turn an arbitrary bit of A into a sign bit.
5415 if (isUnsignedShift || isLeftShift) {
5416 // Calculate bitmask for what gets shifted off the edge.
5417 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5419 C = ConstantExpr::getShl(C, ShiftAmt1C);
5421 C = ConstantExpr::getLShr(C, ShiftAmt1C);
5423 Value *Op = ShiftOp->getOperand(0);
5424 if (Op->getType() != C->getType())
5425 Op = InsertCastBefore(Op, I.getType(), I);
5428 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5429 InsertNewInstBefore(Mask, I);
5431 // Figure out what flavor of shift we should use...
5432 if (ShiftAmt1 == ShiftAmt2) {
5433 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
5434 } else if (ShiftAmt1 < ShiftAmt2) {
5435 return new ShiftInst(I.getOpcode(), Mask,
5436 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
5437 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5438 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5439 return new ShiftInst(Instruction::LShr, Mask,
5440 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5442 return new ShiftInst(ShiftOp->getOpcode(), Mask,
5443 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5446 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
5447 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
5448 Instruction *Shift =
5449 new ShiftInst(ShiftOp->getOpcode(), Op,
5450 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5451 InsertNewInstBefore(Shift, I);
5453 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5454 C = ConstantExpr::getShl(C, Op1);
5455 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5456 InsertNewInstBefore(Mask, I);
5457 return new CastInst(Mask, I.getType());
5460 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
5461 // this case, C1 == C2 and C1 is 8, 16, or 32.
5462 if (ShiftAmt1 == ShiftAmt2) {
5463 const Type *SExtType = 0;
5464 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5465 case 8 : SExtType = Type::SByteTy; break;
5466 case 16: SExtType = Type::ShortTy; break;
5467 case 32: SExtType = Type::IntTy; break;
5471 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5473 InsertNewInstBefore(NewTrunc, I);
5474 return new CastInst(NewTrunc, I.getType());
5483 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5484 /// expression. If so, decompose it, returning some value X, such that Val is
5487 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5489 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5490 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5491 if (CI->getType()->isUnsigned()) {
5492 Offset = CI->getZExtValue();
5494 return ConstantInt::get(Type::UIntTy, 0);
5496 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5497 if (I->getNumOperands() == 2) {
5498 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5499 if (CUI->getType()->isUnsigned()) {
5500 if (I->getOpcode() == Instruction::Shl) {
5501 // This is a value scaled by '1 << the shift amt'.
5502 Scale = 1U << CUI->getZExtValue();
5504 return I->getOperand(0);
5505 } else if (I->getOpcode() == Instruction::Mul) {
5506 // This value is scaled by 'CUI'.
5507 Scale = CUI->getZExtValue();
5509 return I->getOperand(0);
5510 } else if (I->getOpcode() == Instruction::Add) {
5511 // We have X+C. Check to see if we really have (X*C2)+C1,
5512 // where C1 is divisible by C2.
5515 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5516 Offset += CUI->getZExtValue();
5517 if (SubScale > 1 && (Offset % SubScale == 0)) {
5527 // Otherwise, we can't look past this.
5534 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5535 /// try to eliminate the cast by moving the type information into the alloc.
5536 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5537 AllocationInst &AI) {
5538 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5539 if (!PTy) return 0; // Not casting the allocation to a pointer type.
5541 // Remove any uses of AI that are dead.
5542 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5543 std::vector<Instruction*> DeadUsers;
5544 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5545 Instruction *User = cast<Instruction>(*UI++);
5546 if (isInstructionTriviallyDead(User)) {
5547 while (UI != E && *UI == User)
5548 ++UI; // If this instruction uses AI more than once, don't break UI.
5550 // Add operands to the worklist.
5551 AddUsesToWorkList(*User);
5553 DOUT << "IC: DCE: " << *User;
5555 User->eraseFromParent();
5556 removeFromWorkList(User);
5560 // Get the type really allocated and the type casted to.
5561 const Type *AllocElTy = AI.getAllocatedType();
5562 const Type *CastElTy = PTy->getElementType();
5563 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5565 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5566 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5567 if (CastElTyAlign < AllocElTyAlign) return 0;
5569 // If the allocation has multiple uses, only promote it if we are strictly
5570 // increasing the alignment of the resultant allocation. If we keep it the
5571 // same, we open the door to infinite loops of various kinds.
5572 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5574 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5575 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5576 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5578 // See if we can satisfy the modulus by pulling a scale out of the array
5580 unsigned ArraySizeScale, ArrayOffset;
5581 Value *NumElements = // See if the array size is a decomposable linear expr.
5582 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5584 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5586 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5587 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
5589 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5594 // If the allocation size is constant, form a constant mul expression
5595 Amt = ConstantInt::get(Type::UIntTy, Scale);
5596 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5597 Amt = ConstantExpr::getMul(
5598 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5599 // otherwise multiply the amount and the number of elements
5600 else if (Scale != 1) {
5601 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5602 Amt = InsertNewInstBefore(Tmp, AI);
5606 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5607 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
5608 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5609 Amt = InsertNewInstBefore(Tmp, AI);
5612 std::string Name = AI.getName(); AI.setName("");
5613 AllocationInst *New;
5614 if (isa<MallocInst>(AI))
5615 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5617 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5618 InsertNewInstBefore(New, AI);
5620 // If the allocation has multiple uses, insert a cast and change all things
5621 // that used it to use the new cast. This will also hack on CI, but it will
5623 if (!AI.hasOneUse()) {
5624 AddUsesToWorkList(AI);
5625 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5626 InsertNewInstBefore(NewCast, AI);
5627 AI.replaceAllUsesWith(NewCast);
5629 return ReplaceInstUsesWith(CI, New);
5632 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5633 /// and return it without inserting any new casts. This is used by code that
5634 /// tries to decide whether promoting or shrinking integer operations to wider
5635 /// or smaller types will allow us to eliminate a truncate or extend.
5636 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5637 int &NumCastsRemoved) {
5638 if (isa<Constant>(V)) return true;
5640 Instruction *I = dyn_cast<Instruction>(V);
5641 if (!I || !I->hasOneUse()) return false;
5643 switch (I->getOpcode()) {
5644 case Instruction::And:
5645 case Instruction::Or:
5646 case Instruction::Xor:
5647 // These operators can all arbitrarily be extended or truncated.
5648 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5649 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5650 case Instruction::Cast:
5651 // If this is a cast from the destination type, we can trivially eliminate
5652 // it, and this will remove a cast overall.
5653 if (I->getOperand(0)->getType() == Ty) {
5654 // If the first operand is itself a cast, and is eliminable, do not count
5655 // this as an eliminable cast. We would prefer to eliminate those two
5657 if (isa<CastInst>(I->getOperand(0)))
5663 // TODO: Can handle more cases here.
5670 /// EvaluateInDifferentType - Given an expression that
5671 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5672 /// evaluate the expression.
5673 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5674 if (Constant *C = dyn_cast<Constant>(V))
5675 return ConstantExpr::getCast(C, Ty);
5677 // Otherwise, it must be an instruction.
5678 Instruction *I = cast<Instruction>(V);
5679 Instruction *Res = 0;
5680 switch (I->getOpcode()) {
5681 case Instruction::And:
5682 case Instruction::Or:
5683 case Instruction::Xor: {
5684 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5685 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5686 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5687 LHS, RHS, I->getName());
5690 case Instruction::Cast:
5691 // If this is a cast from the destination type, return the input.
5692 if (I->getOperand(0)->getType() == Ty)
5693 return I->getOperand(0);
5695 // TODO: Can handle more cases here.
5696 assert(0 && "Unreachable!");
5700 return InsertNewInstBefore(Res, *I);
5704 // CastInst simplification
5706 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
5707 Value *Src = CI.getOperand(0);
5709 // If the user is casting a value to the same type, eliminate this cast
5711 if (CI.getType() == Src->getType())
5712 return ReplaceInstUsesWith(CI, Src);
5714 if (isa<UndefValue>(Src)) // cast undef -> undef
5715 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5717 // If casting the result of another cast instruction, try to eliminate this
5720 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5721 Value *A = CSrc->getOperand(0);
5722 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5723 CI.getType(), TD)) {
5724 // This instruction now refers directly to the cast's src operand. This
5725 // has a good chance of making CSrc dead.
5726 CI.setOperand(0, CSrc->getOperand(0));
5730 // If this is an A->B->A cast, and we are dealing with integral types, try
5731 // to convert this into a logical 'and' instruction.
5733 if (A->getType()->isInteger() &&
5734 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
5735 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
5736 CSrc->getType()->getPrimitiveSizeInBits() <
5737 CI.getType()->getPrimitiveSizeInBits()&&
5738 A->getType()->getPrimitiveSizeInBits() ==
5739 CI.getType()->getPrimitiveSizeInBits()) {
5740 assert(CSrc->getType() != Type::ULongTy &&
5741 "Cannot have type bigger than ulong!");
5742 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
5743 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
5745 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5746 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5747 if (And->getType() != CI.getType()) {
5748 And->setName(CSrc->getName()+".mask");
5749 InsertNewInstBefore(And, CI);
5750 And = new CastInst(And, CI.getType());
5756 // If this is a cast to bool, turn it into the appropriate setne instruction.
5757 if (CI.getType() == Type::BoolTy)
5758 return BinaryOperator::createSetNE(CI.getOperand(0),
5759 Constant::getNullValue(CI.getOperand(0)->getType()));
5761 // See if we can simplify any instructions used by the LHS whose sole
5762 // purpose is to compute bits we don't care about.
5763 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5764 uint64_t KnownZero, KnownOne;
5765 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5766 KnownZero, KnownOne))
5770 // If casting the result of a getelementptr instruction with no offset, turn
5771 // this into a cast of the original pointer!
5773 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5774 bool AllZeroOperands = true;
5775 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5776 if (!isa<Constant>(GEP->getOperand(i)) ||
5777 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5778 AllZeroOperands = false;
5781 if (AllZeroOperands) {
5782 CI.setOperand(0, GEP->getOperand(0));
5787 // If we are casting a malloc or alloca to a pointer to a type of the same
5788 // size, rewrite the allocation instruction to allocate the "right" type.
5790 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5791 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5794 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5795 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5797 if (isa<PHINode>(Src))
5798 if (Instruction *NV = FoldOpIntoPhi(CI))
5801 // If the source and destination are pointers, and this cast is equivalent to
5802 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5803 // This can enhance SROA and other transforms that want type-safe pointers.
5804 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5805 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5806 const Type *DstTy = DstPTy->getElementType();
5807 const Type *SrcTy = SrcPTy->getElementType();
5809 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5810 unsigned NumZeros = 0;
5811 while (SrcTy != DstTy &&
5812 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5813 SrcTy->getNumContainedTypes() /* not "{}" */) {
5814 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5818 // If we found a path from the src to dest, create the getelementptr now.
5819 if (SrcTy == DstTy) {
5820 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5821 return new GetElementPtrInst(Src, Idxs);
5825 // If the source value is an instruction with only this use, we can attempt to
5826 // propagate the cast into the instruction. Also, only handle integral types
5828 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
5829 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
5830 CI.getType()->isInteger()) { // Don't mess with casts to bool here
5832 int NumCastsRemoved = 0;
5833 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5834 // If this cast is a truncate, evaluting in a different type always
5835 // eliminates the cast, so it is always a win. If this is a noop-cast
5836 // this just removes a noop cast which isn't pointful, but simplifies
5837 // the code. If this is a zero-extension, we need to do an AND to
5838 // maintain the clear top-part of the computation, so we require that
5839 // the input have eliminated at least one cast. If this is a sign
5840 // extension, we insert two new casts (to do the extension) so we
5841 // require that two casts have been eliminated.
5843 switch (getCastType(Src->getType(), CI.getType())) {
5844 default: assert(0 && "Unknown cast type!");
5850 DoXForm = NumCastsRemoved >= 1;
5853 DoXForm = NumCastsRemoved >= 2;
5858 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5859 assert(Res->getType() == CI.getType());
5860 switch (getCastType(Src->getType(), CI.getType())) {
5861 default: assert(0 && "Unknown cast type!");
5864 // Just replace this cast with the result.
5865 return ReplaceInstUsesWith(CI, Res);
5867 // We need to emit an AND to clear the high bits.
5868 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5869 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5870 assert(SrcBitSize < DestBitSize && "Not a zext?");
5872 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5873 C = ConstantExpr::getCast(C, CI.getType());
5874 return BinaryOperator::createAnd(Res, C);
5877 // We need to emit a cast to truncate, then a cast to sext.
5878 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5884 const Type *DestTy = CI.getType();
5885 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5886 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5888 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5889 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5891 switch (SrcI->getOpcode()) {
5892 case Instruction::Add:
5893 case Instruction::Mul:
5894 case Instruction::And:
5895 case Instruction::Or:
5896 case Instruction::Xor:
5897 // If we are discarding information, or just changing the sign, rewrite.
5898 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5899 // Don't insert two casts if they cannot be eliminated. We allow two
5900 // casts to be inserted if the sizes are the same. This could only be
5901 // converting signedness, which is a noop.
5902 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5903 !ValueRequiresCast(Op0, DestTy, TD)) {
5904 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5905 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5906 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5907 ->getOpcode(), Op0c, Op1c);
5911 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5912 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5913 Op1 == ConstantBool::getTrue() &&
5914 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5915 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5916 return BinaryOperator::createXor(New,
5917 ConstantInt::get(CI.getType(), 1));
5920 case Instruction::SDiv:
5921 case Instruction::UDiv:
5922 case Instruction::SRem:
5923 case Instruction::URem:
5924 // If we are just changing the sign, rewrite.
5925 if (DestBitSize == SrcBitSize) {
5926 // Don't insert two casts if they cannot be eliminated. We allow two
5927 // casts to be inserted if the sizes are the same. This could only be
5928 // converting signedness, which is a noop.
5929 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5930 !ValueRequiresCast(Op0, DestTy, TD)) {
5931 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5932 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5933 return BinaryOperator::create(
5934 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5939 case Instruction::Shl:
5940 // Allow changing the sign of the source operand. Do not allow changing
5941 // the size of the shift, UNLESS the shift amount is a constant. We
5942 // must not change variable sized shifts to a smaller size, because it
5943 // is undefined to shift more bits out than exist in the value.
5944 if (DestBitSize == SrcBitSize ||
5945 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5946 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5947 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5950 case Instruction::AShr:
5951 // If this is a signed shr, and if all bits shifted in are about to be
5952 // truncated off, turn it into an unsigned shr to allow greater
5954 if (DestBitSize < SrcBitSize &&
5955 isa<ConstantInt>(Op1)) {
5956 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5957 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5958 // Insert the new logical shift right.
5959 return new ShiftInst(Instruction::LShr, Op0, Op1);
5964 case Instruction::SetEQ:
5965 case Instruction::SetNE:
5966 // We if we are just checking for a seteq of a single bit and casting it
5967 // to an integer. If so, shift the bit to the appropriate place then
5968 // cast to integer to avoid the comparison.
5969 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5970 uint64_t Op1CV = Op1C->getZExtValue();
5971 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5972 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5973 // cast (X == 1) to int --> X iff X has only the low bit set.
5974 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5975 // cast (X != 0) to int --> X iff X has only the low bit set.
5976 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5977 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5978 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5979 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5980 // If Op1C some other power of two, convert:
5981 uint64_t KnownZero, KnownOne;
5982 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5983 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5985 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5986 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5987 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5988 // (X&4) == 2 --> false
5989 // (X&4) != 2 --> true
5990 Constant *Res = ConstantBool::get(isSetNE);
5991 Res = ConstantExpr::getCast(Res, CI.getType());
5992 return ReplaceInstUsesWith(CI, Res);
5995 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5998 // Perform a logical shr by shiftamt.
5999 // Insert the shift to put the result in the low bit.
6000 In = InsertNewInstBefore(new ShiftInst(Instruction::LShr, In,
6001 ConstantInt::get(Type::UByteTy, ShiftAmt),
6002 In->getName()+".lobit"), CI);
6005 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
6006 Constant *One = ConstantInt::get(In->getType(), 1);
6007 In = BinaryOperator::createXor(In, One, "tmp");
6008 InsertNewInstBefore(cast<Instruction>(In), CI);
6011 if (CI.getType() == In->getType())
6012 return ReplaceInstUsesWith(CI, In);
6014 return new CastInst(In, CI.getType());
6022 if (SrcI->hasOneUse()) {
6023 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
6024 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
6025 // because the inputs are known to be a vector. Check to see if this is
6026 // a cast to a vector with the same # elts.
6027 if (isa<PackedType>(CI.getType()) &&
6028 cast<PackedType>(CI.getType())->getNumElements() ==
6029 SVI->getType()->getNumElements()) {
6031 // If either of the operands is a cast from CI.getType(), then
6032 // evaluating the shuffle in the casted destination's type will allow
6033 // us to eliminate at least one cast.
6034 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6035 Tmp->getOperand(0)->getType() == CI.getType()) ||
6036 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6037 Tmp->getOperand(0)->getType() == CI.getType())) {
6038 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
6040 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
6042 // Return a new shuffle vector. Use the same element ID's, as we
6043 // know the vector types match #elts.
6044 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6054 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6056 /// %D = select %cond, %C, %A
6058 /// %C = select %cond, %B, 0
6061 /// Assuming that the specified instruction is an operand to the select, return
6062 /// a bitmask indicating which operands of this instruction are foldable if they
6063 /// equal the other incoming value of the select.
6065 static unsigned GetSelectFoldableOperands(Instruction *I) {
6066 switch (I->getOpcode()) {
6067 case Instruction::Add:
6068 case Instruction::Mul:
6069 case Instruction::And:
6070 case Instruction::Or:
6071 case Instruction::Xor:
6072 return 3; // Can fold through either operand.
6073 case Instruction::Sub: // Can only fold on the amount subtracted.
6074 case Instruction::Shl: // Can only fold on the shift amount.
6075 case Instruction::LShr:
6076 case Instruction::AShr:
6079 return 0; // Cannot fold
6083 /// GetSelectFoldableConstant - For the same transformation as the previous
6084 /// function, return the identity constant that goes into the select.
6085 static Constant *GetSelectFoldableConstant(Instruction *I) {
6086 switch (I->getOpcode()) {
6087 default: assert(0 && "This cannot happen!"); abort();
6088 case Instruction::Add:
6089 case Instruction::Sub:
6090 case Instruction::Or:
6091 case Instruction::Xor:
6092 return Constant::getNullValue(I->getType());
6093 case Instruction::Shl:
6094 case Instruction::LShr:
6095 case Instruction::AShr:
6096 return Constant::getNullValue(Type::UByteTy);
6097 case Instruction::And:
6098 return ConstantInt::getAllOnesValue(I->getType());
6099 case Instruction::Mul:
6100 return ConstantInt::get(I->getType(), 1);
6104 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6105 /// have the same opcode and only one use each. Try to simplify this.
6106 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6108 if (TI->getNumOperands() == 1) {
6109 // If this is a non-volatile load or a cast from the same type,
6111 if (TI->getOpcode() == Instruction::Cast) {
6112 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6115 return 0; // unknown unary op.
6118 // Fold this by inserting a select from the input values.
6119 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6120 FI->getOperand(0), SI.getName()+".v");
6121 InsertNewInstBefore(NewSI, SI);
6122 return new CastInst(NewSI, TI->getType());
6125 // Only handle binary operators here.
6126 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6129 // Figure out if the operations have any operands in common.
6130 Value *MatchOp, *OtherOpT, *OtherOpF;
6132 if (TI->getOperand(0) == FI->getOperand(0)) {
6133 MatchOp = TI->getOperand(0);
6134 OtherOpT = TI->getOperand(1);
6135 OtherOpF = FI->getOperand(1);
6136 MatchIsOpZero = true;
6137 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6138 MatchOp = TI->getOperand(1);
6139 OtherOpT = TI->getOperand(0);
6140 OtherOpF = FI->getOperand(0);
6141 MatchIsOpZero = false;
6142 } else if (!TI->isCommutative()) {
6144 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6145 MatchOp = TI->getOperand(0);
6146 OtherOpT = TI->getOperand(1);
6147 OtherOpF = FI->getOperand(0);
6148 MatchIsOpZero = true;
6149 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6150 MatchOp = TI->getOperand(1);
6151 OtherOpT = TI->getOperand(0);
6152 OtherOpF = FI->getOperand(1);
6153 MatchIsOpZero = true;
6158 // If we reach here, they do have operations in common.
6159 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6160 OtherOpF, SI.getName()+".v");
6161 InsertNewInstBefore(NewSI, SI);
6163 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6165 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6167 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6170 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6172 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6176 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6177 Value *CondVal = SI.getCondition();
6178 Value *TrueVal = SI.getTrueValue();
6179 Value *FalseVal = SI.getFalseValue();
6181 // select true, X, Y -> X
6182 // select false, X, Y -> Y
6183 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6184 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6186 // select C, X, X -> X
6187 if (TrueVal == FalseVal)
6188 return ReplaceInstUsesWith(SI, TrueVal);
6190 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6191 return ReplaceInstUsesWith(SI, FalseVal);
6192 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6193 return ReplaceInstUsesWith(SI, TrueVal);
6194 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6195 if (isa<Constant>(TrueVal))
6196 return ReplaceInstUsesWith(SI, TrueVal);
6198 return ReplaceInstUsesWith(SI, FalseVal);
6201 if (SI.getType() == Type::BoolTy)
6202 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6203 if (C->getValue()) {
6204 // Change: A = select B, true, C --> A = or B, C
6205 return BinaryOperator::createOr(CondVal, FalseVal);
6207 // Change: A = select B, false, C --> A = and !B, C
6209 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6210 "not."+CondVal->getName()), SI);
6211 return BinaryOperator::createAnd(NotCond, FalseVal);
6213 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6214 if (C->getValue() == false) {
6215 // Change: A = select B, C, false --> A = and B, C
6216 return BinaryOperator::createAnd(CondVal, TrueVal);
6218 // Change: A = select B, C, true --> A = or !B, C
6220 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6221 "not."+CondVal->getName()), SI);
6222 return BinaryOperator::createOr(NotCond, TrueVal);
6226 // Selecting between two integer constants?
6227 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6228 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6229 // select C, 1, 0 -> cast C to int
6230 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6231 return new CastInst(CondVal, SI.getType());
6232 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6233 // select C, 0, 1 -> cast !C to int
6235 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6236 "not."+CondVal->getName()), SI);
6237 return new CastInst(NotCond, SI.getType());
6240 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6242 // (x <s 0) ? -1 : 0 -> sra x, 31
6243 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6244 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6245 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6246 bool CanXForm = false;
6247 if (CmpCst->getType()->isSigned())
6248 CanXForm = CmpCst->isNullValue() &&
6249 IC->getOpcode() == Instruction::SetLT;
6251 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6252 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6253 IC->getOpcode() == Instruction::SetGT;
6257 // The comparison constant and the result are not neccessarily the
6258 // same width. In any case, the first step to do is make sure
6259 // that X is signed.
6260 Value *X = IC->getOperand(0);
6261 if (!X->getType()->isSigned())
6262 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6264 // Now that X is signed, we have to make the all ones value. Do
6265 // this by inserting a new SRA.
6266 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6267 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
6268 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6270 InsertNewInstBefore(SRA, SI);
6272 // Finally, convert to the type of the select RHS. If this is
6273 // smaller than the compare value, it will truncate the ones to
6274 // fit. If it is larger, it will sext the ones to fit.
6275 return new CastInst(SRA, SI.getType());
6280 // If one of the constants is zero (we know they can't both be) and we
6281 // have a setcc instruction with zero, and we have an 'and' with the
6282 // non-constant value, eliminate this whole mess. This corresponds to
6283 // cases like this: ((X & 27) ? 27 : 0)
6284 if (TrueValC->isNullValue() || FalseValC->isNullValue())
6285 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6286 cast<Constant>(IC->getOperand(1))->isNullValue())
6287 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6288 if (ICA->getOpcode() == Instruction::And &&
6289 isa<ConstantInt>(ICA->getOperand(1)) &&
6290 (ICA->getOperand(1) == TrueValC ||
6291 ICA->getOperand(1) == FalseValC) &&
6292 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6293 // Okay, now we know that everything is set up, we just don't
6294 // know whether we have a setne or seteq and whether the true or
6295 // false val is the zero.
6296 bool ShouldNotVal = !TrueValC->isNullValue();
6297 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6300 V = InsertNewInstBefore(BinaryOperator::create(
6301 Instruction::Xor, V, ICA->getOperand(1)), SI);
6302 return ReplaceInstUsesWith(SI, V);
6307 // See if we are selecting two values based on a comparison of the two values.
6308 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6309 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6310 // Transform (X == Y) ? X : Y -> Y
6311 if (SCI->getOpcode() == Instruction::SetEQ)
6312 return ReplaceInstUsesWith(SI, FalseVal);
6313 // Transform (X != Y) ? X : Y -> X
6314 if (SCI->getOpcode() == Instruction::SetNE)
6315 return ReplaceInstUsesWith(SI, TrueVal);
6316 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6318 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6319 // Transform (X == Y) ? Y : X -> X
6320 if (SCI->getOpcode() == Instruction::SetEQ)
6321 return ReplaceInstUsesWith(SI, FalseVal);
6322 // Transform (X != Y) ? Y : X -> Y
6323 if (SCI->getOpcode() == Instruction::SetNE)
6324 return ReplaceInstUsesWith(SI, TrueVal);
6325 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6329 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6330 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6331 if (TI->hasOneUse() && FI->hasOneUse()) {
6332 Instruction *AddOp = 0, *SubOp = 0;
6334 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6335 if (TI->getOpcode() == FI->getOpcode())
6336 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6339 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6340 // even legal for FP.
6341 if (TI->getOpcode() == Instruction::Sub &&
6342 FI->getOpcode() == Instruction::Add) {
6343 AddOp = FI; SubOp = TI;
6344 } else if (FI->getOpcode() == Instruction::Sub &&
6345 TI->getOpcode() == Instruction::Add) {
6346 AddOp = TI; SubOp = FI;
6350 Value *OtherAddOp = 0;
6351 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6352 OtherAddOp = AddOp->getOperand(1);
6353 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6354 OtherAddOp = AddOp->getOperand(0);
6358 // So at this point we know we have (Y -> OtherAddOp):
6359 // select C, (add X, Y), (sub X, Z)
6360 Value *NegVal; // Compute -Z
6361 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6362 NegVal = ConstantExpr::getNeg(C);
6364 NegVal = InsertNewInstBefore(
6365 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6368 Value *NewTrueOp = OtherAddOp;
6369 Value *NewFalseOp = NegVal;
6371 std::swap(NewTrueOp, NewFalseOp);
6372 Instruction *NewSel =
6373 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6375 NewSel = InsertNewInstBefore(NewSel, SI);
6376 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6381 // See if we can fold the select into one of our operands.
6382 if (SI.getType()->isInteger()) {
6383 // See the comment above GetSelectFoldableOperands for a description of the
6384 // transformation we are doing here.
6385 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6386 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6387 !isa<Constant>(FalseVal))
6388 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6389 unsigned OpToFold = 0;
6390 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6392 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6397 Constant *C = GetSelectFoldableConstant(TVI);
6398 std::string Name = TVI->getName(); TVI->setName("");
6399 Instruction *NewSel =
6400 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6402 InsertNewInstBefore(NewSel, SI);
6403 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6404 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6405 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6406 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6408 assert(0 && "Unknown instruction!!");
6413 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6414 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6415 !isa<Constant>(TrueVal))
6416 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6417 unsigned OpToFold = 0;
6418 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6420 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6425 Constant *C = GetSelectFoldableConstant(FVI);
6426 std::string Name = FVI->getName(); FVI->setName("");
6427 Instruction *NewSel =
6428 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6430 InsertNewInstBefore(NewSel, SI);
6431 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6432 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6433 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6434 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6436 assert(0 && "Unknown instruction!!");
6442 if (BinaryOperator::isNot(CondVal)) {
6443 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6444 SI.setOperand(1, FalseVal);
6445 SI.setOperand(2, TrueVal);
6452 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6453 /// determine, return it, otherwise return 0.
6454 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6455 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6456 unsigned Align = GV->getAlignment();
6457 if (Align == 0 && TD)
6458 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6460 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6461 unsigned Align = AI->getAlignment();
6462 if (Align == 0 && TD) {
6463 if (isa<AllocaInst>(AI))
6464 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6465 else if (isa<MallocInst>(AI)) {
6466 // Malloc returns maximally aligned memory.
6467 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6468 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6469 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6473 } else if (isa<CastInst>(V) ||
6474 (isa<ConstantExpr>(V) &&
6475 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6476 User *CI = cast<User>(V);
6477 if (isa<PointerType>(CI->getOperand(0)->getType()))
6478 return GetKnownAlignment(CI->getOperand(0), TD);
6480 } else if (isa<GetElementPtrInst>(V) ||
6481 (isa<ConstantExpr>(V) &&
6482 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6483 User *GEPI = cast<User>(V);
6484 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6485 if (BaseAlignment == 0) return 0;
6487 // If all indexes are zero, it is just the alignment of the base pointer.
6488 bool AllZeroOperands = true;
6489 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6490 if (!isa<Constant>(GEPI->getOperand(i)) ||
6491 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6492 AllZeroOperands = false;
6495 if (AllZeroOperands)
6496 return BaseAlignment;
6498 // Otherwise, if the base alignment is >= the alignment we expect for the
6499 // base pointer type, then we know that the resultant pointer is aligned at
6500 // least as much as its type requires.
6503 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6504 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6506 const Type *GEPTy = GEPI->getType();
6507 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6515 /// visitCallInst - CallInst simplification. This mostly only handles folding
6516 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6517 /// the heavy lifting.
6519 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6520 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6521 if (!II) return visitCallSite(&CI);
6523 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6525 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6526 bool Changed = false;
6528 // memmove/cpy/set of zero bytes is a noop.
6529 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6530 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6532 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6533 if (CI->getZExtValue() == 1) {
6534 // Replace the instruction with just byte operations. We would
6535 // transform other cases to loads/stores, but we don't know if
6536 // alignment is sufficient.
6540 // If we have a memmove and the source operation is a constant global,
6541 // then the source and dest pointers can't alias, so we can change this
6542 // into a call to memcpy.
6543 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6544 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6545 if (GVSrc->isConstant()) {
6546 Module *M = CI.getParent()->getParent()->getParent();
6548 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
6550 Name = "llvm.memcpy.i32";
6552 Name = "llvm.memcpy.i64";
6553 Function *MemCpy = M->getOrInsertFunction(Name,
6554 CI.getCalledFunction()->getFunctionType());
6555 CI.setOperand(0, MemCpy);
6560 // If we can determine a pointer alignment that is bigger than currently
6561 // set, update the alignment.
6562 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6563 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6564 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6565 unsigned Align = std::min(Alignment1, Alignment2);
6566 if (MI->getAlignment()->getZExtValue() < Align) {
6567 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
6570 } else if (isa<MemSetInst>(MI)) {
6571 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6572 if (MI->getAlignment()->getZExtValue() < Alignment) {
6573 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
6578 if (Changed) return II;
6580 switch (II->getIntrinsicID()) {
6582 case Intrinsic::ppc_altivec_lvx:
6583 case Intrinsic::ppc_altivec_lvxl:
6584 case Intrinsic::x86_sse_loadu_ps:
6585 case Intrinsic::x86_sse2_loadu_pd:
6586 case Intrinsic::x86_sse2_loadu_dq:
6587 // Turn PPC lvx -> load if the pointer is known aligned.
6588 // Turn X86 loadups -> load if the pointer is known aligned.
6589 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6590 Value *Ptr = InsertCastBefore(II->getOperand(1),
6591 PointerType::get(II->getType()), CI);
6592 return new LoadInst(Ptr);
6595 case Intrinsic::ppc_altivec_stvx:
6596 case Intrinsic::ppc_altivec_stvxl:
6597 // Turn stvx -> store if the pointer is known aligned.
6598 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
6599 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6600 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
6601 return new StoreInst(II->getOperand(1), Ptr);
6604 case Intrinsic::x86_sse_storeu_ps:
6605 case Intrinsic::x86_sse2_storeu_pd:
6606 case Intrinsic::x86_sse2_storeu_dq:
6607 case Intrinsic::x86_sse2_storel_dq:
6608 // Turn X86 storeu -> store if the pointer is known aligned.
6609 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6610 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6611 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6612 return new StoreInst(II->getOperand(2), Ptr);
6616 case Intrinsic::x86_sse_cvttss2si: {
6617 // These intrinsics only demands the 0th element of its input vector. If
6618 // we can simplify the input based on that, do so now.
6620 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6622 II->setOperand(1, V);
6628 case Intrinsic::ppc_altivec_vperm:
6629 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6630 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6631 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6633 // Check that all of the elements are integer constants or undefs.
6634 bool AllEltsOk = true;
6635 for (unsigned i = 0; i != 16; ++i) {
6636 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6637 !isa<UndefValue>(Mask->getOperand(i))) {
6644 // Cast the input vectors to byte vectors.
6645 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6646 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6647 Value *Result = UndefValue::get(Op0->getType());
6649 // Only extract each element once.
6650 Value *ExtractedElts[32];
6651 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6653 for (unsigned i = 0; i != 16; ++i) {
6654 if (isa<UndefValue>(Mask->getOperand(i)))
6656 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
6657 Idx &= 31; // Match the hardware behavior.
6659 if (ExtractedElts[Idx] == 0) {
6661 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
6662 InsertNewInstBefore(Elt, CI);
6663 ExtractedElts[Idx] = Elt;
6666 // Insert this value into the result vector.
6667 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
6668 InsertNewInstBefore(cast<Instruction>(Result), CI);
6670 return new CastInst(Result, CI.getType());
6675 case Intrinsic::stackrestore: {
6676 // If the save is right next to the restore, remove the restore. This can
6677 // happen when variable allocas are DCE'd.
6678 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6679 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6680 BasicBlock::iterator BI = SS;
6682 return EraseInstFromFunction(CI);
6686 // If the stack restore is in a return/unwind block and if there are no
6687 // allocas or calls between the restore and the return, nuke the restore.
6688 TerminatorInst *TI = II->getParent()->getTerminator();
6689 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6690 BasicBlock::iterator BI = II;
6691 bool CannotRemove = false;
6692 for (++BI; &*BI != TI; ++BI) {
6693 if (isa<AllocaInst>(BI) ||
6694 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6695 CannotRemove = true;
6700 return EraseInstFromFunction(CI);
6707 return visitCallSite(II);
6710 // InvokeInst simplification
6712 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6713 return visitCallSite(&II);
6716 // visitCallSite - Improvements for call and invoke instructions.
6718 Instruction *InstCombiner::visitCallSite(CallSite CS) {
6719 bool Changed = false;
6721 // If the callee is a constexpr cast of a function, attempt to move the cast
6722 // to the arguments of the call/invoke.
6723 if (transformConstExprCastCall(CS)) return 0;
6725 Value *Callee = CS.getCalledValue();
6727 if (Function *CalleeF = dyn_cast<Function>(Callee))
6728 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6729 Instruction *OldCall = CS.getInstruction();
6730 // If the call and callee calling conventions don't match, this call must
6731 // be unreachable, as the call is undefined.
6732 new StoreInst(ConstantBool::getTrue(),
6733 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6734 if (!OldCall->use_empty())
6735 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6736 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6737 return EraseInstFromFunction(*OldCall);
6741 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6742 // This instruction is not reachable, just remove it. We insert a store to
6743 // undef so that we know that this code is not reachable, despite the fact
6744 // that we can't modify the CFG here.
6745 new StoreInst(ConstantBool::getTrue(),
6746 UndefValue::get(PointerType::get(Type::BoolTy)),
6747 CS.getInstruction());
6749 if (!CS.getInstruction()->use_empty())
6750 CS.getInstruction()->
6751 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6753 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6754 // Don't break the CFG, insert a dummy cond branch.
6755 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6756 ConstantBool::getTrue(), II);
6758 return EraseInstFromFunction(*CS.getInstruction());
6761 const PointerType *PTy = cast<PointerType>(Callee->getType());
6762 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6763 if (FTy->isVarArg()) {
6764 // See if we can optimize any arguments passed through the varargs area of
6766 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6767 E = CS.arg_end(); I != E; ++I)
6768 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6769 // If this cast does not effect the value passed through the varargs
6770 // area, we can eliminate the use of the cast.
6771 Value *Op = CI->getOperand(0);
6772 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6779 return Changed ? CS.getInstruction() : 0;
6782 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6783 // attempt to move the cast to the arguments of the call/invoke.
6785 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6786 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6787 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6788 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
6790 Function *Callee = cast<Function>(CE->getOperand(0));
6791 Instruction *Caller = CS.getInstruction();
6793 // Okay, this is a cast from a function to a different type. Unless doing so
6794 // would cause a type conversion of one of our arguments, change this call to
6795 // be a direct call with arguments casted to the appropriate types.
6797 const FunctionType *FT = Callee->getFunctionType();
6798 const Type *OldRetTy = Caller->getType();
6800 // Check to see if we are changing the return type...
6801 if (OldRetTy != FT->getReturnType()) {
6802 if (Callee->isExternal() &&
6803 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6804 (isa<PointerType>(FT->getReturnType()) &&
6805 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
6806 && !Caller->use_empty())
6807 return false; // Cannot transform this return value...
6809 // If the callsite is an invoke instruction, and the return value is used by
6810 // a PHI node in a successor, we cannot change the return type of the call
6811 // because there is no place to put the cast instruction (without breaking
6812 // the critical edge). Bail out in this case.
6813 if (!Caller->use_empty())
6814 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6815 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6817 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6818 if (PN->getParent() == II->getNormalDest() ||
6819 PN->getParent() == II->getUnwindDest())
6823 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6824 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6826 CallSite::arg_iterator AI = CS.arg_begin();
6827 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6828 const Type *ParamTy = FT->getParamType(i);
6829 const Type *ActTy = (*AI)->getType();
6830 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
6831 //Either we can cast directly, or we can upconvert the argument
6832 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6833 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6834 ParamTy->isSigned() == ActTy->isSigned() &&
6835 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6836 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6837 c->getSExtValue() > 0);
6838 if (Callee->isExternal() && !isConvertible) return false;
6841 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6842 Callee->isExternal())
6843 return false; // Do not delete arguments unless we have a function body...
6845 // Okay, we decided that this is a safe thing to do: go ahead and start
6846 // inserting cast instructions as necessary...
6847 std::vector<Value*> Args;
6848 Args.reserve(NumActualArgs);
6850 AI = CS.arg_begin();
6851 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6852 const Type *ParamTy = FT->getParamType(i);
6853 if ((*AI)->getType() == ParamTy) {
6854 Args.push_back(*AI);
6856 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6861 // If the function takes more arguments than the call was taking, add them
6863 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6864 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6866 // If we are removing arguments to the function, emit an obnoxious warning...
6867 if (FT->getNumParams() < NumActualArgs)
6868 if (!FT->isVarArg()) {
6869 llvm_cerr << "WARNING: While resolving call to function '"
6870 << Callee->getName() << "' arguments were dropped!\n";
6872 // Add all of the arguments in their promoted form to the arg list...
6873 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6874 const Type *PTy = getPromotedType((*AI)->getType());
6875 if (PTy != (*AI)->getType()) {
6876 // Must promote to pass through va_arg area!
6877 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6878 InsertNewInstBefore(Cast, *Caller);
6879 Args.push_back(Cast);
6881 Args.push_back(*AI);
6886 if (FT->getReturnType() == Type::VoidTy)
6887 Caller->setName(""); // Void type should not have a name...
6890 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6891 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
6892 Args, Caller->getName(), Caller);
6893 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
6895 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
6896 if (cast<CallInst>(Caller)->isTailCall())
6897 cast<CallInst>(NC)->setTailCall();
6898 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
6901 // Insert a cast of the return type as necessary...
6903 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6904 if (NV->getType() != Type::VoidTy) {
6905 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
6907 // If this is an invoke instruction, we should insert it after the first
6908 // non-phi, instruction in the normal successor block.
6909 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6910 BasicBlock::iterator I = II->getNormalDest()->begin();
6911 while (isa<PHINode>(I)) ++I;
6912 InsertNewInstBefore(NC, *I);
6914 // Otherwise, it's a call, just insert cast right after the call instr
6915 InsertNewInstBefore(NC, *Caller);
6917 AddUsersToWorkList(*Caller);
6919 NV = UndefValue::get(Caller->getType());
6923 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6924 Caller->replaceAllUsesWith(NV);
6925 Caller->getParent()->getInstList().erase(Caller);
6926 removeFromWorkList(Caller);
6930 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
6931 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
6932 /// and a single binop.
6933 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6934 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6935 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
6936 isa<GetElementPtrInst>(FirstInst));
6937 unsigned Opc = FirstInst->getOpcode();
6938 Value *LHSVal = FirstInst->getOperand(0);
6939 Value *RHSVal = FirstInst->getOperand(1);
6941 const Type *LHSType = LHSVal->getType();
6942 const Type *RHSType = RHSVal->getType();
6944 // Scan to see if all operands are the same opcode, all have one use, and all
6945 // kill their operands (i.e. the operands have one use).
6946 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
6947 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
6948 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
6949 // Verify type of the LHS matches so we don't fold setcc's of different
6950 // types or GEP's with different index types.
6951 I->getOperand(0)->getType() != LHSType ||
6952 I->getOperand(1)->getType() != RHSType)
6955 // Keep track of which operand needs a phi node.
6956 if (I->getOperand(0) != LHSVal) LHSVal = 0;
6957 if (I->getOperand(1) != RHSVal) RHSVal = 0;
6960 // Otherwise, this is safe to transform, determine if it is profitable.
6962 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
6963 // Indexes are often folded into load/store instructions, so we don't want to
6964 // hide them behind a phi.
6965 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
6968 Value *InLHS = FirstInst->getOperand(0);
6969 Value *InRHS = FirstInst->getOperand(1);
6970 PHINode *NewLHS = 0, *NewRHS = 0;
6972 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
6973 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6974 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
6975 InsertNewInstBefore(NewLHS, PN);
6980 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
6981 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6982 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
6983 InsertNewInstBefore(NewRHS, PN);
6987 // Add all operands to the new PHIs.
6988 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6990 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6991 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6994 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
6995 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
6999 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7000 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7001 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7002 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7004 assert(isa<GetElementPtrInst>(FirstInst));
7005 return new GetElementPtrInst(LHSVal, RHSVal);
7009 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7010 /// of the block that defines it. This means that it must be obvious the value
7011 /// of the load is not changed from the point of the load to the end of the
7013 static bool isSafeToSinkLoad(LoadInst *L) {
7014 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7016 for (++BBI; BBI != E; ++BBI)
7017 if (BBI->mayWriteToMemory())
7023 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7024 // operator and they all are only used by the PHI, PHI together their
7025 // inputs, and do the operation once, to the result of the PHI.
7026 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7027 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7029 // Scan the instruction, looking for input operations that can be folded away.
7030 // If all input operands to the phi are the same instruction (e.g. a cast from
7031 // the same type or "+42") we can pull the operation through the PHI, reducing
7032 // code size and simplifying code.
7033 Constant *ConstantOp = 0;
7034 const Type *CastSrcTy = 0;
7035 bool isVolatile = false;
7036 if (isa<CastInst>(FirstInst)) {
7037 CastSrcTy = FirstInst->getOperand(0)->getType();
7038 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
7039 // Can fold binop or shift here if the RHS is a constant, otherwise call
7040 // FoldPHIArgBinOpIntoPHI.
7041 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7042 if (ConstantOp == 0)
7043 return FoldPHIArgBinOpIntoPHI(PN);
7044 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7045 isVolatile = LI->isVolatile();
7046 // We can't sink the load if the loaded value could be modified between the
7047 // load and the PHI.
7048 if (LI->getParent() != PN.getIncomingBlock(0) ||
7049 !isSafeToSinkLoad(LI))
7051 } else if (isa<GetElementPtrInst>(FirstInst)) {
7052 if (FirstInst->getNumOperands() == 2)
7053 return FoldPHIArgBinOpIntoPHI(PN);
7054 // Can't handle general GEPs yet.
7057 return 0; // Cannot fold this operation.
7060 // Check to see if all arguments are the same operation.
7061 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7062 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7063 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7064 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7067 if (I->getOperand(0)->getType() != CastSrcTy)
7068 return 0; // Cast operation must match.
7069 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7070 // We can't sink the load if the loaded value could be modified between the
7071 // load and the PHI.
7072 if (LI->isVolatile() != isVolatile ||
7073 LI->getParent() != PN.getIncomingBlock(i) ||
7074 !isSafeToSinkLoad(LI))
7076 } else if (I->getOperand(1) != ConstantOp) {
7081 // Okay, they are all the same operation. Create a new PHI node of the
7082 // correct type, and PHI together all of the LHS's of the instructions.
7083 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7084 PN.getName()+".in");
7085 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7087 Value *InVal = FirstInst->getOperand(0);
7088 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7090 // Add all operands to the new PHI.
7091 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7092 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7093 if (NewInVal != InVal)
7095 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7100 // The new PHI unions all of the same values together. This is really
7101 // common, so we handle it intelligently here for compile-time speed.
7105 InsertNewInstBefore(NewPN, PN);
7109 // Insert and return the new operation.
7110 if (isa<CastInst>(FirstInst))
7111 return new CastInst(PhiVal, PN.getType());
7112 else if (isa<LoadInst>(FirstInst))
7113 return new LoadInst(PhiVal, "", isVolatile);
7114 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7115 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7117 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7118 PhiVal, ConstantOp);
7121 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7123 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7124 if (PN->use_empty()) return true;
7125 if (!PN->hasOneUse()) return false;
7127 // Remember this node, and if we find the cycle, return.
7128 if (!PotentiallyDeadPHIs.insert(PN).second)
7131 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7132 return DeadPHICycle(PU, PotentiallyDeadPHIs);
7137 // PHINode simplification
7139 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7140 // If LCSSA is around, don't mess with Phi nodes
7141 if (mustPreserveAnalysisID(LCSSAID)) return 0;
7143 if (Value *V = PN.hasConstantValue())
7144 return ReplaceInstUsesWith(PN, V);
7146 // If all PHI operands are the same operation, pull them through the PHI,
7147 // reducing code size.
7148 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7149 PN.getIncomingValue(0)->hasOneUse())
7150 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7153 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7154 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7155 // PHI)... break the cycle.
7157 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7158 std::set<PHINode*> PotentiallyDeadPHIs;
7159 PotentiallyDeadPHIs.insert(&PN);
7160 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7161 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7167 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7168 Instruction *InsertPoint,
7170 unsigned PS = IC->getTargetData().getPointerSize();
7171 const Type *VTy = V->getType();
7172 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7173 // We must insert a cast to ensure we sign-extend.
7174 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7175 return IC->InsertCastBefore(V, DTy, *InsertPoint);
7179 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7180 Value *PtrOp = GEP.getOperand(0);
7181 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
7182 // If so, eliminate the noop.
7183 if (GEP.getNumOperands() == 1)
7184 return ReplaceInstUsesWith(GEP, PtrOp);
7186 if (isa<UndefValue>(GEP.getOperand(0)))
7187 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7189 bool HasZeroPointerIndex = false;
7190 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7191 HasZeroPointerIndex = C->isNullValue();
7193 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7194 return ReplaceInstUsesWith(GEP, PtrOp);
7196 // Eliminate unneeded casts for indices.
7197 bool MadeChange = false;
7198 gep_type_iterator GTI = gep_type_begin(GEP);
7199 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7200 if (isa<SequentialType>(*GTI)) {
7201 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7202 Value *Src = CI->getOperand(0);
7203 const Type *SrcTy = Src->getType();
7204 const Type *DestTy = CI->getType();
7205 if (Src->getType()->isInteger()) {
7206 if (SrcTy->getPrimitiveSizeInBits() ==
7207 DestTy->getPrimitiveSizeInBits()) {
7208 // We can always eliminate a cast from ulong or long to the other.
7209 // We can always eliminate a cast from uint to int or the other on
7210 // 32-bit pointer platforms.
7211 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7213 GEP.setOperand(i, Src);
7215 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7216 SrcTy->getPrimitiveSize() == 4) {
7217 // We can always eliminate a cast from int to [u]long. We can
7218 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7220 if (SrcTy->isSigned() ||
7221 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7223 GEP.setOperand(i, Src);
7228 // If we are using a wider index than needed for this platform, shrink it
7229 // to what we need. If the incoming value needs a cast instruction,
7230 // insert it. This explicit cast can make subsequent optimizations more
7232 Value *Op = GEP.getOperand(i);
7233 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7234 if (Constant *C = dyn_cast<Constant>(Op)) {
7235 GEP.setOperand(i, ConstantExpr::getCast(C,
7236 TD->getIntPtrType()->getSignedVersion()));
7239 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
7240 GEP.setOperand(i, Op);
7244 // If this is a constant idx, make sure to canonicalize it to be a signed
7245 // operand, otherwise CSE and other optimizations are pessimized.
7246 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7247 if (CUI->getType()->isUnsigned()) {
7249 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7253 if (MadeChange) return &GEP;
7255 // Combine Indices - If the source pointer to this getelementptr instruction
7256 // is a getelementptr instruction, combine the indices of the two
7257 // getelementptr instructions into a single instruction.
7259 std::vector<Value*> SrcGEPOperands;
7260 if (User *Src = dyn_castGetElementPtr(PtrOp))
7261 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7263 if (!SrcGEPOperands.empty()) {
7264 // Note that if our source is a gep chain itself that we wait for that
7265 // chain to be resolved before we perform this transformation. This
7266 // avoids us creating a TON of code in some cases.
7268 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7269 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7270 return 0; // Wait until our source is folded to completion.
7272 std::vector<Value *> Indices;
7274 // Find out whether the last index in the source GEP is a sequential idx.
7275 bool EndsWithSequential = false;
7276 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7277 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7278 EndsWithSequential = !isa<StructType>(*I);
7280 // Can we combine the two pointer arithmetics offsets?
7281 if (EndsWithSequential) {
7282 // Replace: gep (gep %P, long B), long A, ...
7283 // With: T = long A+B; gep %P, T, ...
7285 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7286 if (SO1 == Constant::getNullValue(SO1->getType())) {
7288 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7291 // If they aren't the same type, convert both to an integer of the
7292 // target's pointer size.
7293 if (SO1->getType() != GO1->getType()) {
7294 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7295 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7296 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7297 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7299 unsigned PS = TD->getPointerSize();
7300 if (SO1->getType()->getPrimitiveSize() == PS) {
7301 // Convert GO1 to SO1's type.
7302 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7304 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7305 // Convert SO1 to GO1's type.
7306 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7308 const Type *PT = TD->getIntPtrType();
7309 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7310 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7314 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7315 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7317 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7318 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7322 // Recycle the GEP we already have if possible.
7323 if (SrcGEPOperands.size() == 2) {
7324 GEP.setOperand(0, SrcGEPOperands[0]);
7325 GEP.setOperand(1, Sum);
7328 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7329 SrcGEPOperands.end()-1);
7330 Indices.push_back(Sum);
7331 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7333 } else if (isa<Constant>(*GEP.idx_begin()) &&
7334 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7335 SrcGEPOperands.size() != 1) {
7336 // Otherwise we can do the fold if the first index of the GEP is a zero
7337 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7338 SrcGEPOperands.end());
7339 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7342 if (!Indices.empty())
7343 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7345 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7346 // GEP of global variable. If all of the indices for this GEP are
7347 // constants, we can promote this to a constexpr instead of an instruction.
7349 // Scan for nonconstants...
7350 std::vector<Constant*> Indices;
7351 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7352 for (; I != E && isa<Constant>(*I); ++I)
7353 Indices.push_back(cast<Constant>(*I));
7355 if (I == E) { // If they are all constants...
7356 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7358 // Replace all uses of the GEP with the new constexpr...
7359 return ReplaceInstUsesWith(GEP, CE);
7361 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7362 if (!isa<PointerType>(X->getType())) {
7363 // Not interesting. Source pointer must be a cast from pointer.
7364 } else if (HasZeroPointerIndex) {
7365 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7366 // into : GEP [10 x ubyte]* X, long 0, ...
7368 // This occurs when the program declares an array extern like "int X[];"
7370 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7371 const PointerType *XTy = cast<PointerType>(X->getType());
7372 if (const ArrayType *XATy =
7373 dyn_cast<ArrayType>(XTy->getElementType()))
7374 if (const ArrayType *CATy =
7375 dyn_cast<ArrayType>(CPTy->getElementType()))
7376 if (CATy->getElementType() == XATy->getElementType()) {
7377 // At this point, we know that the cast source type is a pointer
7378 // to an array of the same type as the destination pointer
7379 // array. Because the array type is never stepped over (there
7380 // is a leading zero) we can fold the cast into this GEP.
7381 GEP.setOperand(0, X);
7384 } else if (GEP.getNumOperands() == 2) {
7385 // Transform things like:
7386 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7387 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7388 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7389 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7390 if (isa<ArrayType>(SrcElTy) &&
7391 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7392 TD->getTypeSize(ResElTy)) {
7393 Value *V = InsertNewInstBefore(
7394 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7395 GEP.getOperand(1), GEP.getName()), GEP);
7396 return new CastInst(V, GEP.getType());
7399 // Transform things like:
7400 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7401 // (where tmp = 8*tmp2) into:
7402 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7404 if (isa<ArrayType>(SrcElTy) &&
7405 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7406 uint64_t ArrayEltSize =
7407 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7409 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7410 // allow either a mul, shift, or constant here.
7412 ConstantInt *Scale = 0;
7413 if (ArrayEltSize == 1) {
7414 NewIdx = GEP.getOperand(1);
7415 Scale = ConstantInt::get(NewIdx->getType(), 1);
7416 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7417 NewIdx = ConstantInt::get(CI->getType(), 1);
7419 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7420 if (Inst->getOpcode() == Instruction::Shl &&
7421 isa<ConstantInt>(Inst->getOperand(1))) {
7423 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7424 if (Inst->getType()->isSigned())
7425 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7427 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7428 NewIdx = Inst->getOperand(0);
7429 } else if (Inst->getOpcode() == Instruction::Mul &&
7430 isa<ConstantInt>(Inst->getOperand(1))) {
7431 Scale = cast<ConstantInt>(Inst->getOperand(1));
7432 NewIdx = Inst->getOperand(0);
7436 // If the index will be to exactly the right offset with the scale taken
7437 // out, perform the transformation.
7438 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7439 if (isa<ConstantInt>(Scale))
7440 Scale = ConstantInt::get(Scale->getType(),
7441 Scale->getZExtValue() / ArrayEltSize);
7442 if (Scale->getZExtValue() != 1) {
7443 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7444 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7445 NewIdx = InsertNewInstBefore(Sc, GEP);
7448 // Insert the new GEP instruction.
7450 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7451 NewIdx, GEP.getName());
7452 Idx = InsertNewInstBefore(Idx, GEP);
7453 return new CastInst(Idx, GEP.getType());
7462 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7463 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7464 if (AI.isArrayAllocation()) // Check C != 1
7465 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7467 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7468 AllocationInst *New = 0;
7470 // Create and insert the replacement instruction...
7471 if (isa<MallocInst>(AI))
7472 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7474 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7475 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7478 InsertNewInstBefore(New, AI);
7480 // Scan to the end of the allocation instructions, to skip over a block of
7481 // allocas if possible...
7483 BasicBlock::iterator It = New;
7484 while (isa<AllocationInst>(*It)) ++It;
7486 // Now that I is pointing to the first non-allocation-inst in the block,
7487 // insert our getelementptr instruction...
7489 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7490 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7491 New->getName()+".sub", It);
7493 // Now make everything use the getelementptr instead of the original
7495 return ReplaceInstUsesWith(AI, V);
7496 } else if (isa<UndefValue>(AI.getArraySize())) {
7497 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7500 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7501 // Note that we only do this for alloca's, because malloc should allocate and
7502 // return a unique pointer, even for a zero byte allocation.
7503 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7504 TD->getTypeSize(AI.getAllocatedType()) == 0)
7505 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7510 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7511 Value *Op = FI.getOperand(0);
7513 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7514 if (CastInst *CI = dyn_cast<CastInst>(Op))
7515 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7516 FI.setOperand(0, CI->getOperand(0));
7520 // free undef -> unreachable.
7521 if (isa<UndefValue>(Op)) {
7522 // Insert a new store to null because we cannot modify the CFG here.
7523 new StoreInst(ConstantBool::getTrue(),
7524 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7525 return EraseInstFromFunction(FI);
7528 // If we have 'free null' delete the instruction. This can happen in stl code
7529 // when lots of inlining happens.
7530 if (isa<ConstantPointerNull>(Op))
7531 return EraseInstFromFunction(FI);
7537 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7538 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7539 User *CI = cast<User>(LI.getOperand(0));
7540 Value *CastOp = CI->getOperand(0);
7542 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7543 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7544 const Type *SrcPTy = SrcTy->getElementType();
7546 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7547 isa<PackedType>(DestPTy)) {
7548 // If the source is an array, the code below will not succeed. Check to
7549 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7551 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7552 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7553 if (ASrcTy->getNumElements() != 0) {
7554 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7555 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7556 SrcTy = cast<PointerType>(CastOp->getType());
7557 SrcPTy = SrcTy->getElementType();
7560 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7561 isa<PackedType>(SrcPTy)) &&
7562 // Do not allow turning this into a load of an integer, which is then
7563 // casted to a pointer, this pessimizes pointer analysis a lot.
7564 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7565 IC.getTargetData().getTypeSize(SrcPTy) ==
7566 IC.getTargetData().getTypeSize(DestPTy)) {
7568 // Okay, we are casting from one integer or pointer type to another of
7569 // the same size. Instead of casting the pointer before the load, cast
7570 // the result of the loaded value.
7571 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7573 LI.isVolatile()),LI);
7574 // Now cast the result of the load.
7575 return new CastInst(NewLoad, LI.getType());
7582 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
7583 /// from this value cannot trap. If it is not obviously safe to load from the
7584 /// specified pointer, we do a quick local scan of the basic block containing
7585 /// ScanFrom, to determine if the address is already accessed.
7586 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7587 // If it is an alloca or global variable, it is always safe to load from.
7588 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7590 // Otherwise, be a little bit agressive by scanning the local block where we
7591 // want to check to see if the pointer is already being loaded or stored
7592 // from/to. If so, the previous load or store would have already trapped,
7593 // so there is no harm doing an extra load (also, CSE will later eliminate
7594 // the load entirely).
7595 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7600 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7601 if (LI->getOperand(0) == V) return true;
7602 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7603 if (SI->getOperand(1) == V) return true;
7609 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7610 Value *Op = LI.getOperand(0);
7612 // load (cast X) --> cast (load X) iff safe
7613 if (isa<CastInst>(Op))
7614 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7617 // None of the following transforms are legal for volatile loads.
7618 if (LI.isVolatile()) return 0;
7620 if (&LI.getParent()->front() != &LI) {
7621 BasicBlock::iterator BBI = &LI; --BBI;
7622 // If the instruction immediately before this is a store to the same
7623 // address, do a simple form of store->load forwarding.
7624 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7625 if (SI->getOperand(1) == LI.getOperand(0))
7626 return ReplaceInstUsesWith(LI, SI->getOperand(0));
7627 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7628 if (LIB->getOperand(0) == LI.getOperand(0))
7629 return ReplaceInstUsesWith(LI, LIB);
7632 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7633 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7634 isa<UndefValue>(GEPI->getOperand(0))) {
7635 // Insert a new store to null instruction before the load to indicate
7636 // that this code is not reachable. We do this instead of inserting
7637 // an unreachable instruction directly because we cannot modify the
7639 new StoreInst(UndefValue::get(LI.getType()),
7640 Constant::getNullValue(Op->getType()), &LI);
7641 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7644 if (Constant *C = dyn_cast<Constant>(Op)) {
7645 // load null/undef -> undef
7646 if ((C->isNullValue() || isa<UndefValue>(C))) {
7647 // Insert a new store to null instruction before the load to indicate that
7648 // this code is not reachable. We do this instead of inserting an
7649 // unreachable instruction directly because we cannot modify the CFG.
7650 new StoreInst(UndefValue::get(LI.getType()),
7651 Constant::getNullValue(Op->getType()), &LI);
7652 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7655 // Instcombine load (constant global) into the value loaded.
7656 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7657 if (GV->isConstant() && !GV->isExternal())
7658 return ReplaceInstUsesWith(LI, GV->getInitializer());
7660 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7661 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7662 if (CE->getOpcode() == Instruction::GetElementPtr) {
7663 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7664 if (GV->isConstant() && !GV->isExternal())
7666 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
7667 return ReplaceInstUsesWith(LI, V);
7668 if (CE->getOperand(0)->isNullValue()) {
7669 // Insert a new store to null instruction before the load to indicate
7670 // that this code is not reachable. We do this instead of inserting
7671 // an unreachable instruction directly because we cannot modify the
7673 new StoreInst(UndefValue::get(LI.getType()),
7674 Constant::getNullValue(Op->getType()), &LI);
7675 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7678 } else if (CE->getOpcode() == Instruction::Cast) {
7679 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7684 if (Op->hasOneUse()) {
7685 // Change select and PHI nodes to select values instead of addresses: this
7686 // helps alias analysis out a lot, allows many others simplifications, and
7687 // exposes redundancy in the code.
7689 // Note that we cannot do the transformation unless we know that the
7690 // introduced loads cannot trap! Something like this is valid as long as
7691 // the condition is always false: load (select bool %C, int* null, int* %G),
7692 // but it would not be valid if we transformed it to load from null
7695 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7696 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
7697 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7698 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
7699 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
7700 SI->getOperand(1)->getName()+".val"), LI);
7701 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
7702 SI->getOperand(2)->getName()+".val"), LI);
7703 return new SelectInst(SI->getCondition(), V1, V2);
7706 // load (select (cond, null, P)) -> load P
7707 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7708 if (C->isNullValue()) {
7709 LI.setOperand(0, SI->getOperand(2));
7713 // load (select (cond, P, null)) -> load P
7714 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7715 if (C->isNullValue()) {
7716 LI.setOperand(0, SI->getOperand(1));
7724 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7726 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7727 User *CI = cast<User>(SI.getOperand(1));
7728 Value *CastOp = CI->getOperand(0);
7730 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7731 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7732 const Type *SrcPTy = SrcTy->getElementType();
7734 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7735 // If the source is an array, the code below will not succeed. Check to
7736 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7738 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7739 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7740 if (ASrcTy->getNumElements() != 0) {
7741 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7742 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7743 SrcTy = cast<PointerType>(CastOp->getType());
7744 SrcPTy = SrcTy->getElementType();
7747 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
7748 IC.getTargetData().getTypeSize(SrcPTy) ==
7749 IC.getTargetData().getTypeSize(DestPTy)) {
7751 // Okay, we are casting from one integer or pointer type to another of
7752 // the same size. Instead of casting the pointer before the store, cast
7753 // the value to be stored.
7755 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7756 NewCast = ConstantExpr::getCast(C, SrcPTy);
7758 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7760 SI.getOperand(0)->getName()+".c"), SI);
7762 return new StoreInst(NewCast, CastOp);
7769 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7770 Value *Val = SI.getOperand(0);
7771 Value *Ptr = SI.getOperand(1);
7773 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
7774 EraseInstFromFunction(SI);
7779 // Do really simple DSE, to catch cases where there are several consequtive
7780 // stores to the same location, separated by a few arithmetic operations. This
7781 // situation often occurs with bitfield accesses.
7782 BasicBlock::iterator BBI = &SI;
7783 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7787 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7788 // Prev store isn't volatile, and stores to the same location?
7789 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7792 EraseInstFromFunction(*PrevSI);
7798 // If this is a load, we have to stop. However, if the loaded value is from
7799 // the pointer we're loading and is producing the pointer we're storing,
7800 // then *this* store is dead (X = load P; store X -> P).
7801 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7802 if (LI == Val && LI->getOperand(0) == Ptr) {
7803 EraseInstFromFunction(SI);
7807 // Otherwise, this is a load from some other location. Stores before it
7812 // Don't skip over loads or things that can modify memory.
7813 if (BBI->mayWriteToMemory())
7818 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
7820 // store X, null -> turns into 'unreachable' in SimplifyCFG
7821 if (isa<ConstantPointerNull>(Ptr)) {
7822 if (!isa<UndefValue>(Val)) {
7823 SI.setOperand(0, UndefValue::get(Val->getType()));
7824 if (Instruction *U = dyn_cast<Instruction>(Val))
7825 WorkList.push_back(U); // Dropped a use.
7828 return 0; // Do not modify these!
7831 // store undef, Ptr -> noop
7832 if (isa<UndefValue>(Val)) {
7833 EraseInstFromFunction(SI);
7838 // If the pointer destination is a cast, see if we can fold the cast into the
7840 if (isa<CastInst>(Ptr))
7841 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7843 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7844 if (CE->getOpcode() == Instruction::Cast)
7845 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7849 // If this store is the last instruction in the basic block, and if the block
7850 // ends with an unconditional branch, try to move it to the successor block.
7852 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7853 if (BI->isUnconditional()) {
7854 // Check to see if the successor block has exactly two incoming edges. If
7855 // so, see if the other predecessor contains a store to the same location.
7856 // if so, insert a PHI node (if needed) and move the stores down.
7857 BasicBlock *Dest = BI->getSuccessor(0);
7859 pred_iterator PI = pred_begin(Dest);
7860 BasicBlock *Other = 0;
7861 if (*PI != BI->getParent())
7864 if (PI != pred_end(Dest)) {
7865 if (*PI != BI->getParent())
7870 if (++PI != pred_end(Dest))
7873 if (Other) { // If only one other pred...
7874 BBI = Other->getTerminator();
7875 // Make sure this other block ends in an unconditional branch and that
7876 // there is an instruction before the branch.
7877 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7878 BBI != Other->begin()) {
7880 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7882 // If this instruction is a store to the same location.
7883 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7884 // Okay, we know we can perform this transformation. Insert a PHI
7885 // node now if we need it.
7886 Value *MergedVal = OtherStore->getOperand(0);
7887 if (MergedVal != SI.getOperand(0)) {
7888 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7889 PN->reserveOperandSpace(2);
7890 PN->addIncoming(SI.getOperand(0), SI.getParent());
7891 PN->addIncoming(OtherStore->getOperand(0), Other);
7892 MergedVal = InsertNewInstBefore(PN, Dest->front());
7895 // Advance to a place where it is safe to insert the new store and
7897 BBI = Dest->begin();
7898 while (isa<PHINode>(BBI)) ++BBI;
7899 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7900 OtherStore->isVolatile()), *BBI);
7902 // Nuke the old stores.
7903 EraseInstFromFunction(SI);
7904 EraseInstFromFunction(*OtherStore);
7916 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7917 // Change br (not X), label True, label False to: br X, label False, True
7919 BasicBlock *TrueDest;
7920 BasicBlock *FalseDest;
7921 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7922 !isa<Constant>(X)) {
7923 // Swap Destinations and condition...
7925 BI.setSuccessor(0, FalseDest);
7926 BI.setSuccessor(1, TrueDest);
7930 // Cannonicalize setne -> seteq
7931 Instruction::BinaryOps Op; Value *Y;
7932 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7933 TrueDest, FalseDest)))
7934 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7935 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7936 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7937 std::string Name = I->getName(); I->setName("");
7938 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7939 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
7940 // Swap Destinations and condition...
7941 BI.setCondition(NewSCC);
7942 BI.setSuccessor(0, FalseDest);
7943 BI.setSuccessor(1, TrueDest);
7944 removeFromWorkList(I);
7945 I->getParent()->getInstList().erase(I);
7946 WorkList.push_back(cast<Instruction>(NewSCC));
7953 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7954 Value *Cond = SI.getCondition();
7955 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7956 if (I->getOpcode() == Instruction::Add)
7957 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7958 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7959 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
7960 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
7962 SI.setOperand(0, I->getOperand(0));
7963 WorkList.push_back(I);
7970 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7971 /// is to leave as a vector operation.
7972 static bool CheapToScalarize(Value *V, bool isConstant) {
7973 if (isa<ConstantAggregateZero>(V))
7975 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7976 if (isConstant) return true;
7977 // If all elts are the same, we can extract.
7978 Constant *Op0 = C->getOperand(0);
7979 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7980 if (C->getOperand(i) != Op0)
7984 Instruction *I = dyn_cast<Instruction>(V);
7985 if (!I) return false;
7987 // Insert element gets simplified to the inserted element or is deleted if
7988 // this is constant idx extract element and its a constant idx insertelt.
7989 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7990 isa<ConstantInt>(I->getOperand(2)))
7992 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7994 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7995 if (BO->hasOneUse() &&
7996 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7997 CheapToScalarize(BO->getOperand(1), isConstant)))
8003 /// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8004 /// elements into values that are larger than the #elts in the input.
8005 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8006 unsigned NElts = SVI->getType()->getNumElements();
8007 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8008 return std::vector<unsigned>(NElts, 0);
8009 if (isa<UndefValue>(SVI->getOperand(2)))
8010 return std::vector<unsigned>(NElts, 2*NElts);
8012 std::vector<unsigned> Result;
8013 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8014 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8015 if (isa<UndefValue>(CP->getOperand(i)))
8016 Result.push_back(NElts*2); // undef -> 8
8018 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8022 /// FindScalarElement - Given a vector and an element number, see if the scalar
8023 /// value is already around as a register, for example if it were inserted then
8024 /// extracted from the vector.
8025 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8026 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8027 const PackedType *PTy = cast<PackedType>(V->getType());
8028 unsigned Width = PTy->getNumElements();
8029 if (EltNo >= Width) // Out of range access.
8030 return UndefValue::get(PTy->getElementType());
8032 if (isa<UndefValue>(V))
8033 return UndefValue::get(PTy->getElementType());
8034 else if (isa<ConstantAggregateZero>(V))
8035 return Constant::getNullValue(PTy->getElementType());
8036 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8037 return CP->getOperand(EltNo);
8038 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8039 // If this is an insert to a variable element, we don't know what it is.
8040 if (!isa<ConstantInt>(III->getOperand(2)))
8042 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8044 // If this is an insert to the element we are looking for, return the
8047 return III->getOperand(1);
8049 // Otherwise, the insertelement doesn't modify the value, recurse on its
8051 return FindScalarElement(III->getOperand(0), EltNo);
8052 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8053 unsigned InEl = getShuffleMask(SVI)[EltNo];
8055 return FindScalarElement(SVI->getOperand(0), InEl);
8056 else if (InEl < Width*2)
8057 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8059 return UndefValue::get(PTy->getElementType());
8062 // Otherwise, we don't know.
8066 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8068 // If packed val is undef, replace extract with scalar undef.
8069 if (isa<UndefValue>(EI.getOperand(0)))
8070 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8072 // If packed val is constant 0, replace extract with scalar 0.
8073 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8074 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8076 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8077 // If packed val is constant with uniform operands, replace EI
8078 // with that operand
8079 Constant *op0 = C->getOperand(0);
8080 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8081 if (C->getOperand(i) != op0) {
8086 return ReplaceInstUsesWith(EI, op0);
8089 // If extracting a specified index from the vector, see if we can recursively
8090 // find a previously computed scalar that was inserted into the vector.
8091 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8092 // This instruction only demands the single element from the input vector.
8093 // If the input vector has a single use, simplify it based on this use
8095 uint64_t IndexVal = IdxC->getZExtValue();
8096 if (EI.getOperand(0)->hasOneUse()) {
8098 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8101 EI.setOperand(0, V);
8106 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8107 return ReplaceInstUsesWith(EI, Elt);
8110 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8111 if (I->hasOneUse()) {
8112 // Push extractelement into predecessor operation if legal and
8113 // profitable to do so
8114 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8115 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8116 if (CheapToScalarize(BO, isConstantElt)) {
8117 ExtractElementInst *newEI0 =
8118 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8119 EI.getName()+".lhs");
8120 ExtractElementInst *newEI1 =
8121 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8122 EI.getName()+".rhs");
8123 InsertNewInstBefore(newEI0, EI);
8124 InsertNewInstBefore(newEI1, EI);
8125 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8127 } else if (isa<LoadInst>(I)) {
8128 Value *Ptr = InsertCastBefore(I->getOperand(0),
8129 PointerType::get(EI.getType()), EI);
8130 GetElementPtrInst *GEP =
8131 new GetElementPtrInst(Ptr, EI.getOperand(1),
8132 I->getName() + ".gep");
8133 InsertNewInstBefore(GEP, EI);
8134 return new LoadInst(GEP);
8137 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8138 // Extracting the inserted element?
8139 if (IE->getOperand(2) == EI.getOperand(1))
8140 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8141 // If the inserted and extracted elements are constants, they must not
8142 // be the same value, extract from the pre-inserted value instead.
8143 if (isa<Constant>(IE->getOperand(2)) &&
8144 isa<Constant>(EI.getOperand(1))) {
8145 AddUsesToWorkList(EI);
8146 EI.setOperand(0, IE->getOperand(0));
8149 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8150 // If this is extracting an element from a shufflevector, figure out where
8151 // it came from and extract from the appropriate input element instead.
8152 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8153 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8155 if (SrcIdx < SVI->getType()->getNumElements())
8156 Src = SVI->getOperand(0);
8157 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8158 SrcIdx -= SVI->getType()->getNumElements();
8159 Src = SVI->getOperand(1);
8161 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8163 return new ExtractElementInst(Src, SrcIdx);
8170 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8171 /// elements from either LHS or RHS, return the shuffle mask and true.
8172 /// Otherwise, return false.
8173 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8174 std::vector<Constant*> &Mask) {
8175 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8176 "Invalid CollectSingleShuffleElements");
8177 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8179 if (isa<UndefValue>(V)) {
8180 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8182 } else if (V == LHS) {
8183 for (unsigned i = 0; i != NumElts; ++i)
8184 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8186 } else if (V == RHS) {
8187 for (unsigned i = 0; i != NumElts; ++i)
8188 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
8190 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8191 // If this is an insert of an extract from some other vector, include it.
8192 Value *VecOp = IEI->getOperand(0);
8193 Value *ScalarOp = IEI->getOperand(1);
8194 Value *IdxOp = IEI->getOperand(2);
8196 if (!isa<ConstantInt>(IdxOp))
8198 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8200 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8201 // Okay, we can handle this if the vector we are insertinting into is
8203 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8204 // If so, update the mask to reflect the inserted undef.
8205 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8208 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8209 if (isa<ConstantInt>(EI->getOperand(1)) &&
8210 EI->getOperand(0)->getType() == V->getType()) {
8211 unsigned ExtractedIdx =
8212 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8214 // This must be extracting from either LHS or RHS.
8215 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8216 // Okay, we can handle this if the vector we are insertinting into is
8218 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8219 // If so, update the mask to reflect the inserted value.
8220 if (EI->getOperand(0) == LHS) {
8221 Mask[InsertedIdx & (NumElts-1)] =
8222 ConstantInt::get(Type::UIntTy, ExtractedIdx);
8224 assert(EI->getOperand(0) == RHS);
8225 Mask[InsertedIdx & (NumElts-1)] =
8226 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
8235 // TODO: Handle shufflevector here!
8240 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8241 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8242 /// that computes V and the LHS value of the shuffle.
8243 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8245 assert(isa<PackedType>(V->getType()) &&
8246 (RHS == 0 || V->getType() == RHS->getType()) &&
8247 "Invalid shuffle!");
8248 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8250 if (isa<UndefValue>(V)) {
8251 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8253 } else if (isa<ConstantAggregateZero>(V)) {
8254 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
8256 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8257 // If this is an insert of an extract from some other vector, include it.
8258 Value *VecOp = IEI->getOperand(0);
8259 Value *ScalarOp = IEI->getOperand(1);
8260 Value *IdxOp = IEI->getOperand(2);
8262 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8263 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8264 EI->getOperand(0)->getType() == V->getType()) {
8265 unsigned ExtractedIdx =
8266 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8267 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8269 // Either the extracted from or inserted into vector must be RHSVec,
8270 // otherwise we'd end up with a shuffle of three inputs.
8271 if (EI->getOperand(0) == RHS || RHS == 0) {
8272 RHS = EI->getOperand(0);
8273 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8274 Mask[InsertedIdx & (NumElts-1)] =
8275 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
8280 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8281 // Everything but the extracted element is replaced with the RHS.
8282 for (unsigned i = 0; i != NumElts; ++i) {
8283 if (i != InsertedIdx)
8284 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
8289 // If this insertelement is a chain that comes from exactly these two
8290 // vectors, return the vector and the effective shuffle.
8291 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8292 return EI->getOperand(0);
8297 // TODO: Handle shufflevector here!
8299 // Otherwise, can't do anything fancy. Return an identity vector.
8300 for (unsigned i = 0; i != NumElts; ++i)
8301 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8305 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8306 Value *VecOp = IE.getOperand(0);
8307 Value *ScalarOp = IE.getOperand(1);
8308 Value *IdxOp = IE.getOperand(2);
8310 // If the inserted element was extracted from some other vector, and if the
8311 // indexes are constant, try to turn this into a shufflevector operation.
8312 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8313 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8314 EI->getOperand(0)->getType() == IE.getType()) {
8315 unsigned NumVectorElts = IE.getType()->getNumElements();
8316 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8317 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8319 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8320 return ReplaceInstUsesWith(IE, VecOp);
8322 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8323 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8325 // If we are extracting a value from a vector, then inserting it right
8326 // back into the same place, just use the input vector.
8327 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8328 return ReplaceInstUsesWith(IE, VecOp);
8330 // We could theoretically do this for ANY input. However, doing so could
8331 // turn chains of insertelement instructions into a chain of shufflevector
8332 // instructions, and right now we do not merge shufflevectors. As such,
8333 // only do this in a situation where it is clear that there is benefit.
8334 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8335 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8336 // the values of VecOp, except then one read from EIOp0.
8337 // Build a new shuffle mask.
8338 std::vector<Constant*> Mask;
8339 if (isa<UndefValue>(VecOp))
8340 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8342 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8343 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
8346 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
8347 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8348 ConstantPacked::get(Mask));
8351 // If this insertelement isn't used by some other insertelement, turn it
8352 // (and any insertelements it points to), into one big shuffle.
8353 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8354 std::vector<Constant*> Mask;
8356 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8357 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8358 // We now have a shuffle of LHS, RHS, Mask.
8359 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8368 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8369 Value *LHS = SVI.getOperand(0);
8370 Value *RHS = SVI.getOperand(1);
8371 std::vector<unsigned> Mask = getShuffleMask(&SVI);
8373 bool MadeChange = false;
8375 // Undefined shuffle mask -> undefined value.
8376 if (isa<UndefValue>(SVI.getOperand(2)))
8377 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8379 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8380 // the undef, change them to undefs.
8382 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8383 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8384 if (LHS == RHS || isa<UndefValue>(LHS)) {
8385 if (isa<UndefValue>(LHS) && LHS == RHS) {
8386 // shuffle(undef,undef,mask) -> undef.
8387 return ReplaceInstUsesWith(SVI, LHS);
8390 // Remap any references to RHS to use LHS.
8391 std::vector<Constant*> Elts;
8392 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8394 Elts.push_back(UndefValue::get(Type::UIntTy));
8396 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8397 (Mask[i] < e && isa<UndefValue>(LHS)))
8398 Mask[i] = 2*e; // Turn into undef.
8400 Mask[i] &= (e-1); // Force to LHS.
8401 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
8404 SVI.setOperand(0, SVI.getOperand(1));
8405 SVI.setOperand(1, UndefValue::get(RHS->getType()));
8406 SVI.setOperand(2, ConstantPacked::get(Elts));
8407 LHS = SVI.getOperand(0);
8408 RHS = SVI.getOperand(1);
8412 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8413 bool isLHSID = true, isRHSID = true;
8415 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8416 if (Mask[i] >= e*2) continue; // Ignore undef values.
8417 // Is this an identity shuffle of the LHS value?
8418 isLHSID &= (Mask[i] == i);
8420 // Is this an identity shuffle of the RHS value?
8421 isRHSID &= (Mask[i]-e == i);
8424 // Eliminate identity shuffles.
8425 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8426 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8428 // If the LHS is a shufflevector itself, see if we can combine it with this
8429 // one without producing an unusual shuffle. Here we are really conservative:
8430 // we are absolutely afraid of producing a shuffle mask not in the input
8431 // program, because the code gen may not be smart enough to turn a merged
8432 // shuffle into two specific shuffles: it may produce worse code. As such,
8433 // we only merge two shuffles if the result is one of the two input shuffle
8434 // masks. In this case, merging the shuffles just removes one instruction,
8435 // which we know is safe. This is good for things like turning:
8436 // (splat(splat)) -> splat.
8437 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8438 if (isa<UndefValue>(RHS)) {
8439 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8441 std::vector<unsigned> NewMask;
8442 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8444 NewMask.push_back(2*e);
8446 NewMask.push_back(LHSMask[Mask[i]]);
8448 // If the result mask is equal to the src shuffle or this shuffle mask, do
8450 if (NewMask == LHSMask || NewMask == Mask) {
8451 std::vector<Constant*> Elts;
8452 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8453 if (NewMask[i] >= e*2) {
8454 Elts.push_back(UndefValue::get(Type::UIntTy));
8456 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
8459 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8460 LHSSVI->getOperand(1),
8461 ConstantPacked::get(Elts));
8466 return MadeChange ? &SVI : 0;
8471 void InstCombiner::removeFromWorkList(Instruction *I) {
8472 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8477 /// TryToSinkInstruction - Try to move the specified instruction from its
8478 /// current block into the beginning of DestBlock, which can only happen if it's
8479 /// safe to move the instruction past all of the instructions between it and the
8480 /// end of its block.
8481 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8482 assert(I->hasOneUse() && "Invariants didn't hold!");
8484 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8485 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8487 // Do not sink alloca instructions out of the entry block.
8488 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8491 // We can only sink load instructions if there is nothing between the load and
8492 // the end of block that could change the value.
8493 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8494 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8496 if (Scan->mayWriteToMemory())
8500 BasicBlock::iterator InsertPos = DestBlock->begin();
8501 while (isa<PHINode>(InsertPos)) ++InsertPos;
8503 I->moveBefore(InsertPos);
8508 /// OptimizeConstantExpr - Given a constant expression and target data layout
8509 /// information, symbolically evaluation the constant expr to something simpler
8511 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8514 Constant *Ptr = CE->getOperand(0);
8515 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8516 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8517 // If this is a constant expr gep that is effectively computing an
8518 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8519 bool isFoldableGEP = true;
8520 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8521 if (!isa<ConstantInt>(CE->getOperand(i)))
8522 isFoldableGEP = false;
8523 if (isFoldableGEP) {
8524 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8525 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8526 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
8527 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8528 return ConstantExpr::getCast(C, CE->getType());
8536 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8537 /// all reachable code to the worklist.
8539 /// This has a couple of tricks to make the code faster and more powerful. In
8540 /// particular, we constant fold and DCE instructions as we go, to avoid adding
8541 /// them to the worklist (this significantly speeds up instcombine on code where
8542 /// many instructions are dead or constant). Additionally, if we find a branch
8543 /// whose condition is a known constant, we only visit the reachable successors.
8545 static void AddReachableCodeToWorklist(BasicBlock *BB,
8546 std::set<BasicBlock*> &Visited,
8547 std::vector<Instruction*> &WorkList,
8548 const TargetData *TD) {
8549 // We have now visited this block! If we've already been here, bail out.
8550 if (!Visited.insert(BB).second) return;
8552 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8553 Instruction *Inst = BBI++;
8555 // DCE instruction if trivially dead.
8556 if (isInstructionTriviallyDead(Inst)) {
8558 DOUT << "IC: DCE: " << *Inst;
8559 Inst->eraseFromParent();
8563 // ConstantProp instruction if trivially constant.
8564 if (Constant *C = ConstantFoldInstruction(Inst)) {
8565 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8566 C = OptimizeConstantExpr(CE, TD);
8567 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
8568 Inst->replaceAllUsesWith(C);
8570 Inst->eraseFromParent();
8574 WorkList.push_back(Inst);
8577 // Recursively visit successors. If this is a branch or switch on a constant,
8578 // only visit the reachable successor.
8579 TerminatorInst *TI = BB->getTerminator();
8580 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8581 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8582 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
8583 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8587 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8588 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8589 // See if this is an explicit destination.
8590 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8591 if (SI->getCaseValue(i) == Cond) {
8592 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
8596 // Otherwise it is the default destination.
8597 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
8602 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
8603 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
8606 bool InstCombiner::runOnFunction(Function &F) {
8607 bool Changed = false;
8608 TD = &getAnalysis<TargetData>();
8611 // Do a depth-first traversal of the function, populate the worklist with
8612 // the reachable instructions. Ignore blocks that are not reachable. Keep
8613 // track of which blocks we visit.
8614 std::set<BasicBlock*> Visited;
8615 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
8617 // Do a quick scan over the function. If we find any blocks that are
8618 // unreachable, remove any instructions inside of them. This prevents
8619 // the instcombine code from having to deal with some bad special cases.
8620 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8621 if (!Visited.count(BB)) {
8622 Instruction *Term = BB->getTerminator();
8623 while (Term != BB->begin()) { // Remove instrs bottom-up
8624 BasicBlock::iterator I = Term; --I;
8626 DOUT << "IC: DCE: " << *I;
8629 if (!I->use_empty())
8630 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8631 I->eraseFromParent();
8636 while (!WorkList.empty()) {
8637 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8638 WorkList.pop_back();
8640 // Check to see if we can DCE the instruction.
8641 if (isInstructionTriviallyDead(I)) {
8642 // Add operands to the worklist.
8643 if (I->getNumOperands() < 4)
8644 AddUsesToWorkList(*I);
8647 DOUT << "IC: DCE: " << *I;
8649 I->eraseFromParent();
8650 removeFromWorkList(I);
8654 // Instruction isn't dead, see if we can constant propagate it.
8655 if (Constant *C = ConstantFoldInstruction(I)) {
8656 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8657 C = OptimizeConstantExpr(CE, TD);
8658 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
8660 // Add operands to the worklist.
8661 AddUsesToWorkList(*I);
8662 ReplaceInstUsesWith(*I, C);
8665 I->eraseFromParent();
8666 removeFromWorkList(I);
8670 // See if we can trivially sink this instruction to a successor basic block.
8671 if (I->hasOneUse()) {
8672 BasicBlock *BB = I->getParent();
8673 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8674 if (UserParent != BB) {
8675 bool UserIsSuccessor = false;
8676 // See if the user is one of our successors.
8677 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8678 if (*SI == UserParent) {
8679 UserIsSuccessor = true;
8683 // If the user is one of our immediate successors, and if that successor
8684 // only has us as a predecessors (we'd have to split the critical edge
8685 // otherwise), we can keep going.
8686 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8687 next(pred_begin(UserParent)) == pred_end(UserParent))
8688 // Okay, the CFG is simple enough, try to sink this instruction.
8689 Changed |= TryToSinkInstruction(I, UserParent);
8693 // Now that we have an instruction, try combining it to simplify it...
8694 if (Instruction *Result = visit(*I)) {
8696 // Should we replace the old instruction with a new one?
8698 DOUT << "IC: Old = " << *I
8699 << " New = " << *Result;
8701 // Everything uses the new instruction now.
8702 I->replaceAllUsesWith(Result);
8704 // Push the new instruction and any users onto the worklist.
8705 WorkList.push_back(Result);
8706 AddUsersToWorkList(*Result);
8708 // Move the name to the new instruction first...
8709 std::string OldName = I->getName(); I->setName("");
8710 Result->setName(OldName);
8712 // Insert the new instruction into the basic block...
8713 BasicBlock *InstParent = I->getParent();
8714 BasicBlock::iterator InsertPos = I;
8716 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8717 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8720 InstParent->getInstList().insert(InsertPos, Result);
8722 // Make sure that we reprocess all operands now that we reduced their
8724 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8725 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8726 WorkList.push_back(OpI);
8728 // Instructions can end up on the worklist more than once. Make sure
8729 // we do not process an instruction that has been deleted.
8730 removeFromWorkList(I);
8732 // Erase the old instruction.
8733 InstParent->getInstList().erase(I);
8735 DOUT << "IC: MOD = " << *I;
8737 // If the instruction was modified, it's possible that it is now dead.
8738 // if so, remove it.
8739 if (isInstructionTriviallyDead(I)) {
8740 // Make sure we process all operands now that we are reducing their
8742 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8743 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8744 WorkList.push_back(OpI);
8746 // Instructions may end up in the worklist more than once. Erase all
8747 // occurrences of this instruction.
8748 removeFromWorkList(I);
8749 I->eraseFromParent();
8751 WorkList.push_back(Result);
8752 AddUsersToWorkList(*Result);
8762 FunctionPass *llvm::createInstructionCombiningPass() {
8763 return new InstCombiner();