1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All SetCC instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
57 using namespace llvm::PatternMatch;
60 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
64 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
66 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
69 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
73 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
77 void AddUsersToWorkList(Value &I) {
78 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
80 WorkList.push_back(cast<Instruction>(*UI));
83 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
92 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93 /// dead. Add all of its operands to the worklist, turning them into
94 /// undef's to reduce the number of uses of those instructions.
96 /// Return the specified operand before it is turned into an undef.
98 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99 Value *R = I.getOperand(op);
101 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103 WorkList.push_back(Op);
104 // Set the operand to undef to drop the use.
105 I.setOperand(i, UndefValue::get(Op->getType()));
111 // removeFromWorkList - remove all instances of I from the worklist.
112 void removeFromWorkList(Instruction *I);
114 virtual bool runOnFunction(Function &F);
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117 AU.addRequired<TargetData>();
118 AU.addPreservedID(LCSSAID);
119 AU.setPreservesCFG();
122 TargetData &getTargetData() const { return *TD; }
124 // Visitation implementation - Implement instruction combining for different
125 // instruction types. The semantics are as follows:
127 // null - No change was made
128 // I - Change was made, I is still valid, I may be dead though
129 // otherwise - Change was made, replace I with returned instruction
131 Instruction *visitAdd(BinaryOperator &I);
132 Instruction *visitSub(BinaryOperator &I);
133 Instruction *visitMul(BinaryOperator &I);
134 Instruction *visitURem(BinaryOperator &I);
135 Instruction *visitSRem(BinaryOperator &I);
136 Instruction *visitFRem(BinaryOperator &I);
137 Instruction *commonRemTransforms(BinaryOperator &I);
138 Instruction *commonIRemTransforms(BinaryOperator &I);
139 Instruction *commonDivTransforms(BinaryOperator &I);
140 Instruction *commonIDivTransforms(BinaryOperator &I);
141 Instruction *visitUDiv(BinaryOperator &I);
142 Instruction *visitSDiv(BinaryOperator &I);
143 Instruction *visitFDiv(BinaryOperator &I);
144 Instruction *visitAnd(BinaryOperator &I);
145 Instruction *visitOr (BinaryOperator &I);
146 Instruction *visitXor(BinaryOperator &I);
147 Instruction *visitSetCondInst(SetCondInst &I);
148 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
150 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
151 Instruction::BinaryOps Cond, Instruction &I);
152 Instruction *visitShiftInst(ShiftInst &I);
153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
155 Instruction *visitCastInst(CastInst &CI);
156 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
158 Instruction *visitSelectInst(SelectInst &CI);
159 Instruction *visitCallInst(CallInst &CI);
160 Instruction *visitInvokeInst(InvokeInst &II);
161 Instruction *visitPHINode(PHINode &PN);
162 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
163 Instruction *visitAllocationInst(AllocationInst &AI);
164 Instruction *visitFreeInst(FreeInst &FI);
165 Instruction *visitLoadInst(LoadInst &LI);
166 Instruction *visitStoreInst(StoreInst &SI);
167 Instruction *visitBranchInst(BranchInst &BI);
168 Instruction *visitSwitchInst(SwitchInst &SI);
169 Instruction *visitInsertElementInst(InsertElementInst &IE);
170 Instruction *visitExtractElementInst(ExtractElementInst &EI);
171 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
173 // visitInstruction - Specify what to return for unhandled instructions...
174 Instruction *visitInstruction(Instruction &I) { return 0; }
177 Instruction *visitCallSite(CallSite CS);
178 bool transformConstExprCastCall(CallSite CS);
181 // InsertNewInstBefore - insert an instruction New before instruction Old
182 // in the program. Add the new instruction to the worklist.
184 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
185 assert(New && New->getParent() == 0 &&
186 "New instruction already inserted into a basic block!");
187 BasicBlock *BB = Old.getParent();
188 BB->getInstList().insert(&Old, New); // Insert inst
189 WorkList.push_back(New); // Add to worklist
193 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
194 /// This also adds the cast to the worklist. Finally, this returns the
196 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
197 if (V->getType() == Ty) return V;
199 if (Constant *CV = dyn_cast<Constant>(V))
200 return ConstantExpr::getCast(CV, Ty);
202 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
203 WorkList.push_back(C);
207 // ReplaceInstUsesWith - This method is to be used when an instruction is
208 // found to be dead, replacable with another preexisting expression. Here
209 // we add all uses of I to the worklist, replace all uses of I with the new
210 // value, then return I, so that the inst combiner will know that I was
213 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
214 AddUsersToWorkList(I); // Add all modified instrs to worklist
216 I.replaceAllUsesWith(V);
219 // If we are replacing the instruction with itself, this must be in a
220 // segment of unreachable code, so just clobber the instruction.
221 I.replaceAllUsesWith(UndefValue::get(I.getType()));
226 // UpdateValueUsesWith - This method is to be used when an value is
227 // found to be replacable with another preexisting expression or was
228 // updated. Here we add all uses of I to the worklist, replace all uses of
229 // I with the new value (unless the instruction was just updated), then
230 // return true, so that the inst combiner will know that I was modified.
232 bool UpdateValueUsesWith(Value *Old, Value *New) {
233 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
235 Old->replaceAllUsesWith(New);
236 if (Instruction *I = dyn_cast<Instruction>(Old))
237 WorkList.push_back(I);
238 if (Instruction *I = dyn_cast<Instruction>(New))
239 WorkList.push_back(I);
243 // EraseInstFromFunction - When dealing with an instruction that has side
244 // effects or produces a void value, we can't rely on DCE to delete the
245 // instruction. Instead, visit methods should return the value returned by
247 Instruction *EraseInstFromFunction(Instruction &I) {
248 assert(I.use_empty() && "Cannot erase instruction that is used!");
249 AddUsesToWorkList(I);
250 removeFromWorkList(&I);
252 return 0; // Don't do anything with FI
256 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
257 /// InsertBefore instruction. This is specialized a bit to avoid inserting
258 /// casts that are known to not do anything...
260 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
261 Instruction *InsertBefore);
263 // SimplifyCommutative - This performs a few simplifications for commutative
265 bool SimplifyCommutative(BinaryOperator &I);
267 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
268 uint64_t &KnownZero, uint64_t &KnownOne,
271 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
272 uint64_t &UndefElts, unsigned Depth = 0);
274 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
275 // PHI node as operand #0, see if we can fold the instruction into the PHI
276 // (which is only possible if all operands to the PHI are constants).
277 Instruction *FoldOpIntoPhi(Instruction &I);
279 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
280 // operator and they all are only used by the PHI, PHI together their
281 // inputs, and do the operation once, to the result of the PHI.
282 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
283 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
286 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
287 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
289 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
290 bool isSub, Instruction &I);
291 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
292 bool Inside, Instruction &IB);
293 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
294 Instruction *MatchBSwap(BinaryOperator &I);
296 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
299 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
302 // getComplexity: Assign a complexity or rank value to LLVM Values...
303 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
304 static unsigned getComplexity(Value *V) {
305 if (isa<Instruction>(V)) {
306 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
310 if (isa<Argument>(V)) return 3;
311 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
314 // isOnlyUse - Return true if this instruction will be deleted if we stop using
316 static bool isOnlyUse(Value *V) {
317 return V->hasOneUse() || isa<Constant>(V);
320 // getPromotedType - Return the specified type promoted as it would be to pass
321 // though a va_arg area...
322 static const Type *getPromotedType(const Type *Ty) {
323 switch (Ty->getTypeID()) {
324 case Type::SByteTyID:
325 case Type::ShortTyID: return Type::IntTy;
326 case Type::UByteTyID:
327 case Type::UShortTyID: return Type::UIntTy;
328 case Type::FloatTyID: return Type::DoubleTy;
333 /// isCast - If the specified operand is a CastInst or a constant expr cast,
334 /// return the operand value, otherwise return null.
335 static Value *isCast(Value *V) {
336 if (CastInst *I = dyn_cast<CastInst>(V))
337 return I->getOperand(0);
338 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
339 if (CE->getOpcode() == Instruction::Cast)
340 return CE->getOperand(0);
351 /// getCastType - In the future, we will split the cast instruction into these
352 /// various types. Until then, we have to do the analysis here.
353 static CastType getCastType(const Type *Src, const Type *Dest) {
354 assert(Src->isIntegral() && Dest->isIntegral() &&
355 "Only works on integral types!");
356 unsigned SrcSize = Src->getPrimitiveSizeInBits();
357 unsigned DestSize = Dest->getPrimitiveSizeInBits();
359 if (SrcSize == DestSize) return Noop;
360 if (SrcSize > DestSize) return Truncate;
361 if (Src->isSigned()) return Signext;
366 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
369 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
370 const Type *DstTy, TargetData *TD) {
372 // It is legal to eliminate the instruction if casting A->B->A if the sizes
373 // are identical and the bits don't get reinterpreted (for example
374 // int->float->int would not be allowed).
375 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
378 // If we are casting between pointer and integer types, treat pointers as
379 // integers of the appropriate size for the code below.
380 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
381 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
382 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
384 // Allow free casting and conversion of sizes as long as the sign doesn't
386 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
387 CastType FirstCast = getCastType(SrcTy, MidTy);
388 CastType SecondCast = getCastType(MidTy, DstTy);
390 // Capture the effect of these two casts. If the result is a legal cast,
391 // the CastType is stored here, otherwise a special code is used.
392 static const unsigned CastResult[] = {
393 // First cast is noop
395 // First cast is a truncate
396 1, 1, 4, 4, // trunc->extend is not safe to eliminate
397 // First cast is a sign ext
398 2, 5, 2, 4, // signext->zeroext never ok
399 // First cast is a zero ext
403 unsigned Result = CastResult[FirstCast*4+SecondCast];
405 default: assert(0 && "Illegal table value!");
410 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
411 // truncates, we could eliminate more casts.
412 return (unsigned)getCastType(SrcTy, DstTy) == Result;
414 return false; // Not possible to eliminate this here.
416 // Sign or zero extend followed by truncate is always ok if the result
417 // is a truncate or noop.
418 CastType ResultCast = getCastType(SrcTy, DstTy);
419 if (ResultCast == Noop || ResultCast == Truncate)
421 // Otherwise we are still growing the value, we are only safe if the
422 // result will match the sign/zeroextendness of the result.
423 return ResultCast == FirstCast;
427 // If this is a cast from 'float -> double -> integer', cast from
428 // 'float -> integer' directly, as the value isn't changed by the
429 // float->double conversion.
430 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
431 DstTy->isIntegral() &&
432 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
435 // Packed type conversions don't modify bits.
436 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
442 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
443 /// in any code being generated. It does not require codegen if V is simple
444 /// enough or if the cast can be folded into other casts.
445 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
446 if (V->getType() == Ty || isa<Constant>(V)) return false;
448 // If this is a noop cast, it isn't real codegen.
449 if (V->getType()->isLosslesslyConvertibleTo(Ty))
452 // If this is another cast that can be eliminated, it isn't codegen either.
453 if (const CastInst *CI = dyn_cast<CastInst>(V))
454 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
460 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
461 /// InsertBefore instruction. This is specialized a bit to avoid inserting
462 /// casts that are known to not do anything...
464 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
465 Instruction *InsertBefore) {
466 if (V->getType() == DestTy) return V;
467 if (Constant *C = dyn_cast<Constant>(V))
468 return ConstantExpr::getCast(C, DestTy);
470 return InsertCastBefore(V, DestTy, *InsertBefore);
473 // SimplifyCommutative - This performs a few simplifications for commutative
476 // 1. Order operands such that they are listed from right (least complex) to
477 // left (most complex). This puts constants before unary operators before
480 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
481 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
483 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
484 bool Changed = false;
485 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
486 Changed = !I.swapOperands();
488 if (!I.isAssociative()) return Changed;
489 Instruction::BinaryOps Opcode = I.getOpcode();
490 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
491 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
492 if (isa<Constant>(I.getOperand(1))) {
493 Constant *Folded = ConstantExpr::get(I.getOpcode(),
494 cast<Constant>(I.getOperand(1)),
495 cast<Constant>(Op->getOperand(1)));
496 I.setOperand(0, Op->getOperand(0));
497 I.setOperand(1, Folded);
499 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
500 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
501 isOnlyUse(Op) && isOnlyUse(Op1)) {
502 Constant *C1 = cast<Constant>(Op->getOperand(1));
503 Constant *C2 = cast<Constant>(Op1->getOperand(1));
505 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
506 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
507 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
510 WorkList.push_back(New);
511 I.setOperand(0, New);
512 I.setOperand(1, Folded);
519 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
520 // if the LHS is a constant zero (which is the 'negate' form).
522 static inline Value *dyn_castNegVal(Value *V) {
523 if (BinaryOperator::isNeg(V))
524 return BinaryOperator::getNegArgument(V);
526 // Constants can be considered to be negated values if they can be folded.
527 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
528 return ConstantExpr::getNeg(C);
532 static inline Value *dyn_castNotVal(Value *V) {
533 if (BinaryOperator::isNot(V))
534 return BinaryOperator::getNotArgument(V);
536 // Constants can be considered to be not'ed values...
537 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
538 return ConstantExpr::getNot(C);
542 // dyn_castFoldableMul - If this value is a multiply that can be folded into
543 // other computations (because it has a constant operand), return the
544 // non-constant operand of the multiply, and set CST to point to the multiplier.
545 // Otherwise, return null.
547 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
548 if (V->hasOneUse() && V->getType()->isInteger())
549 if (Instruction *I = dyn_cast<Instruction>(V)) {
550 if (I->getOpcode() == Instruction::Mul)
551 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
552 return I->getOperand(0);
553 if (I->getOpcode() == Instruction::Shl)
554 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
555 // The multiplier is really 1 << CST.
556 Constant *One = ConstantInt::get(V->getType(), 1);
557 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
558 return I->getOperand(0);
564 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
565 /// expression, return it.
566 static User *dyn_castGetElementPtr(Value *V) {
567 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
569 if (CE->getOpcode() == Instruction::GetElementPtr)
570 return cast<User>(V);
574 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
575 static ConstantInt *AddOne(ConstantInt *C) {
576 return cast<ConstantInt>(ConstantExpr::getAdd(C,
577 ConstantInt::get(C->getType(), 1)));
579 static ConstantInt *SubOne(ConstantInt *C) {
580 return cast<ConstantInt>(ConstantExpr::getSub(C,
581 ConstantInt::get(C->getType(), 1)));
584 /// GetConstantInType - Return a ConstantInt with the specified type and value.
586 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
587 if (Ty->isUnsigned())
588 return ConstantInt::get(Ty, Val);
589 else if (Ty->getTypeID() == Type::BoolTyID)
590 return ConstantBool::get(Val);
592 SVal <<= 64-Ty->getPrimitiveSizeInBits();
593 SVal >>= 64-Ty->getPrimitiveSizeInBits();
594 return ConstantInt::get(Ty, SVal);
598 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
599 /// known to be either zero or one and return them in the KnownZero/KnownOne
600 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
602 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
603 uint64_t &KnownOne, unsigned Depth = 0) {
604 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
605 // we cannot optimize based on the assumption that it is zero without changing
606 // it to be an explicit zero. If we don't change it to zero, other code could
607 // optimized based on the contradictory assumption that it is non-zero.
608 // Because instcombine aggressively folds operations with undef args anyway,
609 // this won't lose us code quality.
610 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
611 // We know all of the bits for a constant!
612 KnownOne = CI->getZExtValue() & Mask;
613 KnownZero = ~KnownOne & Mask;
617 KnownZero = KnownOne = 0; // Don't know anything.
618 if (Depth == 6 || Mask == 0)
619 return; // Limit search depth.
621 uint64_t KnownZero2, KnownOne2;
622 Instruction *I = dyn_cast<Instruction>(V);
625 Mask &= V->getType()->getIntegralTypeMask();
627 switch (I->getOpcode()) {
628 case Instruction::And:
629 // If either the LHS or the RHS are Zero, the result is zero.
630 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
632 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
633 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
634 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
636 // Output known-1 bits are only known if set in both the LHS & RHS.
637 KnownOne &= KnownOne2;
638 // Output known-0 are known to be clear if zero in either the LHS | RHS.
639 KnownZero |= KnownZero2;
641 case Instruction::Or:
642 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
644 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
645 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
646 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
648 // Output known-0 bits are only known if clear in both the LHS & RHS.
649 KnownZero &= KnownZero2;
650 // Output known-1 are known to be set if set in either the LHS | RHS.
651 KnownOne |= KnownOne2;
653 case Instruction::Xor: {
654 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
655 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
656 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
657 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
659 // Output known-0 bits are known if clear or set in both the LHS & RHS.
660 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
661 // Output known-1 are known to be set if set in only one of the LHS, RHS.
662 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
663 KnownZero = KnownZeroOut;
666 case Instruction::Select:
667 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
670 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
672 // Only known if known in both the LHS and RHS.
673 KnownOne &= KnownOne2;
674 KnownZero &= KnownZero2;
676 case Instruction::Cast: {
677 const Type *SrcTy = I->getOperand(0)->getType();
678 if (!SrcTy->isIntegral()) return;
680 // If this is an integer truncate or noop, just look in the input.
681 if (SrcTy->getPrimitiveSizeInBits() >=
682 I->getType()->getPrimitiveSizeInBits()) {
683 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
687 // Sign or Zero extension. Compute the bits in the result that are not
688 // present in the input.
689 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
690 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
692 // Handle zero extension.
693 if (!SrcTy->isSigned()) {
694 Mask &= SrcTy->getIntegralTypeMask();
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 // The top bits are known to be zero.
698 KnownZero |= NewBits;
701 Mask &= SrcTy->getIntegralTypeMask();
702 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
703 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
705 // If the sign bit of the input is known set or clear, then we know the
706 // top bits of the result.
707 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
708 if (KnownZero & InSignBit) { // Input sign bit known zero
709 KnownZero |= NewBits;
710 KnownOne &= ~NewBits;
711 } else if (KnownOne & InSignBit) { // Input sign bit known set
713 KnownZero &= ~NewBits;
714 } else { // Input sign bit unknown
715 KnownZero &= ~NewBits;
716 KnownOne &= ~NewBits;
721 case Instruction::Shl:
722 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
723 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
724 uint64_t ShiftAmt = SA->getZExtValue();
726 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
727 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
728 KnownZero <<= ShiftAmt;
729 KnownOne <<= ShiftAmt;
730 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
734 case Instruction::LShr:
735 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
736 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
737 // Compute the new bits that are at the top now.
738 uint64_t ShiftAmt = SA->getZExtValue();
739 uint64_t HighBits = (1ULL << ShiftAmt)-1;
740 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
742 // Unsigned shift right.
744 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
745 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
746 KnownZero >>= ShiftAmt;
747 KnownOne >>= ShiftAmt;
748 KnownZero |= HighBits; // high bits known zero.
752 case Instruction::AShr:
753 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
754 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
755 // Compute the new bits that are at the top now.
756 uint64_t ShiftAmt = SA->getZExtValue();
757 uint64_t HighBits = (1ULL << ShiftAmt)-1;
758 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
760 // Signed shift right.
762 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
763 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
764 KnownZero >>= ShiftAmt;
765 KnownOne >>= ShiftAmt;
767 // Handle the sign bits.
768 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
769 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
771 if (KnownZero & SignBit) { // New bits are known zero.
772 KnownZero |= HighBits;
773 } else if (KnownOne & SignBit) { // New bits are known one.
774 KnownOne |= HighBits;
782 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
783 /// this predicate to simplify operations downstream. Mask is known to be zero
784 /// for bits that V cannot have.
785 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
786 uint64_t KnownZero, KnownOne;
787 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
788 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
789 return (KnownZero & Mask) == Mask;
792 /// ShrinkDemandedConstant - Check to see if the specified operand of the
793 /// specified instruction is a constant integer. If so, check to see if there
794 /// are any bits set in the constant that are not demanded. If so, shrink the
795 /// constant and return true.
796 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
798 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
799 if (!OpC) return false;
801 // If there are no bits set that aren't demanded, nothing to do.
802 if ((~Demanded & OpC->getZExtValue()) == 0)
805 // This is producing any bits that are not needed, shrink the RHS.
806 uint64_t Val = Demanded & OpC->getZExtValue();
807 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
811 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
812 // set of known zero and one bits, compute the maximum and minimum values that
813 // could have the specified known zero and known one bits, returning them in
815 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
818 int64_t &Min, int64_t &Max) {
819 uint64_t TypeBits = Ty->getIntegralTypeMask();
820 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
822 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
824 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
825 // bit if it is unknown.
827 Max = KnownOne|UnknownBits;
829 if (SignBit & UnknownBits) { // Sign bit is unknown
834 // Sign extend the min/max values.
835 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
836 Min = (Min << ShAmt) >> ShAmt;
837 Max = (Max << ShAmt) >> ShAmt;
840 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
841 // a set of known zero and one bits, compute the maximum and minimum values that
842 // could have the specified known zero and known one bits, returning them in
844 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
849 uint64_t TypeBits = Ty->getIntegralTypeMask();
850 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
852 // The minimum value is when the unknown bits are all zeros.
854 // The maximum value is when the unknown bits are all ones.
855 Max = KnownOne|UnknownBits;
859 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
860 /// DemandedMask bits of the result of V are ever used downstream. If we can
861 /// use this information to simplify V, do so and return true. Otherwise,
862 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
863 /// the expression (used to simplify the caller). The KnownZero/One bits may
864 /// only be accurate for those bits in the DemandedMask.
865 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
866 uint64_t &KnownZero, uint64_t &KnownOne,
868 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
869 // We know all of the bits for a constant!
870 KnownOne = CI->getZExtValue() & DemandedMask;
871 KnownZero = ~KnownOne & DemandedMask;
875 KnownZero = KnownOne = 0;
876 if (!V->hasOneUse()) { // Other users may use these bits.
877 if (Depth != 0) { // Not at the root.
878 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
879 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
882 // If this is the root being simplified, allow it to have multiple uses,
883 // just set the DemandedMask to all bits.
884 DemandedMask = V->getType()->getIntegralTypeMask();
885 } else if (DemandedMask == 0) { // Not demanding any bits from V.
886 if (V != UndefValue::get(V->getType()))
887 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
889 } else if (Depth == 6) { // Limit search depth.
893 Instruction *I = dyn_cast<Instruction>(V);
894 if (!I) return false; // Only analyze instructions.
896 DemandedMask &= V->getType()->getIntegralTypeMask();
898 uint64_t KnownZero2, KnownOne2;
899 switch (I->getOpcode()) {
901 case Instruction::And:
902 // If either the LHS or the RHS are Zero, the result is zero.
903 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
904 KnownZero, KnownOne, Depth+1))
906 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
908 // If something is known zero on the RHS, the bits aren't demanded on the
910 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
911 KnownZero2, KnownOne2, Depth+1))
913 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
915 // If all of the demanded bits are known one on one side, return the other.
916 // These bits cannot contribute to the result of the 'and'.
917 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
918 return UpdateValueUsesWith(I, I->getOperand(0));
919 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
920 return UpdateValueUsesWith(I, I->getOperand(1));
922 // If all of the demanded bits in the inputs are known zeros, return zero.
923 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
924 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
926 // If the RHS is a constant, see if we can simplify it.
927 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
928 return UpdateValueUsesWith(I, I);
930 // Output known-1 bits are only known if set in both the LHS & RHS.
931 KnownOne &= KnownOne2;
932 // Output known-0 are known to be clear if zero in either the LHS | RHS.
933 KnownZero |= KnownZero2;
935 case Instruction::Or:
936 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
937 KnownZero, KnownOne, Depth+1))
939 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
940 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
941 KnownZero2, KnownOne2, Depth+1))
943 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
945 // If all of the demanded bits are known zero on one side, return the other.
946 // These bits cannot contribute to the result of the 'or'.
947 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
948 return UpdateValueUsesWith(I, I->getOperand(0));
949 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
950 return UpdateValueUsesWith(I, I->getOperand(1));
952 // If all of the potentially set bits on one side are known to be set on
953 // the other side, just use the 'other' side.
954 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
955 (DemandedMask & (~KnownZero)))
956 return UpdateValueUsesWith(I, I->getOperand(0));
957 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
958 (DemandedMask & (~KnownZero2)))
959 return UpdateValueUsesWith(I, I->getOperand(1));
961 // If the RHS is a constant, see if we can simplify it.
962 if (ShrinkDemandedConstant(I, 1, DemandedMask))
963 return UpdateValueUsesWith(I, I);
965 // Output known-0 bits are only known if clear in both the LHS & RHS.
966 KnownZero &= KnownZero2;
967 // Output known-1 are known to be set if set in either the LHS | RHS.
968 KnownOne |= KnownOne2;
970 case Instruction::Xor: {
971 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
972 KnownZero, KnownOne, Depth+1))
974 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
975 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
976 KnownZero2, KnownOne2, Depth+1))
978 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
980 // If all of the demanded bits are known zero on one side, return the other.
981 // These bits cannot contribute to the result of the 'xor'.
982 if ((DemandedMask & KnownZero) == DemandedMask)
983 return UpdateValueUsesWith(I, I->getOperand(0));
984 if ((DemandedMask & KnownZero2) == DemandedMask)
985 return UpdateValueUsesWith(I, I->getOperand(1));
987 // Output known-0 bits are known if clear or set in both the LHS & RHS.
988 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
989 // Output known-1 are known to be set if set in only one of the LHS, RHS.
990 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
992 // If all of the unknown bits are known to be zero on one side or the other
993 // (but not both) turn this into an *inclusive* or.
994 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
995 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
996 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
998 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1000 InsertNewInstBefore(Or, *I);
1001 return UpdateValueUsesWith(I, Or);
1005 // If all of the demanded bits on one side are known, and all of the set
1006 // bits on that side are also known to be set on the other side, turn this
1007 // into an AND, as we know the bits will be cleared.
1008 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1009 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1010 if ((KnownOne & KnownOne2) == KnownOne) {
1011 Constant *AndC = GetConstantInType(I->getType(),
1012 ~KnownOne & DemandedMask);
1014 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1015 InsertNewInstBefore(And, *I);
1016 return UpdateValueUsesWith(I, And);
1020 // If the RHS is a constant, see if we can simplify it.
1021 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1022 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1023 return UpdateValueUsesWith(I, I);
1025 KnownZero = KnownZeroOut;
1026 KnownOne = KnownOneOut;
1029 case Instruction::Select:
1030 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1031 KnownZero, KnownOne, Depth+1))
1033 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1034 KnownZero2, KnownOne2, Depth+1))
1036 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1037 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1039 // If the operands are constants, see if we can simplify them.
1040 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1041 return UpdateValueUsesWith(I, I);
1042 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1043 return UpdateValueUsesWith(I, I);
1045 // Only known if known in both the LHS and RHS.
1046 KnownOne &= KnownOne2;
1047 KnownZero &= KnownZero2;
1049 case Instruction::Cast: {
1050 const Type *SrcTy = I->getOperand(0)->getType();
1051 if (!SrcTy->isIntegral()) return false;
1053 // If this is an integer truncate or noop, just look in the input.
1054 if (SrcTy->getPrimitiveSizeInBits() >=
1055 I->getType()->getPrimitiveSizeInBits()) {
1056 // Cast to bool is a comparison against 0, which demands all bits. We
1057 // can't propagate anything useful up.
1058 if (I->getType() == Type::BoolTy)
1061 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1062 KnownZero, KnownOne, Depth+1))
1064 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1068 // Sign or Zero extension. Compute the bits in the result that are not
1069 // present in the input.
1070 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1071 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1073 // Handle zero extension.
1074 if (!SrcTy->isSigned()) {
1075 DemandedMask &= SrcTy->getIntegralTypeMask();
1076 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1077 KnownZero, KnownOne, Depth+1))
1079 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1080 // The top bits are known to be zero.
1081 KnownZero |= NewBits;
1084 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1085 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1087 // If any of the sign extended bits are demanded, we know that the sign
1089 if (NewBits & DemandedMask)
1090 InputDemandedBits |= InSignBit;
1092 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1093 KnownZero, KnownOne, Depth+1))
1095 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1097 // If the sign bit of the input is known set or clear, then we know the
1098 // top bits of the result.
1100 // If the input sign bit is known zero, or if the NewBits are not demanded
1101 // convert this into a zero extension.
1102 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1103 // Convert to unsigned first.
1105 InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
1106 // Then cast that to the destination type.
1107 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1108 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1109 return UpdateValueUsesWith(I, NewVal);
1110 } else if (KnownOne & InSignBit) { // Input sign bit known set
1111 KnownOne |= NewBits;
1112 KnownZero &= ~NewBits;
1113 } else { // Input sign bit unknown
1114 KnownZero &= ~NewBits;
1115 KnownOne &= ~NewBits;
1120 case Instruction::Add:
1121 // If there is a constant on the RHS, there are a variety of xformations
1123 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1124 // If null, this should be simplified elsewhere. Some of the xforms here
1125 // won't work if the RHS is zero.
1126 if (RHS->isNullValue())
1129 // Figure out what the input bits are. If the top bits of the and result
1130 // are not demanded, then the add doesn't demand them from its input
1133 // Shift the demanded mask up so that it's at the top of the uint64_t.
1134 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1135 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1137 // If the top bit of the output is demanded, demand everything from the
1138 // input. Otherwise, we demand all the input bits except NLZ top bits.
1139 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1141 // Find information about known zero/one bits in the input.
1142 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1143 KnownZero2, KnownOne2, Depth+1))
1146 // If the RHS of the add has bits set that can't affect the input, reduce
1148 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1149 return UpdateValueUsesWith(I, I);
1151 // Avoid excess work.
1152 if (KnownZero2 == 0 && KnownOne2 == 0)
1155 // Turn it into OR if input bits are zero.
1156 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1158 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1160 InsertNewInstBefore(Or, *I);
1161 return UpdateValueUsesWith(I, Or);
1164 // We can say something about the output known-zero and known-one bits,
1165 // depending on potential carries from the input constant and the
1166 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1167 // bits set and the RHS constant is 0x01001, then we know we have a known
1168 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1170 // To compute this, we first compute the potential carry bits. These are
1171 // the bits which may be modified. I'm not aware of a better way to do
1173 uint64_t RHSVal = RHS->getZExtValue();
1175 bool CarryIn = false;
1176 uint64_t CarryBits = 0;
1177 uint64_t CurBit = 1;
1178 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1179 // Record the current carry in.
1180 if (CarryIn) CarryBits |= CurBit;
1184 // This bit has a carry out unless it is "zero + zero" or
1185 // "zero + anything" with no carry in.
1186 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1187 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1188 } else if (!CarryIn &&
1189 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1190 CarryOut = false; // 0 + anything has no carry out if no carry in.
1192 // Otherwise, we have to assume we have a carry out.
1196 // This stage's carry out becomes the next stage's carry-in.
1200 // Now that we know which bits have carries, compute the known-1/0 sets.
1202 // Bits are known one if they are known zero in one operand and one in the
1203 // other, and there is no input carry.
1204 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1206 // Bits are known zero if they are known zero in both operands and there
1207 // is no input carry.
1208 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1211 case Instruction::Shl:
1212 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1213 uint64_t ShiftAmt = SA->getZExtValue();
1214 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
1215 KnownZero, KnownOne, Depth+1))
1217 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1218 KnownZero <<= ShiftAmt;
1219 KnownOne <<= ShiftAmt;
1220 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
1223 case Instruction::LShr:
1224 // For a logical shift right
1225 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1226 unsigned ShiftAmt = SA->getZExtValue();
1228 // Compute the new bits that are at the top now.
1229 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1230 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1231 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1232 // Unsigned shift right.
1233 if (SimplifyDemandedBits(I->getOperand(0),
1234 (DemandedMask << ShiftAmt) & TypeMask,
1235 KnownZero, KnownOne, Depth+1))
1237 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1238 KnownZero &= TypeMask;
1239 KnownOne &= TypeMask;
1240 KnownZero >>= ShiftAmt;
1241 KnownOne >>= ShiftAmt;
1242 KnownZero |= HighBits; // high bits known zero.
1245 case Instruction::AShr:
1246 // If this is an arithmetic shift right and only the low-bit is set, we can
1247 // always convert this into a logical shr, even if the shift amount is
1248 // variable. The low bit of the shift cannot be an input sign bit unless
1249 // the shift amount is >= the size of the datatype, which is undefined.
1250 if (DemandedMask == 1) {
1251 // Perform the logical shift right.
1252 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1253 I->getOperand(1), I->getName());
1254 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1255 return UpdateValueUsesWith(I, NewVal);
1258 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1259 unsigned ShiftAmt = SA->getZExtValue();
1261 // Compute the new bits that are at the top now.
1262 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1263 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1264 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1265 // Signed shift right.
1266 if (SimplifyDemandedBits(I->getOperand(0),
1267 (DemandedMask << ShiftAmt) & TypeMask,
1268 KnownZero, KnownOne, Depth+1))
1270 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1271 KnownZero &= TypeMask;
1272 KnownOne &= TypeMask;
1273 KnownZero >>= ShiftAmt;
1274 KnownOne >>= ShiftAmt;
1276 // Handle the sign bits.
1277 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1278 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
1280 // If the input sign bit is known to be zero, or if none of the top bits
1281 // are demanded, turn this into an unsigned shift right.
1282 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1283 // Perform the logical shift right.
1284 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1286 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1287 return UpdateValueUsesWith(I, NewVal);
1288 } else if (KnownOne & SignBit) { // New bits are known one.
1289 KnownOne |= HighBits;
1295 // If the client is only demanding bits that we know, return the known
1297 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1298 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1303 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1304 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1305 /// actually used by the caller. This method analyzes which elements of the
1306 /// operand are undef and returns that information in UndefElts.
1308 /// If the information about demanded elements can be used to simplify the
1309 /// operation, the operation is simplified, then the resultant value is
1310 /// returned. This returns null if no change was made.
1311 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1312 uint64_t &UndefElts,
1314 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1315 assert(VWidth <= 64 && "Vector too wide to analyze!");
1316 uint64_t EltMask = ~0ULL >> (64-VWidth);
1317 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1318 "Invalid DemandedElts!");
1320 if (isa<UndefValue>(V)) {
1321 // If the entire vector is undefined, just return this info.
1322 UndefElts = EltMask;
1324 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1325 UndefElts = EltMask;
1326 return UndefValue::get(V->getType());
1330 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1331 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1332 Constant *Undef = UndefValue::get(EltTy);
1334 std::vector<Constant*> Elts;
1335 for (unsigned i = 0; i != VWidth; ++i)
1336 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1337 Elts.push_back(Undef);
1338 UndefElts |= (1ULL << i);
1339 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1340 Elts.push_back(Undef);
1341 UndefElts |= (1ULL << i);
1342 } else { // Otherwise, defined.
1343 Elts.push_back(CP->getOperand(i));
1346 // If we changed the constant, return it.
1347 Constant *NewCP = ConstantPacked::get(Elts);
1348 return NewCP != CP ? NewCP : 0;
1349 } else if (isa<ConstantAggregateZero>(V)) {
1350 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1352 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1353 Constant *Zero = Constant::getNullValue(EltTy);
1354 Constant *Undef = UndefValue::get(EltTy);
1355 std::vector<Constant*> Elts;
1356 for (unsigned i = 0; i != VWidth; ++i)
1357 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1358 UndefElts = DemandedElts ^ EltMask;
1359 return ConstantPacked::get(Elts);
1362 if (!V->hasOneUse()) { // Other users may use these bits.
1363 if (Depth != 0) { // Not at the root.
1364 // TODO: Just compute the UndefElts information recursively.
1368 } else if (Depth == 10) { // Limit search depth.
1372 Instruction *I = dyn_cast<Instruction>(V);
1373 if (!I) return false; // Only analyze instructions.
1375 bool MadeChange = false;
1376 uint64_t UndefElts2;
1378 switch (I->getOpcode()) {
1381 case Instruction::InsertElement: {
1382 // If this is a variable index, we don't know which element it overwrites.
1383 // demand exactly the same input as we produce.
1384 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1386 // Note that we can't propagate undef elt info, because we don't know
1387 // which elt is getting updated.
1388 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1389 UndefElts2, Depth+1);
1390 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1394 // If this is inserting an element that isn't demanded, remove this
1396 unsigned IdxNo = Idx->getZExtValue();
1397 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1398 return AddSoonDeadInstToWorklist(*I, 0);
1400 // Otherwise, the element inserted overwrites whatever was there, so the
1401 // input demanded set is simpler than the output set.
1402 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1403 DemandedElts & ~(1ULL << IdxNo),
1404 UndefElts, Depth+1);
1405 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1407 // The inserted element is defined.
1408 UndefElts |= 1ULL << IdxNo;
1412 case Instruction::And:
1413 case Instruction::Or:
1414 case Instruction::Xor:
1415 case Instruction::Add:
1416 case Instruction::Sub:
1417 case Instruction::Mul:
1418 // div/rem demand all inputs, because they don't want divide by zero.
1419 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1420 UndefElts, Depth+1);
1421 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1422 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1423 UndefElts2, Depth+1);
1424 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1426 // Output elements are undefined if both are undefined. Consider things
1427 // like undef&0. The result is known zero, not undef.
1428 UndefElts &= UndefElts2;
1431 case Instruction::Call: {
1432 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1434 switch (II->getIntrinsicID()) {
1437 // Binary vector operations that work column-wise. A dest element is a
1438 // function of the corresponding input elements from the two inputs.
1439 case Intrinsic::x86_sse_sub_ss:
1440 case Intrinsic::x86_sse_mul_ss:
1441 case Intrinsic::x86_sse_min_ss:
1442 case Intrinsic::x86_sse_max_ss:
1443 case Intrinsic::x86_sse2_sub_sd:
1444 case Intrinsic::x86_sse2_mul_sd:
1445 case Intrinsic::x86_sse2_min_sd:
1446 case Intrinsic::x86_sse2_max_sd:
1447 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1448 UndefElts, Depth+1);
1449 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1450 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1451 UndefElts2, Depth+1);
1452 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1454 // If only the low elt is demanded and this is a scalarizable intrinsic,
1455 // scalarize it now.
1456 if (DemandedElts == 1) {
1457 switch (II->getIntrinsicID()) {
1459 case Intrinsic::x86_sse_sub_ss:
1460 case Intrinsic::x86_sse_mul_ss:
1461 case Intrinsic::x86_sse2_sub_sd:
1462 case Intrinsic::x86_sse2_mul_sd:
1463 // TODO: Lower MIN/MAX/ABS/etc
1464 Value *LHS = II->getOperand(1);
1465 Value *RHS = II->getOperand(2);
1466 // Extract the element as scalars.
1467 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1468 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1470 switch (II->getIntrinsicID()) {
1471 default: assert(0 && "Case stmts out of sync!");
1472 case Intrinsic::x86_sse_sub_ss:
1473 case Intrinsic::x86_sse2_sub_sd:
1474 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1475 II->getName()), *II);
1477 case Intrinsic::x86_sse_mul_ss:
1478 case Intrinsic::x86_sse2_mul_sd:
1479 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1480 II->getName()), *II);
1485 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1487 InsertNewInstBefore(New, *II);
1488 AddSoonDeadInstToWorklist(*II, 0);
1493 // Output elements are undefined if both are undefined. Consider things
1494 // like undef&0. The result is known zero, not undef.
1495 UndefElts &= UndefElts2;
1501 return MadeChange ? I : 0;
1504 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1505 // true when both operands are equal...
1507 static bool isTrueWhenEqual(Instruction &I) {
1508 return I.getOpcode() == Instruction::SetEQ ||
1509 I.getOpcode() == Instruction::SetGE ||
1510 I.getOpcode() == Instruction::SetLE;
1513 /// AssociativeOpt - Perform an optimization on an associative operator. This
1514 /// function is designed to check a chain of associative operators for a
1515 /// potential to apply a certain optimization. Since the optimization may be
1516 /// applicable if the expression was reassociated, this checks the chain, then
1517 /// reassociates the expression as necessary to expose the optimization
1518 /// opportunity. This makes use of a special Functor, which must define
1519 /// 'shouldApply' and 'apply' methods.
1521 template<typename Functor>
1522 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1523 unsigned Opcode = Root.getOpcode();
1524 Value *LHS = Root.getOperand(0);
1526 // Quick check, see if the immediate LHS matches...
1527 if (F.shouldApply(LHS))
1528 return F.apply(Root);
1530 // Otherwise, if the LHS is not of the same opcode as the root, return.
1531 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1532 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1533 // Should we apply this transform to the RHS?
1534 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1536 // If not to the RHS, check to see if we should apply to the LHS...
1537 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1538 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1542 // If the functor wants to apply the optimization to the RHS of LHSI,
1543 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1545 BasicBlock *BB = Root.getParent();
1547 // Now all of the instructions are in the current basic block, go ahead
1548 // and perform the reassociation.
1549 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1551 // First move the selected RHS to the LHS of the root...
1552 Root.setOperand(0, LHSI->getOperand(1));
1554 // Make what used to be the LHS of the root be the user of the root...
1555 Value *ExtraOperand = TmpLHSI->getOperand(1);
1556 if (&Root == TmpLHSI) {
1557 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1560 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1561 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1562 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1563 BasicBlock::iterator ARI = &Root; ++ARI;
1564 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1567 // Now propagate the ExtraOperand down the chain of instructions until we
1569 while (TmpLHSI != LHSI) {
1570 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1571 // Move the instruction to immediately before the chain we are
1572 // constructing to avoid breaking dominance properties.
1573 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1574 BB->getInstList().insert(ARI, NextLHSI);
1577 Value *NextOp = NextLHSI->getOperand(1);
1578 NextLHSI->setOperand(1, ExtraOperand);
1580 ExtraOperand = NextOp;
1583 // Now that the instructions are reassociated, have the functor perform
1584 // the transformation...
1585 return F.apply(Root);
1588 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1594 // AddRHS - Implements: X + X --> X << 1
1597 AddRHS(Value *rhs) : RHS(rhs) {}
1598 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1599 Instruction *apply(BinaryOperator &Add) const {
1600 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1601 ConstantInt::get(Type::UByteTy, 1));
1605 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1607 struct AddMaskingAnd {
1609 AddMaskingAnd(Constant *c) : C2(c) {}
1610 bool shouldApply(Value *LHS) const {
1612 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1613 ConstantExpr::getAnd(C1, C2)->isNullValue();
1615 Instruction *apply(BinaryOperator &Add) const {
1616 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1620 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1622 if (isa<CastInst>(I)) {
1623 if (Constant *SOC = dyn_cast<Constant>(SO))
1624 return ConstantExpr::getCast(SOC, I.getType());
1626 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1627 SO->getName() + ".cast"), I);
1630 // Figure out if the constant is the left or the right argument.
1631 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1632 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1634 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1636 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1637 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1640 Value *Op0 = SO, *Op1 = ConstOperand;
1642 std::swap(Op0, Op1);
1644 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1645 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1646 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1647 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1649 assert(0 && "Unknown binary instruction type!");
1652 return IC->InsertNewInstBefore(New, I);
1655 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1656 // constant as the other operand, try to fold the binary operator into the
1657 // select arguments. This also works for Cast instructions, which obviously do
1658 // not have a second operand.
1659 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1661 // Don't modify shared select instructions
1662 if (!SI->hasOneUse()) return 0;
1663 Value *TV = SI->getOperand(1);
1664 Value *FV = SI->getOperand(2);
1666 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1667 // Bool selects with constant operands can be folded to logical ops.
1668 if (SI->getType() == Type::BoolTy) return 0;
1670 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1671 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1673 return new SelectInst(SI->getCondition(), SelectTrueVal,
1680 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1681 /// node as operand #0, see if we can fold the instruction into the PHI (which
1682 /// is only possible if all operands to the PHI are constants).
1683 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1684 PHINode *PN = cast<PHINode>(I.getOperand(0));
1685 unsigned NumPHIValues = PN->getNumIncomingValues();
1686 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1688 // Check to see if all of the operands of the PHI are constants. If there is
1689 // one non-constant value, remember the BB it is. If there is more than one
1691 BasicBlock *NonConstBB = 0;
1692 for (unsigned i = 0; i != NumPHIValues; ++i)
1693 if (!isa<Constant>(PN->getIncomingValue(i))) {
1694 if (NonConstBB) return 0; // More than one non-const value.
1695 NonConstBB = PN->getIncomingBlock(i);
1697 // If the incoming non-constant value is in I's block, we have an infinite
1699 if (NonConstBB == I.getParent())
1703 // If there is exactly one non-constant value, we can insert a copy of the
1704 // operation in that block. However, if this is a critical edge, we would be
1705 // inserting the computation one some other paths (e.g. inside a loop). Only
1706 // do this if the pred block is unconditionally branching into the phi block.
1708 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1709 if (!BI || !BI->isUnconditional()) return 0;
1712 // Okay, we can do the transformation: create the new PHI node.
1713 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1715 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1716 InsertNewInstBefore(NewPN, *PN);
1718 // Next, add all of the operands to the PHI.
1719 if (I.getNumOperands() == 2) {
1720 Constant *C = cast<Constant>(I.getOperand(1));
1721 for (unsigned i = 0; i != NumPHIValues; ++i) {
1723 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1724 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1726 assert(PN->getIncomingBlock(i) == NonConstBB);
1727 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1728 InV = BinaryOperator::create(BO->getOpcode(),
1729 PN->getIncomingValue(i), C, "phitmp",
1730 NonConstBB->getTerminator());
1731 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1732 InV = new ShiftInst(SI->getOpcode(),
1733 PN->getIncomingValue(i), C, "phitmp",
1734 NonConstBB->getTerminator());
1736 assert(0 && "Unknown binop!");
1738 WorkList.push_back(cast<Instruction>(InV));
1740 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1743 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1744 const Type *RetTy = I.getType();
1745 for (unsigned i = 0; i != NumPHIValues; ++i) {
1747 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1748 InV = ConstantExpr::getCast(InC, RetTy);
1750 assert(PN->getIncomingBlock(i) == NonConstBB);
1751 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1752 NonConstBB->getTerminator());
1753 WorkList.push_back(cast<Instruction>(InV));
1755 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1758 return ReplaceInstUsesWith(I, NewPN);
1761 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1762 bool Changed = SimplifyCommutative(I);
1763 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1765 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1766 // X + undef -> undef
1767 if (isa<UndefValue>(RHS))
1768 return ReplaceInstUsesWith(I, RHS);
1771 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1772 if (RHSC->isNullValue())
1773 return ReplaceInstUsesWith(I, LHS);
1774 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1775 if (CFP->isExactlyValue(-0.0))
1776 return ReplaceInstUsesWith(I, LHS);
1779 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1780 // X + (signbit) --> X ^ signbit
1781 uint64_t Val = CI->getZExtValue();
1782 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1783 return BinaryOperator::createXor(LHS, RHS);
1785 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1786 // (X & 254)+1 -> (X&254)|1
1787 uint64_t KnownZero, KnownOne;
1788 if (!isa<PackedType>(I.getType()) &&
1789 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1790 KnownZero, KnownOne))
1794 if (isa<PHINode>(LHS))
1795 if (Instruction *NV = FoldOpIntoPhi(I))
1798 ConstantInt *XorRHS = 0;
1800 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1801 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1802 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1803 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1805 uint64_t C0080Val = 1ULL << 31;
1806 int64_t CFF80Val = -C0080Val;
1809 if (TySizeBits > Size) {
1811 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1812 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1813 if (RHSSExt == CFF80Val) {
1814 if (XorRHS->getZExtValue() == C0080Val)
1816 } else if (RHSZExt == C0080Val) {
1817 if (XorRHS->getSExtValue() == CFF80Val)
1821 // This is a sign extend if the top bits are known zero.
1822 uint64_t Mask = ~0ULL;
1823 Mask <<= 64-(TySizeBits-Size);
1824 Mask &= XorLHS->getType()->getIntegralTypeMask();
1825 if (!MaskedValueIsZero(XorLHS, Mask))
1826 Size = 0; // Not a sign ext, but can't be any others either.
1833 } while (Size >= 8);
1836 const Type *MiddleType = 0;
1839 case 32: MiddleType = Type::IntTy; break;
1840 case 16: MiddleType = Type::ShortTy; break;
1841 case 8: MiddleType = Type::SByteTy; break;
1844 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1845 InsertNewInstBefore(NewTrunc, I);
1846 return new CastInst(NewTrunc, I.getType());
1852 if (I.getType()->isInteger()) {
1853 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1855 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1856 if (RHSI->getOpcode() == Instruction::Sub)
1857 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1858 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1860 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1861 if (LHSI->getOpcode() == Instruction::Sub)
1862 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1863 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1868 if (Value *V = dyn_castNegVal(LHS))
1869 return BinaryOperator::createSub(RHS, V);
1872 if (!isa<Constant>(RHS))
1873 if (Value *V = dyn_castNegVal(RHS))
1874 return BinaryOperator::createSub(LHS, V);
1878 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1879 if (X == RHS) // X*C + X --> X * (C+1)
1880 return BinaryOperator::createMul(RHS, AddOne(C2));
1882 // X*C1 + X*C2 --> X * (C1+C2)
1884 if (X == dyn_castFoldableMul(RHS, C1))
1885 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1888 // X + X*C --> X * (C+1)
1889 if (dyn_castFoldableMul(RHS, C2) == LHS)
1890 return BinaryOperator::createMul(LHS, AddOne(C2));
1893 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1894 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1895 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1897 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1899 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1900 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1901 return BinaryOperator::createSub(C, X);
1904 // (X & FF00) + xx00 -> (X+xx00) & FF00
1905 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1906 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1907 if (Anded == CRHS) {
1908 // See if all bits from the first bit set in the Add RHS up are included
1909 // in the mask. First, get the rightmost bit.
1910 uint64_t AddRHSV = CRHS->getZExtValue();
1912 // Form a mask of all bits from the lowest bit added through the top.
1913 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1914 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1916 // See if the and mask includes all of these bits.
1917 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1919 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1920 // Okay, the xform is safe. Insert the new add pronto.
1921 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1922 LHS->getName()), I);
1923 return BinaryOperator::createAnd(NewAdd, C2);
1928 // Try to fold constant add into select arguments.
1929 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1930 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1934 // add (cast *A to intptrtype) B ->
1935 // cast (GEP (cast *A to sbyte*) B) ->
1938 CastInst* CI = dyn_cast<CastInst>(LHS);
1941 CI = dyn_cast<CastInst>(RHS);
1944 if (CI && CI->getType()->isSized() &&
1945 (CI->getType()->getPrimitiveSize() ==
1946 TD->getIntPtrType()->getPrimitiveSize())
1947 && isa<PointerType>(CI->getOperand(0)->getType())) {
1948 Value* I2 = InsertCastBefore(CI->getOperand(0),
1949 PointerType::get(Type::SByteTy), I);
1950 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1951 return new CastInst(I2, CI->getType());
1955 return Changed ? &I : 0;
1958 // isSignBit - Return true if the value represented by the constant only has the
1959 // highest order bit set.
1960 static bool isSignBit(ConstantInt *CI) {
1961 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1962 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1965 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1967 static Value *RemoveNoopCast(Value *V) {
1968 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1969 const Type *CTy = CI->getType();
1970 const Type *OpTy = CI->getOperand(0)->getType();
1971 if (CTy->isInteger() && OpTy->isInteger()) {
1972 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1973 return RemoveNoopCast(CI->getOperand(0));
1974 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1975 return RemoveNoopCast(CI->getOperand(0));
1980 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1981 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1983 if (Op0 == Op1) // sub X, X -> 0
1984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1986 // If this is a 'B = x-(-A)', change to B = x+A...
1987 if (Value *V = dyn_castNegVal(Op1))
1988 return BinaryOperator::createAdd(Op0, V);
1990 if (isa<UndefValue>(Op0))
1991 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1992 if (isa<UndefValue>(Op1))
1993 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1995 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1996 // Replace (-1 - A) with (~A)...
1997 if (C->isAllOnesValue())
1998 return BinaryOperator::createNot(Op1);
2000 // C - ~X == X + (1+C)
2002 if (match(Op1, m_Not(m_Value(X))))
2003 return BinaryOperator::createAdd(X,
2004 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
2005 // -((uint)X >> 31) -> ((int)X >> 31)
2006 // -((int)X >> 31) -> ((uint)X >> 31)
2007 if (C->isNullValue()) {
2008 Value *NoopCastedRHS = RemoveNoopCast(Op1);
2009 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
2010 if (SI->getOpcode() == Instruction::LShr) {
2011 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2012 // Check to see if we are shifting out everything but the sign bit.
2013 if (CU->getZExtValue() ==
2014 SI->getType()->getPrimitiveSizeInBits()-1) {
2015 // Ok, the transformation is safe. Insert AShr.
2016 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
2021 else if (SI->getOpcode() == Instruction::AShr) {
2022 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2023 // Check to see if we are shifting out everything but the sign bit.
2024 if (CU->getZExtValue() ==
2025 SI->getType()->getPrimitiveSizeInBits()-1) {
2026 // Ok, the transformation is safe. Insert LShr.
2027 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
2034 // Try to fold constant sub into select arguments.
2035 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2036 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2039 if (isa<PHINode>(Op0))
2040 if (Instruction *NV = FoldOpIntoPhi(I))
2044 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2045 if (Op1I->getOpcode() == Instruction::Add &&
2046 !Op0->getType()->isFloatingPoint()) {
2047 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2048 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2049 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2050 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2051 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2052 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2053 // C1-(X+C2) --> (C1-C2)-X
2054 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2055 Op1I->getOperand(0));
2059 if (Op1I->hasOneUse()) {
2060 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2061 // is not used by anyone else...
2063 if (Op1I->getOpcode() == Instruction::Sub &&
2064 !Op1I->getType()->isFloatingPoint()) {
2065 // Swap the two operands of the subexpr...
2066 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2067 Op1I->setOperand(0, IIOp1);
2068 Op1I->setOperand(1, IIOp0);
2070 // Create the new top level add instruction...
2071 return BinaryOperator::createAdd(Op0, Op1);
2074 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2076 if (Op1I->getOpcode() == Instruction::And &&
2077 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2078 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2081 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2082 return BinaryOperator::createAnd(Op0, NewNot);
2085 // 0 - (X sdiv C) -> (X sdiv -C)
2086 if (Op1I->getOpcode() == Instruction::SDiv)
2087 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2088 if (CSI->isNullValue())
2089 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2090 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2091 ConstantExpr::getNeg(DivRHS));
2093 // X - X*C --> X * (1-C)
2094 ConstantInt *C2 = 0;
2095 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2097 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2098 return BinaryOperator::createMul(Op0, CP1);
2103 if (!Op0->getType()->isFloatingPoint())
2104 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2105 if (Op0I->getOpcode() == Instruction::Add) {
2106 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2107 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2108 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2109 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2110 } else if (Op0I->getOpcode() == Instruction::Sub) {
2111 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2112 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2116 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2117 if (X == Op1) { // X*C - X --> X * (C-1)
2118 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2119 return BinaryOperator::createMul(Op1, CP1);
2122 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2123 if (X == dyn_castFoldableMul(Op1, C2))
2124 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2129 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2130 /// really just returns true if the most significant (sign) bit is set.
2131 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2132 if (RHS->getType()->isSigned()) {
2133 // True if source is LHS < 0 or LHS <= -1
2134 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2135 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2137 ConstantInt *RHSC = cast<ConstantInt>(RHS);
2138 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2139 // the size of the integer type.
2140 if (Opcode == Instruction::SetGE)
2141 return RHSC->getZExtValue() ==
2142 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
2143 if (Opcode == Instruction::SetGT)
2144 return RHSC->getZExtValue() ==
2145 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2150 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2151 bool Changed = SimplifyCommutative(I);
2152 Value *Op0 = I.getOperand(0);
2154 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2155 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2157 // Simplify mul instructions with a constant RHS...
2158 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2159 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2161 // ((X << C1)*C2) == (X * (C2 << C1))
2162 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2163 if (SI->getOpcode() == Instruction::Shl)
2164 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2165 return BinaryOperator::createMul(SI->getOperand(0),
2166 ConstantExpr::getShl(CI, ShOp));
2168 if (CI->isNullValue())
2169 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2170 if (CI->equalsInt(1)) // X * 1 == X
2171 return ReplaceInstUsesWith(I, Op0);
2172 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2173 return BinaryOperator::createNeg(Op0, I.getName());
2175 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2176 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2177 uint64_t C = Log2_64(Val);
2178 return new ShiftInst(Instruction::Shl, Op0,
2179 ConstantInt::get(Type::UByteTy, C));
2181 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2182 if (Op1F->isNullValue())
2183 return ReplaceInstUsesWith(I, Op1);
2185 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2186 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2187 if (Op1F->getValue() == 1.0)
2188 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2191 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2192 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2193 isa<ConstantInt>(Op0I->getOperand(1))) {
2194 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2195 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2197 InsertNewInstBefore(Add, I);
2198 Value *C1C2 = ConstantExpr::getMul(Op1,
2199 cast<Constant>(Op0I->getOperand(1)));
2200 return BinaryOperator::createAdd(Add, C1C2);
2204 // Try to fold constant mul into select arguments.
2205 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2206 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2209 if (isa<PHINode>(Op0))
2210 if (Instruction *NV = FoldOpIntoPhi(I))
2214 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2215 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2216 return BinaryOperator::createMul(Op0v, Op1v);
2218 // If one of the operands of the multiply is a cast from a boolean value, then
2219 // we know the bool is either zero or one, so this is a 'masking' multiply.
2220 // See if we can simplify things based on how the boolean was originally
2222 CastInst *BoolCast = 0;
2223 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2224 if (CI->getOperand(0)->getType() == Type::BoolTy)
2227 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2228 if (CI->getOperand(0)->getType() == Type::BoolTy)
2231 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2232 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2233 const Type *SCOpTy = SCIOp0->getType();
2235 // If the setcc is true iff the sign bit of X is set, then convert this
2236 // multiply into a shift/and combination.
2237 if (isa<ConstantInt>(SCIOp1) &&
2238 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
2239 // Shift the X value right to turn it into "all signbits".
2240 Constant *Amt = ConstantInt::get(Type::UByteTy,
2241 SCOpTy->getPrimitiveSizeInBits()-1);
2242 if (SCIOp0->getType()->isUnsigned()) {
2243 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
2244 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
2248 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2249 BoolCast->getOperand(0)->getName()+
2252 // If the multiply type is not the same as the source type, sign extend
2253 // or truncate to the multiply type.
2254 if (I.getType() != V->getType())
2255 V = InsertCastBefore(V, I.getType(), I);
2257 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2258 return BinaryOperator::createAnd(V, OtherOp);
2263 return Changed ? &I : 0;
2266 /// This function implements the transforms on div instructions that work
2267 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2268 /// used by the visitors to those instructions.
2269 /// @brief Transforms common to all three div instructions
2270 Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
2271 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2274 if (isa<UndefValue>(Op0))
2275 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2277 // X / undef -> undef
2278 if (isa<UndefValue>(Op1))
2279 return ReplaceInstUsesWith(I, Op1);
2281 // Handle cases involving: div X, (select Cond, Y, Z)
2282 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2283 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2284 // same basic block, then we replace the select with Y, and the condition
2285 // of the select with false (if the cond value is in the same BB). If the
2286 // select has uses other than the div, this allows them to be simplified
2287 // also. Note that div X, Y is just as good as div X, 0 (undef)
2288 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2289 if (ST->isNullValue()) {
2290 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2291 if (CondI && CondI->getParent() == I.getParent())
2292 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2293 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2294 I.setOperand(1, SI->getOperand(2));
2296 UpdateValueUsesWith(SI, SI->getOperand(2));
2300 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2301 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2302 if (ST->isNullValue()) {
2303 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2304 if (CondI && CondI->getParent() == I.getParent())
2305 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2306 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2307 I.setOperand(1, SI->getOperand(1));
2309 UpdateValueUsesWith(SI, SI->getOperand(1));
2317 /// This function implements the transforms common to both integer division
2318 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2319 /// division instructions.
2320 /// @brief Common integer divide transforms
2321 Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2322 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2324 if (Instruction *Common = commonDivTransforms(I))
2327 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2329 if (RHS->equalsInt(1))
2330 return ReplaceInstUsesWith(I, Op0);
2332 // (X / C1) / C2 -> X / (C1*C2)
2333 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2334 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2335 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2336 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2337 ConstantExpr::getMul(RHS, LHSRHS));
2340 if (!RHS->isNullValue()) { // avoid X udiv 0
2341 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2342 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2344 if (isa<PHINode>(Op0))
2345 if (Instruction *NV = FoldOpIntoPhi(I))
2350 // 0 / X == 0, we don't need to preserve faults!
2351 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2352 if (LHS->equalsInt(0))
2353 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2358 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2361 // Handle the integer div common cases
2362 if (Instruction *Common = commonIDivTransforms(I))
2365 // X udiv C^2 -> X >> C
2366 // Check to see if this is an unsigned division with an exact power of 2,
2367 // if so, convert to a right shift.
2368 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2369 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2370 if (isPowerOf2_64(Val)) {
2371 uint64_t ShiftAmt = Log2_64(Val);
2372 return new ShiftInst(Instruction::LShr, Op0,
2373 ConstantInt::get(Type::UByteTy, ShiftAmt));
2377 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2378 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2379 if (RHSI->getOpcode() == Instruction::Shl &&
2380 isa<ConstantInt>(RHSI->getOperand(0))) {
2381 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2382 if (isPowerOf2_64(C1)) {
2383 Value *N = RHSI->getOperand(1);
2384 const Type* NTy = N->getType();
2385 if (uint64_t C2 = Log2_64(C1)) {
2386 Constant *C2V = ConstantInt::get(NTy, C2);
2387 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2389 return new ShiftInst(Instruction::LShr, Op0, N);
2394 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2395 // where C1&C2 are powers of two.
2396 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2397 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2398 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2399 if (!STO->isNullValue() && !STO->isNullValue()) {
2400 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2401 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2402 // Compute the shift amounts
2403 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2404 // Construct the "on true" case of the select
2405 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2407 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2408 TSI = InsertNewInstBefore(TSI, I);
2410 // Construct the "on false" case of the select
2411 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2413 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2414 FSI = InsertNewInstBefore(FSI, I);
2416 // construct the select instruction and return it.
2417 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2424 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2425 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2427 // Handle the integer div common cases
2428 if (Instruction *Common = commonIDivTransforms(I))
2431 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2433 if (RHS->isAllOnesValue())
2434 return BinaryOperator::createNeg(Op0);
2437 if (Value *LHSNeg = dyn_castNegVal(Op0))
2438 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2441 // If the sign bits of both operands are zero (i.e. we can prove they are
2442 // unsigned inputs), turn this into a udiv.
2443 if (I.getType()->isInteger()) {
2444 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2445 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2446 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2453 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2454 return commonDivTransforms(I);
2457 /// GetFactor - If we can prove that the specified value is at least a multiple
2458 /// of some factor, return that factor.
2459 static Constant *GetFactor(Value *V) {
2460 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2463 // Unless we can be tricky, we know this is a multiple of 1.
2464 Constant *Result = ConstantInt::get(V->getType(), 1);
2466 Instruction *I = dyn_cast<Instruction>(V);
2467 if (!I) return Result;
2469 if (I->getOpcode() == Instruction::Mul) {
2470 // Handle multiplies by a constant, etc.
2471 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2472 GetFactor(I->getOperand(1)));
2473 } else if (I->getOpcode() == Instruction::Shl) {
2474 // (X<<C) -> X * (1 << C)
2475 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2476 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2477 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2479 } else if (I->getOpcode() == Instruction::And) {
2480 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2481 // X & 0xFFF0 is known to be a multiple of 16.
2482 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2483 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2484 return ConstantExpr::getShl(Result,
2485 ConstantInt::get(Type::UByteTy, Zeros));
2487 } else if (I->getOpcode() == Instruction::Cast) {
2488 Value *Op = I->getOperand(0);
2489 // Only handle int->int casts.
2490 if (!Op->getType()->isInteger()) return Result;
2491 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2496 /// This function implements the transforms on rem instructions that work
2497 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2498 /// is used by the visitors to those instructions.
2499 /// @brief Transforms common to all three rem instructions
2500 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2501 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2503 // 0 % X == 0, we don't need to preserve faults!
2504 if (Constant *LHS = dyn_cast<Constant>(Op0))
2505 if (LHS->isNullValue())
2506 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2508 if (isa<UndefValue>(Op0)) // undef % X -> 0
2509 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2510 if (isa<UndefValue>(Op1))
2511 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2513 // Handle cases involving: rem X, (select Cond, Y, Z)
2514 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2515 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2516 // the same basic block, then we replace the select with Y, and the
2517 // condition of the select with false (if the cond value is in the same
2518 // BB). If the select has uses other than the div, this allows them to be
2520 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2521 if (ST->isNullValue()) {
2522 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2523 if (CondI && CondI->getParent() == I.getParent())
2524 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2525 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2526 I.setOperand(1, SI->getOperand(2));
2528 UpdateValueUsesWith(SI, SI->getOperand(2));
2531 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2532 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2533 if (ST->isNullValue()) {
2534 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2535 if (CondI && CondI->getParent() == I.getParent())
2536 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2537 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2538 I.setOperand(1, SI->getOperand(1));
2540 UpdateValueUsesWith(SI, SI->getOperand(1));
2548 /// This function implements the transforms common to both integer remainder
2549 /// instructions (urem and srem). It is called by the visitors to those integer
2550 /// remainder instructions.
2551 /// @brief Common integer remainder transforms
2552 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2553 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2555 if (Instruction *common = commonRemTransforms(I))
2558 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2559 // X % 0 == undef, we don't need to preserve faults!
2560 if (RHS->equalsInt(0))
2561 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2563 if (RHS->equalsInt(1)) // X % 1 == 0
2564 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2566 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2567 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2568 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2570 } else if (isa<PHINode>(Op0I)) {
2571 if (Instruction *NV = FoldOpIntoPhi(I))
2574 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2575 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2576 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2583 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2584 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2586 if (Instruction *common = commonIRemTransforms(I))
2589 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2590 // X urem C^2 -> X and C
2591 // Check to see if this is an unsigned remainder with an exact power of 2,
2592 // if so, convert to a bitwise and.
2593 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2594 if (isPowerOf2_64(C->getZExtValue()))
2595 return BinaryOperator::createAnd(Op0, SubOne(C));
2598 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2599 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2600 if (RHSI->getOpcode() == Instruction::Shl &&
2601 isa<ConstantInt>(RHSI->getOperand(0))) {
2602 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2603 if (isPowerOf2_64(C1)) {
2604 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2605 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2607 return BinaryOperator::createAnd(Op0, Add);
2612 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2613 // where C1&C2 are powers of two.
2614 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2615 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2616 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2617 // STO == 0 and SFO == 0 handled above.
2618 if (isPowerOf2_64(STO->getZExtValue()) &&
2619 isPowerOf2_64(SFO->getZExtValue())) {
2620 Value *TrueAnd = InsertNewInstBefore(
2621 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2622 Value *FalseAnd = InsertNewInstBefore(
2623 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2624 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2632 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2633 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2635 if (Instruction *common = commonIRemTransforms(I))
2638 if (Value *RHSNeg = dyn_castNegVal(Op1))
2639 if (!isa<ConstantInt>(RHSNeg) ||
2640 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2642 AddUsesToWorkList(I);
2643 I.setOperand(1, RHSNeg);
2647 // If the top bits of both operands are zero (i.e. we can prove they are
2648 // unsigned inputs), turn this into a urem.
2649 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2650 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2651 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2652 return BinaryOperator::createURem(Op0, Op1, I.getName());
2658 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2659 return commonRemTransforms(I);
2662 // isMaxValueMinusOne - return true if this is Max-1
2663 static bool isMaxValueMinusOne(const ConstantInt *C) {
2664 if (C->getType()->isUnsigned())
2665 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2667 // Calculate 0111111111..11111
2668 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2669 int64_t Val = INT64_MAX; // All ones
2670 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2671 return C->getSExtValue() == Val-1;
2674 // isMinValuePlusOne - return true if this is Min+1
2675 static bool isMinValuePlusOne(const ConstantInt *C) {
2676 if (C->getType()->isUnsigned())
2677 return C->getZExtValue() == 1;
2679 // Calculate 1111111111000000000000
2680 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2681 int64_t Val = -1; // All ones
2682 Val <<= TypeBits-1; // Shift over to the right spot
2683 return C->getSExtValue() == Val+1;
2686 // isOneBitSet - Return true if there is exactly one bit set in the specified
2688 static bool isOneBitSet(const ConstantInt *CI) {
2689 uint64_t V = CI->getZExtValue();
2690 return V && (V & (V-1)) == 0;
2693 #if 0 // Currently unused
2694 // isLowOnes - Return true if the constant is of the form 0+1+.
2695 static bool isLowOnes(const ConstantInt *CI) {
2696 uint64_t V = CI->getZExtValue();
2698 // There won't be bits set in parts that the type doesn't contain.
2699 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2701 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2702 return U && V && (U & V) == 0;
2706 // isHighOnes - Return true if the constant is of the form 1+0+.
2707 // This is the same as lowones(~X).
2708 static bool isHighOnes(const ConstantInt *CI) {
2709 uint64_t V = ~CI->getZExtValue();
2710 if (~V == 0) return false; // 0's does not match "1+"
2712 // There won't be bits set in parts that the type doesn't contain.
2713 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2715 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2716 return U && V && (U & V) == 0;
2720 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2721 /// are carefully arranged to allow folding of expressions such as:
2723 /// (A < B) | (A > B) --> (A != B)
2725 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2726 /// represents that the comparison is true if A == B, and bit value '1' is true
2729 static unsigned getSetCondCode(const SetCondInst *SCI) {
2730 switch (SCI->getOpcode()) {
2732 case Instruction::SetGT: return 1;
2733 case Instruction::SetEQ: return 2;
2734 case Instruction::SetGE: return 3;
2735 case Instruction::SetLT: return 4;
2736 case Instruction::SetNE: return 5;
2737 case Instruction::SetLE: return 6;
2740 assert(0 && "Invalid SetCC opcode!");
2745 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2746 /// opcode and two operands into either a constant true or false, or a brand new
2747 /// SetCC instruction.
2748 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2750 case 0: return ConstantBool::getFalse();
2751 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2752 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2753 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2754 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2755 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2756 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2757 case 7: return ConstantBool::getTrue();
2758 default: assert(0 && "Illegal SetCCCode!"); return 0;
2762 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2764 struct FoldSetCCLogical {
2767 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2768 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2769 bool shouldApply(Value *V) const {
2770 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2771 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2772 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2775 Instruction *apply(BinaryOperator &Log) const {
2776 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2777 if (SCI->getOperand(0) != LHS) {
2778 assert(SCI->getOperand(1) == LHS);
2779 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2782 unsigned LHSCode = getSetCondCode(SCI);
2783 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2785 switch (Log.getOpcode()) {
2786 case Instruction::And: Code = LHSCode & RHSCode; break;
2787 case Instruction::Or: Code = LHSCode | RHSCode; break;
2788 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2789 default: assert(0 && "Illegal logical opcode!"); return 0;
2792 Value *RV = getSetCCValue(Code, LHS, RHS);
2793 if (Instruction *I = dyn_cast<Instruction>(RV))
2795 // Otherwise, it's a constant boolean value...
2796 return IC.ReplaceInstUsesWith(Log, RV);
2799 } // end anonymous namespace
2801 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2802 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2803 // guaranteed to be either a shift instruction or a binary operator.
2804 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2805 ConstantIntegral *OpRHS,
2806 ConstantIntegral *AndRHS,
2807 BinaryOperator &TheAnd) {
2808 Value *X = Op->getOperand(0);
2809 Constant *Together = 0;
2810 if (!isa<ShiftInst>(Op))
2811 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2813 switch (Op->getOpcode()) {
2814 case Instruction::Xor:
2815 if (Op->hasOneUse()) {
2816 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2817 std::string OpName = Op->getName(); Op->setName("");
2818 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2819 InsertNewInstBefore(And, TheAnd);
2820 return BinaryOperator::createXor(And, Together);
2823 case Instruction::Or:
2824 if (Together == AndRHS) // (X | C) & C --> C
2825 return ReplaceInstUsesWith(TheAnd, AndRHS);
2827 if (Op->hasOneUse() && Together != OpRHS) {
2828 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2829 std::string Op0Name = Op->getName(); Op->setName("");
2830 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2831 InsertNewInstBefore(Or, TheAnd);
2832 return BinaryOperator::createAnd(Or, AndRHS);
2835 case Instruction::Add:
2836 if (Op->hasOneUse()) {
2837 // Adding a one to a single bit bit-field should be turned into an XOR
2838 // of the bit. First thing to check is to see if this AND is with a
2839 // single bit constant.
2840 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2842 // Clear bits that are not part of the constant.
2843 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2845 // If there is only one bit set...
2846 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2847 // Ok, at this point, we know that we are masking the result of the
2848 // ADD down to exactly one bit. If the constant we are adding has
2849 // no bits set below this bit, then we can eliminate the ADD.
2850 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2852 // Check to see if any bits below the one bit set in AndRHSV are set.
2853 if ((AddRHS & (AndRHSV-1)) == 0) {
2854 // If not, the only thing that can effect the output of the AND is
2855 // the bit specified by AndRHSV. If that bit is set, the effect of
2856 // the XOR is to toggle the bit. If it is clear, then the ADD has
2858 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2859 TheAnd.setOperand(0, X);
2862 std::string Name = Op->getName(); Op->setName("");
2863 // Pull the XOR out of the AND.
2864 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2865 InsertNewInstBefore(NewAnd, TheAnd);
2866 return BinaryOperator::createXor(NewAnd, AndRHS);
2873 case Instruction::Shl: {
2874 // We know that the AND will not produce any of the bits shifted in, so if
2875 // the anded constant includes them, clear them now!
2877 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2878 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2879 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2881 if (CI == ShlMask) { // Masking out bits that the shift already masks
2882 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2883 } else if (CI != AndRHS) { // Reducing bits set in and.
2884 TheAnd.setOperand(1, CI);
2889 case Instruction::LShr:
2891 // We know that the AND will not produce any of the bits shifted in, so if
2892 // the anded constant includes them, clear them now! This only applies to
2893 // unsigned shifts, because a signed shr may bring in set bits!
2895 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2896 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2897 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2899 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2900 return ReplaceInstUsesWith(TheAnd, Op);
2901 } else if (CI != AndRHS) {
2902 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2907 case Instruction::AShr:
2909 // See if this is shifting in some sign extension, then masking it out
2911 if (Op->hasOneUse()) {
2912 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2913 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2914 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2915 if (CI == AndRHS) { // Masking out bits shifted in.
2916 // Make the argument unsigned.
2917 Value *ShVal = Op->getOperand(0);
2918 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2919 OpRHS, Op->getName()),
2921 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2922 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
2931 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2932 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2933 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2934 /// insert new instructions.
2935 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2936 bool Inside, Instruction &IB) {
2937 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2938 "Lo is not <= Hi in range emission code!");
2940 if (Lo == Hi) // Trivially false.
2941 return new SetCondInst(Instruction::SetNE, V, V);
2942 if (cast<ConstantIntegral>(Lo)->isMinValue())
2943 return new SetCondInst(Instruction::SetLT, V, Hi);
2945 Constant *AddCST = ConstantExpr::getNeg(Lo);
2946 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2947 InsertNewInstBefore(Add, IB);
2948 // Convert to unsigned for the comparison.
2949 const Type *UnsType = Add->getType()->getUnsignedVersion();
2950 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2951 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2952 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2953 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2956 if (Lo == Hi) // Trivially true.
2957 return new SetCondInst(Instruction::SetEQ, V, V);
2959 Hi = SubOne(cast<ConstantInt>(Hi));
2961 // V < 0 || V >= Hi ->'V > Hi-1'
2962 if (cast<ConstantIntegral>(Lo)->isMinValue())
2963 return new SetCondInst(Instruction::SetGT, V, Hi);
2965 // Emit X-Lo > Hi-Lo-1
2966 Constant *AddCST = ConstantExpr::getNeg(Lo);
2967 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2968 InsertNewInstBefore(Add, IB);
2969 // Convert to unsigned for the comparison.
2970 const Type *UnsType = Add->getType()->getUnsignedVersion();
2971 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2972 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2973 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2974 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2977 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2978 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2979 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2980 // not, since all 1s are not contiguous.
2981 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2982 uint64_t V = Val->getZExtValue();
2983 if (!isShiftedMask_64(V)) return false;
2985 // look for the first zero bit after the run of ones
2986 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2987 // look for the first non-zero bit
2988 ME = 64-CountLeadingZeros_64(V);
2994 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2995 /// where isSub determines whether the operator is a sub. If we can fold one of
2996 /// the following xforms:
2998 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2999 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3000 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3002 /// return (A +/- B).
3004 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3005 ConstantIntegral *Mask, bool isSub,
3007 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3008 if (!LHSI || LHSI->getNumOperands() != 2 ||
3009 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3011 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3013 switch (LHSI->getOpcode()) {
3015 case Instruction::And:
3016 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3017 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3018 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3021 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3022 // part, we don't need any explicit masks to take them out of A. If that
3023 // is all N is, ignore it.
3025 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3026 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3028 if (MaskedValueIsZero(RHS, Mask))
3033 case Instruction::Or:
3034 case Instruction::Xor:
3035 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3036 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3037 ConstantExpr::getAnd(N, Mask)->isNullValue())
3044 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3046 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3047 return InsertNewInstBefore(New, I);
3050 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3051 bool Changed = SimplifyCommutative(I);
3052 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3054 if (isa<UndefValue>(Op1)) // X & undef -> 0
3055 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3059 return ReplaceInstUsesWith(I, Op1);
3061 // See if we can simplify any instructions used by the instruction whose sole
3062 // purpose is to compute bits we don't care about.
3063 uint64_t KnownZero, KnownOne;
3064 if (!isa<PackedType>(I.getType()) &&
3065 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3066 KnownZero, KnownOne))
3069 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
3070 uint64_t AndRHSMask = AndRHS->getZExtValue();
3071 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
3072 uint64_t NotAndRHS = AndRHSMask^TypeMask;
3074 // Optimize a variety of ((val OP C1) & C2) combinations...
3075 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3076 Instruction *Op0I = cast<Instruction>(Op0);
3077 Value *Op0LHS = Op0I->getOperand(0);
3078 Value *Op0RHS = Op0I->getOperand(1);
3079 switch (Op0I->getOpcode()) {
3080 case Instruction::Xor:
3081 case Instruction::Or:
3082 // If the mask is only needed on one incoming arm, push it up.
3083 if (Op0I->hasOneUse()) {
3084 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3085 // Not masking anything out for the LHS, move to RHS.
3086 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3087 Op0RHS->getName()+".masked");
3088 InsertNewInstBefore(NewRHS, I);
3089 return BinaryOperator::create(
3090 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3092 if (!isa<Constant>(Op0RHS) &&
3093 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3094 // Not masking anything out for the RHS, move to LHS.
3095 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3096 Op0LHS->getName()+".masked");
3097 InsertNewInstBefore(NewLHS, I);
3098 return BinaryOperator::create(
3099 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3104 case Instruction::Add:
3105 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3106 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3107 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3108 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3109 return BinaryOperator::createAnd(V, AndRHS);
3110 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3111 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3114 case Instruction::Sub:
3115 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3116 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3117 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3118 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3119 return BinaryOperator::createAnd(V, AndRHS);
3123 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3124 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3126 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3127 const Type *SrcTy = CI->getOperand(0)->getType();
3129 // If this is an integer truncation or change from signed-to-unsigned, and
3130 // if the source is an and/or with immediate, transform it. This
3131 // frequently occurs for bitfield accesses.
3132 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3133 if (SrcTy->getPrimitiveSizeInBits() >=
3134 I.getType()->getPrimitiveSizeInBits() &&
3135 CastOp->getNumOperands() == 2)
3136 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3137 if (CastOp->getOpcode() == Instruction::And) {
3138 // Change: and (cast (and X, C1) to T), C2
3139 // into : and (cast X to T), trunc(C1)&C2
3140 // This will folds the two ands together, which may allow other
3142 Instruction *NewCast =
3143 new CastInst(CastOp->getOperand(0), I.getType(),
3144 CastOp->getName()+".shrunk");
3145 NewCast = InsertNewInstBefore(NewCast, I);
3147 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3148 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
3149 return BinaryOperator::createAnd(NewCast, C3);
3150 } else if (CastOp->getOpcode() == Instruction::Or) {
3151 // Change: and (cast (or X, C1) to T), C2
3152 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3153 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3154 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3155 return ReplaceInstUsesWith(I, AndRHS);
3160 // Try to fold constant and into select arguments.
3161 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3162 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3164 if (isa<PHINode>(Op0))
3165 if (Instruction *NV = FoldOpIntoPhi(I))
3169 Value *Op0NotVal = dyn_castNotVal(Op0);
3170 Value *Op1NotVal = dyn_castNotVal(Op1);
3172 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3173 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3175 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3176 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3177 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3178 I.getName()+".demorgan");
3179 InsertNewInstBefore(Or, I);
3180 return BinaryOperator::createNot(Or);
3184 Value *A = 0, *B = 0;
3185 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3186 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3187 return ReplaceInstUsesWith(I, Op1);
3188 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3189 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3190 return ReplaceInstUsesWith(I, Op0);
3192 if (Op0->hasOneUse() &&
3193 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3194 if (A == Op1) { // (A^B)&A -> A&(A^B)
3195 I.swapOperands(); // Simplify below
3196 std::swap(Op0, Op1);
3197 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3198 cast<BinaryOperator>(Op0)->swapOperands();
3199 I.swapOperands(); // Simplify below
3200 std::swap(Op0, Op1);
3203 if (Op1->hasOneUse() &&
3204 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3205 if (B == Op0) { // B&(A^B) -> B&(B^A)
3206 cast<BinaryOperator>(Op1)->swapOperands();
3209 if (A == Op0) { // A&(A^B) -> A & ~B
3210 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3211 InsertNewInstBefore(NotB, I);
3212 return BinaryOperator::createAnd(A, NotB);
3218 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3219 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
3220 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3223 Value *LHSVal, *RHSVal;
3224 ConstantInt *LHSCst, *RHSCst;
3225 Instruction::BinaryOps LHSCC, RHSCC;
3226 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3227 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3228 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3229 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3230 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3231 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3232 // Ensure that the larger constant is on the RHS.
3233 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3234 SetCondInst *LHS = cast<SetCondInst>(Op0);
3235 if (cast<ConstantBool>(Cmp)->getValue()) {
3236 std::swap(LHS, RHS);
3237 std::swap(LHSCst, RHSCst);
3238 std::swap(LHSCC, RHSCC);
3241 // At this point, we know we have have two setcc instructions
3242 // comparing a value against two constants and and'ing the result
3243 // together. Because of the above check, we know that we only have
3244 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3245 // FoldSetCCLogical check above), that the two constants are not
3247 assert(LHSCst != RHSCst && "Compares not folded above?");
3250 default: assert(0 && "Unknown integer condition code!");
3251 case Instruction::SetEQ:
3253 default: assert(0 && "Unknown integer condition code!");
3254 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3255 case Instruction::SetGT: // (X == 13 & X > 15) -> false
3256 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3257 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3258 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3259 return ReplaceInstUsesWith(I, LHS);
3261 case Instruction::SetNE:
3263 default: assert(0 && "Unknown integer condition code!");
3264 case Instruction::SetLT:
3265 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3266 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3267 break; // (X != 13 & X < 15) -> no change
3268 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3269 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3270 return ReplaceInstUsesWith(I, RHS);
3271 case Instruction::SetNE:
3272 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3273 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3274 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3275 LHSVal->getName()+".off");
3276 InsertNewInstBefore(Add, I);
3277 const Type *UnsType = Add->getType()->getUnsignedVersion();
3278 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3279 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3280 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3281 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3283 break; // (X != 13 & X != 15) -> no change
3286 case Instruction::SetLT:
3288 default: assert(0 && "Unknown integer condition code!");
3289 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3290 case Instruction::SetGT: // (X < 13 & X > 15) -> false
3291 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3292 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3293 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3294 return ReplaceInstUsesWith(I, LHS);
3296 case Instruction::SetGT:
3298 default: assert(0 && "Unknown integer condition code!");
3299 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3300 return ReplaceInstUsesWith(I, LHS);
3301 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3302 return ReplaceInstUsesWith(I, RHS);
3303 case Instruction::SetNE:
3304 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3305 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3306 break; // (X > 13 & X != 15) -> no change
3307 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3308 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
3314 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3315 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
3316 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3317 const Type *SrcTy = Op0C->getOperand(0)->getType();
3318 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3319 // Only do this if the casts both really cause code to be generated.
3320 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3321 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3322 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3323 Op1C->getOperand(0),
3325 InsertNewInstBefore(NewOp, I);
3326 return new CastInst(NewOp, I.getType());
3331 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3332 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3333 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3334 if (SI0->getOpcode() == SI1->getOpcode() &&
3335 SI0->getOperand(1) == SI1->getOperand(1) &&
3336 (SI0->hasOneUse() || SI1->hasOneUse())) {
3337 Instruction *NewOp =
3338 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3340 SI0->getName()), I);
3341 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3345 return Changed ? &I : 0;
3348 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3349 /// in the result. If it does, and if the specified byte hasn't been filled in
3350 /// yet, fill it in and return false.
3351 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3352 Instruction *I = dyn_cast<Instruction>(V);
3353 if (I == 0) return true;
3355 // If this is an or instruction, it is an inner node of the bswap.
3356 if (I->getOpcode() == Instruction::Or)
3357 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3358 CollectBSwapParts(I->getOperand(1), ByteValues);
3360 // If this is a shift by a constant int, and it is "24", then its operand
3361 // defines a byte. We only handle unsigned types here.
3362 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3363 // Not shifting the entire input by N-1 bytes?
3364 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3365 8*(ByteValues.size()-1))
3369 if (I->getOpcode() == Instruction::Shl) {
3370 // X << 24 defines the top byte with the lowest of the input bytes.
3371 DestNo = ByteValues.size()-1;
3373 // X >>u 24 defines the low byte with the highest of the input bytes.
3377 // If the destination byte value is already defined, the values are or'd
3378 // together, which isn't a bswap (unless it's an or of the same bits).
3379 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3381 ByteValues[DestNo] = I->getOperand(0);
3385 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3387 Value *Shift = 0, *ShiftLHS = 0;
3388 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3389 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3390 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3392 Instruction *SI = cast<Instruction>(Shift);
3394 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3395 if (ShiftAmt->getZExtValue() & 7 ||
3396 ShiftAmt->getZExtValue() > 8*ByteValues.size())
3399 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3401 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3402 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3404 // Unknown mask for bswap.
3405 if (DestByte == ByteValues.size()) return true;
3407 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3409 if (SI->getOpcode() == Instruction::Shl)
3410 SrcByte = DestByte - ShiftBytes;
3412 SrcByte = DestByte + ShiftBytes;
3414 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3415 if (SrcByte != ByteValues.size()-DestByte-1)
3418 // If the destination byte value is already defined, the values are or'd
3419 // together, which isn't a bswap (unless it's an or of the same bits).
3420 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3422 ByteValues[DestByte] = SI->getOperand(0);
3426 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3427 /// If so, insert the new bswap intrinsic and return it.
3428 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3429 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3430 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3433 /// ByteValues - For each byte of the result, we keep track of which value
3434 /// defines each byte.
3435 std::vector<Value*> ByteValues;
3436 ByteValues.resize(I.getType()->getPrimitiveSize());
3438 // Try to find all the pieces corresponding to the bswap.
3439 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3440 CollectBSwapParts(I.getOperand(1), ByteValues))
3443 // Check to see if all of the bytes come from the same value.
3444 Value *V = ByteValues[0];
3445 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3447 // Check to make sure that all of the bytes come from the same value.
3448 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3449 if (ByteValues[i] != V)
3452 // If they do then *success* we can turn this into a bswap. Figure out what
3453 // bswap to make it into.
3454 Module *M = I.getParent()->getParent()->getParent();
3455 const char *FnName = 0;
3456 if (I.getType() == Type::UShortTy)
3457 FnName = "llvm.bswap.i16";
3458 else if (I.getType() == Type::UIntTy)
3459 FnName = "llvm.bswap.i32";
3460 else if (I.getType() == Type::ULongTy)
3461 FnName = "llvm.bswap.i64";
3463 assert(0 && "Unknown integer type!");
3464 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3466 return new CallInst(F, V);
3470 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3471 bool Changed = SimplifyCommutative(I);
3472 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3474 if (isa<UndefValue>(Op1))
3475 return ReplaceInstUsesWith(I, // X | undef -> -1
3476 ConstantIntegral::getAllOnesValue(I.getType()));
3480 return ReplaceInstUsesWith(I, Op0);
3482 // See if we can simplify any instructions used by the instruction whose sole
3483 // purpose is to compute bits we don't care about.
3484 uint64_t KnownZero, KnownOne;
3485 if (!isa<PackedType>(I.getType()) &&
3486 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3487 KnownZero, KnownOne))
3491 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3492 ConstantInt *C1 = 0; Value *X = 0;
3493 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3494 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3495 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3497 InsertNewInstBefore(Or, I);
3498 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3501 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3502 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3503 std::string Op0Name = Op0->getName(); Op0->setName("");
3504 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3505 InsertNewInstBefore(Or, I);
3506 return BinaryOperator::createXor(Or,
3507 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3510 // Try to fold constant and into select arguments.
3511 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3512 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3514 if (isa<PHINode>(Op0))
3515 if (Instruction *NV = FoldOpIntoPhi(I))
3519 Value *A = 0, *B = 0;
3520 ConstantInt *C1 = 0, *C2 = 0;
3522 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3523 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3524 return ReplaceInstUsesWith(I, Op1);
3525 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3526 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3527 return ReplaceInstUsesWith(I, Op0);
3529 // (A | B) | C and A | (B | C) -> bswap if possible.
3530 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3531 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3532 match(Op1, m_Or(m_Value(), m_Value())) ||
3533 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3534 match(Op1, m_Shift(m_Value(), m_Value())))) {
3535 if (Instruction *BSwap = MatchBSwap(I))
3539 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3540 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3541 MaskedValueIsZero(Op1, C1->getZExtValue())) {
3542 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3544 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3547 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3548 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3549 MaskedValueIsZero(Op0, C1->getZExtValue())) {
3550 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3552 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3555 // (A & C1)|(B & C2)
3556 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3557 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3559 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3560 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3563 // If we have: ((V + N) & C1) | (V & C2)
3564 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3565 // replace with V+N.
3566 if (C1 == ConstantExpr::getNot(C2)) {
3567 Value *V1 = 0, *V2 = 0;
3568 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3569 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3570 // Add commutes, try both ways.
3571 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3572 return ReplaceInstUsesWith(I, A);
3573 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3574 return ReplaceInstUsesWith(I, A);
3576 // Or commutes, try both ways.
3577 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3578 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3579 // Add commutes, try both ways.
3580 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3581 return ReplaceInstUsesWith(I, B);
3582 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3583 return ReplaceInstUsesWith(I, B);
3588 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3589 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3590 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3591 if (SI0->getOpcode() == SI1->getOpcode() &&
3592 SI0->getOperand(1) == SI1->getOperand(1) &&
3593 (SI0->hasOneUse() || SI1->hasOneUse())) {
3594 Instruction *NewOp =
3595 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3597 SI0->getName()), I);
3598 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3602 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3603 if (A == Op1) // ~A | A == -1
3604 return ReplaceInstUsesWith(I,
3605 ConstantIntegral::getAllOnesValue(I.getType()));
3609 // Note, A is still live here!
3610 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3612 return ReplaceInstUsesWith(I,
3613 ConstantIntegral::getAllOnesValue(I.getType()));
3615 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3616 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3617 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3618 I.getName()+".demorgan"), I);
3619 return BinaryOperator::createNot(And);
3623 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3624 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3625 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3628 Value *LHSVal, *RHSVal;
3629 ConstantInt *LHSCst, *RHSCst;
3630 Instruction::BinaryOps LHSCC, RHSCC;
3631 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3632 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3633 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3634 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3635 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3636 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3637 // Ensure that the larger constant is on the RHS.
3638 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3639 SetCondInst *LHS = cast<SetCondInst>(Op0);
3640 if (cast<ConstantBool>(Cmp)->getValue()) {
3641 std::swap(LHS, RHS);
3642 std::swap(LHSCst, RHSCst);
3643 std::swap(LHSCC, RHSCC);
3646 // At this point, we know we have have two setcc instructions
3647 // comparing a value against two constants and or'ing the result
3648 // together. Because of the above check, we know that we only have
3649 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3650 // FoldSetCCLogical check above), that the two constants are not
3652 assert(LHSCst != RHSCst && "Compares not folded above?");
3655 default: assert(0 && "Unknown integer condition code!");
3656 case Instruction::SetEQ:
3658 default: assert(0 && "Unknown integer condition code!");
3659 case Instruction::SetEQ:
3660 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3661 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3662 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3663 LHSVal->getName()+".off");
3664 InsertNewInstBefore(Add, I);
3665 const Type *UnsType = Add->getType()->getUnsignedVersion();
3666 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3667 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3668 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3669 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3671 break; // (X == 13 | X == 15) -> no change
3673 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3675 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3676 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3677 return ReplaceInstUsesWith(I, RHS);
3680 case Instruction::SetNE:
3682 default: assert(0 && "Unknown integer condition code!");
3683 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3684 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3685 return ReplaceInstUsesWith(I, LHS);
3686 case Instruction::SetNE: // (X != 13 | X != 15) -> true
3687 case Instruction::SetLT: // (X != 13 | X < 15) -> true
3688 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3691 case Instruction::SetLT:
3693 default: assert(0 && "Unknown integer condition code!");
3694 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3696 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3697 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3698 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3699 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3700 return ReplaceInstUsesWith(I, RHS);
3703 case Instruction::SetGT:
3705 default: assert(0 && "Unknown integer condition code!");
3706 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3707 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3708 return ReplaceInstUsesWith(I, LHS);
3709 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3710 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3711 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3717 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3718 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3719 const Type *SrcTy = Op0C->getOperand(0)->getType();
3720 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3721 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3722 // Only do this if the casts both really cause code to be generated.
3723 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3724 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3725 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3726 Op1C->getOperand(0),
3728 InsertNewInstBefore(NewOp, I);
3729 return new CastInst(NewOp, I.getType());
3734 return Changed ? &I : 0;
3737 // XorSelf - Implements: X ^ X --> 0
3740 XorSelf(Value *rhs) : RHS(rhs) {}
3741 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3742 Instruction *apply(BinaryOperator &Xor) const {
3748 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3749 bool Changed = SimplifyCommutative(I);
3750 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3752 if (isa<UndefValue>(Op1))
3753 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3755 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3756 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3757 assert(Result == &I && "AssociativeOpt didn't work?");
3758 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3761 // See if we can simplify any instructions used by the instruction whose sole
3762 // purpose is to compute bits we don't care about.
3763 uint64_t KnownZero, KnownOne;
3764 if (!isa<PackedType>(I.getType()) &&
3765 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3766 KnownZero, KnownOne))
3769 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3770 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3771 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3772 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3773 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
3774 return new SetCondInst(SCI->getInverseCondition(),
3775 SCI->getOperand(0), SCI->getOperand(1));
3777 // ~(c-X) == X-c-1 == X+(-c-1)
3778 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3779 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3780 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3781 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3782 ConstantInt::get(I.getType(), 1));
3783 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3786 // ~(~X & Y) --> (X | ~Y)
3787 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3788 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3789 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3791 BinaryOperator::createNot(Op0I->getOperand(1),
3792 Op0I->getOperand(1)->getName()+".not");
3793 InsertNewInstBefore(NotY, I);
3794 return BinaryOperator::createOr(Op0NotVal, NotY);
3798 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3799 if (Op0I->getOpcode() == Instruction::Add) {
3800 // ~(X-c) --> (-c-1)-X
3801 if (RHS->isAllOnesValue()) {
3802 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3803 return BinaryOperator::createSub(
3804 ConstantExpr::getSub(NegOp0CI,
3805 ConstantInt::get(I.getType(), 1)),
3806 Op0I->getOperand(0));
3808 } else if (Op0I->getOpcode() == Instruction::Or) {
3809 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3810 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3811 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3812 // Anything in both C1 and C2 is known to be zero, remove it from
3814 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3815 NewRHS = ConstantExpr::getAnd(NewRHS,
3816 ConstantExpr::getNot(CommonBits));
3817 WorkList.push_back(Op0I);
3818 I.setOperand(0, Op0I->getOperand(0));
3819 I.setOperand(1, NewRHS);
3825 // Try to fold constant and into select arguments.
3826 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3827 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3829 if (isa<PHINode>(Op0))
3830 if (Instruction *NV = FoldOpIntoPhi(I))
3834 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
3836 return ReplaceInstUsesWith(I,
3837 ConstantIntegral::getAllOnesValue(I.getType()));
3839 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
3841 return ReplaceInstUsesWith(I,
3842 ConstantIntegral::getAllOnesValue(I.getType()));
3844 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3845 if (Op1I->getOpcode() == Instruction::Or) {
3846 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
3847 Op1I->swapOperands();
3849 std::swap(Op0, Op1);
3850 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
3851 I.swapOperands(); // Simplified below.
3852 std::swap(Op0, Op1);
3854 } else if (Op1I->getOpcode() == Instruction::Xor) {
3855 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3856 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3857 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3858 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3859 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3860 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3861 Op1I->swapOperands();
3862 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3863 I.swapOperands(); // Simplified below.
3864 std::swap(Op0, Op1);
3868 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3869 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3870 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3871 Op0I->swapOperands();
3872 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3873 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3874 InsertNewInstBefore(NotB, I);
3875 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3877 } else if (Op0I->getOpcode() == Instruction::Xor) {
3878 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3879 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3880 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3881 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3882 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3883 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3884 Op0I->swapOperands();
3885 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3886 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3887 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3888 InsertNewInstBefore(N, I);
3889 return BinaryOperator::createAnd(N, Op1);
3893 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3894 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3895 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3898 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3899 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3900 const Type *SrcTy = Op0C->getOperand(0)->getType();
3901 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3902 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3903 // Only do this if the casts both really cause code to be generated.
3904 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3905 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3906 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3907 Op1C->getOperand(0),
3909 InsertNewInstBefore(NewOp, I);
3910 return new CastInst(NewOp, I.getType());
3914 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3915 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3916 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3917 if (SI0->getOpcode() == SI1->getOpcode() &&
3918 SI0->getOperand(1) == SI1->getOperand(1) &&
3919 (SI0->hasOneUse() || SI1->hasOneUse())) {
3920 Instruction *NewOp =
3921 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3923 SI0->getName()), I);
3924 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3928 return Changed ? &I : 0;
3931 static bool isPositive(ConstantInt *C) {
3932 return C->getSExtValue() >= 0;
3935 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3936 /// overflowed for this type.
3937 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3939 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3941 if (In1->getType()->isUnsigned())
3942 return cast<ConstantInt>(Result)->getZExtValue() <
3943 cast<ConstantInt>(In1)->getZExtValue();
3944 if (isPositive(In1) != isPositive(In2))
3946 if (isPositive(In1))
3947 return cast<ConstantInt>(Result)->getSExtValue() <
3948 cast<ConstantInt>(In1)->getSExtValue();
3949 return cast<ConstantInt>(Result)->getSExtValue() >
3950 cast<ConstantInt>(In1)->getSExtValue();
3953 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3954 /// code necessary to compute the offset from the base pointer (without adding
3955 /// in the base pointer). Return the result as a signed integer of intptr size.
3956 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3957 TargetData &TD = IC.getTargetData();
3958 gep_type_iterator GTI = gep_type_begin(GEP);
3959 const Type *UIntPtrTy = TD.getIntPtrType();
3960 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3961 Value *Result = Constant::getNullValue(SIntPtrTy);
3963 // Build a mask for high order bits.
3964 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3966 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3967 Value *Op = GEP->getOperand(i);
3968 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3969 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
3971 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3972 if (!OpC->isNullValue()) {
3973 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3974 Scale = ConstantExpr::getMul(OpC, Scale);
3975 if (Constant *RC = dyn_cast<Constant>(Result))
3976 Result = ConstantExpr::getAdd(RC, Scale);
3978 // Emit an add instruction.
3979 Result = IC.InsertNewInstBefore(
3980 BinaryOperator::createAdd(Result, Scale,
3981 GEP->getName()+".offs"), I);
3985 // Convert to correct type.
3986 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3987 Op->getName()+".c"), I);
3989 // We'll let instcombine(mul) convert this to a shl if possible.
3990 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3991 GEP->getName()+".idx"), I);
3993 // Emit an add instruction.
3994 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3995 GEP->getName()+".offs"), I);
4001 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
4002 /// else. At this point we know that the GEP is on the LHS of the comparison.
4003 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
4004 Instruction::BinaryOps Cond,
4006 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4008 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4009 if (isa<PointerType>(CI->getOperand(0)->getType()))
4010 RHS = CI->getOperand(0);
4012 Value *PtrBase = GEPLHS->getOperand(0);
4013 if (PtrBase == RHS) {
4014 // As an optimization, we don't actually have to compute the actual value of
4015 // OFFSET if this is a seteq or setne comparison, just return whether each
4016 // index is zero or not.
4017 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
4018 Instruction *InVal = 0;
4019 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4020 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4022 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4023 if (isa<UndefValue>(C)) // undef index -> undef.
4024 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4025 if (C->isNullValue())
4027 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4028 EmitIt = false; // This is indexing into a zero sized array?
4029 } else if (isa<ConstantInt>(C))
4030 return ReplaceInstUsesWith(I, // No comparison is needed here.
4031 ConstantBool::get(Cond == Instruction::SetNE));
4036 new SetCondInst(Cond, GEPLHS->getOperand(i),
4037 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4041 InVal = InsertNewInstBefore(InVal, I);
4042 InsertNewInstBefore(Comp, I);
4043 if (Cond == Instruction::SetNE) // True if any are unequal
4044 InVal = BinaryOperator::createOr(InVal, Comp);
4045 else // True if all are equal
4046 InVal = BinaryOperator::createAnd(InVal, Comp);
4054 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4055 ConstantBool::get(Cond == Instruction::SetEQ));
4058 // Only lower this if the setcc is the only user of the GEP or if we expect
4059 // the result to fold to a constant!
4060 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4061 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4062 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4063 return new SetCondInst(Cond, Offset,
4064 Constant::getNullValue(Offset->getType()));
4066 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4067 // If the base pointers are different, but the indices are the same, just
4068 // compare the base pointer.
4069 if (PtrBase != GEPRHS->getOperand(0)) {
4070 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4071 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4072 GEPRHS->getOperand(0)->getType();
4074 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4075 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4076 IndicesTheSame = false;
4080 // If all indices are the same, just compare the base pointers.
4082 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4083 GEPRHS->getOperand(0));
4085 // Otherwise, the base pointers are different and the indices are
4086 // different, bail out.
4090 // If one of the GEPs has all zero indices, recurse.
4091 bool AllZeros = true;
4092 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4093 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4094 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4099 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4100 SetCondInst::getSwappedCondition(Cond), I);
4102 // If the other GEP has all zero indices, recurse.
4104 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4105 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4106 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4111 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4113 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4114 // If the GEPs only differ by one index, compare it.
4115 unsigned NumDifferences = 0; // Keep track of # differences.
4116 unsigned DiffOperand = 0; // The operand that differs.
4117 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4118 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4119 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4120 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4121 // Irreconcilable differences.
4125 if (NumDifferences++) break;
4130 if (NumDifferences == 0) // SAME GEP?
4131 return ReplaceInstUsesWith(I, // No comparison is needed here.
4132 ConstantBool::get(Cond == Instruction::SetEQ));
4133 else if (NumDifferences == 1) {
4134 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4135 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4137 // Convert the operands to signed values to make sure to perform a
4138 // signed comparison.
4139 const Type *NewTy = LHSV->getType()->getSignedVersion();
4140 if (LHSV->getType() != NewTy)
4141 LHSV = InsertCastBefore(LHSV, NewTy, I);
4142 if (RHSV->getType() != NewTy)
4143 RHSV = InsertCastBefore(RHSV, NewTy, I);
4144 return new SetCondInst(Cond, LHSV, RHSV);
4148 // Only lower this if the setcc is the only user of the GEP or if we expect
4149 // the result to fold to a constant!
4150 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4151 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4152 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4153 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4154 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4155 return new SetCondInst(Cond, L, R);
4162 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
4163 bool Changed = SimplifyCommutative(I);
4164 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4165 const Type *Ty = Op0->getType();
4169 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4171 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4172 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4174 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4175 // addresses never equal each other! We already know that Op0 != Op1.
4176 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4177 isa<ConstantPointerNull>(Op0)) &&
4178 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4179 isa<ConstantPointerNull>(Op1)))
4180 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4182 // setcc's with boolean values can always be turned into bitwise operations
4183 if (Ty == Type::BoolTy) {
4184 switch (I.getOpcode()) {
4185 default: assert(0 && "Invalid setcc instruction!");
4186 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
4187 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4188 InsertNewInstBefore(Xor, I);
4189 return BinaryOperator::createNot(Xor);
4191 case Instruction::SetNE:
4192 return BinaryOperator::createXor(Op0, Op1);
4194 case Instruction::SetGT:
4195 std::swap(Op0, Op1); // Change setgt -> setlt
4197 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4198 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4199 InsertNewInstBefore(Not, I);
4200 return BinaryOperator::createAnd(Not, Op1);
4202 case Instruction::SetGE:
4203 std::swap(Op0, Op1); // Change setge -> setle
4205 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4206 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4207 InsertNewInstBefore(Not, I);
4208 return BinaryOperator::createOr(Not, Op1);
4213 // See if we are doing a comparison between a constant and an instruction that
4214 // can be folded into the comparison.
4215 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4216 // Check to see if we are comparing against the minimum or maximum value...
4217 if (CI->isMinValue()) {
4218 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
4219 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4220 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
4221 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4222 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4223 return BinaryOperator::createSetEQ(Op0, Op1);
4224 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4225 return BinaryOperator::createSetNE(Op0, Op1);
4227 } else if (CI->isMaxValue()) {
4228 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
4229 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4230 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
4231 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4232 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4233 return BinaryOperator::createSetEQ(Op0, Op1);
4234 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4235 return BinaryOperator::createSetNE(Op0, Op1);
4237 // Comparing against a value really close to min or max?
4238 } else if (isMinValuePlusOne(CI)) {
4239 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4240 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4241 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4242 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4244 } else if (isMaxValueMinusOne(CI)) {
4245 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4246 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4247 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4248 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4251 // If we still have a setle or setge instruction, turn it into the
4252 // appropriate setlt or setgt instruction. Since the border cases have
4253 // already been handled above, this requires little checking.
4255 if (I.getOpcode() == Instruction::SetLE)
4256 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4257 if (I.getOpcode() == Instruction::SetGE)
4258 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4261 // See if we can fold the comparison based on bits known to be zero or one
4263 uint64_t KnownZero, KnownOne;
4264 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4265 KnownZero, KnownOne, 0))
4268 // Given the known and unknown bits, compute a range that the LHS could be
4270 if (KnownOne | KnownZero) {
4271 if (Ty->isUnsigned()) { // Unsigned comparison.
4273 uint64_t RHSVal = CI->getZExtValue();
4274 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4276 switch (I.getOpcode()) { // LE/GE have been folded already.
4277 default: assert(0 && "Unknown setcc opcode!");
4278 case Instruction::SetEQ:
4279 if (Max < RHSVal || Min > RHSVal)
4280 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4282 case Instruction::SetNE:
4283 if (Max < RHSVal || Min > RHSVal)
4284 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4286 case Instruction::SetLT:
4288 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4290 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4292 case Instruction::SetGT:
4294 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4296 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4299 } else { // Signed comparison.
4301 int64_t RHSVal = CI->getSExtValue();
4302 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4304 switch (I.getOpcode()) { // LE/GE have been folded already.
4305 default: assert(0 && "Unknown setcc opcode!");
4306 case Instruction::SetEQ:
4307 if (Max < RHSVal || Min > RHSVal)
4308 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4310 case Instruction::SetNE:
4311 if (Max < RHSVal || Min > RHSVal)
4312 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4314 case Instruction::SetLT:
4316 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4318 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4320 case Instruction::SetGT:
4322 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4324 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4330 // Since the RHS is a constantInt (CI), if the left hand side is an
4331 // instruction, see if that instruction also has constants so that the
4332 // instruction can be folded into the setcc
4333 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4334 switch (LHSI->getOpcode()) {
4335 case Instruction::And:
4336 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4337 LHSI->getOperand(0)->hasOneUse()) {
4338 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4340 // If an operand is an AND of a truncating cast, we can widen the
4341 // and/compare to be the input width without changing the value
4342 // produced, eliminating a cast.
4343 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4344 // We can do this transformation if either the AND constant does not
4345 // have its sign bit set or if it is an equality comparison.
4346 // Extending a relational comparison when we're checking the sign
4347 // bit would not work.
4348 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4350 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4351 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4352 ConstantInt *NewCST;
4354 if (Cast->getOperand(0)->getType()->isSigned()) {
4355 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4356 AndCST->getZExtValue());
4357 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4358 CI->getZExtValue());
4360 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4361 AndCST->getZExtValue());
4362 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4363 CI->getZExtValue());
4365 Instruction *NewAnd =
4366 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4368 InsertNewInstBefore(NewAnd, I);
4369 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4373 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4374 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4375 // happens a LOT in code produced by the C front-end, for bitfield
4377 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4379 // Check to see if there is a noop-cast between the shift and the and.
4381 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4382 if (CI->getOperand(0)->getType()->isIntegral() &&
4383 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4384 CI->getType()->getPrimitiveSizeInBits())
4385 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4389 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4390 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4391 const Type *AndTy = AndCST->getType(); // Type of the and.
4393 // We can fold this as long as we can't shift unknown bits
4394 // into the mask. This can only happen with signed shift
4395 // rights, as they sign-extend.
4397 bool CanFold = Shift->isLogicalShift();
4399 // To test for the bad case of the signed shr, see if any
4400 // of the bits shifted in could be tested after the mask.
4401 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4402 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4404 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
4406 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4408 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4414 if (Shift->getOpcode() == Instruction::Shl)
4415 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4417 NewCst = ConstantExpr::getShl(CI, ShAmt);
4419 // Check to see if we are shifting out any of the bits being
4421 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4422 // If we shifted bits out, the fold is not going to work out.
4423 // As a special case, check to see if this means that the
4424 // result is always true or false now.
4425 if (I.getOpcode() == Instruction::SetEQ)
4426 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4427 if (I.getOpcode() == Instruction::SetNE)
4428 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4430 I.setOperand(1, NewCst);
4431 Constant *NewAndCST;
4432 if (Shift->getOpcode() == Instruction::Shl)
4433 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4435 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4436 LHSI->setOperand(1, NewAndCST);
4438 LHSI->setOperand(0, Shift->getOperand(0));
4440 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4442 LHSI->setOperand(0, NewCast);
4444 WorkList.push_back(Shift); // Shift is dead.
4445 AddUsesToWorkList(I);
4451 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4452 // preferable because it allows the C<<Y expression to be hoisted out
4453 // of a loop if Y is invariant and X is not.
4454 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4455 I.isEquality() && !Shift->isArithmeticShift() &&
4456 isa<Instruction>(Shift->getOperand(0))) {
4459 if (Shift->getOpcode() == Instruction::LShr) {
4460 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4463 // Make sure we insert a logical shift.
4464 Constant *NewAndCST = AndCST;
4465 if (AndCST->getType()->isSigned())
4466 NewAndCST = ConstantExpr::getCast(AndCST,
4467 AndCST->getType()->getUnsignedVersion());
4468 NS = new ShiftInst(Instruction::LShr, NewAndCST,
4469 Shift->getOperand(1), "tmp");
4471 InsertNewInstBefore(cast<Instruction>(NS), I);
4473 // If C's sign doesn't agree with the and, insert a cast now.
4474 if (NS->getType() != LHSI->getType())
4475 NS = InsertCastBefore(NS, LHSI->getType(), I);
4477 Value *ShiftOp = Shift->getOperand(0);
4478 if (ShiftOp->getType() != LHSI->getType())
4479 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4481 // Compute X & (C << Y).
4482 Instruction *NewAnd =
4483 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4484 InsertNewInstBefore(NewAnd, I);
4486 I.setOperand(0, NewAnd);
4492 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
4493 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4494 if (I.isEquality()) {
4495 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4497 // Check that the shift amount is in range. If not, don't perform
4498 // undefined shifts. When the shift is visited it will be
4500 if (ShAmt->getZExtValue() >= TypeBits)
4503 // If we are comparing against bits always shifted out, the
4504 // comparison cannot succeed.
4506 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4507 if (Comp != CI) {// Comparing against a bit that we know is zero.
4508 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4509 Constant *Cst = ConstantBool::get(IsSetNE);
4510 return ReplaceInstUsesWith(I, Cst);
4513 if (LHSI->hasOneUse()) {
4514 // Otherwise strength reduce the shift into an and.
4515 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4516 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4519 if (CI->getType()->isUnsigned()) {
4520 Mask = ConstantInt::get(CI->getType(), Val);
4521 } else if (ShAmtVal != 0) {
4522 Mask = ConstantInt::get(CI->getType(), Val);
4524 Mask = ConstantInt::getAllOnesValue(CI->getType());
4528 BinaryOperator::createAnd(LHSI->getOperand(0),
4529 Mask, LHSI->getName()+".mask");
4530 Value *And = InsertNewInstBefore(AndI, I);
4531 return new SetCondInst(I.getOpcode(), And,
4532 ConstantExpr::getLShr(CI, ShAmt));
4538 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4539 case Instruction::AShr:
4540 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4541 if (I.isEquality()) {
4542 // Check that the shift amount is in range. If not, don't perform
4543 // undefined shifts. When the shift is visited it will be
4545 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4546 if (ShAmt->getZExtValue() >= TypeBits)
4549 // If we are comparing against bits always shifted out, the
4550 // comparison cannot succeed.
4552 if (CI->getType()->isUnsigned())
4553 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4556 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4559 if (Comp != CI) {// Comparing against a bit that we know is zero.
4560 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4561 Constant *Cst = ConstantBool::get(IsSetNE);
4562 return ReplaceInstUsesWith(I, Cst);
4565 if (LHSI->hasOneUse() || CI->isNullValue()) {
4566 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4568 // Otherwise strength reduce the shift into an and.
4569 uint64_t Val = ~0ULL; // All ones.
4570 Val <<= ShAmtVal; // Shift over to the right spot.
4573 if (CI->getType()->isUnsigned()) {
4574 Val &= ~0ULL >> (64-TypeBits);
4575 Mask = ConstantInt::get(CI->getType(), Val);
4577 Mask = ConstantInt::get(CI->getType(), Val);
4581 BinaryOperator::createAnd(LHSI->getOperand(0),
4582 Mask, LHSI->getName()+".mask");
4583 Value *And = InsertNewInstBefore(AndI, I);
4584 return new SetCondInst(I.getOpcode(), And,
4585 ConstantExpr::getShl(CI, ShAmt));
4591 case Instruction::SDiv:
4592 case Instruction::UDiv:
4593 // Fold: setcc ([us]div X, C1), C2 -> range test
4594 // Fold this div into the comparison, producing a range check.
4595 // Determine, based on the divide type, what the range is being
4596 // checked. If there is an overflow on the low or high side, remember
4597 // it, otherwise compute the range [low, hi) bounding the new value.
4598 // See: InsertRangeTest above for the kinds of replacements possible.
4599 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4600 // FIXME: If the operand types don't match the type of the divide
4601 // then don't attempt this transform. The code below doesn't have the
4602 // logic to deal with a signed divide and an unsigned compare (and
4603 // vice versa). This is because (x /s C1) <s C2 produces different
4604 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4605 // (x /u C1) <u C2. Simply casting the operands and result won't
4606 // work. :( The if statement below tests that condition and bails
4608 const Type* DivRHSTy = DivRHS->getType();
4609 unsigned DivOpCode = LHSI->getOpcode();
4610 if (I.isEquality() &&
4611 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4612 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4615 // Initialize the variables that will indicate the nature of the
4617 bool LoOverflow = false, HiOverflow = false;
4618 ConstantInt *LoBound = 0, *HiBound = 0;
4620 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4621 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4622 // C2 (CI). By solving for X we can turn this into a range check
4623 // instead of computing a divide.
4625 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4627 // Determine if the product overflows by seeing if the product is
4628 // not equal to the divide. Make sure we do the same kind of divide
4629 // as in the LHS instruction that we're folding.
4630 bool ProdOV = !DivRHS->isNullValue() &&
4631 (DivOpCode == Instruction::SDiv ?
4632 ConstantExpr::getSDiv(Prod, DivRHS) :
4633 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4635 // Get the SetCC opcode
4636 Instruction::BinaryOps Opcode = I.getOpcode();
4638 if (DivRHS->isNullValue()) {
4639 // Don't hack on divide by zeros!
4640 } else if (DivOpCode == Instruction::UDiv) { // udiv
4642 LoOverflow = ProdOV;
4643 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4644 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4645 if (CI->isNullValue()) { // (X / pos) op 0
4647 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4649 } else if (isPositive(CI)) { // (X / pos) op pos
4651 LoOverflow = ProdOV;
4652 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4653 } else { // (X / pos) op neg
4654 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4655 LoOverflow = AddWithOverflow(LoBound, Prod,
4656 cast<ConstantInt>(DivRHSH));
4658 HiOverflow = ProdOV;
4660 } else { // Divisor is < 0.
4661 if (CI->isNullValue()) { // (X / neg) op 0
4662 LoBound = AddOne(DivRHS);
4663 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4664 if (HiBound == DivRHS)
4665 LoBound = 0; // - INTMIN = INTMIN
4666 } else if (isPositive(CI)) { // (X / neg) op pos
4667 HiOverflow = LoOverflow = ProdOV;
4669 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4670 HiBound = AddOne(Prod);
4671 } else { // (X / neg) op neg
4673 LoOverflow = HiOverflow = ProdOV;
4674 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4677 // Dividing by a negate swaps the condition.
4678 Opcode = SetCondInst::getSwappedCondition(Opcode);
4682 Value *X = LHSI->getOperand(0);
4684 default: assert(0 && "Unhandled setcc opcode!");
4685 case Instruction::SetEQ:
4686 if (LoOverflow && HiOverflow)
4687 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4688 else if (HiOverflow)
4689 return new SetCondInst(Instruction::SetGE, X, LoBound);
4690 else if (LoOverflow)
4691 return new SetCondInst(Instruction::SetLT, X, HiBound);
4693 return InsertRangeTest(X, LoBound, HiBound, true, I);
4694 case Instruction::SetNE:
4695 if (LoOverflow && HiOverflow)
4696 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4697 else if (HiOverflow)
4698 return new SetCondInst(Instruction::SetLT, X, LoBound);
4699 else if (LoOverflow)
4700 return new SetCondInst(Instruction::SetGE, X, HiBound);
4702 return InsertRangeTest(X, LoBound, HiBound, false, I);
4703 case Instruction::SetLT:
4705 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4706 return new SetCondInst(Instruction::SetLT, X, LoBound);
4707 case Instruction::SetGT:
4709 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4710 return new SetCondInst(Instruction::SetGE, X, HiBound);
4717 // Simplify seteq and setne instructions...
4718 if (I.isEquality()) {
4719 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4721 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4722 // the second operand is a constant, simplify a bit.
4723 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4724 switch (BO->getOpcode()) {
4725 case Instruction::SRem:
4726 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4727 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4729 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4730 if (V > 1 && isPowerOf2_64(V)) {
4731 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4732 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4733 return BinaryOperator::create(I.getOpcode(), NewRem,
4734 Constant::getNullValue(BO->getType()));
4738 case Instruction::Add:
4739 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4740 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4741 if (BO->hasOneUse())
4742 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4743 ConstantExpr::getSub(CI, BOp1C));
4744 } else if (CI->isNullValue()) {
4745 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4746 // efficiently invertible, or if the add has just this one use.
4747 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4749 if (Value *NegVal = dyn_castNegVal(BOp1))
4750 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4751 else if (Value *NegVal = dyn_castNegVal(BOp0))
4752 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4753 else if (BO->hasOneUse()) {
4754 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4756 InsertNewInstBefore(Neg, I);
4757 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4761 case Instruction::Xor:
4762 // For the xor case, we can xor two constants together, eliminating
4763 // the explicit xor.
4764 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4765 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4766 ConstantExpr::getXor(CI, BOC));
4769 case Instruction::Sub:
4770 // Replace (([sub|xor] A, B) != 0) with (A != B)
4771 if (CI->isNullValue())
4772 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4776 case Instruction::Or:
4777 // If bits are being or'd in that are not present in the constant we
4778 // are comparing against, then the comparison could never succeed!
4779 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4780 Constant *NotCI = ConstantExpr::getNot(CI);
4781 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4782 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4786 case Instruction::And:
4787 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4788 // If bits are being compared against that are and'd out, then the
4789 // comparison can never succeed!
4790 if (!ConstantExpr::getAnd(CI,
4791 ConstantExpr::getNot(BOC))->isNullValue())
4792 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4794 // If we have ((X & C) == C), turn it into ((X & C) != 0).
4795 if (CI == BOC && isOneBitSet(CI))
4796 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4797 Instruction::SetNE, Op0,
4798 Constant::getNullValue(CI->getType()));
4800 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4801 // to be a signed value as appropriate.
4802 if (isSignBit(BOC)) {
4803 Value *X = BO->getOperand(0);
4804 // If 'X' is not signed, insert a cast now...
4805 if (!BOC->getType()->isSigned()) {
4806 const Type *DestTy = BOC->getType()->getSignedVersion();
4807 X = InsertCastBefore(X, DestTy, I);
4809 return new SetCondInst(isSetNE ? Instruction::SetLT :
4810 Instruction::SetGE, X,
4811 Constant::getNullValue(X->getType()));
4814 // ((X & ~7) == 0) --> X < 8
4815 if (CI->isNullValue() && isHighOnes(BOC)) {
4816 Value *X = BO->getOperand(0);
4817 Constant *NegX = ConstantExpr::getNeg(BOC);
4819 // If 'X' is signed, insert a cast now.
4820 if (NegX->getType()->isSigned()) {
4821 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4822 X = InsertCastBefore(X, DestTy, I);
4823 NegX = ConstantExpr::getCast(NegX, DestTy);
4826 return new SetCondInst(isSetNE ? Instruction::SetGE :
4827 Instruction::SetLT, X, NegX);
4834 } else { // Not a SetEQ/SetNE
4835 // If the LHS is a cast from an integral value of the same size,
4836 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4837 Value *CastOp = Cast->getOperand(0);
4838 const Type *SrcTy = CastOp->getType();
4839 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4840 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4841 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4842 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4843 "Source and destination signednesses should differ!");
4844 if (Cast->getType()->isSigned()) {
4845 // If this is a signed comparison, check for comparisons in the
4846 // vicinity of zero.
4847 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4849 return BinaryOperator::createSetGT(CastOp,
4850 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4851 else if (I.getOpcode() == Instruction::SetGT &&
4852 cast<ConstantInt>(CI)->getSExtValue() == -1)
4853 // X > -1 => x < 128
4854 return BinaryOperator::createSetLT(CastOp,
4855 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4857 ConstantInt *CUI = cast<ConstantInt>(CI);
4858 if (I.getOpcode() == Instruction::SetLT &&
4859 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
4860 // X < 128 => X > -1
4861 return BinaryOperator::createSetGT(CastOp,
4862 ConstantInt::get(SrcTy, -1));
4863 else if (I.getOpcode() == Instruction::SetGT &&
4864 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
4866 return BinaryOperator::createSetLT(CastOp,
4867 Constant::getNullValue(SrcTy));
4874 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4875 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4876 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4877 switch (LHSI->getOpcode()) {
4878 case Instruction::GetElementPtr:
4879 if (RHSC->isNullValue()) {
4880 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4881 bool isAllZeros = true;
4882 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4883 if (!isa<Constant>(LHSI->getOperand(i)) ||
4884 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4889 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4890 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4894 case Instruction::PHI:
4895 if (Instruction *NV = FoldOpIntoPhi(I))
4898 case Instruction::Select:
4899 // If either operand of the select is a constant, we can fold the
4900 // comparison into the select arms, which will cause one to be
4901 // constant folded and the select turned into a bitwise or.
4902 Value *Op1 = 0, *Op2 = 0;
4903 if (LHSI->hasOneUse()) {
4904 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4905 // Fold the known value into the constant operand.
4906 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4907 // Insert a new SetCC of the other select operand.
4908 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4909 LHSI->getOperand(2), RHSC,
4911 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4912 // Fold the known value into the constant operand.
4913 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4914 // Insert a new SetCC of the other select operand.
4915 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4916 LHSI->getOperand(1), RHSC,
4922 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4927 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4928 if (User *GEP = dyn_castGetElementPtr(Op0))
4929 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4931 if (User *GEP = dyn_castGetElementPtr(Op1))
4932 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4933 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4936 // Test to see if the operands of the setcc are casted versions of other
4937 // values. If the cast can be stripped off both arguments, we do so now.
4938 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4939 Value *CastOp0 = CI->getOperand(0);
4940 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
4941 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
4942 // We keep moving the cast from the left operand over to the right
4943 // operand, where it can often be eliminated completely.
4946 // If operand #1 is a cast instruction, see if we can eliminate it as
4948 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4949 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
4951 Op1 = CI2->getOperand(0);
4953 // If Op1 is a constant, we can fold the cast into the constant.
4954 if (Op1->getType() != Op0->getType())
4955 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4956 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4958 // Otherwise, cast the RHS right before the setcc
4959 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
4961 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4964 // Handle the special case of: setcc (cast bool to X), <cst>
4965 // This comes up when you have code like
4968 // For generality, we handle any zero-extension of any operand comparison
4969 // with a constant or another cast from the same type.
4970 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4971 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4975 if (I.isEquality()) {
4977 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4978 (A == Op1 || B == Op1)) {
4979 // (A^B) == A -> B == 0
4980 Value *OtherVal = A == Op1 ? B : A;
4981 return BinaryOperator::create(I.getOpcode(), OtherVal,
4982 Constant::getNullValue(A->getType()));
4983 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4984 (A == Op0 || B == Op0)) {
4985 // A == (A^B) -> B == 0
4986 Value *OtherVal = A == Op0 ? B : A;
4987 return BinaryOperator::create(I.getOpcode(), OtherVal,
4988 Constant::getNullValue(A->getType()));
4989 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4990 // (A-B) == A -> B == 0
4991 return BinaryOperator::create(I.getOpcode(), B,
4992 Constant::getNullValue(B->getType()));
4993 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4994 // A == (A-B) -> B == 0
4995 return BinaryOperator::create(I.getOpcode(), B,
4996 Constant::getNullValue(B->getType()));
5000 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5001 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5002 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5003 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5004 Value *X = 0, *Y = 0, *Z = 0;
5007 X = B; Y = D; Z = A;
5008 } else if (A == D) {
5009 X = B; Y = C; Z = A;
5010 } else if (B == C) {
5011 X = A; Y = D; Z = B;
5012 } else if (B == D) {
5013 X = A; Y = C; Z = B;
5016 if (X) { // Build (X^Y) & Z
5017 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5018 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5019 I.setOperand(0, Op1);
5020 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5025 return Changed ? &I : 0;
5028 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
5029 // We only handle extending casts so far.
5031 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
5032 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
5033 const Type *SrcTy = LHSCIOp->getType();
5034 const Type *DestTy = SCI.getOperand(0)->getType();
5037 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
5040 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
5041 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
5042 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
5044 // Is this a sign or zero extension?
5045 bool isSignSrc = SrcTy->isSigned();
5046 bool isSignDest = DestTy->isSigned();
5048 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5049 // Not an extension from the same type?
5050 RHSCIOp = CI->getOperand(0);
5051 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5052 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5053 // Compute the constant that would happen if we truncated to SrcTy then
5054 // reextended to DestTy.
5055 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
5057 if (ConstantExpr::getCast(Res, DestTy) == CI) {
5058 // Make sure that src sign and dest sign match. For example,
5060 // %A = cast short %X to uint
5061 // %B = setgt uint %A, 1330
5063 // It is incorrect to transform this into
5065 // %B = setgt short %X, 1330
5067 // because %A may have negative value.
5068 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5069 // OR operation is EQ/NE.
5070 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
5075 // If the value cannot be represented in the shorter type, we cannot emit
5076 // a simple comparison.
5077 if (SCI.getOpcode() == Instruction::SetEQ)
5078 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
5079 if (SCI.getOpcode() == Instruction::SetNE)
5080 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
5082 // Evaluate the comparison for LT.
5084 if (DestTy->isSigned()) {
5085 // We're performing a signed comparison.
5087 // Signed extend and signed comparison.
5088 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
5089 Result = ConstantBool::getFalse();
5091 Result = ConstantBool::getTrue(); // X < (large) --> true
5093 // Unsigned extend and signed comparison.
5094 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5095 Result = ConstantBool::getFalse();
5097 Result = ConstantBool::getTrue();
5100 // We're performing an unsigned comparison.
5102 // Unsigned extend & compare -> always true.
5103 Result = ConstantBool::getTrue();
5105 // We're performing an unsigned comp with a sign extended value.
5106 // This is true if the input is >= 0. [aka >s -1]
5107 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5108 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5109 NegOne, SCI.getName()), SCI);
5113 // Finally, return the value computed.
5114 if (SCI.getOpcode() == Instruction::SetLT) {
5115 return ReplaceInstUsesWith(SCI, Result);
5117 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5118 if (Constant *CI = dyn_cast<Constant>(Result))
5119 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5121 return BinaryOperator::createNot(Result);
5128 // Okay, just insert a compare of the reduced operands now!
5129 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5132 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5133 assert(I.getOperand(1)->getType() == Type::UByteTy);
5134 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5135 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5137 // shl X, 0 == X and shr X, 0 == X
5138 // shl 0, X == 0 and shr 0, X == 0
5139 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
5140 Op0 == Constant::getNullValue(Op0->getType()))
5141 return ReplaceInstUsesWith(I, Op0);
5143 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5144 if (!isLeftShift && I.getType()->isSigned())
5145 return ReplaceInstUsesWith(I, Op0);
5146 else // undef << X -> 0 AND undef >>u X -> 0
5147 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5149 if (isa<UndefValue>(Op1)) {
5150 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
5151 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5153 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5156 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5157 if (I.getOpcode() == Instruction::AShr)
5158 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5159 if (CSI->isAllOnesValue())
5160 return ReplaceInstUsesWith(I, CSI);
5162 // Try to fold constant and into select arguments.
5163 if (isa<Constant>(Op0))
5164 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5165 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5168 // See if we can turn a signed shr into an unsigned shr.
5169 if (I.isArithmeticShift()) {
5170 if (MaskedValueIsZero(Op0,
5171 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5172 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5176 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5177 if (CUI->getType()->isUnsigned())
5178 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5183 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5185 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5186 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5187 I.getOpcode() == Instruction::AShr;
5188 bool isUnsignedShift = !isSignedShift;
5190 // See if we can simplify any instructions used by the instruction whose sole
5191 // purpose is to compute bits we don't care about.
5192 uint64_t KnownZero, KnownOne;
5193 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5194 KnownZero, KnownOne))
5197 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5198 // of a signed value.
5200 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5201 if (Op1->getZExtValue() >= TypeBits) {
5202 if (isUnsignedShift || isLeftShift)
5203 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5205 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
5210 // ((X*C1) << C2) == (X * (C1 << C2))
5211 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5212 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5213 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5214 return BinaryOperator::createMul(BO->getOperand(0),
5215 ConstantExpr::getShl(BOOp, Op1));
5217 // Try to fold constant and into select arguments.
5218 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5219 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5221 if (isa<PHINode>(Op0))
5222 if (Instruction *NV = FoldOpIntoPhi(I))
5225 if (Op0->hasOneUse()) {
5226 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5227 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5230 switch (Op0BO->getOpcode()) {
5232 case Instruction::Add:
5233 case Instruction::And:
5234 case Instruction::Or:
5235 case Instruction::Xor:
5236 // These operators commute.
5237 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
5238 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5239 match(Op0BO->getOperand(1),
5240 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5241 Instruction *YS = new ShiftInst(Instruction::Shl,
5242 Op0BO->getOperand(0), Op1,
5244 InsertNewInstBefore(YS, I); // (Y << C)
5246 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5247 Op0BO->getOperand(1)->getName());
5248 InsertNewInstBefore(X, I); // (X + (Y << C))
5249 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5250 C2 = ConstantExpr::getShl(C2, Op1);
5251 return BinaryOperator::createAnd(X, C2);
5254 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5255 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5256 match(Op0BO->getOperand(1),
5257 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5258 m_ConstantInt(CC))) && V2 == Op1 &&
5259 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5260 Instruction *YS = new ShiftInst(Instruction::Shl,
5261 Op0BO->getOperand(0), Op1,
5263 InsertNewInstBefore(YS, I); // (Y << C)
5265 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5266 V1->getName()+".mask");
5267 InsertNewInstBefore(XM, I); // X & (CC << C)
5269 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5273 case Instruction::Sub:
5274 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5275 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5276 match(Op0BO->getOperand(0),
5277 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5278 Instruction *YS = new ShiftInst(Instruction::Shl,
5279 Op0BO->getOperand(1), Op1,
5281 InsertNewInstBefore(YS, I); // (Y << C)
5283 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5284 Op0BO->getOperand(0)->getName());
5285 InsertNewInstBefore(X, I); // (X + (Y << C))
5286 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5287 C2 = ConstantExpr::getShl(C2, Op1);
5288 return BinaryOperator::createAnd(X, C2);
5291 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
5292 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5293 match(Op0BO->getOperand(0),
5294 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5295 m_ConstantInt(CC))) && V2 == Op1 &&
5296 cast<BinaryOperator>(Op0BO->getOperand(0))
5297 ->getOperand(0)->hasOneUse()) {
5298 Instruction *YS = new ShiftInst(Instruction::Shl,
5299 Op0BO->getOperand(1), Op1,
5301 InsertNewInstBefore(YS, I); // (Y << C)
5303 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5304 V1->getName()+".mask");
5305 InsertNewInstBefore(XM, I); // X & (CC << C)
5307 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5314 // If the operand is an bitwise operator with a constant RHS, and the
5315 // shift is the only use, we can pull it out of the shift.
5316 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5317 bool isValid = true; // Valid only for And, Or, Xor
5318 bool highBitSet = false; // Transform if high bit of constant set?
5320 switch (Op0BO->getOpcode()) {
5321 default: isValid = false; break; // Do not perform transform!
5322 case Instruction::Add:
5323 isValid = isLeftShift;
5325 case Instruction::Or:
5326 case Instruction::Xor:
5329 case Instruction::And:
5334 // If this is a signed shift right, and the high bit is modified
5335 // by the logical operation, do not perform the transformation.
5336 // The highBitSet boolean indicates the value of the high bit of
5337 // the constant which would cause it to be modified for this
5340 if (isValid && !isLeftShift && isSignedShift) {
5341 uint64_t Val = Op0C->getZExtValue();
5342 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5346 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5348 Instruction *NewShift =
5349 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5352 InsertNewInstBefore(NewShift, I);
5354 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5361 // Find out if this is a shift of a shift by a constant.
5362 ShiftInst *ShiftOp = 0;
5363 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5365 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5366 // If this is a noop-integer case of a shift instruction, use the shift.
5367 if (CI->getOperand(0)->getType()->isInteger() &&
5368 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5369 CI->getType()->getPrimitiveSizeInBits() &&
5370 isa<ShiftInst>(CI->getOperand(0))) {
5371 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5375 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5376 // Find the operands and properties of the input shift. Note that the
5377 // signedness of the input shift may differ from the current shift if there
5378 // is a noop cast between the two.
5379 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5380 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5381 ShiftOp->getType()->isSigned() :
5382 ShiftOp->getOpcode() == Instruction::AShr;
5383 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5385 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5387 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5388 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5390 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5391 if (isLeftShift == isShiftOfLeftShift) {
5392 // Do not fold these shifts if the first one is signed and the second one
5393 // is unsigned and this is a right shift. Further, don't do any folding
5395 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5398 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5399 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5400 Amt = Op0->getType()->getPrimitiveSizeInBits();
5402 Value *Op = ShiftOp->getOperand(0);
5403 if (isShiftOfSignedShift != isSignedShift)
5404 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5405 ShiftInst* ShiftResult = new ShiftInst(I.getOpcode(), Op,
5406 ConstantInt::get(Type::UByteTy, Amt));
5407 if (I.getType() == ShiftResult->getType())
5409 InsertNewInstBefore(ShiftResult, I);
5410 return new CastInst(ShiftResult, I.getType());
5413 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5414 // signed types, we can only support the (A >> c1) << c2 configuration,
5415 // because it can not turn an arbitrary bit of A into a sign bit.
5416 if (isUnsignedShift || isLeftShift) {
5417 // Calculate bitmask for what gets shifted off the edge.
5418 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5420 C = ConstantExpr::getShl(C, ShiftAmt1C);
5422 C = ConstantExpr::getLShr(C, ShiftAmt1C);
5424 Value *Op = ShiftOp->getOperand(0);
5425 if (Op->getType() != C->getType())
5426 Op = InsertCastBefore(Op, I.getType(), I);
5429 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5430 InsertNewInstBefore(Mask, I);
5432 // Figure out what flavor of shift we should use...
5433 if (ShiftAmt1 == ShiftAmt2) {
5434 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
5435 } else if (ShiftAmt1 < ShiftAmt2) {
5436 return new ShiftInst(I.getOpcode(), Mask,
5437 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
5438 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5439 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5440 return new ShiftInst(Instruction::LShr, Mask,
5441 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5443 return new ShiftInst(ShiftOp->getOpcode(), Mask,
5444 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5447 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
5448 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
5449 Instruction *Shift =
5450 new ShiftInst(ShiftOp->getOpcode(), Op,
5451 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5452 InsertNewInstBefore(Shift, I);
5454 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5455 C = ConstantExpr::getShl(C, Op1);
5456 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5457 InsertNewInstBefore(Mask, I);
5458 return new CastInst(Mask, I.getType());
5461 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
5462 // this case, C1 == C2 and C1 is 8, 16, or 32.
5463 if (ShiftAmt1 == ShiftAmt2) {
5464 const Type *SExtType = 0;
5465 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5466 case 8 : SExtType = Type::SByteTy; break;
5467 case 16: SExtType = Type::ShortTy; break;
5468 case 32: SExtType = Type::IntTy; break;
5472 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5474 InsertNewInstBefore(NewTrunc, I);
5475 return new CastInst(NewTrunc, I.getType());
5484 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5485 /// expression. If so, decompose it, returning some value X, such that Val is
5488 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5490 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5491 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5492 if (CI->getType()->isUnsigned()) {
5493 Offset = CI->getZExtValue();
5495 return ConstantInt::get(Type::UIntTy, 0);
5497 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5498 if (I->getNumOperands() == 2) {
5499 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5500 if (CUI->getType()->isUnsigned()) {
5501 if (I->getOpcode() == Instruction::Shl) {
5502 // This is a value scaled by '1 << the shift amt'.
5503 Scale = 1U << CUI->getZExtValue();
5505 return I->getOperand(0);
5506 } else if (I->getOpcode() == Instruction::Mul) {
5507 // This value is scaled by 'CUI'.
5508 Scale = CUI->getZExtValue();
5510 return I->getOperand(0);
5511 } else if (I->getOpcode() == Instruction::Add) {
5512 // We have X+C. Check to see if we really have (X*C2)+C1,
5513 // where C1 is divisible by C2.
5516 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5517 Offset += CUI->getZExtValue();
5518 if (SubScale > 1 && (Offset % SubScale == 0)) {
5528 // Otherwise, we can't look past this.
5535 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5536 /// try to eliminate the cast by moving the type information into the alloc.
5537 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5538 AllocationInst &AI) {
5539 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5540 if (!PTy) return 0; // Not casting the allocation to a pointer type.
5542 // Remove any uses of AI that are dead.
5543 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5544 std::vector<Instruction*> DeadUsers;
5545 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5546 Instruction *User = cast<Instruction>(*UI++);
5547 if (isInstructionTriviallyDead(User)) {
5548 while (UI != E && *UI == User)
5549 ++UI; // If this instruction uses AI more than once, don't break UI.
5551 // Add operands to the worklist.
5552 AddUsesToWorkList(*User);
5554 DEBUG(std::cerr << "IC: DCE: " << *User);
5556 User->eraseFromParent();
5557 removeFromWorkList(User);
5561 // Get the type really allocated and the type casted to.
5562 const Type *AllocElTy = AI.getAllocatedType();
5563 const Type *CastElTy = PTy->getElementType();
5564 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5566 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5567 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5568 if (CastElTyAlign < AllocElTyAlign) return 0;
5570 // If the allocation has multiple uses, only promote it if we are strictly
5571 // increasing the alignment of the resultant allocation. If we keep it the
5572 // same, we open the door to infinite loops of various kinds.
5573 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5575 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5576 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5577 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5579 // See if we can satisfy the modulus by pulling a scale out of the array
5581 unsigned ArraySizeScale, ArrayOffset;
5582 Value *NumElements = // See if the array size is a decomposable linear expr.
5583 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5585 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5587 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5588 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
5590 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5595 // If the allocation size is constant, form a constant mul expression
5596 Amt = ConstantInt::get(Type::UIntTy, Scale);
5597 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5598 Amt = ConstantExpr::getMul(
5599 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5600 // otherwise multiply the amount and the number of elements
5601 else if (Scale != 1) {
5602 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5603 Amt = InsertNewInstBefore(Tmp, AI);
5607 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5608 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
5609 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5610 Amt = InsertNewInstBefore(Tmp, AI);
5613 std::string Name = AI.getName(); AI.setName("");
5614 AllocationInst *New;
5615 if (isa<MallocInst>(AI))
5616 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5618 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5619 InsertNewInstBefore(New, AI);
5621 // If the allocation has multiple uses, insert a cast and change all things
5622 // that used it to use the new cast. This will also hack on CI, but it will
5624 if (!AI.hasOneUse()) {
5625 AddUsesToWorkList(AI);
5626 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5627 InsertNewInstBefore(NewCast, AI);
5628 AI.replaceAllUsesWith(NewCast);
5630 return ReplaceInstUsesWith(CI, New);
5633 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5634 /// and return it without inserting any new casts. This is used by code that
5635 /// tries to decide whether promoting or shrinking integer operations to wider
5636 /// or smaller types will allow us to eliminate a truncate or extend.
5637 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5638 int &NumCastsRemoved) {
5639 if (isa<Constant>(V)) return true;
5641 Instruction *I = dyn_cast<Instruction>(V);
5642 if (!I || !I->hasOneUse()) return false;
5644 switch (I->getOpcode()) {
5645 case Instruction::And:
5646 case Instruction::Or:
5647 case Instruction::Xor:
5648 // These operators can all arbitrarily be extended or truncated.
5649 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5650 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5651 case Instruction::Cast:
5652 // If this is a cast from the destination type, we can trivially eliminate
5653 // it, and this will remove a cast overall.
5654 if (I->getOperand(0)->getType() == Ty) {
5655 // If the first operand is itself a cast, and is eliminable, do not count
5656 // this as an eliminable cast. We would prefer to eliminate those two
5658 if (isa<CastInst>(I->getOperand(0)))
5664 // TODO: Can handle more cases here.
5671 /// EvaluateInDifferentType - Given an expression that
5672 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5673 /// evaluate the expression.
5674 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5675 if (Constant *C = dyn_cast<Constant>(V))
5676 return ConstantExpr::getCast(C, Ty);
5678 // Otherwise, it must be an instruction.
5679 Instruction *I = cast<Instruction>(V);
5680 Instruction *Res = 0;
5681 switch (I->getOpcode()) {
5682 case Instruction::And:
5683 case Instruction::Or:
5684 case Instruction::Xor: {
5685 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5686 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5687 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5688 LHS, RHS, I->getName());
5691 case Instruction::Cast:
5692 // If this is a cast from the destination type, return the input.
5693 if (I->getOperand(0)->getType() == Ty)
5694 return I->getOperand(0);
5696 // TODO: Can handle more cases here.
5697 assert(0 && "Unreachable!");
5701 return InsertNewInstBefore(Res, *I);
5705 // CastInst simplification
5707 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
5708 Value *Src = CI.getOperand(0);
5710 // If the user is casting a value to the same type, eliminate this cast
5712 if (CI.getType() == Src->getType())
5713 return ReplaceInstUsesWith(CI, Src);
5715 if (isa<UndefValue>(Src)) // cast undef -> undef
5716 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5718 // If casting the result of another cast instruction, try to eliminate this
5721 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5722 Value *A = CSrc->getOperand(0);
5723 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5724 CI.getType(), TD)) {
5725 // This instruction now refers directly to the cast's src operand. This
5726 // has a good chance of making CSrc dead.
5727 CI.setOperand(0, CSrc->getOperand(0));
5731 // If this is an A->B->A cast, and we are dealing with integral types, try
5732 // to convert this into a logical 'and' instruction.
5734 if (A->getType()->isInteger() &&
5735 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
5736 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
5737 CSrc->getType()->getPrimitiveSizeInBits() <
5738 CI.getType()->getPrimitiveSizeInBits()&&
5739 A->getType()->getPrimitiveSizeInBits() ==
5740 CI.getType()->getPrimitiveSizeInBits()) {
5741 assert(CSrc->getType() != Type::ULongTy &&
5742 "Cannot have type bigger than ulong!");
5743 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
5744 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
5746 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5747 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5748 if (And->getType() != CI.getType()) {
5749 And->setName(CSrc->getName()+".mask");
5750 InsertNewInstBefore(And, CI);
5751 And = new CastInst(And, CI.getType());
5757 // If this is a cast to bool, turn it into the appropriate setne instruction.
5758 if (CI.getType() == Type::BoolTy)
5759 return BinaryOperator::createSetNE(CI.getOperand(0),
5760 Constant::getNullValue(CI.getOperand(0)->getType()));
5762 // See if we can simplify any instructions used by the LHS whose sole
5763 // purpose is to compute bits we don't care about.
5764 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5765 uint64_t KnownZero, KnownOne;
5766 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5767 KnownZero, KnownOne))
5771 // If casting the result of a getelementptr instruction with no offset, turn
5772 // this into a cast of the original pointer!
5774 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5775 bool AllZeroOperands = true;
5776 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5777 if (!isa<Constant>(GEP->getOperand(i)) ||
5778 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5779 AllZeroOperands = false;
5782 if (AllZeroOperands) {
5783 CI.setOperand(0, GEP->getOperand(0));
5788 // If we are casting a malloc or alloca to a pointer to a type of the same
5789 // size, rewrite the allocation instruction to allocate the "right" type.
5791 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5792 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5795 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5796 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5798 if (isa<PHINode>(Src))
5799 if (Instruction *NV = FoldOpIntoPhi(CI))
5802 // If the source and destination are pointers, and this cast is equivalent to
5803 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5804 // This can enhance SROA and other transforms that want type-safe pointers.
5805 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5806 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5807 const Type *DstTy = DstPTy->getElementType();
5808 const Type *SrcTy = SrcPTy->getElementType();
5810 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5811 unsigned NumZeros = 0;
5812 while (SrcTy != DstTy &&
5813 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5814 SrcTy->getNumContainedTypes() /* not "{}" */) {
5815 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5819 // If we found a path from the src to dest, create the getelementptr now.
5820 if (SrcTy == DstTy) {
5821 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5822 return new GetElementPtrInst(Src, Idxs);
5826 // If the source value is an instruction with only this use, we can attempt to
5827 // propagate the cast into the instruction. Also, only handle integral types
5829 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
5830 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
5831 CI.getType()->isInteger()) { // Don't mess with casts to bool here
5833 int NumCastsRemoved = 0;
5834 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5835 // If this cast is a truncate, evaluting in a different type always
5836 // eliminates the cast, so it is always a win. If this is a noop-cast
5837 // this just removes a noop cast which isn't pointful, but simplifies
5838 // the code. If this is a zero-extension, we need to do an AND to
5839 // maintain the clear top-part of the computation, so we require that
5840 // the input have eliminated at least one cast. If this is a sign
5841 // extension, we insert two new casts (to do the extension) so we
5842 // require that two casts have been eliminated.
5844 switch (getCastType(Src->getType(), CI.getType())) {
5845 default: assert(0 && "Unknown cast type!");
5851 DoXForm = NumCastsRemoved >= 1;
5854 DoXForm = NumCastsRemoved >= 2;
5859 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5860 assert(Res->getType() == CI.getType());
5861 switch (getCastType(Src->getType(), CI.getType())) {
5862 default: assert(0 && "Unknown cast type!");
5865 // Just replace this cast with the result.
5866 return ReplaceInstUsesWith(CI, Res);
5868 // We need to emit an AND to clear the high bits.
5869 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5870 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5871 assert(SrcBitSize < DestBitSize && "Not a zext?");
5873 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5874 C = ConstantExpr::getCast(C, CI.getType());
5875 return BinaryOperator::createAnd(Res, C);
5878 // We need to emit a cast to truncate, then a cast to sext.
5879 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5885 const Type *DestTy = CI.getType();
5886 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5887 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5889 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5890 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5892 switch (SrcI->getOpcode()) {
5893 case Instruction::Add:
5894 case Instruction::Mul:
5895 case Instruction::And:
5896 case Instruction::Or:
5897 case Instruction::Xor:
5898 // If we are discarding information, or just changing the sign, rewrite.
5899 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5900 // Don't insert two casts if they cannot be eliminated. We allow two
5901 // casts to be inserted if the sizes are the same. This could only be
5902 // converting signedness, which is a noop.
5903 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5904 !ValueRequiresCast(Op0, DestTy, TD)) {
5905 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5906 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5907 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5908 ->getOpcode(), Op0c, Op1c);
5912 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5913 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5914 Op1 == ConstantBool::getTrue() &&
5915 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5916 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5917 return BinaryOperator::createXor(New,
5918 ConstantInt::get(CI.getType(), 1));
5921 case Instruction::SDiv:
5922 case Instruction::UDiv:
5923 case Instruction::SRem:
5924 case Instruction::URem:
5925 // If we are just changing the sign, rewrite.
5926 if (DestBitSize == SrcBitSize) {
5927 // Don't insert two casts if they cannot be eliminated. We allow two
5928 // casts to be inserted if the sizes are the same. This could only be
5929 // converting signedness, which is a noop.
5930 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5931 !ValueRequiresCast(Op0, DestTy, TD)) {
5932 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5933 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5934 return BinaryOperator::create(
5935 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5940 case Instruction::Shl:
5941 // Allow changing the sign of the source operand. Do not allow changing
5942 // the size of the shift, UNLESS the shift amount is a constant. We
5943 // must not change variable sized shifts to a smaller size, because it
5944 // is undefined to shift more bits out than exist in the value.
5945 if (DestBitSize == SrcBitSize ||
5946 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5947 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5948 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5951 case Instruction::AShr:
5952 // If this is a signed shr, and if all bits shifted in are about to be
5953 // truncated off, turn it into an unsigned shr to allow greater
5955 if (DestBitSize < SrcBitSize &&
5956 isa<ConstantInt>(Op1)) {
5957 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5958 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5959 // Insert the new logical shift right.
5960 return new ShiftInst(Instruction::LShr, Op0, Op1);
5965 case Instruction::SetEQ:
5966 case Instruction::SetNE:
5967 // We if we are just checking for a seteq of a single bit and casting it
5968 // to an integer. If so, shift the bit to the appropriate place then
5969 // cast to integer to avoid the comparison.
5970 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5971 uint64_t Op1CV = Op1C->getZExtValue();
5972 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5973 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5974 // cast (X == 1) to int --> X iff X has only the low bit set.
5975 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5976 // cast (X != 0) to int --> X iff X has only the low bit set.
5977 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5978 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5979 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5980 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5981 // If Op1C some other power of two, convert:
5982 uint64_t KnownZero, KnownOne;
5983 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5984 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5986 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5987 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5988 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5989 // (X&4) == 2 --> false
5990 // (X&4) != 2 --> true
5991 Constant *Res = ConstantBool::get(isSetNE);
5992 Res = ConstantExpr::getCast(Res, CI.getType());
5993 return ReplaceInstUsesWith(CI, Res);
5996 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5999 // Perform a logical shr by shiftamt.
6000 // Insert the shift to put the result in the low bit.
6001 In = InsertNewInstBefore(new ShiftInst(Instruction::LShr, In,
6002 ConstantInt::get(Type::UByteTy, ShiftAmt),
6003 In->getName()+".lobit"), CI);
6006 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
6007 Constant *One = ConstantInt::get(In->getType(), 1);
6008 In = BinaryOperator::createXor(In, One, "tmp");
6009 InsertNewInstBefore(cast<Instruction>(In), CI);
6012 if (CI.getType() == In->getType())
6013 return ReplaceInstUsesWith(CI, In);
6015 return new CastInst(In, CI.getType());
6023 if (SrcI->hasOneUse()) {
6024 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
6025 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
6026 // because the inputs are known to be a vector. Check to see if this is
6027 // a cast to a vector with the same # elts.
6028 if (isa<PackedType>(CI.getType()) &&
6029 cast<PackedType>(CI.getType())->getNumElements() ==
6030 SVI->getType()->getNumElements()) {
6032 // If either of the operands is a cast from CI.getType(), then
6033 // evaluating the shuffle in the casted destination's type will allow
6034 // us to eliminate at least one cast.
6035 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6036 Tmp->getOperand(0)->getType() == CI.getType()) ||
6037 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6038 Tmp->getOperand(0)->getType() == CI.getType())) {
6039 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
6041 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
6043 // Return a new shuffle vector. Use the same element ID's, as we
6044 // know the vector types match #elts.
6045 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6055 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6057 /// %D = select %cond, %C, %A
6059 /// %C = select %cond, %B, 0
6062 /// Assuming that the specified instruction is an operand to the select, return
6063 /// a bitmask indicating which operands of this instruction are foldable if they
6064 /// equal the other incoming value of the select.
6066 static unsigned GetSelectFoldableOperands(Instruction *I) {
6067 switch (I->getOpcode()) {
6068 case Instruction::Add:
6069 case Instruction::Mul:
6070 case Instruction::And:
6071 case Instruction::Or:
6072 case Instruction::Xor:
6073 return 3; // Can fold through either operand.
6074 case Instruction::Sub: // Can only fold on the amount subtracted.
6075 case Instruction::Shl: // Can only fold on the shift amount.
6076 case Instruction::LShr:
6077 case Instruction::AShr:
6080 return 0; // Cannot fold
6084 /// GetSelectFoldableConstant - For the same transformation as the previous
6085 /// function, return the identity constant that goes into the select.
6086 static Constant *GetSelectFoldableConstant(Instruction *I) {
6087 switch (I->getOpcode()) {
6088 default: assert(0 && "This cannot happen!"); abort();
6089 case Instruction::Add:
6090 case Instruction::Sub:
6091 case Instruction::Or:
6092 case Instruction::Xor:
6093 return Constant::getNullValue(I->getType());
6094 case Instruction::Shl:
6095 case Instruction::LShr:
6096 case Instruction::AShr:
6097 return Constant::getNullValue(Type::UByteTy);
6098 case Instruction::And:
6099 return ConstantInt::getAllOnesValue(I->getType());
6100 case Instruction::Mul:
6101 return ConstantInt::get(I->getType(), 1);
6105 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6106 /// have the same opcode and only one use each. Try to simplify this.
6107 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6109 if (TI->getNumOperands() == 1) {
6110 // If this is a non-volatile load or a cast from the same type,
6112 if (TI->getOpcode() == Instruction::Cast) {
6113 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6116 return 0; // unknown unary op.
6119 // Fold this by inserting a select from the input values.
6120 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6121 FI->getOperand(0), SI.getName()+".v");
6122 InsertNewInstBefore(NewSI, SI);
6123 return new CastInst(NewSI, TI->getType());
6126 // Only handle binary operators here.
6127 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6130 // Figure out if the operations have any operands in common.
6131 Value *MatchOp, *OtherOpT, *OtherOpF;
6133 if (TI->getOperand(0) == FI->getOperand(0)) {
6134 MatchOp = TI->getOperand(0);
6135 OtherOpT = TI->getOperand(1);
6136 OtherOpF = FI->getOperand(1);
6137 MatchIsOpZero = true;
6138 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6139 MatchOp = TI->getOperand(1);
6140 OtherOpT = TI->getOperand(0);
6141 OtherOpF = FI->getOperand(0);
6142 MatchIsOpZero = false;
6143 } else if (!TI->isCommutative()) {
6145 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6146 MatchOp = TI->getOperand(0);
6147 OtherOpT = TI->getOperand(1);
6148 OtherOpF = FI->getOperand(0);
6149 MatchIsOpZero = true;
6150 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6151 MatchOp = TI->getOperand(1);
6152 OtherOpT = TI->getOperand(0);
6153 OtherOpF = FI->getOperand(1);
6154 MatchIsOpZero = true;
6159 // If we reach here, they do have operations in common.
6160 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6161 OtherOpF, SI.getName()+".v");
6162 InsertNewInstBefore(NewSI, SI);
6164 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6166 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6168 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6171 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6173 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6177 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6178 Value *CondVal = SI.getCondition();
6179 Value *TrueVal = SI.getTrueValue();
6180 Value *FalseVal = SI.getFalseValue();
6182 // select true, X, Y -> X
6183 // select false, X, Y -> Y
6184 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6185 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6187 // select C, X, X -> X
6188 if (TrueVal == FalseVal)
6189 return ReplaceInstUsesWith(SI, TrueVal);
6191 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6192 return ReplaceInstUsesWith(SI, FalseVal);
6193 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6194 return ReplaceInstUsesWith(SI, TrueVal);
6195 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6196 if (isa<Constant>(TrueVal))
6197 return ReplaceInstUsesWith(SI, TrueVal);
6199 return ReplaceInstUsesWith(SI, FalseVal);
6202 if (SI.getType() == Type::BoolTy)
6203 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6204 if (C->getValue()) {
6205 // Change: A = select B, true, C --> A = or B, C
6206 return BinaryOperator::createOr(CondVal, FalseVal);
6208 // Change: A = select B, false, C --> A = and !B, C
6210 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6211 "not."+CondVal->getName()), SI);
6212 return BinaryOperator::createAnd(NotCond, FalseVal);
6214 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6215 if (C->getValue() == false) {
6216 // Change: A = select B, C, false --> A = and B, C
6217 return BinaryOperator::createAnd(CondVal, TrueVal);
6219 // Change: A = select B, C, true --> A = or !B, C
6221 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6222 "not."+CondVal->getName()), SI);
6223 return BinaryOperator::createOr(NotCond, TrueVal);
6227 // Selecting between two integer constants?
6228 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6229 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6230 // select C, 1, 0 -> cast C to int
6231 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6232 return new CastInst(CondVal, SI.getType());
6233 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6234 // select C, 0, 1 -> cast !C to int
6236 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6237 "not."+CondVal->getName()), SI);
6238 return new CastInst(NotCond, SI.getType());
6241 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6243 // (x <s 0) ? -1 : 0 -> sra x, 31
6244 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6245 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6246 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6247 bool CanXForm = false;
6248 if (CmpCst->getType()->isSigned())
6249 CanXForm = CmpCst->isNullValue() &&
6250 IC->getOpcode() == Instruction::SetLT;
6252 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6253 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6254 IC->getOpcode() == Instruction::SetGT;
6258 // The comparison constant and the result are not neccessarily the
6259 // same width. In any case, the first step to do is make sure
6260 // that X is signed.
6261 Value *X = IC->getOperand(0);
6262 if (!X->getType()->isSigned())
6263 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6265 // Now that X is signed, we have to make the all ones value. Do
6266 // this by inserting a new SRA.
6267 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6268 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
6269 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6271 InsertNewInstBefore(SRA, SI);
6273 // Finally, convert to the type of the select RHS. If this is
6274 // smaller than the compare value, it will truncate the ones to
6275 // fit. If it is larger, it will sext the ones to fit.
6276 return new CastInst(SRA, SI.getType());
6281 // If one of the constants is zero (we know they can't both be) and we
6282 // have a setcc instruction with zero, and we have an 'and' with the
6283 // non-constant value, eliminate this whole mess. This corresponds to
6284 // cases like this: ((X & 27) ? 27 : 0)
6285 if (TrueValC->isNullValue() || FalseValC->isNullValue())
6286 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6287 cast<Constant>(IC->getOperand(1))->isNullValue())
6288 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6289 if (ICA->getOpcode() == Instruction::And &&
6290 isa<ConstantInt>(ICA->getOperand(1)) &&
6291 (ICA->getOperand(1) == TrueValC ||
6292 ICA->getOperand(1) == FalseValC) &&
6293 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6294 // Okay, now we know that everything is set up, we just don't
6295 // know whether we have a setne or seteq and whether the true or
6296 // false val is the zero.
6297 bool ShouldNotVal = !TrueValC->isNullValue();
6298 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6301 V = InsertNewInstBefore(BinaryOperator::create(
6302 Instruction::Xor, V, ICA->getOperand(1)), SI);
6303 return ReplaceInstUsesWith(SI, V);
6308 // See if we are selecting two values based on a comparison of the two values.
6309 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6310 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6311 // Transform (X == Y) ? X : Y -> Y
6312 if (SCI->getOpcode() == Instruction::SetEQ)
6313 return ReplaceInstUsesWith(SI, FalseVal);
6314 // Transform (X != Y) ? X : Y -> X
6315 if (SCI->getOpcode() == Instruction::SetNE)
6316 return ReplaceInstUsesWith(SI, TrueVal);
6317 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6319 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6320 // Transform (X == Y) ? Y : X -> X
6321 if (SCI->getOpcode() == Instruction::SetEQ)
6322 return ReplaceInstUsesWith(SI, FalseVal);
6323 // Transform (X != Y) ? Y : X -> Y
6324 if (SCI->getOpcode() == Instruction::SetNE)
6325 return ReplaceInstUsesWith(SI, TrueVal);
6326 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6330 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6331 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6332 if (TI->hasOneUse() && FI->hasOneUse()) {
6333 Instruction *AddOp = 0, *SubOp = 0;
6335 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6336 if (TI->getOpcode() == FI->getOpcode())
6337 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6340 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6341 // even legal for FP.
6342 if (TI->getOpcode() == Instruction::Sub &&
6343 FI->getOpcode() == Instruction::Add) {
6344 AddOp = FI; SubOp = TI;
6345 } else if (FI->getOpcode() == Instruction::Sub &&
6346 TI->getOpcode() == Instruction::Add) {
6347 AddOp = TI; SubOp = FI;
6351 Value *OtherAddOp = 0;
6352 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6353 OtherAddOp = AddOp->getOperand(1);
6354 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6355 OtherAddOp = AddOp->getOperand(0);
6359 // So at this point we know we have (Y -> OtherAddOp):
6360 // select C, (add X, Y), (sub X, Z)
6361 Value *NegVal; // Compute -Z
6362 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6363 NegVal = ConstantExpr::getNeg(C);
6365 NegVal = InsertNewInstBefore(
6366 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6369 Value *NewTrueOp = OtherAddOp;
6370 Value *NewFalseOp = NegVal;
6372 std::swap(NewTrueOp, NewFalseOp);
6373 Instruction *NewSel =
6374 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6376 NewSel = InsertNewInstBefore(NewSel, SI);
6377 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6382 // See if we can fold the select into one of our operands.
6383 if (SI.getType()->isInteger()) {
6384 // See the comment above GetSelectFoldableOperands for a description of the
6385 // transformation we are doing here.
6386 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6387 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6388 !isa<Constant>(FalseVal))
6389 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6390 unsigned OpToFold = 0;
6391 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6393 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6398 Constant *C = GetSelectFoldableConstant(TVI);
6399 std::string Name = TVI->getName(); TVI->setName("");
6400 Instruction *NewSel =
6401 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6403 InsertNewInstBefore(NewSel, SI);
6404 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6405 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6406 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6407 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6409 assert(0 && "Unknown instruction!!");
6414 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6415 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6416 !isa<Constant>(TrueVal))
6417 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6418 unsigned OpToFold = 0;
6419 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6421 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6426 Constant *C = GetSelectFoldableConstant(FVI);
6427 std::string Name = FVI->getName(); FVI->setName("");
6428 Instruction *NewSel =
6429 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6431 InsertNewInstBefore(NewSel, SI);
6432 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6433 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6434 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6435 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6437 assert(0 && "Unknown instruction!!");
6443 if (BinaryOperator::isNot(CondVal)) {
6444 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6445 SI.setOperand(1, FalseVal);
6446 SI.setOperand(2, TrueVal);
6453 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6454 /// determine, return it, otherwise return 0.
6455 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6456 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6457 unsigned Align = GV->getAlignment();
6458 if (Align == 0 && TD)
6459 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6461 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6462 unsigned Align = AI->getAlignment();
6463 if (Align == 0 && TD) {
6464 if (isa<AllocaInst>(AI))
6465 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6466 else if (isa<MallocInst>(AI)) {
6467 // Malloc returns maximally aligned memory.
6468 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6469 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6470 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6474 } else if (isa<CastInst>(V) ||
6475 (isa<ConstantExpr>(V) &&
6476 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6477 User *CI = cast<User>(V);
6478 if (isa<PointerType>(CI->getOperand(0)->getType()))
6479 return GetKnownAlignment(CI->getOperand(0), TD);
6481 } else if (isa<GetElementPtrInst>(V) ||
6482 (isa<ConstantExpr>(V) &&
6483 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6484 User *GEPI = cast<User>(V);
6485 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6486 if (BaseAlignment == 0) return 0;
6488 // If all indexes are zero, it is just the alignment of the base pointer.
6489 bool AllZeroOperands = true;
6490 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6491 if (!isa<Constant>(GEPI->getOperand(i)) ||
6492 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6493 AllZeroOperands = false;
6496 if (AllZeroOperands)
6497 return BaseAlignment;
6499 // Otherwise, if the base alignment is >= the alignment we expect for the
6500 // base pointer type, then we know that the resultant pointer is aligned at
6501 // least as much as its type requires.
6504 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6505 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6507 const Type *GEPTy = GEPI->getType();
6508 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6516 /// visitCallInst - CallInst simplification. This mostly only handles folding
6517 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6518 /// the heavy lifting.
6520 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6521 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6522 if (!II) return visitCallSite(&CI);
6524 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6526 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6527 bool Changed = false;
6529 // memmove/cpy/set of zero bytes is a noop.
6530 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6531 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6533 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6534 if (CI->getZExtValue() == 1) {
6535 // Replace the instruction with just byte operations. We would
6536 // transform other cases to loads/stores, but we don't know if
6537 // alignment is sufficient.
6541 // If we have a memmove and the source operation is a constant global,
6542 // then the source and dest pointers can't alias, so we can change this
6543 // into a call to memcpy.
6544 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6545 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6546 if (GVSrc->isConstant()) {
6547 Module *M = CI.getParent()->getParent()->getParent();
6549 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
6551 Name = "llvm.memcpy.i32";
6553 Name = "llvm.memcpy.i64";
6554 Function *MemCpy = M->getOrInsertFunction(Name,
6555 CI.getCalledFunction()->getFunctionType());
6556 CI.setOperand(0, MemCpy);
6561 // If we can determine a pointer alignment that is bigger than currently
6562 // set, update the alignment.
6563 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6564 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6565 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6566 unsigned Align = std::min(Alignment1, Alignment2);
6567 if (MI->getAlignment()->getZExtValue() < Align) {
6568 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
6571 } else if (isa<MemSetInst>(MI)) {
6572 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6573 if (MI->getAlignment()->getZExtValue() < Alignment) {
6574 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
6579 if (Changed) return II;
6581 switch (II->getIntrinsicID()) {
6583 case Intrinsic::ppc_altivec_lvx:
6584 case Intrinsic::ppc_altivec_lvxl:
6585 case Intrinsic::x86_sse_loadu_ps:
6586 case Intrinsic::x86_sse2_loadu_pd:
6587 case Intrinsic::x86_sse2_loadu_dq:
6588 // Turn PPC lvx -> load if the pointer is known aligned.
6589 // Turn X86 loadups -> load if the pointer is known aligned.
6590 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6591 Value *Ptr = InsertCastBefore(II->getOperand(1),
6592 PointerType::get(II->getType()), CI);
6593 return new LoadInst(Ptr);
6596 case Intrinsic::ppc_altivec_stvx:
6597 case Intrinsic::ppc_altivec_stvxl:
6598 // Turn stvx -> store if the pointer is known aligned.
6599 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
6600 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6601 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
6602 return new StoreInst(II->getOperand(1), Ptr);
6605 case Intrinsic::x86_sse_storeu_ps:
6606 case Intrinsic::x86_sse2_storeu_pd:
6607 case Intrinsic::x86_sse2_storeu_dq:
6608 case Intrinsic::x86_sse2_storel_dq:
6609 // Turn X86 storeu -> store if the pointer is known aligned.
6610 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6611 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6612 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6613 return new StoreInst(II->getOperand(2), Ptr);
6617 case Intrinsic::x86_sse_cvttss2si: {
6618 // These intrinsics only demands the 0th element of its input vector. If
6619 // we can simplify the input based on that, do so now.
6621 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6623 II->setOperand(1, V);
6629 case Intrinsic::ppc_altivec_vperm:
6630 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6631 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6632 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6634 // Check that all of the elements are integer constants or undefs.
6635 bool AllEltsOk = true;
6636 for (unsigned i = 0; i != 16; ++i) {
6637 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6638 !isa<UndefValue>(Mask->getOperand(i))) {
6645 // Cast the input vectors to byte vectors.
6646 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6647 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6648 Value *Result = UndefValue::get(Op0->getType());
6650 // Only extract each element once.
6651 Value *ExtractedElts[32];
6652 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6654 for (unsigned i = 0; i != 16; ++i) {
6655 if (isa<UndefValue>(Mask->getOperand(i)))
6657 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
6658 Idx &= 31; // Match the hardware behavior.
6660 if (ExtractedElts[Idx] == 0) {
6662 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
6663 InsertNewInstBefore(Elt, CI);
6664 ExtractedElts[Idx] = Elt;
6667 // Insert this value into the result vector.
6668 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
6669 InsertNewInstBefore(cast<Instruction>(Result), CI);
6671 return new CastInst(Result, CI.getType());
6676 case Intrinsic::stackrestore: {
6677 // If the save is right next to the restore, remove the restore. This can
6678 // happen when variable allocas are DCE'd.
6679 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6680 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6681 BasicBlock::iterator BI = SS;
6683 return EraseInstFromFunction(CI);
6687 // If the stack restore is in a return/unwind block and if there are no
6688 // allocas or calls between the restore and the return, nuke the restore.
6689 TerminatorInst *TI = II->getParent()->getTerminator();
6690 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6691 BasicBlock::iterator BI = II;
6692 bool CannotRemove = false;
6693 for (++BI; &*BI != TI; ++BI) {
6694 if (isa<AllocaInst>(BI) ||
6695 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6696 CannotRemove = true;
6701 return EraseInstFromFunction(CI);
6708 return visitCallSite(II);
6711 // InvokeInst simplification
6713 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6714 return visitCallSite(&II);
6717 // visitCallSite - Improvements for call and invoke instructions.
6719 Instruction *InstCombiner::visitCallSite(CallSite CS) {
6720 bool Changed = false;
6722 // If the callee is a constexpr cast of a function, attempt to move the cast
6723 // to the arguments of the call/invoke.
6724 if (transformConstExprCastCall(CS)) return 0;
6726 Value *Callee = CS.getCalledValue();
6728 if (Function *CalleeF = dyn_cast<Function>(Callee))
6729 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6730 Instruction *OldCall = CS.getInstruction();
6731 // If the call and callee calling conventions don't match, this call must
6732 // be unreachable, as the call is undefined.
6733 new StoreInst(ConstantBool::getTrue(),
6734 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6735 if (!OldCall->use_empty())
6736 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6737 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6738 return EraseInstFromFunction(*OldCall);
6742 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6743 // This instruction is not reachable, just remove it. We insert a store to
6744 // undef so that we know that this code is not reachable, despite the fact
6745 // that we can't modify the CFG here.
6746 new StoreInst(ConstantBool::getTrue(),
6747 UndefValue::get(PointerType::get(Type::BoolTy)),
6748 CS.getInstruction());
6750 if (!CS.getInstruction()->use_empty())
6751 CS.getInstruction()->
6752 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6754 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6755 // Don't break the CFG, insert a dummy cond branch.
6756 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6757 ConstantBool::getTrue(), II);
6759 return EraseInstFromFunction(*CS.getInstruction());
6762 const PointerType *PTy = cast<PointerType>(Callee->getType());
6763 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6764 if (FTy->isVarArg()) {
6765 // See if we can optimize any arguments passed through the varargs area of
6767 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6768 E = CS.arg_end(); I != E; ++I)
6769 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6770 // If this cast does not effect the value passed through the varargs
6771 // area, we can eliminate the use of the cast.
6772 Value *Op = CI->getOperand(0);
6773 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6780 return Changed ? CS.getInstruction() : 0;
6783 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6784 // attempt to move the cast to the arguments of the call/invoke.
6786 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6787 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6788 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6789 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
6791 Function *Callee = cast<Function>(CE->getOperand(0));
6792 Instruction *Caller = CS.getInstruction();
6794 // Okay, this is a cast from a function to a different type. Unless doing so
6795 // would cause a type conversion of one of our arguments, change this call to
6796 // be a direct call with arguments casted to the appropriate types.
6798 const FunctionType *FT = Callee->getFunctionType();
6799 const Type *OldRetTy = Caller->getType();
6801 // Check to see if we are changing the return type...
6802 if (OldRetTy != FT->getReturnType()) {
6803 if (Callee->isExternal() &&
6804 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6805 (isa<PointerType>(FT->getReturnType()) &&
6806 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
6807 && !Caller->use_empty())
6808 return false; // Cannot transform this return value...
6810 // If the callsite is an invoke instruction, and the return value is used by
6811 // a PHI node in a successor, we cannot change the return type of the call
6812 // because there is no place to put the cast instruction (without breaking
6813 // the critical edge). Bail out in this case.
6814 if (!Caller->use_empty())
6815 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6816 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6818 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6819 if (PN->getParent() == II->getNormalDest() ||
6820 PN->getParent() == II->getUnwindDest())
6824 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6825 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6827 CallSite::arg_iterator AI = CS.arg_begin();
6828 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6829 const Type *ParamTy = FT->getParamType(i);
6830 const Type *ActTy = (*AI)->getType();
6831 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
6832 //Either we can cast directly, or we can upconvert the argument
6833 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6834 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6835 ParamTy->isSigned() == ActTy->isSigned() &&
6836 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6837 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6838 c->getSExtValue() > 0);
6839 if (Callee->isExternal() && !isConvertible) return false;
6842 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6843 Callee->isExternal())
6844 return false; // Do not delete arguments unless we have a function body...
6846 // Okay, we decided that this is a safe thing to do: go ahead and start
6847 // inserting cast instructions as necessary...
6848 std::vector<Value*> Args;
6849 Args.reserve(NumActualArgs);
6851 AI = CS.arg_begin();
6852 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6853 const Type *ParamTy = FT->getParamType(i);
6854 if ((*AI)->getType() == ParamTy) {
6855 Args.push_back(*AI);
6857 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6862 // If the function takes more arguments than the call was taking, add them
6864 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6865 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6867 // If we are removing arguments to the function, emit an obnoxious warning...
6868 if (FT->getNumParams() < NumActualArgs)
6869 if (!FT->isVarArg()) {
6870 std::cerr << "WARNING: While resolving call to function '"
6871 << Callee->getName() << "' arguments were dropped!\n";
6873 // Add all of the arguments in their promoted form to the arg list...
6874 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6875 const Type *PTy = getPromotedType((*AI)->getType());
6876 if (PTy != (*AI)->getType()) {
6877 // Must promote to pass through va_arg area!
6878 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6879 InsertNewInstBefore(Cast, *Caller);
6880 Args.push_back(Cast);
6882 Args.push_back(*AI);
6887 if (FT->getReturnType() == Type::VoidTy)
6888 Caller->setName(""); // Void type should not have a name...
6891 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6892 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
6893 Args, Caller->getName(), Caller);
6894 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
6896 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
6897 if (cast<CallInst>(Caller)->isTailCall())
6898 cast<CallInst>(NC)->setTailCall();
6899 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
6902 // Insert a cast of the return type as necessary...
6904 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6905 if (NV->getType() != Type::VoidTy) {
6906 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
6908 // If this is an invoke instruction, we should insert it after the first
6909 // non-phi, instruction in the normal successor block.
6910 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6911 BasicBlock::iterator I = II->getNormalDest()->begin();
6912 while (isa<PHINode>(I)) ++I;
6913 InsertNewInstBefore(NC, *I);
6915 // Otherwise, it's a call, just insert cast right after the call instr
6916 InsertNewInstBefore(NC, *Caller);
6918 AddUsersToWorkList(*Caller);
6920 NV = UndefValue::get(Caller->getType());
6924 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6925 Caller->replaceAllUsesWith(NV);
6926 Caller->getParent()->getInstList().erase(Caller);
6927 removeFromWorkList(Caller);
6931 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
6932 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
6933 /// and a single binop.
6934 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6935 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6936 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
6937 isa<GetElementPtrInst>(FirstInst));
6938 unsigned Opc = FirstInst->getOpcode();
6939 Value *LHSVal = FirstInst->getOperand(0);
6940 Value *RHSVal = FirstInst->getOperand(1);
6942 const Type *LHSType = LHSVal->getType();
6943 const Type *RHSType = RHSVal->getType();
6945 // Scan to see if all operands are the same opcode, all have one use, and all
6946 // kill their operands (i.e. the operands have one use).
6947 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
6948 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
6949 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
6950 // Verify type of the LHS matches so we don't fold setcc's of different
6951 // types or GEP's with different index types.
6952 I->getOperand(0)->getType() != LHSType ||
6953 I->getOperand(1)->getType() != RHSType)
6956 // Keep track of which operand needs a phi node.
6957 if (I->getOperand(0) != LHSVal) LHSVal = 0;
6958 if (I->getOperand(1) != RHSVal) RHSVal = 0;
6961 // Otherwise, this is safe to transform, determine if it is profitable.
6963 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
6964 // Indexes are often folded into load/store instructions, so we don't want to
6965 // hide them behind a phi.
6966 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
6969 Value *InLHS = FirstInst->getOperand(0);
6970 Value *InRHS = FirstInst->getOperand(1);
6971 PHINode *NewLHS = 0, *NewRHS = 0;
6973 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
6974 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6975 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
6976 InsertNewInstBefore(NewLHS, PN);
6981 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
6982 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6983 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
6984 InsertNewInstBefore(NewRHS, PN);
6988 // Add all operands to the new PHIs.
6989 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6991 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6992 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6995 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
6996 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7000 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7001 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7002 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7003 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7005 assert(isa<GetElementPtrInst>(FirstInst));
7006 return new GetElementPtrInst(LHSVal, RHSVal);
7010 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7011 /// of the block that defines it. This means that it must be obvious the value
7012 /// of the load is not changed from the point of the load to the end of the
7014 static bool isSafeToSinkLoad(LoadInst *L) {
7015 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7017 for (++BBI; BBI != E; ++BBI)
7018 if (BBI->mayWriteToMemory())
7024 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7025 // operator and they all are only used by the PHI, PHI together their
7026 // inputs, and do the operation once, to the result of the PHI.
7027 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7028 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7030 // Scan the instruction, looking for input operations that can be folded away.
7031 // If all input operands to the phi are the same instruction (e.g. a cast from
7032 // the same type or "+42") we can pull the operation through the PHI, reducing
7033 // code size and simplifying code.
7034 Constant *ConstantOp = 0;
7035 const Type *CastSrcTy = 0;
7036 bool isVolatile = false;
7037 if (isa<CastInst>(FirstInst)) {
7038 CastSrcTy = FirstInst->getOperand(0)->getType();
7039 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
7040 // Can fold binop or shift here if the RHS is a constant, otherwise call
7041 // FoldPHIArgBinOpIntoPHI.
7042 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7043 if (ConstantOp == 0)
7044 return FoldPHIArgBinOpIntoPHI(PN);
7045 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7046 isVolatile = LI->isVolatile();
7047 // We can't sink the load if the loaded value could be modified between the
7048 // load and the PHI.
7049 if (LI->getParent() != PN.getIncomingBlock(0) ||
7050 !isSafeToSinkLoad(LI))
7052 } else if (isa<GetElementPtrInst>(FirstInst)) {
7053 if (FirstInst->getNumOperands() == 2)
7054 return FoldPHIArgBinOpIntoPHI(PN);
7055 // Can't handle general GEPs yet.
7058 return 0; // Cannot fold this operation.
7061 // Check to see if all arguments are the same operation.
7062 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7063 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7064 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7065 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7068 if (I->getOperand(0)->getType() != CastSrcTy)
7069 return 0; // Cast operation must match.
7070 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7071 // We can't sink the load if the loaded value could be modified between the
7072 // load and the PHI.
7073 if (LI->isVolatile() != isVolatile ||
7074 LI->getParent() != PN.getIncomingBlock(i) ||
7075 !isSafeToSinkLoad(LI))
7077 } else if (I->getOperand(1) != ConstantOp) {
7082 // Okay, they are all the same operation. Create a new PHI node of the
7083 // correct type, and PHI together all of the LHS's of the instructions.
7084 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7085 PN.getName()+".in");
7086 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7088 Value *InVal = FirstInst->getOperand(0);
7089 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7091 // Add all operands to the new PHI.
7092 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7093 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7094 if (NewInVal != InVal)
7096 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7101 // The new PHI unions all of the same values together. This is really
7102 // common, so we handle it intelligently here for compile-time speed.
7106 InsertNewInstBefore(NewPN, PN);
7110 // Insert and return the new operation.
7111 if (isa<CastInst>(FirstInst))
7112 return new CastInst(PhiVal, PN.getType());
7113 else if (isa<LoadInst>(FirstInst))
7114 return new LoadInst(PhiVal, "", isVolatile);
7115 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7116 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7118 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7119 PhiVal, ConstantOp);
7122 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7124 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7125 if (PN->use_empty()) return true;
7126 if (!PN->hasOneUse()) return false;
7128 // Remember this node, and if we find the cycle, return.
7129 if (!PotentiallyDeadPHIs.insert(PN).second)
7132 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7133 return DeadPHICycle(PU, PotentiallyDeadPHIs);
7138 // PHINode simplification
7140 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7141 // If LCSSA is around, don't mess with Phi nodes
7142 if (mustPreserveAnalysisID(LCSSAID)) return 0;
7144 if (Value *V = PN.hasConstantValue())
7145 return ReplaceInstUsesWith(PN, V);
7147 // If the only user of this instruction is a cast instruction, and all of the
7148 // incoming values are constants, change this PHI to merge together the casted
7151 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
7152 if (CI->getType() != PN.getType()) { // noop casts will be folded
7153 bool AllConstant = true;
7154 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
7155 if (!isa<Constant>(PN.getIncomingValue(i))) {
7156 AllConstant = false;
7160 // Make a new PHI with all casted values.
7161 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
7162 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
7163 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
7164 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
7165 PN.getIncomingBlock(i));
7168 // Update the cast instruction.
7169 CI->setOperand(0, New);
7170 WorkList.push_back(CI); // revisit the cast instruction to fold.
7171 WorkList.push_back(New); // Make sure to revisit the new Phi
7172 return &PN; // PN is now dead!
7176 // If all PHI operands are the same operation, pull them through the PHI,
7177 // reducing code size.
7178 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7179 PN.getIncomingValue(0)->hasOneUse())
7180 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7183 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7184 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7185 // PHI)... break the cycle.
7187 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7188 std::set<PHINode*> PotentiallyDeadPHIs;
7189 PotentiallyDeadPHIs.insert(&PN);
7190 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7191 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7197 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7198 Instruction *InsertPoint,
7200 unsigned PS = IC->getTargetData().getPointerSize();
7201 const Type *VTy = V->getType();
7202 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7203 // We must insert a cast to ensure we sign-extend.
7204 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7205 return IC->InsertCastBefore(V, DTy, *InsertPoint);
7209 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7210 Value *PtrOp = GEP.getOperand(0);
7211 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
7212 // If so, eliminate the noop.
7213 if (GEP.getNumOperands() == 1)
7214 return ReplaceInstUsesWith(GEP, PtrOp);
7216 if (isa<UndefValue>(GEP.getOperand(0)))
7217 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7219 bool HasZeroPointerIndex = false;
7220 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7221 HasZeroPointerIndex = C->isNullValue();
7223 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7224 return ReplaceInstUsesWith(GEP, PtrOp);
7226 // Eliminate unneeded casts for indices.
7227 bool MadeChange = false;
7228 gep_type_iterator GTI = gep_type_begin(GEP);
7229 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7230 if (isa<SequentialType>(*GTI)) {
7231 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7232 Value *Src = CI->getOperand(0);
7233 const Type *SrcTy = Src->getType();
7234 const Type *DestTy = CI->getType();
7235 if (Src->getType()->isInteger()) {
7236 if (SrcTy->getPrimitiveSizeInBits() ==
7237 DestTy->getPrimitiveSizeInBits()) {
7238 // We can always eliminate a cast from ulong or long to the other.
7239 // We can always eliminate a cast from uint to int or the other on
7240 // 32-bit pointer platforms.
7241 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7243 GEP.setOperand(i, Src);
7245 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7246 SrcTy->getPrimitiveSize() == 4) {
7247 // We can always eliminate a cast from int to [u]long. We can
7248 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7250 if (SrcTy->isSigned() ||
7251 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7253 GEP.setOperand(i, Src);
7258 // If we are using a wider index than needed for this platform, shrink it
7259 // to what we need. If the incoming value needs a cast instruction,
7260 // insert it. This explicit cast can make subsequent optimizations more
7262 Value *Op = GEP.getOperand(i);
7263 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7264 if (Constant *C = dyn_cast<Constant>(Op)) {
7265 GEP.setOperand(i, ConstantExpr::getCast(C,
7266 TD->getIntPtrType()->getSignedVersion()));
7269 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
7270 GEP.setOperand(i, Op);
7274 // If this is a constant idx, make sure to canonicalize it to be a signed
7275 // operand, otherwise CSE and other optimizations are pessimized.
7276 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7277 if (CUI->getType()->isUnsigned()) {
7279 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7283 if (MadeChange) return &GEP;
7285 // Combine Indices - If the source pointer to this getelementptr instruction
7286 // is a getelementptr instruction, combine the indices of the two
7287 // getelementptr instructions into a single instruction.
7289 std::vector<Value*> SrcGEPOperands;
7290 if (User *Src = dyn_castGetElementPtr(PtrOp))
7291 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7293 if (!SrcGEPOperands.empty()) {
7294 // Note that if our source is a gep chain itself that we wait for that
7295 // chain to be resolved before we perform this transformation. This
7296 // avoids us creating a TON of code in some cases.
7298 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7299 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7300 return 0; // Wait until our source is folded to completion.
7302 std::vector<Value *> Indices;
7304 // Find out whether the last index in the source GEP is a sequential idx.
7305 bool EndsWithSequential = false;
7306 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7307 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7308 EndsWithSequential = !isa<StructType>(*I);
7310 // Can we combine the two pointer arithmetics offsets?
7311 if (EndsWithSequential) {
7312 // Replace: gep (gep %P, long B), long A, ...
7313 // With: T = long A+B; gep %P, T, ...
7315 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7316 if (SO1 == Constant::getNullValue(SO1->getType())) {
7318 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7321 // If they aren't the same type, convert both to an integer of the
7322 // target's pointer size.
7323 if (SO1->getType() != GO1->getType()) {
7324 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7325 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7326 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7327 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7329 unsigned PS = TD->getPointerSize();
7330 if (SO1->getType()->getPrimitiveSize() == PS) {
7331 // Convert GO1 to SO1's type.
7332 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7334 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7335 // Convert SO1 to GO1's type.
7336 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7338 const Type *PT = TD->getIntPtrType();
7339 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7340 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7344 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7345 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7347 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7348 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7352 // Recycle the GEP we already have if possible.
7353 if (SrcGEPOperands.size() == 2) {
7354 GEP.setOperand(0, SrcGEPOperands[0]);
7355 GEP.setOperand(1, Sum);
7358 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7359 SrcGEPOperands.end()-1);
7360 Indices.push_back(Sum);
7361 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7363 } else if (isa<Constant>(*GEP.idx_begin()) &&
7364 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7365 SrcGEPOperands.size() != 1) {
7366 // Otherwise we can do the fold if the first index of the GEP is a zero
7367 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7368 SrcGEPOperands.end());
7369 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7372 if (!Indices.empty())
7373 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7375 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7376 // GEP of global variable. If all of the indices for this GEP are
7377 // constants, we can promote this to a constexpr instead of an instruction.
7379 // Scan for nonconstants...
7380 std::vector<Constant*> Indices;
7381 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7382 for (; I != E && isa<Constant>(*I); ++I)
7383 Indices.push_back(cast<Constant>(*I));
7385 if (I == E) { // If they are all constants...
7386 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7388 // Replace all uses of the GEP with the new constexpr...
7389 return ReplaceInstUsesWith(GEP, CE);
7391 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7392 if (!isa<PointerType>(X->getType())) {
7393 // Not interesting. Source pointer must be a cast from pointer.
7394 } else if (HasZeroPointerIndex) {
7395 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7396 // into : GEP [10 x ubyte]* X, long 0, ...
7398 // This occurs when the program declares an array extern like "int X[];"
7400 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7401 const PointerType *XTy = cast<PointerType>(X->getType());
7402 if (const ArrayType *XATy =
7403 dyn_cast<ArrayType>(XTy->getElementType()))
7404 if (const ArrayType *CATy =
7405 dyn_cast<ArrayType>(CPTy->getElementType()))
7406 if (CATy->getElementType() == XATy->getElementType()) {
7407 // At this point, we know that the cast source type is a pointer
7408 // to an array of the same type as the destination pointer
7409 // array. Because the array type is never stepped over (there
7410 // is a leading zero) we can fold the cast into this GEP.
7411 GEP.setOperand(0, X);
7414 } else if (GEP.getNumOperands() == 2) {
7415 // Transform things like:
7416 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7417 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7418 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7419 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7420 if (isa<ArrayType>(SrcElTy) &&
7421 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7422 TD->getTypeSize(ResElTy)) {
7423 Value *V = InsertNewInstBefore(
7424 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7425 GEP.getOperand(1), GEP.getName()), GEP);
7426 return new CastInst(V, GEP.getType());
7429 // Transform things like:
7430 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7431 // (where tmp = 8*tmp2) into:
7432 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7434 if (isa<ArrayType>(SrcElTy) &&
7435 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7436 uint64_t ArrayEltSize =
7437 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7439 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7440 // allow either a mul, shift, or constant here.
7442 ConstantInt *Scale = 0;
7443 if (ArrayEltSize == 1) {
7444 NewIdx = GEP.getOperand(1);
7445 Scale = ConstantInt::get(NewIdx->getType(), 1);
7446 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7447 NewIdx = ConstantInt::get(CI->getType(), 1);
7449 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7450 if (Inst->getOpcode() == Instruction::Shl &&
7451 isa<ConstantInt>(Inst->getOperand(1))) {
7453 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7454 if (Inst->getType()->isSigned())
7455 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7457 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7458 NewIdx = Inst->getOperand(0);
7459 } else if (Inst->getOpcode() == Instruction::Mul &&
7460 isa<ConstantInt>(Inst->getOperand(1))) {
7461 Scale = cast<ConstantInt>(Inst->getOperand(1));
7462 NewIdx = Inst->getOperand(0);
7466 // If the index will be to exactly the right offset with the scale taken
7467 // out, perform the transformation.
7468 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7469 if (isa<ConstantInt>(Scale))
7470 Scale = ConstantInt::get(Scale->getType(),
7471 Scale->getZExtValue() / ArrayEltSize);
7472 if (Scale->getZExtValue() != 1) {
7473 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7474 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7475 NewIdx = InsertNewInstBefore(Sc, GEP);
7478 // Insert the new GEP instruction.
7480 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7481 NewIdx, GEP.getName());
7482 Idx = InsertNewInstBefore(Idx, GEP);
7483 return new CastInst(Idx, GEP.getType());
7492 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7493 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7494 if (AI.isArrayAllocation()) // Check C != 1
7495 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7497 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7498 AllocationInst *New = 0;
7500 // Create and insert the replacement instruction...
7501 if (isa<MallocInst>(AI))
7502 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7504 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7505 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7508 InsertNewInstBefore(New, AI);
7510 // Scan to the end of the allocation instructions, to skip over a block of
7511 // allocas if possible...
7513 BasicBlock::iterator It = New;
7514 while (isa<AllocationInst>(*It)) ++It;
7516 // Now that I is pointing to the first non-allocation-inst in the block,
7517 // insert our getelementptr instruction...
7519 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7520 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7521 New->getName()+".sub", It);
7523 // Now make everything use the getelementptr instead of the original
7525 return ReplaceInstUsesWith(AI, V);
7526 } else if (isa<UndefValue>(AI.getArraySize())) {
7527 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7530 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7531 // Note that we only do this for alloca's, because malloc should allocate and
7532 // return a unique pointer, even for a zero byte allocation.
7533 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7534 TD->getTypeSize(AI.getAllocatedType()) == 0)
7535 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7540 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7541 Value *Op = FI.getOperand(0);
7543 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7544 if (CastInst *CI = dyn_cast<CastInst>(Op))
7545 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7546 FI.setOperand(0, CI->getOperand(0));
7550 // free undef -> unreachable.
7551 if (isa<UndefValue>(Op)) {
7552 // Insert a new store to null because we cannot modify the CFG here.
7553 new StoreInst(ConstantBool::getTrue(),
7554 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7555 return EraseInstFromFunction(FI);
7558 // If we have 'free null' delete the instruction. This can happen in stl code
7559 // when lots of inlining happens.
7560 if (isa<ConstantPointerNull>(Op))
7561 return EraseInstFromFunction(FI);
7567 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7568 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7569 User *CI = cast<User>(LI.getOperand(0));
7570 Value *CastOp = CI->getOperand(0);
7572 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7573 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7574 const Type *SrcPTy = SrcTy->getElementType();
7576 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7577 isa<PackedType>(DestPTy)) {
7578 // If the source is an array, the code below will not succeed. Check to
7579 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7581 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7582 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7583 if (ASrcTy->getNumElements() != 0) {
7584 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7585 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7586 SrcTy = cast<PointerType>(CastOp->getType());
7587 SrcPTy = SrcTy->getElementType();
7590 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7591 isa<PackedType>(SrcPTy)) &&
7592 // Do not allow turning this into a load of an integer, which is then
7593 // casted to a pointer, this pessimizes pointer analysis a lot.
7594 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7595 IC.getTargetData().getTypeSize(SrcPTy) ==
7596 IC.getTargetData().getTypeSize(DestPTy)) {
7598 // Okay, we are casting from one integer or pointer type to another of
7599 // the same size. Instead of casting the pointer before the load, cast
7600 // the result of the loaded value.
7601 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7603 LI.isVolatile()),LI);
7604 // Now cast the result of the load.
7605 return new CastInst(NewLoad, LI.getType());
7612 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
7613 /// from this value cannot trap. If it is not obviously safe to load from the
7614 /// specified pointer, we do a quick local scan of the basic block containing
7615 /// ScanFrom, to determine if the address is already accessed.
7616 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7617 // If it is an alloca or global variable, it is always safe to load from.
7618 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7620 // Otherwise, be a little bit agressive by scanning the local block where we
7621 // want to check to see if the pointer is already being loaded or stored
7622 // from/to. If so, the previous load or store would have already trapped,
7623 // so there is no harm doing an extra load (also, CSE will later eliminate
7624 // the load entirely).
7625 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7630 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7631 if (LI->getOperand(0) == V) return true;
7632 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7633 if (SI->getOperand(1) == V) return true;
7639 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7640 Value *Op = LI.getOperand(0);
7642 // load (cast X) --> cast (load X) iff safe
7643 if (isa<CastInst>(Op))
7644 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7647 // None of the following transforms are legal for volatile loads.
7648 if (LI.isVolatile()) return 0;
7650 if (&LI.getParent()->front() != &LI) {
7651 BasicBlock::iterator BBI = &LI; --BBI;
7652 // If the instruction immediately before this is a store to the same
7653 // address, do a simple form of store->load forwarding.
7654 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7655 if (SI->getOperand(1) == LI.getOperand(0))
7656 return ReplaceInstUsesWith(LI, SI->getOperand(0));
7657 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7658 if (LIB->getOperand(0) == LI.getOperand(0))
7659 return ReplaceInstUsesWith(LI, LIB);
7662 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7663 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7664 isa<UndefValue>(GEPI->getOperand(0))) {
7665 // Insert a new store to null instruction before the load to indicate
7666 // that this code is not reachable. We do this instead of inserting
7667 // an unreachable instruction directly because we cannot modify the
7669 new StoreInst(UndefValue::get(LI.getType()),
7670 Constant::getNullValue(Op->getType()), &LI);
7671 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7674 if (Constant *C = dyn_cast<Constant>(Op)) {
7675 // load null/undef -> undef
7676 if ((C->isNullValue() || isa<UndefValue>(C))) {
7677 // Insert a new store to null instruction before the load to indicate that
7678 // this code is not reachable. We do this instead of inserting an
7679 // unreachable instruction directly because we cannot modify the CFG.
7680 new StoreInst(UndefValue::get(LI.getType()),
7681 Constant::getNullValue(Op->getType()), &LI);
7682 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7685 // Instcombine load (constant global) into the value loaded.
7686 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7687 if (GV->isConstant() && !GV->isExternal())
7688 return ReplaceInstUsesWith(LI, GV->getInitializer());
7690 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7691 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7692 if (CE->getOpcode() == Instruction::GetElementPtr) {
7693 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7694 if (GV->isConstant() && !GV->isExternal())
7696 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
7697 return ReplaceInstUsesWith(LI, V);
7698 if (CE->getOperand(0)->isNullValue()) {
7699 // Insert a new store to null instruction before the load to indicate
7700 // that this code is not reachable. We do this instead of inserting
7701 // an unreachable instruction directly because we cannot modify the
7703 new StoreInst(UndefValue::get(LI.getType()),
7704 Constant::getNullValue(Op->getType()), &LI);
7705 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7708 } else if (CE->getOpcode() == Instruction::Cast) {
7709 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7714 if (Op->hasOneUse()) {
7715 // Change select and PHI nodes to select values instead of addresses: this
7716 // helps alias analysis out a lot, allows many others simplifications, and
7717 // exposes redundancy in the code.
7719 // Note that we cannot do the transformation unless we know that the
7720 // introduced loads cannot trap! Something like this is valid as long as
7721 // the condition is always false: load (select bool %C, int* null, int* %G),
7722 // but it would not be valid if we transformed it to load from null
7725 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7726 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
7727 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7728 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
7729 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
7730 SI->getOperand(1)->getName()+".val"), LI);
7731 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
7732 SI->getOperand(2)->getName()+".val"), LI);
7733 return new SelectInst(SI->getCondition(), V1, V2);
7736 // load (select (cond, null, P)) -> load P
7737 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7738 if (C->isNullValue()) {
7739 LI.setOperand(0, SI->getOperand(2));
7743 // load (select (cond, P, null)) -> load P
7744 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7745 if (C->isNullValue()) {
7746 LI.setOperand(0, SI->getOperand(1));
7754 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7756 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7757 User *CI = cast<User>(SI.getOperand(1));
7758 Value *CastOp = CI->getOperand(0);
7760 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7761 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7762 const Type *SrcPTy = SrcTy->getElementType();
7764 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7765 // If the source is an array, the code below will not succeed. Check to
7766 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7768 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7769 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7770 if (ASrcTy->getNumElements() != 0) {
7771 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7772 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7773 SrcTy = cast<PointerType>(CastOp->getType());
7774 SrcPTy = SrcTy->getElementType();
7777 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
7778 IC.getTargetData().getTypeSize(SrcPTy) ==
7779 IC.getTargetData().getTypeSize(DestPTy)) {
7781 // Okay, we are casting from one integer or pointer type to another of
7782 // the same size. Instead of casting the pointer before the store, cast
7783 // the value to be stored.
7785 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7786 NewCast = ConstantExpr::getCast(C, SrcPTy);
7788 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7790 SI.getOperand(0)->getName()+".c"), SI);
7792 return new StoreInst(NewCast, CastOp);
7799 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7800 Value *Val = SI.getOperand(0);
7801 Value *Ptr = SI.getOperand(1);
7803 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
7804 EraseInstFromFunction(SI);
7809 // Do really simple DSE, to catch cases where there are several consequtive
7810 // stores to the same location, separated by a few arithmetic operations. This
7811 // situation often occurs with bitfield accesses.
7812 BasicBlock::iterator BBI = &SI;
7813 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7817 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7818 // Prev store isn't volatile, and stores to the same location?
7819 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7822 EraseInstFromFunction(*PrevSI);
7828 // If this is a load, we have to stop. However, if the loaded value is from
7829 // the pointer we're loading and is producing the pointer we're storing,
7830 // then *this* store is dead (X = load P; store X -> P).
7831 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7832 if (LI == Val && LI->getOperand(0) == Ptr) {
7833 EraseInstFromFunction(SI);
7837 // Otherwise, this is a load from some other location. Stores before it
7842 // Don't skip over loads or things that can modify memory.
7843 if (BBI->mayWriteToMemory())
7848 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
7850 // store X, null -> turns into 'unreachable' in SimplifyCFG
7851 if (isa<ConstantPointerNull>(Ptr)) {
7852 if (!isa<UndefValue>(Val)) {
7853 SI.setOperand(0, UndefValue::get(Val->getType()));
7854 if (Instruction *U = dyn_cast<Instruction>(Val))
7855 WorkList.push_back(U); // Dropped a use.
7858 return 0; // Do not modify these!
7861 // store undef, Ptr -> noop
7862 if (isa<UndefValue>(Val)) {
7863 EraseInstFromFunction(SI);
7868 // If the pointer destination is a cast, see if we can fold the cast into the
7870 if (isa<CastInst>(Ptr))
7871 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7873 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7874 if (CE->getOpcode() == Instruction::Cast)
7875 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7879 // If this store is the last instruction in the basic block, and if the block
7880 // ends with an unconditional branch, try to move it to the successor block.
7882 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7883 if (BI->isUnconditional()) {
7884 // Check to see if the successor block has exactly two incoming edges. If
7885 // so, see if the other predecessor contains a store to the same location.
7886 // if so, insert a PHI node (if needed) and move the stores down.
7887 BasicBlock *Dest = BI->getSuccessor(0);
7889 pred_iterator PI = pred_begin(Dest);
7890 BasicBlock *Other = 0;
7891 if (*PI != BI->getParent())
7894 if (PI != pred_end(Dest)) {
7895 if (*PI != BI->getParent())
7900 if (++PI != pred_end(Dest))
7903 if (Other) { // If only one other pred...
7904 BBI = Other->getTerminator();
7905 // Make sure this other block ends in an unconditional branch and that
7906 // there is an instruction before the branch.
7907 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7908 BBI != Other->begin()) {
7910 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7912 // If this instruction is a store to the same location.
7913 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7914 // Okay, we know we can perform this transformation. Insert a PHI
7915 // node now if we need it.
7916 Value *MergedVal = OtherStore->getOperand(0);
7917 if (MergedVal != SI.getOperand(0)) {
7918 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7919 PN->reserveOperandSpace(2);
7920 PN->addIncoming(SI.getOperand(0), SI.getParent());
7921 PN->addIncoming(OtherStore->getOperand(0), Other);
7922 MergedVal = InsertNewInstBefore(PN, Dest->front());
7925 // Advance to a place where it is safe to insert the new store and
7927 BBI = Dest->begin();
7928 while (isa<PHINode>(BBI)) ++BBI;
7929 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7930 OtherStore->isVolatile()), *BBI);
7932 // Nuke the old stores.
7933 EraseInstFromFunction(SI);
7934 EraseInstFromFunction(*OtherStore);
7946 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7947 // Change br (not X), label True, label False to: br X, label False, True
7949 BasicBlock *TrueDest;
7950 BasicBlock *FalseDest;
7951 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7952 !isa<Constant>(X)) {
7953 // Swap Destinations and condition...
7955 BI.setSuccessor(0, FalseDest);
7956 BI.setSuccessor(1, TrueDest);
7960 // Cannonicalize setne -> seteq
7961 Instruction::BinaryOps Op; Value *Y;
7962 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7963 TrueDest, FalseDest)))
7964 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7965 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7966 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7967 std::string Name = I->getName(); I->setName("");
7968 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7969 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
7970 // Swap Destinations and condition...
7971 BI.setCondition(NewSCC);
7972 BI.setSuccessor(0, FalseDest);
7973 BI.setSuccessor(1, TrueDest);
7974 removeFromWorkList(I);
7975 I->getParent()->getInstList().erase(I);
7976 WorkList.push_back(cast<Instruction>(NewSCC));
7983 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7984 Value *Cond = SI.getCondition();
7985 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7986 if (I->getOpcode() == Instruction::Add)
7987 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7988 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7989 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
7990 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
7992 SI.setOperand(0, I->getOperand(0));
7993 WorkList.push_back(I);
8000 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8001 /// is to leave as a vector operation.
8002 static bool CheapToScalarize(Value *V, bool isConstant) {
8003 if (isa<ConstantAggregateZero>(V))
8005 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8006 if (isConstant) return true;
8007 // If all elts are the same, we can extract.
8008 Constant *Op0 = C->getOperand(0);
8009 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8010 if (C->getOperand(i) != Op0)
8014 Instruction *I = dyn_cast<Instruction>(V);
8015 if (!I) return false;
8017 // Insert element gets simplified to the inserted element or is deleted if
8018 // this is constant idx extract element and its a constant idx insertelt.
8019 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8020 isa<ConstantInt>(I->getOperand(2)))
8022 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8024 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8025 if (BO->hasOneUse() &&
8026 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8027 CheapToScalarize(BO->getOperand(1), isConstant)))
8033 /// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8034 /// elements into values that are larger than the #elts in the input.
8035 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8036 unsigned NElts = SVI->getType()->getNumElements();
8037 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8038 return std::vector<unsigned>(NElts, 0);
8039 if (isa<UndefValue>(SVI->getOperand(2)))
8040 return std::vector<unsigned>(NElts, 2*NElts);
8042 std::vector<unsigned> Result;
8043 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8044 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8045 if (isa<UndefValue>(CP->getOperand(i)))
8046 Result.push_back(NElts*2); // undef -> 8
8048 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8052 /// FindScalarElement - Given a vector and an element number, see if the scalar
8053 /// value is already around as a register, for example if it were inserted then
8054 /// extracted from the vector.
8055 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8056 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8057 const PackedType *PTy = cast<PackedType>(V->getType());
8058 unsigned Width = PTy->getNumElements();
8059 if (EltNo >= Width) // Out of range access.
8060 return UndefValue::get(PTy->getElementType());
8062 if (isa<UndefValue>(V))
8063 return UndefValue::get(PTy->getElementType());
8064 else if (isa<ConstantAggregateZero>(V))
8065 return Constant::getNullValue(PTy->getElementType());
8066 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8067 return CP->getOperand(EltNo);
8068 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8069 // If this is an insert to a variable element, we don't know what it is.
8070 if (!isa<ConstantInt>(III->getOperand(2)))
8072 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8074 // If this is an insert to the element we are looking for, return the
8077 return III->getOperand(1);
8079 // Otherwise, the insertelement doesn't modify the value, recurse on its
8081 return FindScalarElement(III->getOperand(0), EltNo);
8082 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8083 unsigned InEl = getShuffleMask(SVI)[EltNo];
8085 return FindScalarElement(SVI->getOperand(0), InEl);
8086 else if (InEl < Width*2)
8087 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8089 return UndefValue::get(PTy->getElementType());
8092 // Otherwise, we don't know.
8096 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8098 // If packed val is undef, replace extract with scalar undef.
8099 if (isa<UndefValue>(EI.getOperand(0)))
8100 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8102 // If packed val is constant 0, replace extract with scalar 0.
8103 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8104 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8106 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8107 // If packed val is constant with uniform operands, replace EI
8108 // with that operand
8109 Constant *op0 = C->getOperand(0);
8110 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8111 if (C->getOperand(i) != op0) {
8116 return ReplaceInstUsesWith(EI, op0);
8119 // If extracting a specified index from the vector, see if we can recursively
8120 // find a previously computed scalar that was inserted into the vector.
8121 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8122 // This instruction only demands the single element from the input vector.
8123 // If the input vector has a single use, simplify it based on this use
8125 uint64_t IndexVal = IdxC->getZExtValue();
8126 if (EI.getOperand(0)->hasOneUse()) {
8128 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8131 EI.setOperand(0, V);
8136 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8137 return ReplaceInstUsesWith(EI, Elt);
8140 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8141 if (I->hasOneUse()) {
8142 // Push extractelement into predecessor operation if legal and
8143 // profitable to do so
8144 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8145 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8146 if (CheapToScalarize(BO, isConstantElt)) {
8147 ExtractElementInst *newEI0 =
8148 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8149 EI.getName()+".lhs");
8150 ExtractElementInst *newEI1 =
8151 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8152 EI.getName()+".rhs");
8153 InsertNewInstBefore(newEI0, EI);
8154 InsertNewInstBefore(newEI1, EI);
8155 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8157 } else if (isa<LoadInst>(I)) {
8158 Value *Ptr = InsertCastBefore(I->getOperand(0),
8159 PointerType::get(EI.getType()), EI);
8160 GetElementPtrInst *GEP =
8161 new GetElementPtrInst(Ptr, EI.getOperand(1),
8162 I->getName() + ".gep");
8163 InsertNewInstBefore(GEP, EI);
8164 return new LoadInst(GEP);
8167 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8168 // Extracting the inserted element?
8169 if (IE->getOperand(2) == EI.getOperand(1))
8170 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8171 // If the inserted and extracted elements are constants, they must not
8172 // be the same value, extract from the pre-inserted value instead.
8173 if (isa<Constant>(IE->getOperand(2)) &&
8174 isa<Constant>(EI.getOperand(1))) {
8175 AddUsesToWorkList(EI);
8176 EI.setOperand(0, IE->getOperand(0));
8179 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8180 // If this is extracting an element from a shufflevector, figure out where
8181 // it came from and extract from the appropriate input element instead.
8182 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8183 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8185 if (SrcIdx < SVI->getType()->getNumElements())
8186 Src = SVI->getOperand(0);
8187 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8188 SrcIdx -= SVI->getType()->getNumElements();
8189 Src = SVI->getOperand(1);
8191 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8193 return new ExtractElementInst(Src, SrcIdx);
8200 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8201 /// elements from either LHS or RHS, return the shuffle mask and true.
8202 /// Otherwise, return false.
8203 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8204 std::vector<Constant*> &Mask) {
8205 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8206 "Invalid CollectSingleShuffleElements");
8207 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8209 if (isa<UndefValue>(V)) {
8210 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8212 } else if (V == LHS) {
8213 for (unsigned i = 0; i != NumElts; ++i)
8214 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8216 } else if (V == RHS) {
8217 for (unsigned i = 0; i != NumElts; ++i)
8218 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
8220 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8221 // If this is an insert of an extract from some other vector, include it.
8222 Value *VecOp = IEI->getOperand(0);
8223 Value *ScalarOp = IEI->getOperand(1);
8224 Value *IdxOp = IEI->getOperand(2);
8226 if (!isa<ConstantInt>(IdxOp))
8228 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8230 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8231 // Okay, we can handle this if the vector we are insertinting into is
8233 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8234 // If so, update the mask to reflect the inserted undef.
8235 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8238 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8239 if (isa<ConstantInt>(EI->getOperand(1)) &&
8240 EI->getOperand(0)->getType() == V->getType()) {
8241 unsigned ExtractedIdx =
8242 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8244 // This must be extracting from either LHS or RHS.
8245 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8246 // Okay, we can handle this if the vector we are insertinting into is
8248 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8249 // If so, update the mask to reflect the inserted value.
8250 if (EI->getOperand(0) == LHS) {
8251 Mask[InsertedIdx & (NumElts-1)] =
8252 ConstantInt::get(Type::UIntTy, ExtractedIdx);
8254 assert(EI->getOperand(0) == RHS);
8255 Mask[InsertedIdx & (NumElts-1)] =
8256 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
8265 // TODO: Handle shufflevector here!
8270 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8271 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8272 /// that computes V and the LHS value of the shuffle.
8273 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8275 assert(isa<PackedType>(V->getType()) &&
8276 (RHS == 0 || V->getType() == RHS->getType()) &&
8277 "Invalid shuffle!");
8278 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8280 if (isa<UndefValue>(V)) {
8281 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8283 } else if (isa<ConstantAggregateZero>(V)) {
8284 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
8286 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8287 // If this is an insert of an extract from some other vector, include it.
8288 Value *VecOp = IEI->getOperand(0);
8289 Value *ScalarOp = IEI->getOperand(1);
8290 Value *IdxOp = IEI->getOperand(2);
8292 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8293 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8294 EI->getOperand(0)->getType() == V->getType()) {
8295 unsigned ExtractedIdx =
8296 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8297 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8299 // Either the extracted from or inserted into vector must be RHSVec,
8300 // otherwise we'd end up with a shuffle of three inputs.
8301 if (EI->getOperand(0) == RHS || RHS == 0) {
8302 RHS = EI->getOperand(0);
8303 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8304 Mask[InsertedIdx & (NumElts-1)] =
8305 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
8310 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8311 // Everything but the extracted element is replaced with the RHS.
8312 for (unsigned i = 0; i != NumElts; ++i) {
8313 if (i != InsertedIdx)
8314 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
8319 // If this insertelement is a chain that comes from exactly these two
8320 // vectors, return the vector and the effective shuffle.
8321 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8322 return EI->getOperand(0);
8327 // TODO: Handle shufflevector here!
8329 // Otherwise, can't do anything fancy. Return an identity vector.
8330 for (unsigned i = 0; i != NumElts; ++i)
8331 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8335 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8336 Value *VecOp = IE.getOperand(0);
8337 Value *ScalarOp = IE.getOperand(1);
8338 Value *IdxOp = IE.getOperand(2);
8340 // If the inserted element was extracted from some other vector, and if the
8341 // indexes are constant, try to turn this into a shufflevector operation.
8342 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8343 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8344 EI->getOperand(0)->getType() == IE.getType()) {
8345 unsigned NumVectorElts = IE.getType()->getNumElements();
8346 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8347 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8349 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8350 return ReplaceInstUsesWith(IE, VecOp);
8352 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8353 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8355 // If we are extracting a value from a vector, then inserting it right
8356 // back into the same place, just use the input vector.
8357 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8358 return ReplaceInstUsesWith(IE, VecOp);
8360 // We could theoretically do this for ANY input. However, doing so could
8361 // turn chains of insertelement instructions into a chain of shufflevector
8362 // instructions, and right now we do not merge shufflevectors. As such,
8363 // only do this in a situation where it is clear that there is benefit.
8364 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8365 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8366 // the values of VecOp, except then one read from EIOp0.
8367 // Build a new shuffle mask.
8368 std::vector<Constant*> Mask;
8369 if (isa<UndefValue>(VecOp))
8370 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8372 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8373 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
8376 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
8377 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8378 ConstantPacked::get(Mask));
8381 // If this insertelement isn't used by some other insertelement, turn it
8382 // (and any insertelements it points to), into one big shuffle.
8383 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8384 std::vector<Constant*> Mask;
8386 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8387 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8388 // We now have a shuffle of LHS, RHS, Mask.
8389 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8398 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8399 Value *LHS = SVI.getOperand(0);
8400 Value *RHS = SVI.getOperand(1);
8401 std::vector<unsigned> Mask = getShuffleMask(&SVI);
8403 bool MadeChange = false;
8405 // Undefined shuffle mask -> undefined value.
8406 if (isa<UndefValue>(SVI.getOperand(2)))
8407 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8409 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8410 // the undef, change them to undefs.
8412 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8413 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8414 if (LHS == RHS || isa<UndefValue>(LHS)) {
8415 if (isa<UndefValue>(LHS) && LHS == RHS) {
8416 // shuffle(undef,undef,mask) -> undef.
8417 return ReplaceInstUsesWith(SVI, LHS);
8420 // Remap any references to RHS to use LHS.
8421 std::vector<Constant*> Elts;
8422 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8424 Elts.push_back(UndefValue::get(Type::UIntTy));
8426 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8427 (Mask[i] < e && isa<UndefValue>(LHS)))
8428 Mask[i] = 2*e; // Turn into undef.
8430 Mask[i] &= (e-1); // Force to LHS.
8431 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
8434 SVI.setOperand(0, SVI.getOperand(1));
8435 SVI.setOperand(1, UndefValue::get(RHS->getType()));
8436 SVI.setOperand(2, ConstantPacked::get(Elts));
8437 LHS = SVI.getOperand(0);
8438 RHS = SVI.getOperand(1);
8442 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8443 bool isLHSID = true, isRHSID = true;
8445 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8446 if (Mask[i] >= e*2) continue; // Ignore undef values.
8447 // Is this an identity shuffle of the LHS value?
8448 isLHSID &= (Mask[i] == i);
8450 // Is this an identity shuffle of the RHS value?
8451 isRHSID &= (Mask[i]-e == i);
8454 // Eliminate identity shuffles.
8455 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8456 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8458 // If the LHS is a shufflevector itself, see if we can combine it with this
8459 // one without producing an unusual shuffle. Here we are really conservative:
8460 // we are absolutely afraid of producing a shuffle mask not in the input
8461 // program, because the code gen may not be smart enough to turn a merged
8462 // shuffle into two specific shuffles: it may produce worse code. As such,
8463 // we only merge two shuffles if the result is one of the two input shuffle
8464 // masks. In this case, merging the shuffles just removes one instruction,
8465 // which we know is safe. This is good for things like turning:
8466 // (splat(splat)) -> splat.
8467 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8468 if (isa<UndefValue>(RHS)) {
8469 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8471 std::vector<unsigned> NewMask;
8472 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8474 NewMask.push_back(2*e);
8476 NewMask.push_back(LHSMask[Mask[i]]);
8478 // If the result mask is equal to the src shuffle or this shuffle mask, do
8480 if (NewMask == LHSMask || NewMask == Mask) {
8481 std::vector<Constant*> Elts;
8482 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8483 if (NewMask[i] >= e*2) {
8484 Elts.push_back(UndefValue::get(Type::UIntTy));
8486 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
8489 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8490 LHSSVI->getOperand(1),
8491 ConstantPacked::get(Elts));
8496 return MadeChange ? &SVI : 0;
8501 void InstCombiner::removeFromWorkList(Instruction *I) {
8502 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8507 /// TryToSinkInstruction - Try to move the specified instruction from its
8508 /// current block into the beginning of DestBlock, which can only happen if it's
8509 /// safe to move the instruction past all of the instructions between it and the
8510 /// end of its block.
8511 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8512 assert(I->hasOneUse() && "Invariants didn't hold!");
8514 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8515 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8517 // Do not sink alloca instructions out of the entry block.
8518 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8521 // We can only sink load instructions if there is nothing between the load and
8522 // the end of block that could change the value.
8523 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8524 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8526 if (Scan->mayWriteToMemory())
8530 BasicBlock::iterator InsertPos = DestBlock->begin();
8531 while (isa<PHINode>(InsertPos)) ++InsertPos;
8533 I->moveBefore(InsertPos);
8538 /// OptimizeConstantExpr - Given a constant expression and target data layout
8539 /// information, symbolically evaluation the constant expr to something simpler
8541 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8544 Constant *Ptr = CE->getOperand(0);
8545 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8546 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8547 // If this is a constant expr gep that is effectively computing an
8548 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8549 bool isFoldableGEP = true;
8550 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8551 if (!isa<ConstantInt>(CE->getOperand(i)))
8552 isFoldableGEP = false;
8553 if (isFoldableGEP) {
8554 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8555 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8556 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
8557 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8558 return ConstantExpr::getCast(C, CE->getType());
8566 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8567 /// all reachable code to the worklist.
8569 /// This has a couple of tricks to make the code faster and more powerful. In
8570 /// particular, we constant fold and DCE instructions as we go, to avoid adding
8571 /// them to the worklist (this significantly speeds up instcombine on code where
8572 /// many instructions are dead or constant). Additionally, if we find a branch
8573 /// whose condition is a known constant, we only visit the reachable successors.
8575 static void AddReachableCodeToWorklist(BasicBlock *BB,
8576 std::set<BasicBlock*> &Visited,
8577 std::vector<Instruction*> &WorkList,
8578 const TargetData *TD) {
8579 // We have now visited this block! If we've already been here, bail out.
8580 if (!Visited.insert(BB).second) return;
8582 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8583 Instruction *Inst = BBI++;
8585 // DCE instruction if trivially dead.
8586 if (isInstructionTriviallyDead(Inst)) {
8588 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8589 Inst->eraseFromParent();
8593 // ConstantProp instruction if trivially constant.
8594 if (Constant *C = ConstantFoldInstruction(Inst)) {
8595 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8596 C = OptimizeConstantExpr(CE, TD);
8597 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8598 Inst->replaceAllUsesWith(C);
8600 Inst->eraseFromParent();
8604 WorkList.push_back(Inst);
8607 // Recursively visit successors. If this is a branch or switch on a constant,
8608 // only visit the reachable successor.
8609 TerminatorInst *TI = BB->getTerminator();
8610 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8611 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8612 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
8613 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8617 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8618 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8619 // See if this is an explicit destination.
8620 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8621 if (SI->getCaseValue(i) == Cond) {
8622 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
8626 // Otherwise it is the default destination.
8627 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
8632 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
8633 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
8636 bool InstCombiner::runOnFunction(Function &F) {
8637 bool Changed = false;
8638 TD = &getAnalysis<TargetData>();
8641 // Do a depth-first traversal of the function, populate the worklist with
8642 // the reachable instructions. Ignore blocks that are not reachable. Keep
8643 // track of which blocks we visit.
8644 std::set<BasicBlock*> Visited;
8645 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
8647 // Do a quick scan over the function. If we find any blocks that are
8648 // unreachable, remove any instructions inside of them. This prevents
8649 // the instcombine code from having to deal with some bad special cases.
8650 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8651 if (!Visited.count(BB)) {
8652 Instruction *Term = BB->getTerminator();
8653 while (Term != BB->begin()) { // Remove instrs bottom-up
8654 BasicBlock::iterator I = Term; --I;
8656 DEBUG(std::cerr << "IC: DCE: " << *I);
8659 if (!I->use_empty())
8660 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8661 I->eraseFromParent();
8666 while (!WorkList.empty()) {
8667 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8668 WorkList.pop_back();
8670 // Check to see if we can DCE the instruction.
8671 if (isInstructionTriviallyDead(I)) {
8672 // Add operands to the worklist.
8673 if (I->getNumOperands() < 4)
8674 AddUsesToWorkList(*I);
8677 DEBUG(std::cerr << "IC: DCE: " << *I);
8679 I->eraseFromParent();
8680 removeFromWorkList(I);
8684 // Instruction isn't dead, see if we can constant propagate it.
8685 if (Constant *C = ConstantFoldInstruction(I)) {
8686 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8687 C = OptimizeConstantExpr(CE, TD);
8688 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8690 // Add operands to the worklist.
8691 AddUsesToWorkList(*I);
8692 ReplaceInstUsesWith(*I, C);
8695 I->eraseFromParent();
8696 removeFromWorkList(I);
8700 // See if we can trivially sink this instruction to a successor basic block.
8701 if (I->hasOneUse()) {
8702 BasicBlock *BB = I->getParent();
8703 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8704 if (UserParent != BB) {
8705 bool UserIsSuccessor = false;
8706 // See if the user is one of our successors.
8707 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8708 if (*SI == UserParent) {
8709 UserIsSuccessor = true;
8713 // If the user is one of our immediate successors, and if that successor
8714 // only has us as a predecessors (we'd have to split the critical edge
8715 // otherwise), we can keep going.
8716 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8717 next(pred_begin(UserParent)) == pred_end(UserParent))
8718 // Okay, the CFG is simple enough, try to sink this instruction.
8719 Changed |= TryToSinkInstruction(I, UserParent);
8723 // Now that we have an instruction, try combining it to simplify it...
8724 if (Instruction *Result = visit(*I)) {
8726 // Should we replace the old instruction with a new one?
8728 DEBUG(std::cerr << "IC: Old = " << *I
8729 << " New = " << *Result);
8731 // Everything uses the new instruction now.
8732 I->replaceAllUsesWith(Result);
8734 // Push the new instruction and any users onto the worklist.
8735 WorkList.push_back(Result);
8736 AddUsersToWorkList(*Result);
8738 // Move the name to the new instruction first...
8739 std::string OldName = I->getName(); I->setName("");
8740 Result->setName(OldName);
8742 // Insert the new instruction into the basic block...
8743 BasicBlock *InstParent = I->getParent();
8744 BasicBlock::iterator InsertPos = I;
8746 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8747 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8750 InstParent->getInstList().insert(InsertPos, Result);
8752 // Make sure that we reprocess all operands now that we reduced their
8754 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8755 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8756 WorkList.push_back(OpI);
8758 // Instructions can end up on the worklist more than once. Make sure
8759 // we do not process an instruction that has been deleted.
8760 removeFromWorkList(I);
8762 // Erase the old instruction.
8763 InstParent->getInstList().erase(I);
8765 DEBUG(std::cerr << "IC: MOD = " << *I);
8767 // If the instruction was modified, it's possible that it is now dead.
8768 // if so, remove it.
8769 if (isInstructionTriviallyDead(I)) {
8770 // Make sure we process all operands now that we are reducing their
8772 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8773 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8774 WorkList.push_back(OpI);
8776 // Instructions may end up in the worklist more than once. Erase all
8777 // occurrences of this instruction.
8778 removeFromWorkList(I);
8779 I->eraseFromParent();
8781 WorkList.push_back(Result);
8782 AddUsersToWorkList(*Result);
8792 FunctionPass *llvm::createInstructionCombiningPass() {
8793 return new InstCombiner();