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. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp 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/Analysis/ConstantFolding.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstVisitor.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/PatternMatch.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/ADT/DenseMap.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/ADT/STLExtras.h"
61 using namespace llvm::PatternMatch;
63 STATISTIC(NumCombined , "Number of insts combined");
64 STATISTIC(NumConstProp, "Number of constant folds");
65 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67 STATISTIC(NumSunkInst , "Number of instructions sunk");
70 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
73 // Worklist of all of the instructions that need to be simplified.
74 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
77 bool MustPreserveLCSSA;
79 /// AddToWorkList - Add the specified instruction to the worklist if it
80 /// isn't already in it.
81 void AddToWorkList(Instruction *I) {
82 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83 Worklist.push_back(I);
86 // RemoveFromWorkList - remove I from the worklist if it exists.
87 void RemoveFromWorkList(Instruction *I) {
88 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89 if (It == WorklistMap.end()) return; // Not in worklist.
91 // Don't bother moving everything down, just null out the slot.
92 Worklist[It->second] = 0;
94 WorklistMap.erase(It);
97 Instruction *RemoveOneFromWorkList() {
98 Instruction *I = Worklist.back();
100 WorklistMap.erase(I);
105 /// AddUsersToWorkList - When an instruction is simplified, add all users of
106 /// the instruction to the work lists because they might get more simplified
109 void AddUsersToWorkList(Value &I) {
110 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
112 AddToWorkList(cast<Instruction>(*UI));
115 /// AddUsesToWorkList - When an instruction is simplified, add operands to
116 /// the work lists because they might get more simplified now.
118 void AddUsesToWorkList(Instruction &I) {
119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
124 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125 /// dead. Add all of its operands to the worklist, turning them into
126 /// undef's to reduce the number of uses of those instructions.
128 /// Return the specified operand before it is turned into an undef.
130 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131 Value *R = I.getOperand(op);
133 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
136 // Set the operand to undef to drop the use.
137 I.setOperand(i, UndefValue::get(Op->getType()));
144 virtual bool runOnFunction(Function &F);
146 bool DoOneIteration(Function &F, unsigned ItNum);
148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
149 AU.addRequired<TargetData>();
150 AU.addPreservedID(LCSSAID);
151 AU.setPreservesCFG();
154 TargetData &getTargetData() const { return *TD; }
156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
159 // null - No change was made
160 // I - Change was made, I is still valid, I may be dead though
161 // otherwise - Change was made, replace I with returned instruction
163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitSub(BinaryOperator &I);
165 Instruction *visitMul(BinaryOperator &I);
166 Instruction *visitURem(BinaryOperator &I);
167 Instruction *visitSRem(BinaryOperator &I);
168 Instruction *visitFRem(BinaryOperator &I);
169 Instruction *commonRemTransforms(BinaryOperator &I);
170 Instruction *commonIRemTransforms(BinaryOperator &I);
171 Instruction *commonDivTransforms(BinaryOperator &I);
172 Instruction *commonIDivTransforms(BinaryOperator &I);
173 Instruction *visitUDiv(BinaryOperator &I);
174 Instruction *visitSDiv(BinaryOperator &I);
175 Instruction *visitFDiv(BinaryOperator &I);
176 Instruction *visitAnd(BinaryOperator &I);
177 Instruction *visitOr (BinaryOperator &I);
178 Instruction *visitXor(BinaryOperator &I);
179 Instruction *visitShl(BinaryOperator &I);
180 Instruction *visitAShr(BinaryOperator &I);
181 Instruction *visitLShr(BinaryOperator &I);
182 Instruction *commonShiftTransforms(BinaryOperator &I);
183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
187 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188 ICmpInst::Predicate Cond, Instruction &I);
189 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
191 Instruction *commonCastTransforms(CastInst &CI);
192 Instruction *commonIntCastTransforms(CastInst &CI);
193 Instruction *visitTrunc(CastInst &CI);
194 Instruction *visitZExt(CastInst &CI);
195 Instruction *visitSExt(CastInst &CI);
196 Instruction *visitFPTrunc(CastInst &CI);
197 Instruction *visitFPExt(CastInst &CI);
198 Instruction *visitFPToUI(CastInst &CI);
199 Instruction *visitFPToSI(CastInst &CI);
200 Instruction *visitUIToFP(CastInst &CI);
201 Instruction *visitSIToFP(CastInst &CI);
202 Instruction *visitPtrToInt(CastInst &CI);
203 Instruction *visitIntToPtr(CastInst &CI);
204 Instruction *visitBitCast(CastInst &CI);
205 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
207 Instruction *visitSelectInst(SelectInst &CI);
208 Instruction *visitCallInst(CallInst &CI);
209 Instruction *visitInvokeInst(InvokeInst &II);
210 Instruction *visitPHINode(PHINode &PN);
211 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
212 Instruction *visitAllocationInst(AllocationInst &AI);
213 Instruction *visitFreeInst(FreeInst &FI);
214 Instruction *visitLoadInst(LoadInst &LI);
215 Instruction *visitStoreInst(StoreInst &SI);
216 Instruction *visitBranchInst(BranchInst &BI);
217 Instruction *visitSwitchInst(SwitchInst &SI);
218 Instruction *visitInsertElementInst(InsertElementInst &IE);
219 Instruction *visitExtractElementInst(ExtractElementInst &EI);
220 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
222 // visitInstruction - Specify what to return for unhandled instructions...
223 Instruction *visitInstruction(Instruction &I) { return 0; }
226 Instruction *visitCallSite(CallSite CS);
227 bool transformConstExprCastCall(CallSite CS);
230 // InsertNewInstBefore - insert an instruction New before instruction Old
231 // in the program. Add the new instruction to the worklist.
233 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
234 assert(New && New->getParent() == 0 &&
235 "New instruction already inserted into a basic block!");
236 BasicBlock *BB = Old.getParent();
237 BB->getInstList().insert(&Old, New); // Insert inst
242 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243 /// This also adds the cast to the worklist. Finally, this returns the
245 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
247 if (V->getType() == Ty) return V;
249 if (Constant *CV = dyn_cast<Constant>(V))
250 return ConstantExpr::getCast(opc, CV, Ty);
252 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
257 // ReplaceInstUsesWith - This method is to be used when an instruction is
258 // found to be dead, replacable with another preexisting expression. Here
259 // we add all uses of I to the worklist, replace all uses of I with the new
260 // value, then return I, so that the inst combiner will know that I was
263 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
264 AddUsersToWorkList(I); // Add all modified instrs to worklist
266 I.replaceAllUsesWith(V);
269 // If we are replacing the instruction with itself, this must be in a
270 // segment of unreachable code, so just clobber the instruction.
271 I.replaceAllUsesWith(UndefValue::get(I.getType()));
276 // UpdateValueUsesWith - This method is to be used when an value is
277 // found to be replacable with another preexisting expression or was
278 // updated. Here we add all uses of I to the worklist, replace all uses of
279 // I with the new value (unless the instruction was just updated), then
280 // return true, so that the inst combiner will know that I was modified.
282 bool UpdateValueUsesWith(Value *Old, Value *New) {
283 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
285 Old->replaceAllUsesWith(New);
286 if (Instruction *I = dyn_cast<Instruction>(Old))
288 if (Instruction *I = dyn_cast<Instruction>(New))
293 // EraseInstFromFunction - When dealing with an instruction that has side
294 // effects or produces a void value, we can't rely on DCE to delete the
295 // instruction. Instead, visit methods should return the value returned by
297 Instruction *EraseInstFromFunction(Instruction &I) {
298 assert(I.use_empty() && "Cannot erase instruction that is used!");
299 AddUsesToWorkList(I);
300 RemoveFromWorkList(&I);
302 return 0; // Don't do anything with FI
306 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307 /// InsertBefore instruction. This is specialized a bit to avoid inserting
308 /// casts that are known to not do anything...
310 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311 Value *V, const Type *DestTy,
312 Instruction *InsertBefore);
314 /// SimplifyCommutative - This performs a few simplifications for
315 /// commutative operators.
316 bool SimplifyCommutative(BinaryOperator &I);
318 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319 /// most-complex to least-complex order.
320 bool SimplifyCompare(CmpInst &I);
322 bool SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
323 uint64_t &KnownZero, uint64_t &KnownOne,
326 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
327 APInt& KnownZero, APInt& KnownOne,
330 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
331 uint64_t &UndefElts, unsigned Depth = 0);
333 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
334 // PHI node as operand #0, see if we can fold the instruction into the PHI
335 // (which is only possible if all operands to the PHI are constants).
336 Instruction *FoldOpIntoPhi(Instruction &I);
338 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
339 // operator and they all are only used by the PHI, PHI together their
340 // inputs, and do the operation once, to the result of the PHI.
341 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
342 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
345 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
346 ConstantInt *AndRHS, BinaryOperator &TheAnd);
348 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
349 bool isSub, Instruction &I);
350 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
351 bool isSigned, bool Inside, Instruction &IB);
352 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
353 Instruction *MatchBSwap(BinaryOperator &I);
355 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
358 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
361 // getComplexity: Assign a complexity or rank value to LLVM Values...
362 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
363 static unsigned getComplexity(Value *V) {
364 if (isa<Instruction>(V)) {
365 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
369 if (isa<Argument>(V)) return 3;
370 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
373 // isOnlyUse - Return true if this instruction will be deleted if we stop using
375 static bool isOnlyUse(Value *V) {
376 return V->hasOneUse() || isa<Constant>(V);
379 // getPromotedType - Return the specified type promoted as it would be to pass
380 // though a va_arg area...
381 static const Type *getPromotedType(const Type *Ty) {
382 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
383 if (ITy->getBitWidth() < 32)
384 return Type::Int32Ty;
385 } else if (Ty == Type::FloatTy)
386 return Type::DoubleTy;
390 /// getBitCastOperand - If the specified operand is a CastInst or a constant
391 /// expression bitcast, return the operand value, otherwise return null.
392 static Value *getBitCastOperand(Value *V) {
393 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
394 return I->getOperand(0);
395 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
396 if (CE->getOpcode() == Instruction::BitCast)
397 return CE->getOperand(0);
401 /// This function is a wrapper around CastInst::isEliminableCastPair. It
402 /// simply extracts arguments and returns what that function returns.
403 static Instruction::CastOps
404 isEliminableCastPair(
405 const CastInst *CI, ///< The first cast instruction
406 unsigned opcode, ///< The opcode of the second cast instruction
407 const Type *DstTy, ///< The target type for the second cast instruction
408 TargetData *TD ///< The target data for pointer size
411 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
412 const Type *MidTy = CI->getType(); // B from above
414 // Get the opcodes of the two Cast instructions
415 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
416 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
418 return Instruction::CastOps(
419 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
420 DstTy, TD->getIntPtrType()));
423 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
424 /// in any code being generated. It does not require codegen if V is simple
425 /// enough or if the cast can be folded into other casts.
426 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
427 const Type *Ty, TargetData *TD) {
428 if (V->getType() == Ty || isa<Constant>(V)) return false;
430 // If this is another cast that can be eliminated, it isn't codegen either.
431 if (const CastInst *CI = dyn_cast<CastInst>(V))
432 if (isEliminableCastPair(CI, opcode, Ty, TD))
437 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
438 /// InsertBefore instruction. This is specialized a bit to avoid inserting
439 /// casts that are known to not do anything...
441 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
442 Value *V, const Type *DestTy,
443 Instruction *InsertBefore) {
444 if (V->getType() == DestTy) return V;
445 if (Constant *C = dyn_cast<Constant>(V))
446 return ConstantExpr::getCast(opcode, C, DestTy);
448 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
451 // SimplifyCommutative - This performs a few simplifications for commutative
454 // 1. Order operands such that they are listed from right (least complex) to
455 // left (most complex). This puts constants before unary operators before
458 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
459 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
461 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
462 bool Changed = false;
463 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
464 Changed = !I.swapOperands();
466 if (!I.isAssociative()) return Changed;
467 Instruction::BinaryOps Opcode = I.getOpcode();
468 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
469 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
470 if (isa<Constant>(I.getOperand(1))) {
471 Constant *Folded = ConstantExpr::get(I.getOpcode(),
472 cast<Constant>(I.getOperand(1)),
473 cast<Constant>(Op->getOperand(1)));
474 I.setOperand(0, Op->getOperand(0));
475 I.setOperand(1, Folded);
477 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
478 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
479 isOnlyUse(Op) && isOnlyUse(Op1)) {
480 Constant *C1 = cast<Constant>(Op->getOperand(1));
481 Constant *C2 = cast<Constant>(Op1->getOperand(1));
483 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
484 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
485 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
489 I.setOperand(0, New);
490 I.setOperand(1, Folded);
497 /// SimplifyCompare - For a CmpInst this function just orders the operands
498 /// so that theyare listed from right (least complex) to left (most complex).
499 /// This puts constants before unary operators before binary operators.
500 bool InstCombiner::SimplifyCompare(CmpInst &I) {
501 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
504 // Compare instructions are not associative so there's nothing else we can do.
508 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
509 // if the LHS is a constant zero (which is the 'negate' form).
511 static inline Value *dyn_castNegVal(Value *V) {
512 if (BinaryOperator::isNeg(V))
513 return BinaryOperator::getNegArgument(V);
515 // Constants can be considered to be negated values if they can be folded.
516 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
517 return ConstantExpr::getNeg(C);
521 static inline Value *dyn_castNotVal(Value *V) {
522 if (BinaryOperator::isNot(V))
523 return BinaryOperator::getNotArgument(V);
525 // Constants can be considered to be not'ed values...
526 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
527 return ConstantExpr::getNot(C);
531 // dyn_castFoldableMul - If this value is a multiply that can be folded into
532 // other computations (because it has a constant operand), return the
533 // non-constant operand of the multiply, and set CST to point to the multiplier.
534 // Otherwise, return null.
536 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
537 if (V->hasOneUse() && V->getType()->isInteger())
538 if (Instruction *I = dyn_cast<Instruction>(V)) {
539 if (I->getOpcode() == Instruction::Mul)
540 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
541 return I->getOperand(0);
542 if (I->getOpcode() == Instruction::Shl)
543 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
544 // The multiplier is really 1 << CST.
545 Constant *One = ConstantInt::get(V->getType(), 1);
546 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
547 return I->getOperand(0);
553 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
554 /// expression, return it.
555 static User *dyn_castGetElementPtr(Value *V) {
556 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
557 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
558 if (CE->getOpcode() == Instruction::GetElementPtr)
559 return cast<User>(V);
563 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
564 static ConstantInt *AddOne(ConstantInt *C) {
565 return cast<ConstantInt>(ConstantExpr::getAdd(C,
566 ConstantInt::get(C->getType(), 1)));
568 static ConstantInt *SubOne(ConstantInt *C) {
569 return cast<ConstantInt>(ConstantExpr::getSub(C,
570 ConstantInt::get(C->getType(), 1)));
573 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
574 /// known to be either zero or one and return them in the KnownZero/KnownOne
575 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
577 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
578 /// we cannot optimize based on the assumption that it is zero without changing
579 /// it to be an explicit zero. If we don't change it to zero, other code could
580 /// optimized based on the contradictory assumption that it is non-zero.
581 /// Because instcombine aggressively folds operations with undef args anyway,
582 /// this won't lose us code quality.
583 static void ComputeMaskedBits(Value *V, APInt Mask, APInt& KnownZero,
584 APInt& KnownOne, unsigned Depth = 0) {
585 assert(V && "No Value?");
586 assert(Depth <= 6 && "Limit Search Depth");
587 uint32_t BitWidth = Mask.getBitWidth();
588 const IntegerType *VTy = cast<IntegerType>(V->getType());
589 assert(VTy->getBitWidth() == BitWidth &&
590 KnownZero.getBitWidth() == BitWidth &&
591 KnownOne.getBitWidth() == BitWidth &&
592 "VTy, Mask, KnownOne and KnownZero should have same BitWidth");
593 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
594 // We know all of the bits for a constant!
595 KnownOne = CI->getValue() & Mask;
596 KnownZero = ~KnownOne & Mask;
600 if (Depth == 6 || Mask == 0)
601 return; // Limit search depth.
603 Instruction *I = dyn_cast<Instruction>(V);
606 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
607 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
608 Mask &= APInt::getAllOnesValue(BitWidth);
610 switch (I->getOpcode()) {
611 case Instruction::And:
612 // If either the LHS or the RHS are Zero, the result is zero.
613 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
615 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
616 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
617 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
619 // Output known-1 bits are only known if set in both the LHS & RHS.
620 KnownOne &= KnownOne2;
621 // Output known-0 are known to be clear if zero in either the LHS | RHS.
622 KnownZero |= KnownZero2;
624 case Instruction::Or:
625 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
627 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
628 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
629 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
631 // Output known-0 bits are only known if clear in both the LHS & RHS.
632 KnownZero &= KnownZero2;
633 // Output known-1 are known to be set if set in either the LHS | RHS.
634 KnownOne |= KnownOne2;
636 case Instruction::Xor: {
637 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
638 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
639 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
640 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
642 // Output known-0 bits are known if clear or set in both the LHS & RHS.
643 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
644 // Output known-1 are known to be set if set in only one of the LHS, RHS.
645 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
646 KnownZero = KnownZeroOut;
649 case Instruction::Select:
650 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
651 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
652 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
653 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
655 // Only known if known in both the LHS and RHS.
656 KnownOne &= KnownOne2;
657 KnownZero &= KnownZero2;
659 case Instruction::FPTrunc:
660 case Instruction::FPExt:
661 case Instruction::FPToUI:
662 case Instruction::FPToSI:
663 case Instruction::SIToFP:
664 case Instruction::PtrToInt:
665 case Instruction::UIToFP:
666 case Instruction::IntToPtr:
667 return; // Can't work with floating point or pointers
668 case Instruction::Trunc: {
669 // All these have integer operands
670 uint32_t SrcBitWidth =
671 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
672 ComputeMaskedBits(I->getOperand(0), Mask.zext(SrcBitWidth),
673 KnownZero.zext(SrcBitWidth), KnownOne.zext(SrcBitWidth), Depth+1);
674 KnownZero.trunc(BitWidth);
675 KnownOne.trunc(BitWidth);
678 case Instruction::BitCast: {
679 const Type *SrcTy = I->getOperand(0)->getType();
680 if (SrcTy->isInteger()) {
681 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
686 case Instruction::ZExt: {
687 // Compute the bits in the result that are not present in the input.
688 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
689 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
691 uint32_t SrcBitWidth = SrcTy->getBitWidth();
692 ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth),
693 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
694 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
695 // The top bits are known to be zero.
696 KnownZero.zext(BitWidth);
697 KnownOne.zext(BitWidth);
698 KnownZero |= NewBits;
701 case Instruction::SExt: {
702 // Compute the bits in the result that are not present in the input.
703 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
704 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
706 uint32_t SrcBitWidth = SrcTy->getBitWidth();
707 ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth),
708 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
709 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
710 KnownZero.zext(BitWidth);
711 KnownOne.zext(BitWidth);
713 // If the sign bit of the input is known set or clear, then we know the
714 // top bits of the result.
715 APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
716 InSignBit.zext(BitWidth);
717 if ((KnownZero & InSignBit) != 0) { // Input sign bit known zero
718 KnownZero |= NewBits;
719 KnownOne &= ~NewBits;
720 } else if ((KnownOne & InSignBit) != 0) { // Input sign bit known set
722 KnownZero &= ~NewBits;
723 } else { // Input sign bit unknown
724 KnownZero &= ~NewBits;
725 KnownOne &= ~NewBits;
729 case Instruction::Shl:
730 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
731 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
732 uint64_t ShiftAmt = SA->getZExtValue();
733 Mask = APIntOps::lshr(Mask, ShiftAmt);
734 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
735 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
736 KnownZero <<= ShiftAmt;
737 KnownOne <<= ShiftAmt;
738 KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1; // low bits known zero.
742 case Instruction::LShr:
743 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
744 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
745 // Compute the new bits that are at the top now.
746 uint64_t ShiftAmt = SA->getZExtValue();
747 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
749 // Unsigned shift right.
751 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
753 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
754 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
755 KnownZero |= HighBits; // high bits known zero.
759 case Instruction::AShr:
760 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
761 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
762 // Compute the new bits that are at the top now.
763 uint64_t ShiftAmt = SA->getZExtValue();
764 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
766 // Signed shift right.
768 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
769 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
770 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
771 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
773 // Handle the sign bits and adjust to where it is now in the mask.
774 APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
776 if ((KnownZero & SignBit) != 0) { // New bits are known zero.
777 KnownZero |= HighBits;
778 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
779 KnownOne |= HighBits;
787 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
788 /// known to be either zero or one and return them in the KnownZero/KnownOne
789 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
791 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
792 uint64_t &KnownOne, unsigned Depth = 0) {
793 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
794 // we cannot optimize based on the assumption that it is zero without changing
795 // it to be an explicit zero. If we don't change it to zero, other code could
796 // optimized based on the contradictory assumption that it is non-zero.
797 // Because instcombine aggressively folds operations with undef args anyway,
798 // this won't lose us code quality.
799 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800 // We know all of the bits for a constant!
801 KnownOne = CI->getZExtValue() & Mask;
802 KnownZero = ~KnownOne & Mask;
806 KnownZero = KnownOne = 0; // Don't know anything.
807 if (Depth == 6 || Mask == 0)
808 return; // Limit search depth.
810 uint64_t KnownZero2, KnownOne2;
811 Instruction *I = dyn_cast<Instruction>(V);
814 Mask &= cast<IntegerType>(V->getType())->getBitMask();
816 switch (I->getOpcode()) {
817 case Instruction::And:
818 // If either the LHS or the RHS are Zero, the result is zero.
819 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
821 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
822 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
823 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
825 // Output known-1 bits are only known if set in both the LHS & RHS.
826 KnownOne &= KnownOne2;
827 // Output known-0 are known to be clear if zero in either the LHS | RHS.
828 KnownZero |= KnownZero2;
830 case Instruction::Or:
831 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
833 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
834 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
835 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
837 // Output known-0 bits are only known if clear in both the LHS & RHS.
838 KnownZero &= KnownZero2;
839 // Output known-1 are known to be set if set in either the LHS | RHS.
840 KnownOne |= KnownOne2;
842 case Instruction::Xor: {
843 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
844 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
845 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
846 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
848 // Output known-0 bits are known if clear or set in both the LHS & RHS.
849 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
850 // Output known-1 are known to be set if set in only one of the LHS, RHS.
851 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
852 KnownZero = KnownZeroOut;
855 case Instruction::Select:
856 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
857 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
859 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
861 // Only known if known in both the LHS and RHS.
862 KnownOne &= KnownOne2;
863 KnownZero &= KnownZero2;
865 case Instruction::FPTrunc:
866 case Instruction::FPExt:
867 case Instruction::FPToUI:
868 case Instruction::FPToSI:
869 case Instruction::SIToFP:
870 case Instruction::PtrToInt:
871 case Instruction::UIToFP:
872 case Instruction::IntToPtr:
873 return; // Can't work with floating point or pointers
874 case Instruction::Trunc:
875 // All these have integer operands
876 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
878 case Instruction::BitCast: {
879 const Type *SrcTy = I->getOperand(0)->getType();
880 if (SrcTy->isInteger()) {
881 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
886 case Instruction::ZExt: {
887 // Compute the bits in the result that are not present in the input.
888 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
889 uint64_t NotIn = ~SrcTy->getBitMask();
890 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
892 Mask &= SrcTy->getBitMask();
893 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
894 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
895 // The top bits are known to be zero.
896 KnownZero |= NewBits;
899 case Instruction::SExt: {
900 // Compute the bits in the result that are not present in the input.
901 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
902 uint64_t NotIn = ~SrcTy->getBitMask();
903 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
905 Mask &= SrcTy->getBitMask();
906 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
907 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
909 // If the sign bit of the input is known set or clear, then we know the
910 // top bits of the result.
911 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
912 if (KnownZero & InSignBit) { // Input sign bit known zero
913 KnownZero |= NewBits;
914 KnownOne &= ~NewBits;
915 } else if (KnownOne & InSignBit) { // Input sign bit known set
917 KnownZero &= ~NewBits;
918 } else { // Input sign bit unknown
919 KnownZero &= ~NewBits;
920 KnownOne &= ~NewBits;
924 case Instruction::Shl:
925 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
926 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
927 uint64_t ShiftAmt = SA->getZExtValue();
929 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
930 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
931 KnownZero <<= ShiftAmt;
932 KnownOne <<= ShiftAmt;
933 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
937 case Instruction::LShr:
938 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
939 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
940 // Compute the new bits that are at the top now.
941 uint64_t ShiftAmt = SA->getZExtValue();
942 uint64_t HighBits = (1ULL << ShiftAmt)-1;
943 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
945 // Unsigned shift right.
947 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
948 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
949 KnownZero >>= ShiftAmt;
950 KnownOne >>= ShiftAmt;
951 KnownZero |= HighBits; // high bits known zero.
955 case Instruction::AShr:
956 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
957 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
958 // Compute the new bits that are at the top now.
959 uint64_t ShiftAmt = SA->getZExtValue();
960 uint64_t HighBits = (1ULL << ShiftAmt)-1;
961 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
963 // Signed shift right.
965 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
966 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
967 KnownZero >>= ShiftAmt;
968 KnownOne >>= ShiftAmt;
970 // Handle the sign bits.
971 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
972 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
974 if (KnownZero & SignBit) { // New bits are known zero.
975 KnownZero |= HighBits;
976 } else if (KnownOne & SignBit) { // New bits are known one.
977 KnownOne |= HighBits;
985 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
986 /// this predicate to simplify operations downstream. Mask is known to be zero
987 /// for bits that V cannot have.
988 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
989 uint64_t KnownZero, KnownOne;
990 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
991 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
992 return (KnownZero & Mask) == Mask;
996 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
997 /// this predicate to simplify operations downstream. Mask is known to be zero
998 /// for bits that V cannot have.
999 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
1000 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1001 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1002 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1003 return (KnownZero & Mask) == Mask;
1007 /// ShrinkDemandedConstant - Check to see if the specified operand of the
1008 /// specified instruction is a constant integer. If so, check to see if there
1009 /// are any bits set in the constant that are not demanded. If so, shrink the
1010 /// constant and return true.
1011 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1012 uint64_t Demanded) {
1013 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1014 if (!OpC) return false;
1016 // If there are no bits set that aren't demanded, nothing to do.
1017 if ((~Demanded & OpC->getZExtValue()) == 0)
1020 // This is producing any bits that are not needed, shrink the RHS.
1021 uint64_t Val = Demanded & OpC->getZExtValue();
1022 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
1026 /// ShrinkDemandedConstant - Check to see if the specified operand of the
1027 /// specified instruction is a constant integer. If so, check to see if there
1028 /// are any bits set in the constant that are not demanded. If so, shrink the
1029 /// constant and return true.
1030 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1032 assert(I && "No instruction?");
1033 assert(OpNo < I->getNumOperands() && "Operand index too large");
1035 // If the operand is not a constant integer, nothing to do.
1036 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1037 if (!OpC) return false;
1039 // If there are no bits set that aren't demanded, nothing to do.
1040 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1041 if ((~Demanded & OpC->getValue()) == 0)
1044 // This instruction is producing bits that are not demanded. Shrink the RHS.
1045 Demanded &= OpC->getValue();
1046 I->setOperand(OpNo, ConstantInt::get(Demanded));
1050 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1051 // set of known zero and one bits, compute the maximum and minimum values that
1052 // could have the specified known zero and known one bits, returning them in
1054 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1057 int64_t &Min, int64_t &Max) {
1058 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
1059 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1061 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
1063 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1064 // bit if it is unknown.
1066 Max = KnownOne|UnknownBits;
1068 if (SignBit & UnknownBits) { // Sign bit is unknown
1073 // Sign extend the min/max values.
1074 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
1075 Min = (Min << ShAmt) >> ShAmt;
1076 Max = (Max << ShAmt) >> ShAmt;
1079 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1080 // a set of known zero and one bits, compute the maximum and minimum values that
1081 // could have the specified known zero and known one bits, returning them in
1083 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1088 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
1089 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1091 // The minimum value is when the unknown bits are all zeros.
1093 // The maximum value is when the unknown bits are all ones.
1094 Max = KnownOne|UnknownBits;
1098 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
1099 /// DemandedMask bits of the result of V are ever used downstream. If we can
1100 /// use this information to simplify V, do so and return true. Otherwise,
1101 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
1102 /// the expression (used to simplify the caller). The KnownZero/One bits may
1103 /// only be accurate for those bits in the DemandedMask.
1104 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1105 uint64_t &KnownZero, uint64_t &KnownOne,
1107 const IntegerType *VTy = cast<IntegerType>(V->getType());
1108 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1109 // We know all of the bits for a constant!
1110 KnownOne = CI->getZExtValue() & DemandedMask;
1111 KnownZero = ~KnownOne & DemandedMask;
1115 KnownZero = KnownOne = 0;
1116 if (!V->hasOneUse()) { // Other users may use these bits.
1117 if (Depth != 0) { // Not at the root.
1118 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1119 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1122 // If this is the root being simplified, allow it to have multiple uses,
1123 // just set the DemandedMask to all bits.
1124 DemandedMask = VTy->getBitMask();
1125 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1126 if (V != UndefValue::get(VTy))
1127 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1129 } else if (Depth == 6) { // Limit search depth.
1133 Instruction *I = dyn_cast<Instruction>(V);
1134 if (!I) return false; // Only analyze instructions.
1136 DemandedMask &= VTy->getBitMask();
1138 uint64_t KnownZero2 = 0, KnownOne2 = 0;
1139 switch (I->getOpcode()) {
1141 case Instruction::And:
1142 // If either the LHS or the RHS are Zero, the result is zero.
1143 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1144 KnownZero, KnownOne, Depth+1))
1146 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1148 // If something is known zero on the RHS, the bits aren't demanded on the
1150 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1151 KnownZero2, KnownOne2, Depth+1))
1153 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1155 // If all of the demanded bits are known 1 on one side, return the other.
1156 // These bits cannot contribute to the result of the 'and'.
1157 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1158 return UpdateValueUsesWith(I, I->getOperand(0));
1159 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1160 return UpdateValueUsesWith(I, I->getOperand(1));
1162 // If all of the demanded bits in the inputs are known zeros, return zero.
1163 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
1164 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1166 // If the RHS is a constant, see if we can simplify it.
1167 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
1168 return UpdateValueUsesWith(I, I);
1170 // Output known-1 bits are only known if set in both the LHS & RHS.
1171 KnownOne &= KnownOne2;
1172 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1173 KnownZero |= KnownZero2;
1175 case Instruction::Or:
1176 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1177 KnownZero, KnownOne, Depth+1))
1179 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1180 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
1181 KnownZero2, KnownOne2, Depth+1))
1183 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1185 // If all of the demanded bits are known zero on one side, return the other.
1186 // These bits cannot contribute to the result of the 'or'.
1187 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
1188 return UpdateValueUsesWith(I, I->getOperand(0));
1189 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
1190 return UpdateValueUsesWith(I, I->getOperand(1));
1192 // If all of the potentially set bits on one side are known to be set on
1193 // the other side, just use the 'other' side.
1194 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
1195 (DemandedMask & (~KnownZero)))
1196 return UpdateValueUsesWith(I, I->getOperand(0));
1197 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
1198 (DemandedMask & (~KnownZero2)))
1199 return UpdateValueUsesWith(I, I->getOperand(1));
1201 // If the RHS is a constant, see if we can simplify it.
1202 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1203 return UpdateValueUsesWith(I, I);
1205 // Output known-0 bits are only known if clear in both the LHS & RHS.
1206 KnownZero &= KnownZero2;
1207 // Output known-1 are known to be set if set in either the LHS | RHS.
1208 KnownOne |= KnownOne2;
1210 case Instruction::Xor: {
1211 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1212 KnownZero, KnownOne, Depth+1))
1214 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1215 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1216 KnownZero2, KnownOne2, Depth+1))
1218 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1220 // If all of the demanded bits are known zero on one side, return the other.
1221 // These bits cannot contribute to the result of the 'xor'.
1222 if ((DemandedMask & KnownZero) == DemandedMask)
1223 return UpdateValueUsesWith(I, I->getOperand(0));
1224 if ((DemandedMask & KnownZero2) == DemandedMask)
1225 return UpdateValueUsesWith(I, I->getOperand(1));
1227 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1228 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1229 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1230 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1232 // If all of the demanded bits are known to be zero on one side or the
1233 // other, turn this into an *inclusive* or.
1234 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1235 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1237 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1239 InsertNewInstBefore(Or, *I);
1240 return UpdateValueUsesWith(I, Or);
1243 // If all of the demanded bits on one side are known, and all of the set
1244 // bits on that side are also known to be set on the other side, turn this
1245 // into an AND, as we know the bits will be cleared.
1246 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1247 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1248 if ((KnownOne & KnownOne2) == KnownOne) {
1249 Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
1251 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1252 InsertNewInstBefore(And, *I);
1253 return UpdateValueUsesWith(I, And);
1257 // If the RHS is a constant, see if we can simplify it.
1258 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1259 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1260 return UpdateValueUsesWith(I, I);
1262 KnownZero = KnownZeroOut;
1263 KnownOne = KnownOneOut;
1266 case Instruction::Select:
1267 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1268 KnownZero, KnownOne, Depth+1))
1270 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1271 KnownZero2, KnownOne2, Depth+1))
1273 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1274 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1276 // If the operands are constants, see if we can simplify them.
1277 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1278 return UpdateValueUsesWith(I, I);
1279 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1280 return UpdateValueUsesWith(I, I);
1282 // Only known if known in both the LHS and RHS.
1283 KnownOne &= KnownOne2;
1284 KnownZero &= KnownZero2;
1286 case Instruction::Trunc:
1287 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1288 KnownZero, KnownOne, Depth+1))
1290 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1292 case Instruction::BitCast:
1293 if (!I->getOperand(0)->getType()->isInteger())
1296 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1297 KnownZero, KnownOne, Depth+1))
1299 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1301 case Instruction::ZExt: {
1302 // Compute the bits in the result that are not present in the input.
1303 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1304 uint64_t NotIn = ~SrcTy->getBitMask();
1305 uint64_t NewBits = VTy->getBitMask() & NotIn;
1307 DemandedMask &= SrcTy->getBitMask();
1308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1309 KnownZero, KnownOne, Depth+1))
1311 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1312 // The top bits are known to be zero.
1313 KnownZero |= NewBits;
1316 case Instruction::SExt: {
1317 // Compute the bits in the result that are not present in the input.
1318 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1319 uint64_t NotIn = ~SrcTy->getBitMask();
1320 uint64_t NewBits = VTy->getBitMask() & NotIn;
1322 // Get the sign bit for the source type
1323 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1324 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
1326 // If any of the sign extended bits are demanded, we know that the sign
1328 if (NewBits & DemandedMask)
1329 InputDemandedBits |= InSignBit;
1331 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1332 KnownZero, KnownOne, Depth+1))
1334 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1336 // If the sign bit of the input is known set or clear, then we know the
1337 // top bits of the result.
1339 // If the input sign bit is known zero, or if the NewBits are not demanded
1340 // convert this into a zero extension.
1341 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1342 // Convert to ZExt cast
1343 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1344 return UpdateValueUsesWith(I, NewCast);
1345 } else if (KnownOne & InSignBit) { // Input sign bit known set
1346 KnownOne |= NewBits;
1347 KnownZero &= ~NewBits;
1348 } else { // Input sign bit unknown
1349 KnownZero &= ~NewBits;
1350 KnownOne &= ~NewBits;
1354 case Instruction::Add:
1355 // If there is a constant on the RHS, there are a variety of xformations
1357 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1358 // If null, this should be simplified elsewhere. Some of the xforms here
1359 // won't work if the RHS is zero.
1360 if (RHS->isNullValue())
1363 // Figure out what the input bits are. If the top bits of the and result
1364 // are not demanded, then the add doesn't demand them from its input
1367 // Shift the demanded mask up so that it's at the top of the uint64_t.
1368 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
1369 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1371 // If the top bit of the output is demanded, demand everything from the
1372 // input. Otherwise, we demand all the input bits except NLZ top bits.
1373 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1375 // Find information about known zero/one bits in the input.
1376 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1377 KnownZero2, KnownOne2, Depth+1))
1380 // If the RHS of the add has bits set that can't affect the input, reduce
1382 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1383 return UpdateValueUsesWith(I, I);
1385 // Avoid excess work.
1386 if (KnownZero2 == 0 && KnownOne2 == 0)
1389 // Turn it into OR if input bits are zero.
1390 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1392 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1394 InsertNewInstBefore(Or, *I);
1395 return UpdateValueUsesWith(I, Or);
1398 // We can say something about the output known-zero and known-one bits,
1399 // depending on potential carries from the input constant and the
1400 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1401 // bits set and the RHS constant is 0x01001, then we know we have a known
1402 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1404 // To compute this, we first compute the potential carry bits. These are
1405 // the bits which may be modified. I'm not aware of a better way to do
1407 uint64_t RHSVal = RHS->getZExtValue();
1409 bool CarryIn = false;
1410 uint64_t CarryBits = 0;
1411 uint64_t CurBit = 1;
1412 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1413 // Record the current carry in.
1414 if (CarryIn) CarryBits |= CurBit;
1418 // This bit has a carry out unless it is "zero + zero" or
1419 // "zero + anything" with no carry in.
1420 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1421 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1422 } else if (!CarryIn &&
1423 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1424 CarryOut = false; // 0 + anything has no carry out if no carry in.
1426 // Otherwise, we have to assume we have a carry out.
1430 // This stage's carry out becomes the next stage's carry-in.
1434 // Now that we know which bits have carries, compute the known-1/0 sets.
1436 // Bits are known one if they are known zero in one operand and one in the
1437 // other, and there is no input carry.
1438 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1440 // Bits are known zero if they are known zero in both operands and there
1441 // is no input carry.
1442 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1444 // If the high-bits of this ADD are not demanded, then it does not demand
1445 // the high bits of its LHS or RHS.
1446 if ((DemandedMask & VTy->getSignBit()) == 0) {
1447 // Right fill the mask of bits for this ADD to demand the most
1448 // significant bit and all those below it.
1449 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1450 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1451 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1452 KnownZero2, KnownOne2, Depth+1))
1454 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1455 KnownZero2, KnownOne2, Depth+1))
1460 case Instruction::Sub:
1461 // If the high-bits of this SUB are not demanded, then it does not demand
1462 // the high bits of its LHS or RHS.
1463 if ((DemandedMask & VTy->getSignBit()) == 0) {
1464 // Right fill the mask of bits for this SUB to demand the most
1465 // significant bit and all those below it.
1466 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1467 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1468 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1469 KnownZero2, KnownOne2, Depth+1))
1471 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1472 KnownZero2, KnownOne2, Depth+1))
1476 case Instruction::Shl:
1477 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1478 uint64_t ShiftAmt = SA->getZExtValue();
1479 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
1480 KnownZero, KnownOne, Depth+1))
1482 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1483 KnownZero <<= ShiftAmt;
1484 KnownOne <<= ShiftAmt;
1485 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
1488 case Instruction::LShr:
1489 // For a logical shift right
1490 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1491 unsigned ShiftAmt = SA->getZExtValue();
1493 // Compute the new bits that are at the top now.
1494 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1495 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1496 uint64_t TypeMask = VTy->getBitMask();
1497 // Unsigned shift right.
1498 if (SimplifyDemandedBits(I->getOperand(0),
1499 (DemandedMask << ShiftAmt) & TypeMask,
1500 KnownZero, KnownOne, Depth+1))
1502 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1503 KnownZero &= TypeMask;
1504 KnownOne &= TypeMask;
1505 KnownZero >>= ShiftAmt;
1506 KnownOne >>= ShiftAmt;
1507 KnownZero |= HighBits; // high bits known zero.
1510 case Instruction::AShr:
1511 // If this is an arithmetic shift right and only the low-bit is set, we can
1512 // always convert this into a logical shr, even if the shift amount is
1513 // variable. The low bit of the shift cannot be an input sign bit unless
1514 // the shift amount is >= the size of the datatype, which is undefined.
1515 if (DemandedMask == 1) {
1516 // Perform the logical shift right.
1517 Value *NewVal = BinaryOperator::createLShr(
1518 I->getOperand(0), I->getOperand(1), I->getName());
1519 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1520 return UpdateValueUsesWith(I, NewVal);
1523 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1524 unsigned ShiftAmt = SA->getZExtValue();
1526 // Compute the new bits that are at the top now.
1527 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1528 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1529 uint64_t TypeMask = VTy->getBitMask();
1530 // Signed shift right.
1531 if (SimplifyDemandedBits(I->getOperand(0),
1532 (DemandedMask << ShiftAmt) & TypeMask,
1533 KnownZero, KnownOne, Depth+1))
1535 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1536 KnownZero &= TypeMask;
1537 KnownOne &= TypeMask;
1538 KnownZero >>= ShiftAmt;
1539 KnownOne >>= ShiftAmt;
1541 // Handle the sign bits.
1542 uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
1543 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
1545 // If the input sign bit is known to be zero, or if none of the top bits
1546 // are demanded, turn this into an unsigned shift right.
1547 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1548 // Perform the logical shift right.
1549 Value *NewVal = BinaryOperator::createLShr(
1550 I->getOperand(0), SA, I->getName());
1551 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1552 return UpdateValueUsesWith(I, NewVal);
1553 } else if (KnownOne & SignBit) { // New bits are known one.
1554 KnownOne |= HighBits;
1560 // If the client is only demanding bits that we know, return the known
1562 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1563 return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
1567 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1568 /// value based on the demanded bits. When this function is called, it is known
1569 /// that only the bits set in DemandedMask of the result of V are ever used
1570 /// downstream. Consequently, depending on the mask and V, it may be possible
1571 /// to replace V with a constant or one of its operands. In such cases, this
1572 /// function does the replacement and returns true. In all other cases, it
1573 /// returns false after analyzing the expression and setting KnownOne and known
1574 /// to be one in the expression. KnownZero contains all the bits that are known
1575 /// to be zero in the expression. These are provided to potentially allow the
1576 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1577 /// the expression. KnownOne and KnownZero always follow the invariant that
1578 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1579 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1580 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1581 /// and KnownOne must all be the same.
1582 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1583 APInt& KnownZero, APInt& KnownOne,
1585 assert(V != 0 && "Null pointer of Value???");
1586 assert(Depth <= 6 && "Limit Search Depth");
1587 uint32_t BitWidth = DemandedMask.getBitWidth();
1588 const IntegerType *VTy = cast<IntegerType>(V->getType());
1589 assert(VTy->getBitWidth() == BitWidth &&
1590 KnownZero.getBitWidth() == BitWidth &&
1591 KnownOne.getBitWidth() == BitWidth &&
1592 "Value *V, DemandedMask, KnownZero and KnownOne \
1593 must have same BitWidth");
1594 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1595 // We know all of the bits for a constant!
1596 KnownOne = CI->getValue() & DemandedMask;
1597 KnownZero = ~KnownOne & DemandedMask;
1603 if (!V->hasOneUse()) { // Other users may use these bits.
1604 if (Depth != 0) { // Not at the root.
1605 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1606 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1609 // If this is the root being simplified, allow it to have multiple uses,
1610 // just set the DemandedMask to all bits.
1611 DemandedMask = APInt::getAllOnesValue(BitWidth);
1612 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1613 if (V != UndefValue::get(VTy))
1614 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1616 } else if (Depth == 6) { // Limit search depth.
1620 Instruction *I = dyn_cast<Instruction>(V);
1621 if (!I) return false; // Only analyze instructions.
1623 DemandedMask &= APInt::getAllOnesValue(BitWidth);
1625 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1626 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1627 switch (I->getOpcode()) {
1629 case Instruction::And:
1630 // If either the LHS or the RHS are Zero, the result is zero.
1631 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1632 RHSKnownZero, RHSKnownOne, Depth+1))
1634 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1635 "Bits known to be one AND zero?");
1637 // If something is known zero on the RHS, the bits aren't demanded on the
1639 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1640 LHSKnownZero, LHSKnownOne, Depth+1))
1642 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1643 "Bits known to be one AND zero?");
1645 // If all of the demanded bits are known 1 on one side, return the other.
1646 // These bits cannot contribute to the result of the 'and'.
1647 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1648 (DemandedMask & ~LHSKnownZero))
1649 return UpdateValueUsesWith(I, I->getOperand(0));
1650 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1651 (DemandedMask & ~RHSKnownZero))
1652 return UpdateValueUsesWith(I, I->getOperand(1));
1654 // If all of the demanded bits in the inputs are known zeros, return zero.
1655 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1656 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1658 // If the RHS is a constant, see if we can simplify it.
1659 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1660 return UpdateValueUsesWith(I, I);
1662 // Output known-1 bits are only known if set in both the LHS & RHS.
1663 RHSKnownOne &= LHSKnownOne;
1664 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1665 RHSKnownZero |= LHSKnownZero;
1667 case Instruction::Or:
1668 // If either the LHS or the RHS are One, the result is One.
1669 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1670 RHSKnownZero, RHSKnownOne, Depth+1))
1672 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1673 "Bits known to be one AND zero?");
1674 // If something is known one on the RHS, the bits aren't demanded on the
1676 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1677 LHSKnownZero, LHSKnownOne, Depth+1))
1679 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1680 "Bits known to be one AND zero?");
1682 // If all of the demanded bits are known zero on one side, return the other.
1683 // These bits cannot contribute to the result of the 'or'.
1684 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1685 (DemandedMask & ~LHSKnownOne))
1686 return UpdateValueUsesWith(I, I->getOperand(0));
1687 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1688 (DemandedMask & ~RHSKnownOne))
1689 return UpdateValueUsesWith(I, I->getOperand(1));
1691 // If all of the potentially set bits on one side are known to be set on
1692 // the other side, just use the 'other' side.
1693 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1694 (DemandedMask & (~RHSKnownZero)))
1695 return UpdateValueUsesWith(I, I->getOperand(0));
1696 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1697 (DemandedMask & (~LHSKnownZero)))
1698 return UpdateValueUsesWith(I, I->getOperand(1));
1700 // If the RHS is a constant, see if we can simplify it.
1701 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1702 return UpdateValueUsesWith(I, I);
1704 // Output known-0 bits are only known if clear in both the LHS & RHS.
1705 RHSKnownZero &= LHSKnownZero;
1706 // Output known-1 are known to be set if set in either the LHS | RHS.
1707 RHSKnownOne |= LHSKnownOne;
1709 case Instruction::Xor: {
1710 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1711 RHSKnownZero, RHSKnownOne, Depth+1))
1713 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1714 "Bits known to be one AND zero?");
1715 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1716 LHSKnownZero, LHSKnownOne, Depth+1))
1718 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1719 "Bits known to be one AND zero?");
1721 // If all of the demanded bits are known zero on one side, return the other.
1722 // These bits cannot contribute to the result of the 'xor'.
1723 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1724 return UpdateValueUsesWith(I, I->getOperand(0));
1725 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1726 return UpdateValueUsesWith(I, I->getOperand(1));
1728 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1729 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1730 (RHSKnownOne & LHSKnownOne);
1731 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1732 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1733 (RHSKnownOne & LHSKnownZero);
1735 // If all of the demanded bits are known to be zero on one side or the
1736 // other, turn this into an *inclusive* or.
1737 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1738 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1740 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1742 InsertNewInstBefore(Or, *I);
1743 return UpdateValueUsesWith(I, Or);
1746 // If all of the demanded bits on one side are known, and all of the set
1747 // bits on that side are also known to be set on the other side, turn this
1748 // into an AND, as we know the bits will be cleared.
1749 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1750 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1752 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1753 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1755 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1756 InsertNewInstBefore(And, *I);
1757 return UpdateValueUsesWith(I, And);
1761 // If the RHS is a constant, see if we can simplify it.
1762 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1763 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1764 return UpdateValueUsesWith(I, I);
1766 RHSKnownZero = KnownZeroOut;
1767 RHSKnownOne = KnownOneOut;
1770 case Instruction::Select:
1771 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1772 RHSKnownZero, RHSKnownOne, Depth+1))
1774 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1775 LHSKnownZero, LHSKnownOne, Depth+1))
1777 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1778 "Bits known to be one AND zero?");
1779 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1780 "Bits known to be one AND zero?");
1782 // If the operands are constants, see if we can simplify them.
1783 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1784 return UpdateValueUsesWith(I, I);
1785 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1786 return UpdateValueUsesWith(I, I);
1788 // Only known if known in both the LHS and RHS.
1789 RHSKnownOne &= LHSKnownOne;
1790 RHSKnownZero &= LHSKnownZero;
1792 case Instruction::Trunc: {
1794 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1795 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1796 RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1798 DemandedMask.trunc(BitWidth);
1799 RHSKnownZero.trunc(BitWidth);
1800 RHSKnownOne.trunc(BitWidth);
1801 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1802 "Bits known to be one AND zero?");
1805 case Instruction::BitCast:
1806 if (!I->getOperand(0)->getType()->isInteger())
1809 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1810 RHSKnownZero, RHSKnownOne, Depth+1))
1812 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1813 "Bits known to be one AND zero?");
1815 case Instruction::ZExt: {
1816 // Compute the bits in the result that are not present in the input.
1817 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1818 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1820 DemandedMask &= SrcTy->getMask().zext(BitWidth);
1821 uint32_t zextBf = SrcTy->getBitWidth();
1822 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1823 RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1825 DemandedMask.zext(BitWidth);
1826 RHSKnownZero.zext(BitWidth);
1827 RHSKnownOne.zext(BitWidth);
1828 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1829 "Bits known to be one AND zero?");
1830 // The top bits are known to be zero.
1831 RHSKnownZero |= NewBits;
1834 case Instruction::SExt: {
1835 // Compute the bits in the result that are not present in the input.
1836 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1837 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1839 // Get the sign bit for the source type
1840 APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1841 InSignBit.zext(BitWidth);
1842 APInt InputDemandedBits = DemandedMask &
1843 SrcTy->getMask().zext(BitWidth);
1845 // If any of the sign extended bits are demanded, we know that the sign
1847 if ((NewBits & DemandedMask) != 0)
1848 InputDemandedBits |= InSignBit;
1850 uint32_t sextBf = SrcTy->getBitWidth();
1851 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1852 RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1854 InputDemandedBits.zext(BitWidth);
1855 RHSKnownZero.zext(BitWidth);
1856 RHSKnownOne.zext(BitWidth);
1857 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1858 "Bits known to be one AND zero?");
1860 // If the sign bit of the input is known set or clear, then we know the
1861 // top bits of the result.
1863 // If the input sign bit is known zero, or if the NewBits are not demanded
1864 // convert this into a zero extension.
1865 if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1867 // Convert to ZExt cast
1868 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1869 return UpdateValueUsesWith(I, NewCast);
1870 } else if ((RHSKnownOne & InSignBit) != 0) { // Input sign bit known set
1871 RHSKnownOne |= NewBits;
1872 RHSKnownZero &= ~NewBits;
1873 } else { // Input sign bit unknown
1874 RHSKnownZero &= ~NewBits;
1875 RHSKnownOne &= ~NewBits;
1879 case Instruction::Add: {
1880 // Figure out what the input bits are. If the top bits of the and result
1881 // are not demanded, then the add doesn't demand them from its input
1883 unsigned NLZ = DemandedMask.countLeadingZeros();
1885 // If there is a constant on the RHS, there are a variety of xformations
1887 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1888 // If null, this should be simplified elsewhere. Some of the xforms here
1889 // won't work if the RHS is zero.
1893 // If the top bit of the output is demanded, demand everything from the
1894 // input. Otherwise, we demand all the input bits except NLZ top bits.
1895 APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1897 // Find information about known zero/one bits in the input.
1898 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1899 LHSKnownZero, LHSKnownOne, Depth+1))
1902 // If the RHS of the add has bits set that can't affect the input, reduce
1904 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1905 return UpdateValueUsesWith(I, I);
1907 // Avoid excess work.
1908 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1911 // Turn it into OR if input bits are zero.
1912 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1914 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1916 InsertNewInstBefore(Or, *I);
1917 return UpdateValueUsesWith(I, Or);
1920 // We can say something about the output known-zero and known-one bits,
1921 // depending on potential carries from the input constant and the
1922 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1923 // bits set and the RHS constant is 0x01001, then we know we have a known
1924 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1926 // To compute this, we first compute the potential carry bits. These are
1927 // the bits which may be modified. I'm not aware of a better way to do
1929 APInt RHSVal(RHS->getValue());
1931 bool CarryIn = false;
1932 APInt CarryBits(BitWidth, 0);
1933 const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1934 *RHSRawVal = RHSVal.getRawData();
1935 for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1936 uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1937 XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1938 uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1939 if (AddVal < RHSRawVal[i])
1943 CarryBits.setWordToValue(i, WordCarryBits);
1946 // Now that we know which bits have carries, compute the known-1/0 sets.
1948 // Bits are known one if they are known zero in one operand and one in the
1949 // other, and there is no input carry.
1950 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1951 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1953 // Bits are known zero if they are known zero in both operands and there
1954 // is no input carry.
1955 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1957 // If the high-bits of this ADD are not demanded, then it does not demand
1958 // the high bits of its LHS or RHS.
1959 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1960 // Right fill the mask of bits for this ADD to demand the most
1961 // significant bit and all those below it.
1962 APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1963 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1964 LHSKnownZero, LHSKnownOne, Depth+1))
1966 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1967 LHSKnownZero, LHSKnownOne, Depth+1))
1973 case Instruction::Sub:
1974 // If the high-bits of this SUB are not demanded, then it does not demand
1975 // the high bits of its LHS or RHS.
1976 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1977 // Right fill the mask of bits for this SUB to demand the most
1978 // significant bit and all those below it.
1979 unsigned NLZ = DemandedMask.countLeadingZeros();
1980 APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1981 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1982 LHSKnownZero, LHSKnownOne, Depth+1))
1984 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1985 LHSKnownZero, LHSKnownOne, Depth+1))
1989 case Instruction::Shl:
1990 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1991 uint64_t ShiftAmt = SA->getZExtValue();
1992 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt),
1993 RHSKnownZero, RHSKnownOne, Depth+1))
1995 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1996 "Bits known to be one AND zero?");
1997 RHSKnownZero <<= ShiftAmt;
1998 RHSKnownOne <<= ShiftAmt;
1999 // low bits known zero.
2001 RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
2004 case Instruction::LShr:
2005 // For a logical shift right
2006 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2007 unsigned ShiftAmt = SA->getZExtValue();
2009 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2010 // Unsigned shift right.
2011 if (SimplifyDemandedBits(I->getOperand(0),
2012 (DemandedMask.shl(ShiftAmt)) & TypeMask,
2013 RHSKnownZero, RHSKnownOne, Depth+1))
2015 assert((RHSKnownZero & RHSKnownOne) == 0 &&
2016 "Bits known to be one AND zero?");
2017 RHSKnownZero &= TypeMask;
2018 RHSKnownOne &= TypeMask;
2019 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2020 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2022 // Compute the new bits that are at the top now.
2023 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(
2024 BitWidth - ShiftAmt));
2025 RHSKnownZero |= HighBits; // high bits known zero.
2029 case Instruction::AShr:
2030 // If this is an arithmetic shift right and only the low-bit is set, we can
2031 // always convert this into a logical shr, even if the shift amount is
2032 // variable. The low bit of the shift cannot be an input sign bit unless
2033 // the shift amount is >= the size of the datatype, which is undefined.
2034 if (DemandedMask == 1) {
2035 // Perform the logical shift right.
2036 Value *NewVal = BinaryOperator::createLShr(
2037 I->getOperand(0), I->getOperand(1), I->getName());
2038 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2039 return UpdateValueUsesWith(I, NewVal);
2042 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2043 unsigned ShiftAmt = SA->getZExtValue();
2045 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2046 // Signed shift right.
2047 if (SimplifyDemandedBits(I->getOperand(0),
2048 (DemandedMask.shl(ShiftAmt)) & TypeMask,
2049 RHSKnownZero, RHSKnownOne, Depth+1))
2051 assert((RHSKnownZero & RHSKnownOne) == 0 &&
2052 "Bits known to be one AND zero?");
2053 // Compute the new bits that are at the top now.
2054 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth - ShiftAmt));
2055 RHSKnownZero &= TypeMask;
2056 RHSKnownOne &= TypeMask;
2057 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2058 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2060 // Handle the sign bits.
2061 APInt SignBit(APInt::getSignBit(BitWidth));
2062 // Adjust to where it is now in the mask.
2063 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
2065 // If the input sign bit is known to be zero, or if none of the top bits
2066 // are demanded, turn this into an unsigned shift right.
2067 if ((RHSKnownZero & SignBit) != 0 ||
2068 (HighBits & ~DemandedMask) == HighBits) {
2069 // Perform the logical shift right.
2070 Value *NewVal = BinaryOperator::createLShr(
2071 I->getOperand(0), SA, I->getName());
2072 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2073 return UpdateValueUsesWith(I, NewVal);
2074 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
2075 RHSKnownOne |= HighBits;
2081 // If the client is only demanding bits that we know, return the known
2083 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
2084 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
2089 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
2090 /// 64 or fewer elements. DemandedElts contains the set of elements that are
2091 /// actually used by the caller. This method analyzes which elements of the
2092 /// operand are undef and returns that information in UndefElts.
2094 /// If the information about demanded elements can be used to simplify the
2095 /// operation, the operation is simplified, then the resultant value is
2096 /// returned. This returns null if no change was made.
2097 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
2098 uint64_t &UndefElts,
2100 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
2101 assert(VWidth <= 64 && "Vector too wide to analyze!");
2102 uint64_t EltMask = ~0ULL >> (64-VWidth);
2103 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
2104 "Invalid DemandedElts!");
2106 if (isa<UndefValue>(V)) {
2107 // If the entire vector is undefined, just return this info.
2108 UndefElts = EltMask;
2110 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
2111 UndefElts = EltMask;
2112 return UndefValue::get(V->getType());
2116 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
2117 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
2118 Constant *Undef = UndefValue::get(EltTy);
2120 std::vector<Constant*> Elts;
2121 for (unsigned i = 0; i != VWidth; ++i)
2122 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
2123 Elts.push_back(Undef);
2124 UndefElts |= (1ULL << i);
2125 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
2126 Elts.push_back(Undef);
2127 UndefElts |= (1ULL << i);
2128 } else { // Otherwise, defined.
2129 Elts.push_back(CP->getOperand(i));
2132 // If we changed the constant, return it.
2133 Constant *NewCP = ConstantVector::get(Elts);
2134 return NewCP != CP ? NewCP : 0;
2135 } else if (isa<ConstantAggregateZero>(V)) {
2136 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
2138 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
2139 Constant *Zero = Constant::getNullValue(EltTy);
2140 Constant *Undef = UndefValue::get(EltTy);
2141 std::vector<Constant*> Elts;
2142 for (unsigned i = 0; i != VWidth; ++i)
2143 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
2144 UndefElts = DemandedElts ^ EltMask;
2145 return ConstantVector::get(Elts);
2148 if (!V->hasOneUse()) { // Other users may use these bits.
2149 if (Depth != 0) { // Not at the root.
2150 // TODO: Just compute the UndefElts information recursively.
2154 } else if (Depth == 10) { // Limit search depth.
2158 Instruction *I = dyn_cast<Instruction>(V);
2159 if (!I) return false; // Only analyze instructions.
2161 bool MadeChange = false;
2162 uint64_t UndefElts2;
2164 switch (I->getOpcode()) {
2167 case Instruction::InsertElement: {
2168 // If this is a variable index, we don't know which element it overwrites.
2169 // demand exactly the same input as we produce.
2170 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
2172 // Note that we can't propagate undef elt info, because we don't know
2173 // which elt is getting updated.
2174 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2175 UndefElts2, Depth+1);
2176 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2180 // If this is inserting an element that isn't demanded, remove this
2182 unsigned IdxNo = Idx->getZExtValue();
2183 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
2184 return AddSoonDeadInstToWorklist(*I, 0);
2186 // Otherwise, the element inserted overwrites whatever was there, so the
2187 // input demanded set is simpler than the output set.
2188 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
2189 DemandedElts & ~(1ULL << IdxNo),
2190 UndefElts, Depth+1);
2191 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2193 // The inserted element is defined.
2194 UndefElts |= 1ULL << IdxNo;
2198 case Instruction::And:
2199 case Instruction::Or:
2200 case Instruction::Xor:
2201 case Instruction::Add:
2202 case Instruction::Sub:
2203 case Instruction::Mul:
2204 // div/rem demand all inputs, because they don't want divide by zero.
2205 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2206 UndefElts, Depth+1);
2207 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2208 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
2209 UndefElts2, Depth+1);
2210 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
2212 // Output elements are undefined if both are undefined. Consider things
2213 // like undef&0. The result is known zero, not undef.
2214 UndefElts &= UndefElts2;
2217 case Instruction::Call: {
2218 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2220 switch (II->getIntrinsicID()) {
2223 // Binary vector operations that work column-wise. A dest element is a
2224 // function of the corresponding input elements from the two inputs.
2225 case Intrinsic::x86_sse_sub_ss:
2226 case Intrinsic::x86_sse_mul_ss:
2227 case Intrinsic::x86_sse_min_ss:
2228 case Intrinsic::x86_sse_max_ss:
2229 case Intrinsic::x86_sse2_sub_sd:
2230 case Intrinsic::x86_sse2_mul_sd:
2231 case Intrinsic::x86_sse2_min_sd:
2232 case Intrinsic::x86_sse2_max_sd:
2233 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2234 UndefElts, Depth+1);
2235 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2236 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2237 UndefElts2, Depth+1);
2238 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2240 // If only the low elt is demanded and this is a scalarizable intrinsic,
2241 // scalarize it now.
2242 if (DemandedElts == 1) {
2243 switch (II->getIntrinsicID()) {
2245 case Intrinsic::x86_sse_sub_ss:
2246 case Intrinsic::x86_sse_mul_ss:
2247 case Intrinsic::x86_sse2_sub_sd:
2248 case Intrinsic::x86_sse2_mul_sd:
2249 // TODO: Lower MIN/MAX/ABS/etc
2250 Value *LHS = II->getOperand(1);
2251 Value *RHS = II->getOperand(2);
2252 // Extract the element as scalars.
2253 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2254 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2256 switch (II->getIntrinsicID()) {
2257 default: assert(0 && "Case stmts out of sync!");
2258 case Intrinsic::x86_sse_sub_ss:
2259 case Intrinsic::x86_sse2_sub_sd:
2260 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2261 II->getName()), *II);
2263 case Intrinsic::x86_sse_mul_ss:
2264 case Intrinsic::x86_sse2_mul_sd:
2265 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2266 II->getName()), *II);
2271 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
2273 InsertNewInstBefore(New, *II);
2274 AddSoonDeadInstToWorklist(*II, 0);
2279 // Output elements are undefined if both are undefined. Consider things
2280 // like undef&0. The result is known zero, not undef.
2281 UndefElts &= UndefElts2;
2287 return MadeChange ? I : 0;
2290 /// @returns true if the specified compare instruction is
2291 /// true when both operands are equal...
2292 /// @brief Determine if the ICmpInst returns true if both operands are equal
2293 static bool isTrueWhenEqual(ICmpInst &ICI) {
2294 ICmpInst::Predicate pred = ICI.getPredicate();
2295 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2296 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2297 pred == ICmpInst::ICMP_SLE;
2300 /// AssociativeOpt - Perform an optimization on an associative operator. This
2301 /// function is designed to check a chain of associative operators for a
2302 /// potential to apply a certain optimization. Since the optimization may be
2303 /// applicable if the expression was reassociated, this checks the chain, then
2304 /// reassociates the expression as necessary to expose the optimization
2305 /// opportunity. This makes use of a special Functor, which must define
2306 /// 'shouldApply' and 'apply' methods.
2308 template<typename Functor>
2309 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2310 unsigned Opcode = Root.getOpcode();
2311 Value *LHS = Root.getOperand(0);
2313 // Quick check, see if the immediate LHS matches...
2314 if (F.shouldApply(LHS))
2315 return F.apply(Root);
2317 // Otherwise, if the LHS is not of the same opcode as the root, return.
2318 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2319 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2320 // Should we apply this transform to the RHS?
2321 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2323 // If not to the RHS, check to see if we should apply to the LHS...
2324 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2325 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2329 // If the functor wants to apply the optimization to the RHS of LHSI,
2330 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2332 BasicBlock *BB = Root.getParent();
2334 // Now all of the instructions are in the current basic block, go ahead
2335 // and perform the reassociation.
2336 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2338 // First move the selected RHS to the LHS of the root...
2339 Root.setOperand(0, LHSI->getOperand(1));
2341 // Make what used to be the LHS of the root be the user of the root...
2342 Value *ExtraOperand = TmpLHSI->getOperand(1);
2343 if (&Root == TmpLHSI) {
2344 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2347 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
2348 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
2349 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2350 BasicBlock::iterator ARI = &Root; ++ARI;
2351 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2354 // Now propagate the ExtraOperand down the chain of instructions until we
2356 while (TmpLHSI != LHSI) {
2357 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2358 // Move the instruction to immediately before the chain we are
2359 // constructing to avoid breaking dominance properties.
2360 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2361 BB->getInstList().insert(ARI, NextLHSI);
2364 Value *NextOp = NextLHSI->getOperand(1);
2365 NextLHSI->setOperand(1, ExtraOperand);
2367 ExtraOperand = NextOp;
2370 // Now that the instructions are reassociated, have the functor perform
2371 // the transformation...
2372 return F.apply(Root);
2375 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2381 // AddRHS - Implements: X + X --> X << 1
2384 AddRHS(Value *rhs) : RHS(rhs) {}
2385 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2386 Instruction *apply(BinaryOperator &Add) const {
2387 return BinaryOperator::createShl(Add.getOperand(0),
2388 ConstantInt::get(Add.getType(), 1));
2392 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2394 struct AddMaskingAnd {
2396 AddMaskingAnd(Constant *c) : C2(c) {}
2397 bool shouldApply(Value *LHS) const {
2399 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2400 ConstantExpr::getAnd(C1, C2)->isNullValue();
2402 Instruction *apply(BinaryOperator &Add) const {
2403 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
2407 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2409 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2410 if (Constant *SOC = dyn_cast<Constant>(SO))
2411 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2413 return IC->InsertNewInstBefore(CastInst::create(
2414 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2417 // Figure out if the constant is the left or the right argument.
2418 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2419 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2421 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2423 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2424 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2427 Value *Op0 = SO, *Op1 = ConstOperand;
2429 std::swap(Op0, Op1);
2431 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2432 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2433 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2434 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2435 SO->getName()+".cmp");
2437 assert(0 && "Unknown binary instruction type!");
2440 return IC->InsertNewInstBefore(New, I);
2443 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2444 // constant as the other operand, try to fold the binary operator into the
2445 // select arguments. This also works for Cast instructions, which obviously do
2446 // not have a second operand.
2447 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2449 // Don't modify shared select instructions
2450 if (!SI->hasOneUse()) return 0;
2451 Value *TV = SI->getOperand(1);
2452 Value *FV = SI->getOperand(2);
2454 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2455 // Bool selects with constant operands can be folded to logical ops.
2456 if (SI->getType() == Type::Int1Ty) return 0;
2458 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2459 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2461 return new SelectInst(SI->getCondition(), SelectTrueVal,
2468 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2469 /// node as operand #0, see if we can fold the instruction into the PHI (which
2470 /// is only possible if all operands to the PHI are constants).
2471 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2472 PHINode *PN = cast<PHINode>(I.getOperand(0));
2473 unsigned NumPHIValues = PN->getNumIncomingValues();
2474 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2476 // Check to see if all of the operands of the PHI are constants. If there is
2477 // one non-constant value, remember the BB it is. If there is more than one
2478 // or if *it* is a PHI, bail out.
2479 BasicBlock *NonConstBB = 0;
2480 for (unsigned i = 0; i != NumPHIValues; ++i)
2481 if (!isa<Constant>(PN->getIncomingValue(i))) {
2482 if (NonConstBB) return 0; // More than one non-const value.
2483 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2484 NonConstBB = PN->getIncomingBlock(i);
2486 // If the incoming non-constant value is in I's block, we have an infinite
2488 if (NonConstBB == I.getParent())
2492 // If there is exactly one non-constant value, we can insert a copy of the
2493 // operation in that block. However, if this is a critical edge, we would be
2494 // inserting the computation one some other paths (e.g. inside a loop). Only
2495 // do this if the pred block is unconditionally branching into the phi block.
2497 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2498 if (!BI || !BI->isUnconditional()) return 0;
2501 // Okay, we can do the transformation: create the new PHI node.
2502 PHINode *NewPN = new PHINode(I.getType(), "");
2503 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2504 InsertNewInstBefore(NewPN, *PN);
2505 NewPN->takeName(PN);
2507 // Next, add all of the operands to the PHI.
2508 if (I.getNumOperands() == 2) {
2509 Constant *C = cast<Constant>(I.getOperand(1));
2510 for (unsigned i = 0; i != NumPHIValues; ++i) {
2512 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2513 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2514 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2516 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2518 assert(PN->getIncomingBlock(i) == NonConstBB);
2519 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2520 InV = BinaryOperator::create(BO->getOpcode(),
2521 PN->getIncomingValue(i), C, "phitmp",
2522 NonConstBB->getTerminator());
2523 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2524 InV = CmpInst::create(CI->getOpcode(),
2526 PN->getIncomingValue(i), C, "phitmp",
2527 NonConstBB->getTerminator());
2529 assert(0 && "Unknown binop!");
2531 AddToWorkList(cast<Instruction>(InV));
2533 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2536 CastInst *CI = cast<CastInst>(&I);
2537 const Type *RetTy = CI->getType();
2538 for (unsigned i = 0; i != NumPHIValues; ++i) {
2540 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2541 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2543 assert(PN->getIncomingBlock(i) == NonConstBB);
2544 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2545 I.getType(), "phitmp",
2546 NonConstBB->getTerminator());
2547 AddToWorkList(cast<Instruction>(InV));
2549 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2552 return ReplaceInstUsesWith(I, NewPN);
2555 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2556 bool Changed = SimplifyCommutative(I);
2557 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2559 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2560 // X + undef -> undef
2561 if (isa<UndefValue>(RHS))
2562 return ReplaceInstUsesWith(I, RHS);
2565 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2566 if (RHSC->isNullValue())
2567 return ReplaceInstUsesWith(I, LHS);
2568 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2569 if (CFP->isExactlyValue(-0.0))
2570 return ReplaceInstUsesWith(I, LHS);
2573 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2574 // X + (signbit) --> X ^ signbit
2575 uint64_t Val = CI->getZExtValue();
2576 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
2577 return BinaryOperator::createXor(LHS, RHS);
2579 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2580 // (X & 254)+1 -> (X&254)|1
2581 uint64_t KnownZero, KnownOne;
2582 if (!isa<VectorType>(I.getType()) &&
2583 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
2584 KnownZero, KnownOne))
2588 if (isa<PHINode>(LHS))
2589 if (Instruction *NV = FoldOpIntoPhi(I))
2592 ConstantInt *XorRHS = 0;
2594 if (isa<ConstantInt>(RHSC) &&
2595 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2596 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2597 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2598 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2600 uint64_t C0080Val = 1ULL << 31;
2601 int64_t CFF80Val = -C0080Val;
2604 if (TySizeBits > Size) {
2606 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2607 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2608 if (RHSSExt == CFF80Val) {
2609 if (XorRHS->getZExtValue() == C0080Val)
2611 } else if (RHSZExt == C0080Val) {
2612 if (XorRHS->getSExtValue() == CFF80Val)
2616 // This is a sign extend if the top bits are known zero.
2617 uint64_t Mask = ~0ULL;
2618 Mask <<= 64-(TySizeBits-Size);
2619 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
2620 if (!MaskedValueIsZero(XorLHS, Mask))
2621 Size = 0; // Not a sign ext, but can't be any others either.
2628 } while (Size >= 8);
2631 const Type *MiddleType = 0;
2634 case 32: MiddleType = Type::Int32Ty; break;
2635 case 16: MiddleType = Type::Int16Ty; break;
2636 case 8: MiddleType = Type::Int8Ty; break;
2639 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2640 InsertNewInstBefore(NewTrunc, I);
2641 return new SExtInst(NewTrunc, I.getType());
2647 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2648 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2650 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2651 if (RHSI->getOpcode() == Instruction::Sub)
2652 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2653 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2655 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2656 if (LHSI->getOpcode() == Instruction::Sub)
2657 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2658 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2663 if (Value *V = dyn_castNegVal(LHS))
2664 return BinaryOperator::createSub(RHS, V);
2667 if (!isa<Constant>(RHS))
2668 if (Value *V = dyn_castNegVal(RHS))
2669 return BinaryOperator::createSub(LHS, V);
2673 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2674 if (X == RHS) // X*C + X --> X * (C+1)
2675 return BinaryOperator::createMul(RHS, AddOne(C2));
2677 // X*C1 + X*C2 --> X * (C1+C2)
2679 if (X == dyn_castFoldableMul(RHS, C1))
2680 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
2683 // X + X*C --> X * (C+1)
2684 if (dyn_castFoldableMul(RHS, C2) == LHS)
2685 return BinaryOperator::createMul(LHS, AddOne(C2));
2687 // X + ~X --> -1 since ~X = -X-1
2688 if (dyn_castNotVal(LHS) == RHS ||
2689 dyn_castNotVal(RHS) == LHS)
2690 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2693 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2694 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2695 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2698 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2700 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
2701 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2702 return BinaryOperator::createSub(C, X);
2705 // (X & FF00) + xx00 -> (X+xx00) & FF00
2706 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2707 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2708 if (Anded == CRHS) {
2709 // See if all bits from the first bit set in the Add RHS up are included
2710 // in the mask. First, get the rightmost bit.
2711 uint64_t AddRHSV = CRHS->getZExtValue();
2713 // Form a mask of all bits from the lowest bit added through the top.
2714 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
2715 AddRHSHighBits &= C2->getType()->getBitMask();
2717 // See if the and mask includes all of these bits.
2718 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
2720 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2721 // Okay, the xform is safe. Insert the new add pronto.
2722 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2723 LHS->getName()), I);
2724 return BinaryOperator::createAnd(NewAdd, C2);
2729 // Try to fold constant add into select arguments.
2730 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2731 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2735 // add (cast *A to intptrtype) B ->
2736 // cast (GEP (cast *A to sbyte*) B) ->
2739 CastInst *CI = dyn_cast<CastInst>(LHS);
2742 CI = dyn_cast<CastInst>(RHS);
2745 if (CI && CI->getType()->isSized() &&
2746 (CI->getType()->getPrimitiveSizeInBits() ==
2747 TD->getIntPtrType()->getPrimitiveSizeInBits())
2748 && isa<PointerType>(CI->getOperand(0)->getType())) {
2749 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2750 PointerType::get(Type::Int8Ty), I);
2751 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2752 return new PtrToIntInst(I2, CI->getType());
2756 return Changed ? &I : 0;
2759 // isSignBit - Return true if the value represented by the constant only has the
2760 // highest order bit set.
2761 static bool isSignBit(ConstantInt *CI) {
2762 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
2763 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
2766 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2769 if (Op0 == Op1) // sub X, X -> 0
2770 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2772 // If this is a 'B = x-(-A)', change to B = x+A...
2773 if (Value *V = dyn_castNegVal(Op1))
2774 return BinaryOperator::createAdd(Op0, V);
2776 if (isa<UndefValue>(Op0))
2777 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2778 if (isa<UndefValue>(Op1))
2779 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2781 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2782 // Replace (-1 - A) with (~A)...
2783 if (C->isAllOnesValue())
2784 return BinaryOperator::createNot(Op1);
2786 // C - ~X == X + (1+C)
2788 if (match(Op1, m_Not(m_Value(X))))
2789 return BinaryOperator::createAdd(X,
2790 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
2791 // -(X >>u 31) -> (X >>s 31)
2792 // -(X >>s 31) -> (X >>u 31)
2793 if (C->isNullValue()) {
2794 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2795 if (SI->getOpcode() == Instruction::LShr) {
2796 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2797 // Check to see if we are shifting out everything but the sign bit.
2798 if (CU->getZExtValue() ==
2799 SI->getType()->getPrimitiveSizeInBits()-1) {
2800 // Ok, the transformation is safe. Insert AShr.
2801 return BinaryOperator::create(Instruction::AShr,
2802 SI->getOperand(0), CU, SI->getName());
2806 else if (SI->getOpcode() == Instruction::AShr) {
2807 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2808 // Check to see if we are shifting out everything but the sign bit.
2809 if (CU->getZExtValue() ==
2810 SI->getType()->getPrimitiveSizeInBits()-1) {
2811 // Ok, the transformation is safe. Insert LShr.
2812 return BinaryOperator::createLShr(
2813 SI->getOperand(0), CU, SI->getName());
2819 // Try to fold constant sub into select arguments.
2820 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2821 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2824 if (isa<PHINode>(Op0))
2825 if (Instruction *NV = FoldOpIntoPhi(I))
2829 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2830 if (Op1I->getOpcode() == Instruction::Add &&
2831 !Op0->getType()->isFPOrFPVector()) {
2832 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2833 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2834 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2835 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2836 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2837 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2838 // C1-(X+C2) --> (C1-C2)-X
2839 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2840 Op1I->getOperand(0));
2844 if (Op1I->hasOneUse()) {
2845 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2846 // is not used by anyone else...
2848 if (Op1I->getOpcode() == Instruction::Sub &&
2849 !Op1I->getType()->isFPOrFPVector()) {
2850 // Swap the two operands of the subexpr...
2851 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2852 Op1I->setOperand(0, IIOp1);
2853 Op1I->setOperand(1, IIOp0);
2855 // Create the new top level add instruction...
2856 return BinaryOperator::createAdd(Op0, Op1);
2859 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2861 if (Op1I->getOpcode() == Instruction::And &&
2862 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2863 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2866 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2867 return BinaryOperator::createAnd(Op0, NewNot);
2870 // 0 - (X sdiv C) -> (X sdiv -C)
2871 if (Op1I->getOpcode() == Instruction::SDiv)
2872 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2873 if (CSI->isNullValue())
2874 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2875 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2876 ConstantExpr::getNeg(DivRHS));
2878 // X - X*C --> X * (1-C)
2879 ConstantInt *C2 = 0;
2880 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2882 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2883 return BinaryOperator::createMul(Op0, CP1);
2888 if (!Op0->getType()->isFPOrFPVector())
2889 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2890 if (Op0I->getOpcode() == Instruction::Add) {
2891 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2892 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2893 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2894 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2895 } else if (Op0I->getOpcode() == Instruction::Sub) {
2896 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2897 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2901 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2902 if (X == Op1) { // X*C - X --> X * (C-1)
2903 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2904 return BinaryOperator::createMul(Op1, CP1);
2907 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2908 if (X == dyn_castFoldableMul(Op1, C2))
2909 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2914 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2915 /// really just returns true if the most significant (sign) bit is set.
2916 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2918 case ICmpInst::ICMP_SLT:
2919 // True if LHS s< RHS and RHS == 0
2920 return RHS->isNullValue();
2921 case ICmpInst::ICMP_SLE:
2922 // True if LHS s<= RHS and RHS == -1
2923 return RHS->isAllOnesValue();
2924 case ICmpInst::ICMP_UGE:
2925 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2926 return RHS->getZExtValue() == (1ULL <<
2927 (RHS->getType()->getPrimitiveSizeInBits()-1));
2928 case ICmpInst::ICMP_UGT:
2929 // True if LHS u> RHS and RHS == high-bit-mask - 1
2930 return RHS->getZExtValue() ==
2931 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2937 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2938 bool Changed = SimplifyCommutative(I);
2939 Value *Op0 = I.getOperand(0);
2941 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2942 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2944 // Simplify mul instructions with a constant RHS...
2945 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2946 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2948 // ((X << C1)*C2) == (X * (C2 << C1))
2949 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2950 if (SI->getOpcode() == Instruction::Shl)
2951 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2952 return BinaryOperator::createMul(SI->getOperand(0),
2953 ConstantExpr::getShl(CI, ShOp));
2955 if (CI->isNullValue())
2956 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2957 if (CI->equalsInt(1)) // X * 1 == X
2958 return ReplaceInstUsesWith(I, Op0);
2959 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2960 return BinaryOperator::createNeg(Op0, I.getName());
2962 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2963 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2964 uint64_t C = Log2_64(Val);
2965 return BinaryOperator::createShl(Op0,
2966 ConstantInt::get(Op0->getType(), C));
2968 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2969 if (Op1F->isNullValue())
2970 return ReplaceInstUsesWith(I, Op1);
2972 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2973 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2974 if (Op1F->getValue() == 1.0)
2975 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2978 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2979 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2980 isa<ConstantInt>(Op0I->getOperand(1))) {
2981 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2982 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2984 InsertNewInstBefore(Add, I);
2985 Value *C1C2 = ConstantExpr::getMul(Op1,
2986 cast<Constant>(Op0I->getOperand(1)));
2987 return BinaryOperator::createAdd(Add, C1C2);
2991 // Try to fold constant mul into select arguments.
2992 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2993 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2996 if (isa<PHINode>(Op0))
2997 if (Instruction *NV = FoldOpIntoPhi(I))
3001 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3002 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
3003 return BinaryOperator::createMul(Op0v, Op1v);
3005 // If one of the operands of the multiply is a cast from a boolean value, then
3006 // we know the bool is either zero or one, so this is a 'masking' multiply.
3007 // See if we can simplify things based on how the boolean was originally
3009 CastInst *BoolCast = 0;
3010 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
3011 if (CI->getOperand(0)->getType() == Type::Int1Ty)
3014 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
3015 if (CI->getOperand(0)->getType() == Type::Int1Ty)
3018 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
3019 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3020 const Type *SCOpTy = SCIOp0->getType();
3022 // If the icmp is true iff the sign bit of X is set, then convert this
3023 // multiply into a shift/and combination.
3024 if (isa<ConstantInt>(SCIOp1) &&
3025 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
3026 // Shift the X value right to turn it into "all signbits".
3027 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
3028 SCOpTy->getPrimitiveSizeInBits()-1);
3030 InsertNewInstBefore(
3031 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
3032 BoolCast->getOperand(0)->getName()+
3035 // If the multiply type is not the same as the source type, sign extend
3036 // or truncate to the multiply type.
3037 if (I.getType() != V->getType()) {
3038 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
3039 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
3040 Instruction::CastOps opcode =
3041 (SrcBits == DstBits ? Instruction::BitCast :
3042 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3043 V = InsertCastBefore(opcode, V, I.getType(), I);
3046 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
3047 return BinaryOperator::createAnd(V, OtherOp);
3052 return Changed ? &I : 0;
3055 /// This function implements the transforms on div instructions that work
3056 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3057 /// used by the visitors to those instructions.
3058 /// @brief Transforms common to all three div instructions
3059 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3060 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3063 if (isa<UndefValue>(Op0))
3064 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3066 // X / undef -> undef
3067 if (isa<UndefValue>(Op1))
3068 return ReplaceInstUsesWith(I, Op1);
3070 // Handle cases involving: div X, (select Cond, Y, Z)
3071 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3072 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
3073 // same basic block, then we replace the select with Y, and the condition
3074 // of the select with false (if the cond value is in the same BB). If the
3075 // select has uses other than the div, this allows them to be simplified
3076 // also. Note that div X, Y is just as good as div X, 0 (undef)
3077 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3078 if (ST->isNullValue()) {
3079 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3080 if (CondI && CondI->getParent() == I.getParent())
3081 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3082 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3083 I.setOperand(1, SI->getOperand(2));
3085 UpdateValueUsesWith(SI, SI->getOperand(2));
3089 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
3090 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3091 if (ST->isNullValue()) {
3092 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3093 if (CondI && CondI->getParent() == I.getParent())
3094 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3095 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3096 I.setOperand(1, SI->getOperand(1));
3098 UpdateValueUsesWith(SI, SI->getOperand(1));
3106 /// This function implements the transforms common to both integer division
3107 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3108 /// division instructions.
3109 /// @brief Common integer divide transforms
3110 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3113 if (Instruction *Common = commonDivTransforms(I))
3116 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3118 if (RHS->equalsInt(1))
3119 return ReplaceInstUsesWith(I, Op0);
3121 // (X / C1) / C2 -> X / (C1*C2)
3122 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3123 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3124 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3125 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3126 ConstantExpr::getMul(RHS, LHSRHS));
3129 if (!RHS->isNullValue()) { // avoid X udiv 0
3130 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3131 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3133 if (isa<PHINode>(Op0))
3134 if (Instruction *NV = FoldOpIntoPhi(I))
3139 // 0 / X == 0, we don't need to preserve faults!
3140 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3141 if (LHS->equalsInt(0))
3142 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3147 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3148 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3150 // Handle the integer div common cases
3151 if (Instruction *Common = commonIDivTransforms(I))
3154 // X udiv C^2 -> X >> C
3155 // Check to see if this is an unsigned division with an exact power of 2,
3156 // if so, convert to a right shift.
3157 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3158 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
3159 if (isPowerOf2_64(Val)) {
3160 uint64_t ShiftAmt = Log2_64(Val);
3161 return BinaryOperator::createLShr(Op0,
3162 ConstantInt::get(Op0->getType(), ShiftAmt));
3166 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3167 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3168 if (RHSI->getOpcode() == Instruction::Shl &&
3169 isa<ConstantInt>(RHSI->getOperand(0))) {
3170 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
3171 if (isPowerOf2_64(C1)) {
3172 Value *N = RHSI->getOperand(1);
3173 const Type *NTy = N->getType();
3174 if (uint64_t C2 = Log2_64(C1)) {
3175 Constant *C2V = ConstantInt::get(NTy, C2);
3176 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
3178 return BinaryOperator::createLShr(Op0, N);
3183 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3184 // where C1&C2 are powers of two.
3185 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3186 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3187 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3188 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
3189 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
3190 // Compute the shift amounts
3191 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
3192 // Construct the "on true" case of the select
3193 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3194 Instruction *TSI = BinaryOperator::createLShr(
3195 Op0, TC, SI->getName()+".t");
3196 TSI = InsertNewInstBefore(TSI, I);
3198 // Construct the "on false" case of the select
3199 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3200 Instruction *FSI = BinaryOperator::createLShr(
3201 Op0, FC, SI->getName()+".f");
3202 FSI = InsertNewInstBefore(FSI, I);
3204 // construct the select instruction and return it.
3205 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
3211 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3212 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3214 // Handle the integer div common cases
3215 if (Instruction *Common = commonIDivTransforms(I))
3218 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3220 if (RHS->isAllOnesValue())
3221 return BinaryOperator::createNeg(Op0);
3224 if (Value *LHSNeg = dyn_castNegVal(Op0))
3225 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3228 // If the sign bits of both operands are zero (i.e. we can prove they are
3229 // unsigned inputs), turn this into a udiv.
3230 if (I.getType()->isInteger()) {
3231 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3232 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3233 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3240 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3241 return commonDivTransforms(I);
3244 /// GetFactor - If we can prove that the specified value is at least a multiple
3245 /// of some factor, return that factor.
3246 static Constant *GetFactor(Value *V) {
3247 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3250 // Unless we can be tricky, we know this is a multiple of 1.
3251 Constant *Result = ConstantInt::get(V->getType(), 1);
3253 Instruction *I = dyn_cast<Instruction>(V);
3254 if (!I) return Result;
3256 if (I->getOpcode() == Instruction::Mul) {
3257 // Handle multiplies by a constant, etc.
3258 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
3259 GetFactor(I->getOperand(1)));
3260 } else if (I->getOpcode() == Instruction::Shl) {
3261 // (X<<C) -> X * (1 << C)
3262 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
3263 ShRHS = ConstantExpr::getShl(Result, ShRHS);
3264 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
3266 } else if (I->getOpcode() == Instruction::And) {
3267 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3268 // X & 0xFFF0 is known to be a multiple of 16.
3269 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
3270 if (Zeros != V->getType()->getPrimitiveSizeInBits())
3271 return ConstantExpr::getShl(Result,
3272 ConstantInt::get(Result->getType(), Zeros));
3274 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3275 // Only handle int->int casts.
3276 if (!CI->isIntegerCast())
3278 Value *Op = CI->getOperand(0);
3279 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
3284 /// This function implements the transforms on rem instructions that work
3285 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3286 /// is used by the visitors to those instructions.
3287 /// @brief Transforms common to all three rem instructions
3288 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3289 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3291 // 0 % X == 0, we don't need to preserve faults!
3292 if (Constant *LHS = dyn_cast<Constant>(Op0))
3293 if (LHS->isNullValue())
3294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3296 if (isa<UndefValue>(Op0)) // undef % X -> 0
3297 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3298 if (isa<UndefValue>(Op1))
3299 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3301 // Handle cases involving: rem X, (select Cond, Y, Z)
3302 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3303 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3304 // the same basic block, then we replace the select with Y, and the
3305 // condition of the select with false (if the cond value is in the same
3306 // BB). If the select has uses other than the div, this allows them to be
3308 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3309 if (ST->isNullValue()) {
3310 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3311 if (CondI && CondI->getParent() == I.getParent())
3312 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3313 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3314 I.setOperand(1, SI->getOperand(2));
3316 UpdateValueUsesWith(SI, SI->getOperand(2));
3319 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3320 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3321 if (ST->isNullValue()) {
3322 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3323 if (CondI && CondI->getParent() == I.getParent())
3324 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3325 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3326 I.setOperand(1, SI->getOperand(1));
3328 UpdateValueUsesWith(SI, SI->getOperand(1));
3336 /// This function implements the transforms common to both integer remainder
3337 /// instructions (urem and srem). It is called by the visitors to those integer
3338 /// remainder instructions.
3339 /// @brief Common integer remainder transforms
3340 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3341 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3343 if (Instruction *common = commonRemTransforms(I))
3346 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3347 // X % 0 == undef, we don't need to preserve faults!
3348 if (RHS->equalsInt(0))
3349 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3351 if (RHS->equalsInt(1)) // X % 1 == 0
3352 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3354 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3355 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3356 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3358 } else if (isa<PHINode>(Op0I)) {
3359 if (Instruction *NV = FoldOpIntoPhi(I))
3362 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
3363 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
3364 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3371 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3372 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3374 if (Instruction *common = commonIRemTransforms(I))
3377 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3378 // X urem C^2 -> X and C
3379 // Check to see if this is an unsigned remainder with an exact power of 2,
3380 // if so, convert to a bitwise and.
3381 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3382 if (isPowerOf2_64(C->getZExtValue()))
3383 return BinaryOperator::createAnd(Op0, SubOne(C));
3386 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3387 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3388 if (RHSI->getOpcode() == Instruction::Shl &&
3389 isa<ConstantInt>(RHSI->getOperand(0))) {
3390 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
3391 if (isPowerOf2_64(C1)) {
3392 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3393 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3395 return BinaryOperator::createAnd(Op0, Add);
3400 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3401 // where C1&C2 are powers of two.
3402 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3403 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3404 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3405 // STO == 0 and SFO == 0 handled above.
3406 if (isPowerOf2_64(STO->getZExtValue()) &&
3407 isPowerOf2_64(SFO->getZExtValue())) {
3408 Value *TrueAnd = InsertNewInstBefore(
3409 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3410 Value *FalseAnd = InsertNewInstBefore(
3411 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3412 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3420 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3421 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3423 if (Instruction *common = commonIRemTransforms(I))
3426 if (Value *RHSNeg = dyn_castNegVal(Op1))
3427 if (!isa<ConstantInt>(RHSNeg) ||
3428 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
3430 AddUsesToWorkList(I);
3431 I.setOperand(1, RHSNeg);
3435 // If the top bits of both operands are zero (i.e. we can prove they are
3436 // unsigned inputs), turn this into a urem.
3437 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3438 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3439 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3440 return BinaryOperator::createURem(Op0, Op1, I.getName());
3446 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3447 return commonRemTransforms(I);
3450 // isMaxValueMinusOne - return true if this is Max-1
3451 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3453 // Calculate 0111111111..11111
3454 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
3455 int64_t Val = INT64_MAX; // All ones
3456 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
3457 return C->getSExtValue() == Val-1;
3459 return C->getZExtValue() == C->getType()->getBitMask()-1;
3462 // isMinValuePlusOne - return true if this is Min+1
3463 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3465 // Calculate 1111111111000000000000
3466 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
3467 int64_t Val = -1; // All ones
3468 Val <<= TypeBits-1; // Shift over to the right spot
3469 return C->getSExtValue() == Val+1;
3471 return C->getZExtValue() == 1; // unsigned
3474 // isOneBitSet - Return true if there is exactly one bit set in the specified
3476 static bool isOneBitSet(const ConstantInt *CI) {
3477 uint64_t V = CI->getZExtValue();
3478 return V && (V & (V-1)) == 0;
3481 #if 0 // Currently unused
3482 // isLowOnes - Return true if the constant is of the form 0+1+.
3483 static bool isLowOnes(const ConstantInt *CI) {
3484 uint64_t V = CI->getZExtValue();
3486 // There won't be bits set in parts that the type doesn't contain.
3487 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
3489 uint64_t U = V+1; // If it is low ones, this should be a power of two.
3490 return U && V && (U & V) == 0;
3494 // isHighOnes - Return true if the constant is of the form 1+0+.
3495 // This is the same as lowones(~X).
3496 static bool isHighOnes(const ConstantInt *CI) {
3497 uint64_t V = ~CI->getZExtValue();
3498 if (~V == 0) return false; // 0's does not match "1+"
3500 // There won't be bits set in parts that the type doesn't contain.
3501 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
3503 uint64_t U = V+1; // If it is low ones, this should be a power of two.
3504 return U && V && (U & V) == 0;
3507 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3508 /// are carefully arranged to allow folding of expressions such as:
3510 /// (A < B) | (A > B) --> (A != B)
3512 /// Note that this is only valid if the first and second predicates have the
3513 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3515 /// Three bits are used to represent the condition, as follows:
3520 /// <=> Value Definition
3521 /// 000 0 Always false
3528 /// 111 7 Always true
3530 static unsigned getICmpCode(const ICmpInst *ICI) {
3531 switch (ICI->getPredicate()) {
3533 case ICmpInst::ICMP_UGT: return 1; // 001
3534 case ICmpInst::ICMP_SGT: return 1; // 001
3535 case ICmpInst::ICMP_EQ: return 2; // 010
3536 case ICmpInst::ICMP_UGE: return 3; // 011
3537 case ICmpInst::ICMP_SGE: return 3; // 011
3538 case ICmpInst::ICMP_ULT: return 4; // 100
3539 case ICmpInst::ICMP_SLT: return 4; // 100
3540 case ICmpInst::ICMP_NE: return 5; // 101
3541 case ICmpInst::ICMP_ULE: return 6; // 110
3542 case ICmpInst::ICMP_SLE: return 6; // 110
3545 assert(0 && "Invalid ICmp predicate!");
3550 /// getICmpValue - This is the complement of getICmpCode, which turns an
3551 /// opcode and two operands into either a constant true or false, or a brand
3552 /// new /// ICmp instruction. The sign is passed in to determine which kind
3553 /// of predicate to use in new icmp instructions.
3554 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3556 default: assert(0 && "Illegal ICmp code!");
3557 case 0: return ConstantInt::getFalse();
3560 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3562 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3563 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3566 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3568 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3571 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3573 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3574 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3577 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3579 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3580 case 7: return ConstantInt::getTrue();
3584 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3585 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3586 (ICmpInst::isSignedPredicate(p1) &&
3587 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3588 (ICmpInst::isSignedPredicate(p2) &&
3589 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3593 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3594 struct FoldICmpLogical {
3597 ICmpInst::Predicate pred;
3598 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3599 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3600 pred(ICI->getPredicate()) {}
3601 bool shouldApply(Value *V) const {
3602 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3603 if (PredicatesFoldable(pred, ICI->getPredicate()))
3604 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3605 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3608 Instruction *apply(Instruction &Log) const {
3609 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3610 if (ICI->getOperand(0) != LHS) {
3611 assert(ICI->getOperand(1) == LHS);
3612 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3615 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3616 unsigned LHSCode = getICmpCode(ICI);
3617 unsigned RHSCode = getICmpCode(RHSICI);
3619 switch (Log.getOpcode()) {
3620 case Instruction::And: Code = LHSCode & RHSCode; break;
3621 case Instruction::Or: Code = LHSCode | RHSCode; break;
3622 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3623 default: assert(0 && "Illegal logical opcode!"); return 0;
3626 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3627 ICmpInst::isSignedPredicate(ICI->getPredicate());
3629 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3630 if (Instruction *I = dyn_cast<Instruction>(RV))
3632 // Otherwise, it's a constant boolean value...
3633 return IC.ReplaceInstUsesWith(Log, RV);
3636 } // end anonymous namespace
3638 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3639 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3640 // guaranteed to be a binary operator.
3641 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3643 ConstantInt *AndRHS,
3644 BinaryOperator &TheAnd) {
3645 Value *X = Op->getOperand(0);
3646 Constant *Together = 0;
3648 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3650 switch (Op->getOpcode()) {
3651 case Instruction::Xor:
3652 if (Op->hasOneUse()) {
3653 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3654 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3655 InsertNewInstBefore(And, TheAnd);
3657 return BinaryOperator::createXor(And, Together);
3660 case Instruction::Or:
3661 if (Together == AndRHS) // (X | C) & C --> C
3662 return ReplaceInstUsesWith(TheAnd, AndRHS);
3664 if (Op->hasOneUse() && Together != OpRHS) {
3665 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3666 Instruction *Or = BinaryOperator::createOr(X, Together);
3667 InsertNewInstBefore(Or, TheAnd);
3669 return BinaryOperator::createAnd(Or, AndRHS);
3672 case Instruction::Add:
3673 if (Op->hasOneUse()) {
3674 // Adding a one to a single bit bit-field should be turned into an XOR
3675 // of the bit. First thing to check is to see if this AND is with a
3676 // single bit constant.
3677 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
3679 // Clear bits that are not part of the constant.
3680 AndRHSV &= AndRHS->getType()->getBitMask();
3682 // If there is only one bit set...
3683 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3684 // Ok, at this point, we know that we are masking the result of the
3685 // ADD down to exactly one bit. If the constant we are adding has
3686 // no bits set below this bit, then we can eliminate the ADD.
3687 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
3689 // Check to see if any bits below the one bit set in AndRHSV are set.
3690 if ((AddRHS & (AndRHSV-1)) == 0) {
3691 // If not, the only thing that can effect the output of the AND is
3692 // the bit specified by AndRHSV. If that bit is set, the effect of
3693 // the XOR is to toggle the bit. If it is clear, then the ADD has
3695 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3696 TheAnd.setOperand(0, X);
3699 // Pull the XOR out of the AND.
3700 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3701 InsertNewInstBefore(NewAnd, TheAnd);
3702 NewAnd->takeName(Op);
3703 return BinaryOperator::createXor(NewAnd, AndRHS);
3710 case Instruction::Shl: {
3711 // We know that the AND will not produce any of the bits shifted in, so if
3712 // the anded constant includes them, clear them now!
3714 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3715 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3716 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
3718 if (CI == ShlMask) { // Masking out bits that the shift already masks
3719 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3720 } else if (CI != AndRHS) { // Reducing bits set in and.
3721 TheAnd.setOperand(1, CI);
3726 case Instruction::LShr:
3728 // We know that the AND will not produce any of the bits shifted in, so if
3729 // the anded constant includes them, clear them now! This only applies to
3730 // unsigned shifts, because a signed shr may bring in set bits!
3732 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3733 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3734 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
3736 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3737 return ReplaceInstUsesWith(TheAnd, Op);
3738 } else if (CI != AndRHS) {
3739 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3744 case Instruction::AShr:
3746 // See if this is shifting in some sign extension, then masking it out
3748 if (Op->hasOneUse()) {
3749 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3750 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3751 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3752 if (C == AndRHS) { // Masking out bits shifted in.
3753 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3754 // Make the argument unsigned.
3755 Value *ShVal = Op->getOperand(0);
3756 ShVal = InsertNewInstBefore(
3757 BinaryOperator::createLShr(ShVal, OpRHS,
3758 Op->getName()), TheAnd);
3759 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3768 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3769 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3770 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3771 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3772 /// insert new instructions.
3773 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3774 bool isSigned, bool Inside,
3776 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3777 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3778 "Lo is not <= Hi in range emission code!");
3781 if (Lo == Hi) // Trivially false.
3782 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3784 // V >= Min && V < Hi --> V < Hi
3785 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3786 ICmpInst::Predicate pred = (isSigned ?
3787 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3788 return new ICmpInst(pred, V, Hi);
3791 // Emit V-Lo <u Hi-Lo
3792 Constant *NegLo = ConstantExpr::getNeg(Lo);
3793 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3794 InsertNewInstBefore(Add, IB);
3795 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3796 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3799 if (Lo == Hi) // Trivially true.
3800 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3802 // V < Min || V >= Hi ->'V > Hi-1'
3803 Hi = SubOne(cast<ConstantInt>(Hi));
3804 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3805 ICmpInst::Predicate pred = (isSigned ?
3806 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3807 return new ICmpInst(pred, V, Hi);
3810 // Emit V-Lo > Hi-1-Lo
3811 Constant *NegLo = ConstantExpr::getNeg(Lo);
3812 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3813 InsertNewInstBefore(Add, IB);
3814 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3815 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3818 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3819 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3820 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3821 // not, since all 1s are not contiguous.
3822 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
3823 uint64_t V = Val->getZExtValue();
3824 if (!isShiftedMask_64(V)) return false;
3826 // look for the first zero bit after the run of ones
3827 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3828 // look for the first non-zero bit
3829 ME = 64-CountLeadingZeros_64(V);
3835 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3836 /// where isSub determines whether the operator is a sub. If we can fold one of
3837 /// the following xforms:
3839 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3840 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3841 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3843 /// return (A +/- B).
3845 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3846 ConstantInt *Mask, bool isSub,
3848 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3849 if (!LHSI || LHSI->getNumOperands() != 2 ||
3850 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3852 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3854 switch (LHSI->getOpcode()) {
3856 case Instruction::And:
3857 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3858 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3859 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3862 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3863 // part, we don't need any explicit masks to take them out of A. If that
3864 // is all N is, ignore it.
3866 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3867 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
3869 if (MaskedValueIsZero(RHS, Mask))
3874 case Instruction::Or:
3875 case Instruction::Xor:
3876 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3877 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3878 ConstantExpr::getAnd(N, Mask)->isNullValue())
3885 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3887 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3888 return InsertNewInstBefore(New, I);
3891 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3892 bool Changed = SimplifyCommutative(I);
3893 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3895 if (isa<UndefValue>(Op1)) // X & undef -> 0
3896 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3900 return ReplaceInstUsesWith(I, Op1);
3902 // See if we can simplify any instructions used by the instruction whose sole
3903 // purpose is to compute bits we don't care about.
3904 uint64_t KnownZero, KnownOne;
3905 if (!isa<VectorType>(I.getType())) {
3906 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3907 KnownZero, KnownOne))
3910 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3911 if (CP->isAllOnesValue())
3912 return ReplaceInstUsesWith(I, I.getOperand(0));
3916 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3917 uint64_t AndRHSMask = AndRHS->getZExtValue();
3918 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
3919 uint64_t NotAndRHS = AndRHSMask^TypeMask;
3921 // Optimize a variety of ((val OP C1) & C2) combinations...
3922 if (isa<BinaryOperator>(Op0)) {
3923 Instruction *Op0I = cast<Instruction>(Op0);
3924 Value *Op0LHS = Op0I->getOperand(0);
3925 Value *Op0RHS = Op0I->getOperand(1);
3926 switch (Op0I->getOpcode()) {
3927 case Instruction::Xor:
3928 case Instruction::Or:
3929 // If the mask is only needed on one incoming arm, push it up.
3930 if (Op0I->hasOneUse()) {
3931 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3932 // Not masking anything out for the LHS, move to RHS.
3933 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3934 Op0RHS->getName()+".masked");
3935 InsertNewInstBefore(NewRHS, I);
3936 return BinaryOperator::create(
3937 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3939 if (!isa<Constant>(Op0RHS) &&
3940 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3941 // Not masking anything out for the RHS, move to LHS.
3942 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3943 Op0LHS->getName()+".masked");
3944 InsertNewInstBefore(NewLHS, I);
3945 return BinaryOperator::create(
3946 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3951 case Instruction::Add:
3952 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3953 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3954 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3955 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3956 return BinaryOperator::createAnd(V, AndRHS);
3957 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3958 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3961 case Instruction::Sub:
3962 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3963 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3964 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3965 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3966 return BinaryOperator::createAnd(V, AndRHS);
3970 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3971 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3973 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3974 // If this is an integer truncation or change from signed-to-unsigned, and
3975 // if the source is an and/or with immediate, transform it. This
3976 // frequently occurs for bitfield accesses.
3977 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3978 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3979 CastOp->getNumOperands() == 2)
3980 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3981 if (CastOp->getOpcode() == Instruction::And) {
3982 // Change: and (cast (and X, C1) to T), C2
3983 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3984 // This will fold the two constants together, which may allow
3985 // other simplifications.
3986 Instruction *NewCast = CastInst::createTruncOrBitCast(
3987 CastOp->getOperand(0), I.getType(),
3988 CastOp->getName()+".shrunk");
3989 NewCast = InsertNewInstBefore(NewCast, I);
3990 // trunc_or_bitcast(C1)&C2
3991 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3992 C3 = ConstantExpr::getAnd(C3, AndRHS);
3993 return BinaryOperator::createAnd(NewCast, C3);
3994 } else if (CastOp->getOpcode() == Instruction::Or) {
3995 // Change: and (cast (or X, C1) to T), C2
3996 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3997 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3998 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3999 return ReplaceInstUsesWith(I, AndRHS);
4004 // Try to fold constant and into select arguments.
4005 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4006 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4008 if (isa<PHINode>(Op0))
4009 if (Instruction *NV = FoldOpIntoPhi(I))
4013 Value *Op0NotVal = dyn_castNotVal(Op0);
4014 Value *Op1NotVal = dyn_castNotVal(Op1);
4016 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4019 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4020 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4021 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
4022 I.getName()+".demorgan");
4023 InsertNewInstBefore(Or, I);
4024 return BinaryOperator::createNot(Or);
4028 Value *A = 0, *B = 0;
4029 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
4030 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4031 return ReplaceInstUsesWith(I, Op1);
4032 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
4033 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4034 return ReplaceInstUsesWith(I, Op0);
4036 if (Op0->hasOneUse() &&
4037 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4038 if (A == Op1) { // (A^B)&A -> A&(A^B)
4039 I.swapOperands(); // Simplify below
4040 std::swap(Op0, Op1);
4041 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4042 cast<BinaryOperator>(Op0)->swapOperands();
4043 I.swapOperands(); // Simplify below
4044 std::swap(Op0, Op1);
4047 if (Op1->hasOneUse() &&
4048 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4049 if (B == Op0) { // B&(A^B) -> B&(B^A)
4050 cast<BinaryOperator>(Op1)->swapOperands();
4053 if (A == Op0) { // A&(A^B) -> A & ~B
4054 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
4055 InsertNewInstBefore(NotB, I);
4056 return BinaryOperator::createAnd(A, NotB);
4061 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4062 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4063 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4066 Value *LHSVal, *RHSVal;
4067 ConstantInt *LHSCst, *RHSCst;
4068 ICmpInst::Predicate LHSCC, RHSCC;
4069 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4070 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4071 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4072 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4073 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4074 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4075 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4076 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
4077 // Ensure that the larger constant is on the RHS.
4078 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
4079 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4080 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4081 ICmpInst *LHS = cast<ICmpInst>(Op0);
4082 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4083 std::swap(LHS, RHS);
4084 std::swap(LHSCst, RHSCst);
4085 std::swap(LHSCC, RHSCC);
4088 // At this point, we know we have have two icmp instructions
4089 // comparing a value against two constants and and'ing the result
4090 // together. Because of the above check, we know that we only have
4091 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4092 // (from the FoldICmpLogical check above), that the two constants
4093 // are not equal and that the larger constant is on the RHS
4094 assert(LHSCst != RHSCst && "Compares not folded above?");
4097 default: assert(0 && "Unknown integer condition code!");
4098 case ICmpInst::ICMP_EQ:
4100 default: assert(0 && "Unknown integer condition code!");
4101 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4102 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4103 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
4104 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4105 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4106 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4107 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4108 return ReplaceInstUsesWith(I, LHS);
4110 case ICmpInst::ICMP_NE:
4112 default: assert(0 && "Unknown integer condition code!");
4113 case ICmpInst::ICMP_ULT:
4114 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4115 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4116 break; // (X != 13 & X u< 15) -> no change
4117 case ICmpInst::ICMP_SLT:
4118 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4119 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4120 break; // (X != 13 & X s< 15) -> no change
4121 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4122 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4123 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4124 return ReplaceInstUsesWith(I, RHS);
4125 case ICmpInst::ICMP_NE:
4126 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4127 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4128 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4129 LHSVal->getName()+".off");
4130 InsertNewInstBefore(Add, I);
4131 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4132 ConstantInt::get(Add->getType(), 1));
4134 break; // (X != 13 & X != 15) -> no change
4137 case ICmpInst::ICMP_ULT:
4139 default: assert(0 && "Unknown integer condition code!");
4140 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4141 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
4142 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4143 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4145 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4146 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4147 return ReplaceInstUsesWith(I, LHS);
4148 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4152 case ICmpInst::ICMP_SLT:
4154 default: assert(0 && "Unknown integer condition code!");
4155 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4156 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
4157 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4158 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4160 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4161 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4162 return ReplaceInstUsesWith(I, LHS);
4163 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4167 case ICmpInst::ICMP_UGT:
4169 default: assert(0 && "Unknown integer condition code!");
4170 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4171 return ReplaceInstUsesWith(I, LHS);
4172 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4173 return ReplaceInstUsesWith(I, RHS);
4174 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4176 case ICmpInst::ICMP_NE:
4177 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4178 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4179 break; // (X u> 13 & X != 15) -> no change
4180 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4181 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4183 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4187 case ICmpInst::ICMP_SGT:
4189 default: assert(0 && "Unknown integer condition code!");
4190 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
4191 return ReplaceInstUsesWith(I, LHS);
4192 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4193 return ReplaceInstUsesWith(I, RHS);
4194 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4196 case ICmpInst::ICMP_NE:
4197 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4198 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4199 break; // (X s> 13 & X != 15) -> no change
4200 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4201 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4203 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4211 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4212 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4213 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4214 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4215 const Type *SrcTy = Op0C->getOperand(0)->getType();
4216 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4217 // Only do this if the casts both really cause code to be generated.
4218 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4220 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4222 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4223 Op1C->getOperand(0),
4225 InsertNewInstBefore(NewOp, I);
4226 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4230 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4231 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4232 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4233 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4234 SI0->getOperand(1) == SI1->getOperand(1) &&
4235 (SI0->hasOneUse() || SI1->hasOneUse())) {
4236 Instruction *NewOp =
4237 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4239 SI0->getName()), I);
4240 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4241 SI1->getOperand(1));
4245 return Changed ? &I : 0;
4248 /// CollectBSwapParts - Look to see if the specified value defines a single byte
4249 /// in the result. If it does, and if the specified byte hasn't been filled in
4250 /// yet, fill it in and return false.
4251 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4252 Instruction *I = dyn_cast<Instruction>(V);
4253 if (I == 0) return true;
4255 // If this is an or instruction, it is an inner node of the bswap.
4256 if (I->getOpcode() == Instruction::Or)
4257 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4258 CollectBSwapParts(I->getOperand(1), ByteValues);
4260 // If this is a shift by a constant int, and it is "24", then its operand
4261 // defines a byte. We only handle unsigned types here.
4262 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4263 // Not shifting the entire input by N-1 bytes?
4264 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
4265 8*(ByteValues.size()-1))
4269 if (I->getOpcode() == Instruction::Shl) {
4270 // X << 24 defines the top byte with the lowest of the input bytes.
4271 DestNo = ByteValues.size()-1;
4273 // X >>u 24 defines the low byte with the highest of the input bytes.
4277 // If the destination byte value is already defined, the values are or'd
4278 // together, which isn't a bswap (unless it's an or of the same bits).
4279 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4281 ByteValues[DestNo] = I->getOperand(0);
4285 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4287 Value *Shift = 0, *ShiftLHS = 0;
4288 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4289 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4290 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4292 Instruction *SI = cast<Instruction>(Shift);
4294 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4295 if (ShiftAmt->getZExtValue() & 7 ||
4296 ShiftAmt->getZExtValue() > 8*ByteValues.size())
4299 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4301 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4302 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
4304 // Unknown mask for bswap.
4305 if (DestByte == ByteValues.size()) return true;
4307 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4309 if (SI->getOpcode() == Instruction::Shl)
4310 SrcByte = DestByte - ShiftBytes;
4312 SrcByte = DestByte + ShiftBytes;
4314 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4315 if (SrcByte != ByteValues.size()-DestByte-1)
4318 // If the destination byte value is already defined, the values are or'd
4319 // together, which isn't a bswap (unless it's an or of the same bits).
4320 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4322 ByteValues[DestByte] = SI->getOperand(0);
4326 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4327 /// If so, insert the new bswap intrinsic and return it.
4328 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4329 // We cannot bswap one byte.
4330 if (I.getType() == Type::Int8Ty)
4333 /// ByteValues - For each byte of the result, we keep track of which value
4334 /// defines each byte.
4335 SmallVector<Value*, 8> ByteValues;
4336 ByteValues.resize(TD->getTypeSize(I.getType()));
4338 // Try to find all the pieces corresponding to the bswap.
4339 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4340 CollectBSwapParts(I.getOperand(1), ByteValues))
4343 // Check to see if all of the bytes come from the same value.
4344 Value *V = ByteValues[0];
4345 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4347 // Check to make sure that all of the bytes come from the same value.
4348 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4349 if (ByteValues[i] != V)
4352 // If they do then *success* we can turn this into a bswap. Figure out what
4353 // bswap to make it into.
4354 Module *M = I.getParent()->getParent()->getParent();
4355 const char *FnName = 0;
4356 if (I.getType() == Type::Int16Ty)
4357 FnName = "llvm.bswap.i16";
4358 else if (I.getType() == Type::Int32Ty)
4359 FnName = "llvm.bswap.i32";
4360 else if (I.getType() == Type::Int64Ty)
4361 FnName = "llvm.bswap.i64";
4363 assert(0 && "Unknown integer type!");
4364 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
4365 return new CallInst(F, V);
4369 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4370 bool Changed = SimplifyCommutative(I);
4371 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4373 if (isa<UndefValue>(Op1))
4374 return ReplaceInstUsesWith(I, // X | undef -> -1
4375 ConstantInt::getAllOnesValue(I.getType()));
4379 return ReplaceInstUsesWith(I, Op0);
4381 // See if we can simplify any instructions used by the instruction whose sole
4382 // purpose is to compute bits we don't care about.
4383 uint64_t KnownZero, KnownOne;
4384 if (!isa<VectorType>(I.getType()) &&
4385 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
4386 KnownZero, KnownOne))
4390 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4391 ConstantInt *C1 = 0; Value *X = 0;
4392 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4393 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4394 Instruction *Or = BinaryOperator::createOr(X, RHS);
4395 InsertNewInstBefore(Or, I);
4397 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
4400 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4401 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4402 Instruction *Or = BinaryOperator::createOr(X, RHS);
4403 InsertNewInstBefore(Or, I);
4405 return BinaryOperator::createXor(Or,
4406 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
4409 // Try to fold constant and into select arguments.
4410 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4411 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4413 if (isa<PHINode>(Op0))
4414 if (Instruction *NV = FoldOpIntoPhi(I))
4418 Value *A = 0, *B = 0;
4419 ConstantInt *C1 = 0, *C2 = 0;
4421 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4422 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4423 return ReplaceInstUsesWith(I, Op1);
4424 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4425 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4426 return ReplaceInstUsesWith(I, Op0);
4428 // (A | B) | C and A | (B | C) -> bswap if possible.
4429 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4430 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4431 match(Op1, m_Or(m_Value(), m_Value())) ||
4432 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4433 match(Op1, m_Shift(m_Value(), m_Value())))) {
4434 if (Instruction *BSwap = MatchBSwap(I))
4438 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4439 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4440 MaskedValueIsZero(Op1, C1->getZExtValue())) {
4441 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4442 InsertNewInstBefore(NOr, I);
4444 return BinaryOperator::createXor(NOr, C1);
4447 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4448 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4449 MaskedValueIsZero(Op0, C1->getZExtValue())) {
4450 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4451 InsertNewInstBefore(NOr, I);
4453 return BinaryOperator::createXor(NOr, C1);
4456 // (A & C1)|(B & C2)
4457 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
4458 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
4460 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
4461 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
4464 // If we have: ((V + N) & C1) | (V & C2)
4465 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4466 // replace with V+N.
4467 if (C1 == ConstantExpr::getNot(C2)) {
4468 Value *V1 = 0, *V2 = 0;
4469 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
4470 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4471 // Add commutes, try both ways.
4472 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
4473 return ReplaceInstUsesWith(I, A);
4474 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
4475 return ReplaceInstUsesWith(I, A);
4477 // Or commutes, try both ways.
4478 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
4479 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4480 // Add commutes, try both ways.
4481 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
4482 return ReplaceInstUsesWith(I, B);
4483 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
4484 return ReplaceInstUsesWith(I, B);
4489 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4490 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4491 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4492 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4493 SI0->getOperand(1) == SI1->getOperand(1) &&
4494 (SI0->hasOneUse() || SI1->hasOneUse())) {
4495 Instruction *NewOp =
4496 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4498 SI0->getName()), I);
4499 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4500 SI1->getOperand(1));
4504 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4505 if (A == Op1) // ~A | A == -1
4506 return ReplaceInstUsesWith(I,
4507 ConstantInt::getAllOnesValue(I.getType()));
4511 // Note, A is still live here!
4512 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4514 return ReplaceInstUsesWith(I,
4515 ConstantInt::getAllOnesValue(I.getType()));
4517 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4518 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4519 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4520 I.getName()+".demorgan"), I);
4521 return BinaryOperator::createNot(And);
4525 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4526 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4527 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4530 Value *LHSVal, *RHSVal;
4531 ConstantInt *LHSCst, *RHSCst;
4532 ICmpInst::Predicate LHSCC, RHSCC;
4533 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4534 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4535 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4536 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4537 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4538 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4539 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4540 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
4541 // Ensure that the larger constant is on the RHS.
4542 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
4543 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4544 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4545 ICmpInst *LHS = cast<ICmpInst>(Op0);
4546 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4547 std::swap(LHS, RHS);
4548 std::swap(LHSCst, RHSCst);
4549 std::swap(LHSCC, RHSCC);
4552 // At this point, we know we have have two icmp instructions
4553 // comparing a value against two constants and or'ing the result
4554 // together. Because of the above check, we know that we only have
4555 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4556 // FoldICmpLogical check above), that the two constants are not
4558 assert(LHSCst != RHSCst && "Compares not folded above?");
4561 default: assert(0 && "Unknown integer condition code!");
4562 case ICmpInst::ICMP_EQ:
4564 default: assert(0 && "Unknown integer condition code!");
4565 case ICmpInst::ICMP_EQ:
4566 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4567 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4568 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4569 LHSVal->getName()+".off");
4570 InsertNewInstBefore(Add, I);
4571 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4572 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4574 break; // (X == 13 | X == 15) -> no change
4575 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4576 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4578 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4579 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4580 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4581 return ReplaceInstUsesWith(I, RHS);
4584 case ICmpInst::ICMP_NE:
4586 default: assert(0 && "Unknown integer condition code!");
4587 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4588 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4589 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4590 return ReplaceInstUsesWith(I, LHS);
4591 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4592 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4593 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4594 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4597 case ICmpInst::ICMP_ULT:
4599 default: assert(0 && "Unknown integer condition code!");
4600 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4602 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4603 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4605 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4607 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4608 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4609 return ReplaceInstUsesWith(I, RHS);
4610 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4614 case ICmpInst::ICMP_SLT:
4616 default: assert(0 && "Unknown integer condition code!");
4617 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4619 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4620 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4622 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4624 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4625 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4626 return ReplaceInstUsesWith(I, RHS);
4627 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4631 case ICmpInst::ICMP_UGT:
4633 default: assert(0 && "Unknown integer condition code!");
4634 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4635 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4636 return ReplaceInstUsesWith(I, LHS);
4637 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4639 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4640 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4641 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4642 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4646 case ICmpInst::ICMP_SGT:
4648 default: assert(0 && "Unknown integer condition code!");
4649 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4650 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4651 return ReplaceInstUsesWith(I, LHS);
4652 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4654 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4655 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4656 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4657 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4665 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4666 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4667 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4668 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4669 const Type *SrcTy = Op0C->getOperand(0)->getType();
4670 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4671 // Only do this if the casts both really cause code to be generated.
4672 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4674 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4676 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4677 Op1C->getOperand(0),
4679 InsertNewInstBefore(NewOp, I);
4680 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4685 return Changed ? &I : 0;
4688 // XorSelf - Implements: X ^ X --> 0
4691 XorSelf(Value *rhs) : RHS(rhs) {}
4692 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4693 Instruction *apply(BinaryOperator &Xor) const {
4699 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4700 bool Changed = SimplifyCommutative(I);
4701 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4703 if (isa<UndefValue>(Op1))
4704 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4706 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4707 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4708 assert(Result == &I && "AssociativeOpt didn't work?");
4709 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4712 // See if we can simplify any instructions used by the instruction whose sole
4713 // purpose is to compute bits we don't care about.
4714 uint64_t KnownZero, KnownOne;
4715 if (!isa<VectorType>(I.getType()) &&
4716 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
4717 KnownZero, KnownOne))
4720 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4721 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4722 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4723 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
4724 return new ICmpInst(ICI->getInversePredicate(),
4725 ICI->getOperand(0), ICI->getOperand(1));
4727 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4728 // ~(c-X) == X-c-1 == X+(-c-1)
4729 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4730 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4731 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4732 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4733 ConstantInt::get(I.getType(), 1));
4734 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4737 // ~(~X & Y) --> (X | ~Y)
4738 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4739 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4740 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4742 BinaryOperator::createNot(Op0I->getOperand(1),
4743 Op0I->getOperand(1)->getName()+".not");
4744 InsertNewInstBefore(NotY, I);
4745 return BinaryOperator::createOr(Op0NotVal, NotY);
4749 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4750 if (Op0I->getOpcode() == Instruction::Add) {
4751 // ~(X-c) --> (-c-1)-X
4752 if (RHS->isAllOnesValue()) {
4753 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4754 return BinaryOperator::createSub(
4755 ConstantExpr::getSub(NegOp0CI,
4756 ConstantInt::get(I.getType(), 1)),
4757 Op0I->getOperand(0));
4759 } else if (Op0I->getOpcode() == Instruction::Or) {
4760 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4761 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
4762 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4763 // Anything in both C1 and C2 is known to be zero, remove it from
4765 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4766 NewRHS = ConstantExpr::getAnd(NewRHS,
4767 ConstantExpr::getNot(CommonBits));
4768 AddToWorkList(Op0I);
4769 I.setOperand(0, Op0I->getOperand(0));
4770 I.setOperand(1, NewRHS);
4776 // Try to fold constant and into select arguments.
4777 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4778 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4780 if (isa<PHINode>(Op0))
4781 if (Instruction *NV = FoldOpIntoPhi(I))
4785 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4787 return ReplaceInstUsesWith(I,
4788 ConstantInt::getAllOnesValue(I.getType()));
4790 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4792 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
4795 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4798 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4799 if (A == Op0) { // B^(B|A) == (A|B)^B
4800 Op1I->swapOperands();
4802 std::swap(Op0, Op1);
4803 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4804 I.swapOperands(); // Simplified below.
4805 std::swap(Op0, Op1);
4807 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4808 if (Op0 == A) // A^(A^B) == B
4809 return ReplaceInstUsesWith(I, B);
4810 else if (Op0 == B) // A^(B^A) == B
4811 return ReplaceInstUsesWith(I, A);
4812 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4813 if (A == Op0) // A^(A&B) -> A^(B&A)
4814 Op1I->swapOperands();
4815 if (B == Op0) { // A^(B&A) -> (B&A)^A
4816 I.swapOperands(); // Simplified below.
4817 std::swap(Op0, Op1);
4822 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4825 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4826 if (A == Op1) // (B|A)^B == (A|B)^B
4828 if (B == Op1) { // (A|B)^B == A & ~B
4830 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4831 return BinaryOperator::createAnd(A, NotB);
4833 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4834 if (Op1 == A) // (A^B)^A == B
4835 return ReplaceInstUsesWith(I, B);
4836 else if (Op1 == B) // (B^A)^A == B
4837 return ReplaceInstUsesWith(I, A);
4838 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4839 if (A == Op1) // (A&B)^A -> (B&A)^A
4841 if (B == Op1 && // (B&A)^A == ~B & A
4842 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4844 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4845 return BinaryOperator::createAnd(N, Op1);
4850 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4851 if (Op0I && Op1I && Op0I->isShift() &&
4852 Op0I->getOpcode() == Op1I->getOpcode() &&
4853 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4854 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4855 Instruction *NewOp =
4856 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4857 Op1I->getOperand(0),
4858 Op0I->getName()), I);
4859 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4860 Op1I->getOperand(1));
4864 Value *A, *B, *C, *D;
4865 // (A & B)^(A | B) -> A ^ B
4866 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4867 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4868 if ((A == C && B == D) || (A == D && B == C))
4869 return BinaryOperator::createXor(A, B);
4871 // (A | B)^(A & B) -> A ^ B
4872 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4873 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4874 if ((A == C && B == D) || (A == D && B == C))
4875 return BinaryOperator::createXor(A, B);
4879 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4880 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4881 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4882 // (X & Y)^(X & Y) -> (Y^Z) & X
4883 Value *X = 0, *Y = 0, *Z = 0;
4885 X = A, Y = B, Z = D;
4887 X = A, Y = B, Z = C;
4889 X = B, Y = A, Z = D;
4891 X = B, Y = A, Z = C;
4894 Instruction *NewOp =
4895 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4896 return BinaryOperator::createAnd(NewOp, X);
4901 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4902 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4903 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4906 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4907 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4908 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4909 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4910 const Type *SrcTy = Op0C->getOperand(0)->getType();
4911 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4912 // Only do this if the casts both really cause code to be generated.
4913 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4915 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4917 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4918 Op1C->getOperand(0),
4920 InsertNewInstBefore(NewOp, I);
4921 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4925 return Changed ? &I : 0;
4928 static bool isPositive(ConstantInt *C) {
4929 return C->getSExtValue() >= 0;
4932 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4933 /// overflowed for this type.
4934 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4936 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4938 return cast<ConstantInt>(Result)->getZExtValue() <
4939 cast<ConstantInt>(In1)->getZExtValue();
4942 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4943 /// code necessary to compute the offset from the base pointer (without adding
4944 /// in the base pointer). Return the result as a signed integer of intptr size.
4945 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4946 TargetData &TD = IC.getTargetData();
4947 gep_type_iterator GTI = gep_type_begin(GEP);
4948 const Type *IntPtrTy = TD.getIntPtrType();
4949 Value *Result = Constant::getNullValue(IntPtrTy);
4951 // Build a mask for high order bits.
4952 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4954 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4955 Value *Op = GEP->getOperand(i);
4956 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4957 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4958 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4959 if (!OpC->isNullValue()) {
4960 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4961 Scale = ConstantExpr::getMul(OpC, Scale);
4962 if (Constant *RC = dyn_cast<Constant>(Result))
4963 Result = ConstantExpr::getAdd(RC, Scale);
4965 // Emit an add instruction.
4966 Result = IC.InsertNewInstBefore(
4967 BinaryOperator::createAdd(Result, Scale,
4968 GEP->getName()+".offs"), I);
4972 // Convert to correct type.
4973 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4974 Op->getName()+".c"), I);
4976 // We'll let instcombine(mul) convert this to a shl if possible.
4977 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4978 GEP->getName()+".idx"), I);
4980 // Emit an add instruction.
4981 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4982 GEP->getName()+".offs"), I);
4988 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4989 /// else. At this point we know that the GEP is on the LHS of the comparison.
4990 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4991 ICmpInst::Predicate Cond,
4993 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4995 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4996 if (isa<PointerType>(CI->getOperand(0)->getType()))
4997 RHS = CI->getOperand(0);
4999 Value *PtrBase = GEPLHS->getOperand(0);
5000 if (PtrBase == RHS) {
5001 // As an optimization, we don't actually have to compute the actual value of
5002 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
5003 // each index is zero or not.
5004 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
5005 Instruction *InVal = 0;
5006 gep_type_iterator GTI = gep_type_begin(GEPLHS);
5007 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
5009 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
5010 if (isa<UndefValue>(C)) // undef index -> undef.
5011 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5012 if (C->isNullValue())
5014 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
5015 EmitIt = false; // This is indexing into a zero sized array?
5016 } else if (isa<ConstantInt>(C))
5017 return ReplaceInstUsesWith(I, // No comparison is needed here.
5018 ConstantInt::get(Type::Int1Ty,
5019 Cond == ICmpInst::ICMP_NE));
5024 new ICmpInst(Cond, GEPLHS->getOperand(i),
5025 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
5029 InVal = InsertNewInstBefore(InVal, I);
5030 InsertNewInstBefore(Comp, I);
5031 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
5032 InVal = BinaryOperator::createOr(InVal, Comp);
5033 else // True if all are equal
5034 InVal = BinaryOperator::createAnd(InVal, Comp);
5042 // No comparison is needed here, all indexes = 0
5043 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5044 Cond == ICmpInst::ICMP_EQ));
5047 // Only lower this if the icmp is the only user of the GEP or if we expect
5048 // the result to fold to a constant!
5049 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
5050 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5051 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
5052 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5053 Constant::getNullValue(Offset->getType()));
5055 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5056 // If the base pointers are different, but the indices are the same, just
5057 // compare the base pointer.
5058 if (PtrBase != GEPRHS->getOperand(0)) {
5059 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5060 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5061 GEPRHS->getOperand(0)->getType();
5063 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5064 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5065 IndicesTheSame = false;
5069 // If all indices are the same, just compare the base pointers.
5071 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5072 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5074 // Otherwise, the base pointers are different and the indices are
5075 // different, bail out.
5079 // If one of the GEPs has all zero indices, recurse.
5080 bool AllZeros = true;
5081 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5082 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5083 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5088 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5089 ICmpInst::getSwappedPredicate(Cond), I);
5091 // If the other GEP has all zero indices, recurse.
5093 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5094 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5095 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5100 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5102 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5103 // If the GEPs only differ by one index, compare it.
5104 unsigned NumDifferences = 0; // Keep track of # differences.
5105 unsigned DiffOperand = 0; // The operand that differs.
5106 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5107 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5108 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5109 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5110 // Irreconcilable differences.
5114 if (NumDifferences++) break;
5119 if (NumDifferences == 0) // SAME GEP?
5120 return ReplaceInstUsesWith(I, // No comparison is needed here.
5121 ConstantInt::get(Type::Int1Ty,
5122 Cond == ICmpInst::ICMP_EQ));
5123 else if (NumDifferences == 1) {
5124 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5125 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5126 // Make sure we do a signed comparison here.
5127 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5131 // Only lower this if the icmp is the only user of the GEP or if we expect
5132 // the result to fold to a constant!
5133 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5134 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5135 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5136 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5137 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5138 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5144 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5145 bool Changed = SimplifyCompare(I);
5146 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5148 // Fold trivial predicates.
5149 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5150 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5151 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5152 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5154 // Simplify 'fcmp pred X, X'
5156 switch (I.getPredicate()) {
5157 default: assert(0 && "Unknown predicate!");
5158 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5159 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5160 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5161 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5162 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5163 case FCmpInst::FCMP_OLT: // True if ordered and less than
5164 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5165 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5167 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5168 case FCmpInst::FCMP_ULT: // True if unordered or less than
5169 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5170 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5171 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5172 I.setPredicate(FCmpInst::FCMP_UNO);
5173 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5176 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5177 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5178 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5179 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5180 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5181 I.setPredicate(FCmpInst::FCMP_ORD);
5182 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5187 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5188 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5190 // Handle fcmp with constant RHS
5191 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5192 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5193 switch (LHSI->getOpcode()) {
5194 case Instruction::PHI:
5195 if (Instruction *NV = FoldOpIntoPhi(I))
5198 case Instruction::Select:
5199 // If either operand of the select is a constant, we can fold the
5200 // comparison into the select arms, which will cause one to be
5201 // constant folded and the select turned into a bitwise or.
5202 Value *Op1 = 0, *Op2 = 0;
5203 if (LHSI->hasOneUse()) {
5204 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5205 // Fold the known value into the constant operand.
5206 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5207 // Insert a new FCmp of the other select operand.
5208 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5209 LHSI->getOperand(2), RHSC,
5211 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5212 // Fold the known value into the constant operand.
5213 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5214 // Insert a new FCmp of the other select operand.
5215 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5216 LHSI->getOperand(1), RHSC,
5222 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5227 return Changed ? &I : 0;
5230 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5231 bool Changed = SimplifyCompare(I);
5232 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5233 const Type *Ty = Op0->getType();
5237 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5238 isTrueWhenEqual(I)));
5240 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5241 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5243 // icmp of GlobalValues can never equal each other as long as they aren't
5244 // external weak linkage type.
5245 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
5246 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
5247 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
5248 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5249 !isTrueWhenEqual(I)));
5251 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5252 // addresses never equal each other! We already know that Op0 != Op1.
5253 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5254 isa<ConstantPointerNull>(Op0)) &&
5255 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5256 isa<ConstantPointerNull>(Op1)))
5257 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5258 !isTrueWhenEqual(I)));
5260 // icmp's with boolean values can always be turned into bitwise operations
5261 if (Ty == Type::Int1Ty) {
5262 switch (I.getPredicate()) {
5263 default: assert(0 && "Invalid icmp instruction!");
5264 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
5265 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
5266 InsertNewInstBefore(Xor, I);
5267 return BinaryOperator::createNot(Xor);
5269 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
5270 return BinaryOperator::createXor(Op0, Op1);
5272 case ICmpInst::ICMP_UGT:
5273 case ICmpInst::ICMP_SGT:
5274 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5276 case ICmpInst::ICMP_ULT:
5277 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
5278 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5279 InsertNewInstBefore(Not, I);
5280 return BinaryOperator::createAnd(Not, Op1);
5282 case ICmpInst::ICMP_UGE:
5283 case ICmpInst::ICMP_SGE:
5284 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5286 case ICmpInst::ICMP_ULE:
5287 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
5288 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5289 InsertNewInstBefore(Not, I);
5290 return BinaryOperator::createOr(Not, Op1);
5295 // See if we are doing a comparison between a constant and an instruction that
5296 // can be folded into the comparison.
5297 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5298 switch (I.getPredicate()) {
5300 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5301 if (CI->isMinValue(false))
5302 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5303 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5304 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5305 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5306 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5309 case ICmpInst::ICMP_SLT:
5310 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5311 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5312 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5313 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5314 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5315 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5318 case ICmpInst::ICMP_UGT:
5319 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5320 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5321 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5322 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5323 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5324 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5327 case ICmpInst::ICMP_SGT:
5328 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5329 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5330 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5331 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5332 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5333 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5336 case ICmpInst::ICMP_ULE:
5337 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5338 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5339 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5340 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5341 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5342 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5345 case ICmpInst::ICMP_SLE:
5346 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5347 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5348 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5349 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5350 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5351 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5354 case ICmpInst::ICMP_UGE:
5355 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5356 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5357 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5358 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5359 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5360 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5363 case ICmpInst::ICMP_SGE:
5364 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5365 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5366 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5367 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5368 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5369 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5373 // If we still have a icmp le or icmp ge instruction, turn it into the
5374 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5375 // already been handled above, this requires little checking.
5377 if (I.getPredicate() == ICmpInst::ICMP_ULE)
5378 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5379 if (I.getPredicate() == ICmpInst::ICMP_SLE)
5380 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5381 if (I.getPredicate() == ICmpInst::ICMP_UGE)
5382 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5383 if (I.getPredicate() == ICmpInst::ICMP_SGE)
5384 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5386 // See if we can fold the comparison based on bits known to be zero or one
5388 uint64_t KnownZero, KnownOne;
5389 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
5390 KnownZero, KnownOne, 0))
5393 // Given the known and unknown bits, compute a range that the LHS could be
5395 if (KnownOne | KnownZero) {
5396 // Compute the Min, Max and RHS values based on the known bits. For the
5397 // EQ and NE we use unsigned values.
5398 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
5399 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
5400 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5401 SRHSVal = CI->getSExtValue();
5402 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
5405 URHSVal = CI->getZExtValue();
5406 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
5409 switch (I.getPredicate()) { // LE/GE have been folded already.
5410 default: assert(0 && "Unknown icmp opcode!");
5411 case ICmpInst::ICMP_EQ:
5412 if (UMax < URHSVal || UMin > URHSVal)
5413 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5415 case ICmpInst::ICMP_NE:
5416 if (UMax < URHSVal || UMin > URHSVal)
5417 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5419 case ICmpInst::ICMP_ULT:
5421 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5423 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5425 case ICmpInst::ICMP_UGT:
5427 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5429 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5431 case ICmpInst::ICMP_SLT:
5433 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5435 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5437 case ICmpInst::ICMP_SGT:
5439 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5441 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5446 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5447 // instruction, see if that instruction also has constants so that the
5448 // instruction can be folded into the icmp
5449 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5450 switch (LHSI->getOpcode()) {
5451 case Instruction::And:
5452 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5453 LHSI->getOperand(0)->hasOneUse()) {
5454 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5456 // If the LHS is an AND of a truncating cast, we can widen the
5457 // and/compare to be the input width without changing the value
5458 // produced, eliminating a cast.
5459 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
5460 // We can do this transformation if either the AND constant does not
5461 // have its sign bit set or if it is an equality comparison.
5462 // Extending a relational comparison when we're checking the sign
5463 // bit would not work.
5464 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
5466 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
5467 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
5468 ConstantInt *NewCST;
5470 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
5471 AndCST->getZExtValue());
5472 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
5473 CI->getZExtValue());
5474 Instruction *NewAnd =
5475 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
5477 InsertNewInstBefore(NewAnd, I);
5478 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
5482 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5483 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5484 // happens a LOT in code produced by the C front-end, for bitfield
5486 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5487 if (Shift && !Shift->isShift())
5491 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5492 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5493 const Type *AndTy = AndCST->getType(); // Type of the and.
5495 // We can fold this as long as we can't shift unknown bits
5496 // into the mask. This can only happen with signed shift
5497 // rights, as they sign-extend.
5499 bool CanFold = Shift->isLogicalShift();
5501 // To test for the bad case of the signed shr, see if any
5502 // of the bits shifted in could be tested after the mask.
5503 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
5504 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
5506 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
5508 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
5510 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
5516 if (Shift->getOpcode() == Instruction::Shl)
5517 NewCst = ConstantExpr::getLShr(CI, ShAmt);
5519 NewCst = ConstantExpr::getShl(CI, ShAmt);
5521 // Check to see if we are shifting out any of the bits being
5523 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
5524 // If we shifted bits out, the fold is not going to work out.
5525 // As a special case, check to see if this means that the
5526 // result is always true or false now.
5527 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5528 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5529 if (I.getPredicate() == ICmpInst::ICMP_NE)
5530 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5532 I.setOperand(1, NewCst);
5533 Constant *NewAndCST;
5534 if (Shift->getOpcode() == Instruction::Shl)
5535 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5537 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5538 LHSI->setOperand(1, NewAndCST);
5539 LHSI->setOperand(0, Shift->getOperand(0));
5540 AddToWorkList(Shift); // Shift is dead.
5541 AddUsesToWorkList(I);
5547 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5548 // preferable because it allows the C<<Y expression to be hoisted out
5549 // of a loop if Y is invariant and X is not.
5550 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
5551 I.isEquality() && !Shift->isArithmeticShift() &&
5552 isa<Instruction>(Shift->getOperand(0))) {
5555 if (Shift->getOpcode() == Instruction::LShr) {
5556 NS = BinaryOperator::createShl(AndCST,
5557 Shift->getOperand(1), "tmp");
5559 // Insert a logical shift.
5560 NS = BinaryOperator::createLShr(AndCST,
5561 Shift->getOperand(1), "tmp");
5563 InsertNewInstBefore(cast<Instruction>(NS), I);
5565 // Compute X & (C << Y).
5566 Instruction *NewAnd = BinaryOperator::createAnd(
5567 Shift->getOperand(0), NS, LHSI->getName());
5568 InsertNewInstBefore(NewAnd, I);
5570 I.setOperand(0, NewAnd);
5576 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
5577 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5578 if (I.isEquality()) {
5579 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5581 // Check that the shift amount is in range. If not, don't perform
5582 // undefined shifts. When the shift is visited it will be
5584 if (ShAmt->getZExtValue() >= TypeBits)
5587 // If we are comparing against bits always shifted out, the
5588 // comparison cannot succeed.
5590 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
5591 if (Comp != CI) {// Comparing against a bit that we know is zero.
5592 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5593 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5594 return ReplaceInstUsesWith(I, Cst);
5597 if (LHSI->hasOneUse()) {
5598 // Otherwise strength reduce the shift into an and.
5599 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
5600 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
5601 Constant *Mask = ConstantInt::get(CI->getType(), Val);
5604 BinaryOperator::createAnd(LHSI->getOperand(0),
5605 Mask, LHSI->getName()+".mask");
5606 Value *And = InsertNewInstBefore(AndI, I);
5607 return new ICmpInst(I.getPredicate(), And,
5608 ConstantExpr::getLShr(CI, ShAmt));
5614 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5615 case Instruction::AShr:
5616 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5617 if (I.isEquality()) {
5618 // Check that the shift amount is in range. If not, don't perform
5619 // undefined shifts. When the shift is visited it will be
5621 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5622 if (ShAmt->getZExtValue() >= TypeBits)
5625 // If we are comparing against bits always shifted out, the
5626 // comparison cannot succeed.
5628 if (LHSI->getOpcode() == Instruction::LShr)
5629 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
5632 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
5635 if (Comp != CI) {// Comparing against a bit that we know is zero.
5636 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5637 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5638 return ReplaceInstUsesWith(I, Cst);
5641 if (LHSI->hasOneUse() || CI->isNullValue()) {
5642 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
5644 // Otherwise strength reduce the shift into an and.
5645 uint64_t Val = ~0ULL; // All ones.
5646 Val <<= ShAmtVal; // Shift over to the right spot.
5647 Val &= ~0ULL >> (64-TypeBits);
5648 Constant *Mask = ConstantInt::get(CI->getType(), Val);
5651 BinaryOperator::createAnd(LHSI->getOperand(0),
5652 Mask, LHSI->getName()+".mask");
5653 Value *And = InsertNewInstBefore(AndI, I);
5654 return new ICmpInst(I.getPredicate(), And,
5655 ConstantExpr::getShl(CI, ShAmt));
5661 case Instruction::SDiv:
5662 case Instruction::UDiv:
5663 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5664 // Fold this div into the comparison, producing a range check.
5665 // Determine, based on the divide type, what the range is being
5666 // checked. If there is an overflow on the low or high side, remember
5667 // it, otherwise compute the range [low, hi) bounding the new value.
5668 // See: InsertRangeTest above for the kinds of replacements possible.
5669 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5670 // FIXME: If the operand types don't match the type of the divide
5671 // then don't attempt this transform. The code below doesn't have the
5672 // logic to deal with a signed divide and an unsigned compare (and
5673 // vice versa). This is because (x /s C1) <s C2 produces different
5674 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5675 // (x /u C1) <u C2. Simply casting the operands and result won't
5676 // work. :( The if statement below tests that condition and bails
5678 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5679 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
5682 // Initialize the variables that will indicate the nature of the
5684 bool LoOverflow = false, HiOverflow = false;
5685 ConstantInt *LoBound = 0, *HiBound = 0;
5687 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5688 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5689 // C2 (CI). By solving for X we can turn this into a range check
5690 // instead of computing a divide.
5692 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
5694 // Determine if the product overflows by seeing if the product is
5695 // not equal to the divide. Make sure we do the same kind of divide
5696 // as in the LHS instruction that we're folding.
5697 bool ProdOV = !DivRHS->isNullValue() &&
5698 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5699 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
5701 // Get the ICmp opcode
5702 ICmpInst::Predicate predicate = I.getPredicate();
5704 if (DivRHS->isNullValue()) {
5705 // Don't hack on divide by zeros!
5706 } else if (!DivIsSigned) { // udiv
5708 LoOverflow = ProdOV;
5709 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
5710 } else if (isPositive(DivRHS)) { // Divisor is > 0.
5711 if (CI->isNullValue()) { // (X / pos) op 0
5713 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5715 } else if (isPositive(CI)) { // (X / pos) op pos
5717 LoOverflow = ProdOV;
5718 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
5719 } else { // (X / pos) op neg
5720 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5721 LoOverflow = AddWithOverflow(LoBound, Prod,
5722 cast<ConstantInt>(DivRHSH));
5724 HiOverflow = ProdOV;
5726 } else { // Divisor is < 0.
5727 if (CI->isNullValue()) { // (X / neg) op 0
5728 LoBound = AddOne(DivRHS);
5729 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5730 if (HiBound == DivRHS)
5731 LoBound = 0; // - INTMIN = INTMIN
5732 } else if (isPositive(CI)) { // (X / neg) op pos
5733 HiOverflow = LoOverflow = ProdOV;
5735 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
5736 HiBound = AddOne(Prod);
5737 } else { // (X / neg) op neg
5739 LoOverflow = HiOverflow = ProdOV;
5740 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5743 // Dividing by a negate swaps the condition.
5744 predicate = ICmpInst::getSwappedPredicate(predicate);
5748 Value *X = LHSI->getOperand(0);
5749 switch (predicate) {
5750 default: assert(0 && "Unhandled icmp opcode!");
5751 case ICmpInst::ICMP_EQ:
5752 if (LoOverflow && HiOverflow)
5753 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5754 else if (HiOverflow)
5755 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5756 ICmpInst::ICMP_UGE, X, LoBound);
5757 else if (LoOverflow)
5758 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5759 ICmpInst::ICMP_ULT, X, HiBound);
5761 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5763 case ICmpInst::ICMP_NE:
5764 if (LoOverflow && HiOverflow)
5765 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5766 else if (HiOverflow)
5767 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5768 ICmpInst::ICMP_ULT, X, LoBound);
5769 else if (LoOverflow)
5770 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5771 ICmpInst::ICMP_UGE, X, HiBound);
5773 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5775 case ICmpInst::ICMP_ULT:
5776 case ICmpInst::ICMP_SLT:
5778 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5779 return new ICmpInst(predicate, X, LoBound);
5780 case ICmpInst::ICMP_UGT:
5781 case ICmpInst::ICMP_SGT:
5783 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5784 if (predicate == ICmpInst::ICMP_UGT)
5785 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5787 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5794 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5795 if (I.isEquality()) {
5796 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5798 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5799 // the second operand is a constant, simplify a bit.
5800 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5801 switch (BO->getOpcode()) {
5802 case Instruction::SRem:
5803 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5804 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
5806 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
5807 if (V > 1 && isPowerOf2_64(V)) {
5808 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5809 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
5810 return new ICmpInst(I.getPredicate(), NewRem,
5811 Constant::getNullValue(BO->getType()));
5815 case Instruction::Add:
5816 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5817 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5818 if (BO->hasOneUse())
5819 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5820 ConstantExpr::getSub(CI, BOp1C));
5821 } else if (CI->isNullValue()) {
5822 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5823 // efficiently invertible, or if the add has just this one use.
5824 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5826 if (Value *NegVal = dyn_castNegVal(BOp1))
5827 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
5828 else if (Value *NegVal = dyn_castNegVal(BOp0))
5829 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
5830 else if (BO->hasOneUse()) {
5831 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5832 InsertNewInstBefore(Neg, I);
5834 return new ICmpInst(I.getPredicate(), BOp0, Neg);
5838 case Instruction::Xor:
5839 // For the xor case, we can xor two constants together, eliminating
5840 // the explicit xor.
5841 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5842 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5843 ConstantExpr::getXor(CI, BOC));
5846 case Instruction::Sub:
5847 // Replace (([sub|xor] A, B) != 0) with (A != B)
5848 if (CI->isNullValue())
5849 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5853 case Instruction::Or:
5854 // If bits are being or'd in that are not present in the constant we
5855 // are comparing against, then the comparison could never succeed!
5856 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5857 Constant *NotCI = ConstantExpr::getNot(CI);
5858 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5859 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5864 case Instruction::And:
5865 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5866 // If bits are being compared against that are and'd out, then the
5867 // comparison can never succeed!
5868 if (!ConstantExpr::getAnd(CI,
5869 ConstantExpr::getNot(BOC))->isNullValue())
5870 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5873 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5874 if (CI == BOC && isOneBitSet(CI))
5875 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5876 ICmpInst::ICMP_NE, Op0,
5877 Constant::getNullValue(CI->getType()));
5879 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5880 if (isSignBit(BOC)) {
5881 Value *X = BO->getOperand(0);
5882 Constant *Zero = Constant::getNullValue(X->getType());
5883 ICmpInst::Predicate pred = isICMP_NE ?
5884 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5885 return new ICmpInst(pred, X, Zero);
5888 // ((X & ~7) == 0) --> X < 8
5889 if (CI->isNullValue() && isHighOnes(BOC)) {
5890 Value *X = BO->getOperand(0);
5891 Constant *NegX = ConstantExpr::getNeg(BOC);
5892 ICmpInst::Predicate pred = isICMP_NE ?
5893 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5894 return new ICmpInst(pred, X, NegX);
5900 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5901 // Handle set{eq|ne} <intrinsic>, intcst.
5902 switch (II->getIntrinsicID()) {
5904 case Intrinsic::bswap_i16:
5905 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5906 AddToWorkList(II); // Dead?
5907 I.setOperand(0, II->getOperand(1));
5908 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5909 ByteSwap_16(CI->getZExtValue())));
5911 case Intrinsic::bswap_i32:
5912 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5913 AddToWorkList(II); // Dead?
5914 I.setOperand(0, II->getOperand(1));
5915 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5916 ByteSwap_32(CI->getZExtValue())));
5918 case Intrinsic::bswap_i64:
5919 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5920 AddToWorkList(II); // Dead?
5921 I.setOperand(0, II->getOperand(1));
5922 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5923 ByteSwap_64(CI->getZExtValue())));
5927 } else { // Not a ICMP_EQ/ICMP_NE
5928 // If the LHS is a cast from an integral value of the same size, then
5929 // since we know the RHS is a constant, try to simlify.
5930 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5931 Value *CastOp = Cast->getOperand(0);
5932 const Type *SrcTy = CastOp->getType();
5933 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5934 if (SrcTy->isInteger() &&
5935 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5936 // If this is an unsigned comparison, try to make the comparison use
5937 // smaller constant values.
5938 switch (I.getPredicate()) {
5940 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5941 ConstantInt *CUI = cast<ConstantInt>(CI);
5942 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5943 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5944 ConstantInt::get(SrcTy, -1ULL));
5947 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5948 ConstantInt *CUI = cast<ConstantInt>(CI);
5949 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5950 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5951 Constant::getNullValue(SrcTy));
5961 // Handle icmp with constant RHS
5962 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5963 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5964 switch (LHSI->getOpcode()) {
5965 case Instruction::GetElementPtr:
5966 if (RHSC->isNullValue()) {
5967 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5968 bool isAllZeros = true;
5969 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5970 if (!isa<Constant>(LHSI->getOperand(i)) ||
5971 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5976 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5977 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5981 case Instruction::PHI:
5982 if (Instruction *NV = FoldOpIntoPhi(I))
5985 case Instruction::Select:
5986 // If either operand of the select is a constant, we can fold the
5987 // comparison into the select arms, which will cause one to be
5988 // constant folded and the select turned into a bitwise or.
5989 Value *Op1 = 0, *Op2 = 0;
5990 if (LHSI->hasOneUse()) {
5991 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5992 // Fold the known value into the constant operand.
5993 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5994 // Insert a new ICmp of the other select operand.
5995 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5996 LHSI->getOperand(2), RHSC,
5998 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5999 // Fold the known value into the constant operand.
6000 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6001 // Insert a new ICmp of the other select operand.
6002 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6003 LHSI->getOperand(1), RHSC,
6009 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
6014 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6015 if (User *GEP = dyn_castGetElementPtr(Op0))
6016 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6018 if (User *GEP = dyn_castGetElementPtr(Op1))
6019 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6020 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6023 // Test to see if the operands of the icmp are casted versions of other
6024 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6026 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6027 if (isa<PointerType>(Op0->getType()) &&
6028 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6029 // We keep moving the cast from the left operand over to the right
6030 // operand, where it can often be eliminated completely.
6031 Op0 = CI->getOperand(0);
6033 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6034 // so eliminate it as well.
6035 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6036 Op1 = CI2->getOperand(0);
6038 // If Op1 is a constant, we can fold the cast into the constant.
6039 if (Op0->getType() != Op1->getType())
6040 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6041 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6043 // Otherwise, cast the RHS right before the icmp
6044 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
6046 return new ICmpInst(I.getPredicate(), Op0, Op1);
6050 if (isa<CastInst>(Op0)) {
6051 // Handle the special case of: icmp (cast bool to X), <cst>
6052 // This comes up when you have code like
6055 // For generality, we handle any zero-extension of any operand comparison
6056 // with a constant or another cast from the same type.
6057 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6058 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6062 if (I.isEquality()) {
6063 Value *A, *B, *C, *D;
6064 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6065 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6066 Value *OtherVal = A == Op1 ? B : A;
6067 return new ICmpInst(I.getPredicate(), OtherVal,
6068 Constant::getNullValue(A->getType()));
6071 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6072 // A^c1 == C^c2 --> A == C^(c1^c2)
6073 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6074 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6075 if (Op1->hasOneUse()) {
6076 Constant *NC = ConstantExpr::getXor(C1, C2);
6077 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
6078 return new ICmpInst(I.getPredicate(), A,
6079 InsertNewInstBefore(Xor, I));
6082 // A^B == A^D -> B == D
6083 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6084 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6085 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6086 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6090 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6091 (A == Op0 || B == Op0)) {
6092 // A == (A^B) -> B == 0
6093 Value *OtherVal = A == Op0 ? B : A;
6094 return new ICmpInst(I.getPredicate(), OtherVal,
6095 Constant::getNullValue(A->getType()));
6097 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6098 // (A-B) == A -> B == 0
6099 return new ICmpInst(I.getPredicate(), B,
6100 Constant::getNullValue(B->getType()));
6102 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6103 // A == (A-B) -> B == 0
6104 return new ICmpInst(I.getPredicate(), B,
6105 Constant::getNullValue(B->getType()));
6108 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6109 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6110 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6111 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6112 Value *X = 0, *Y = 0, *Z = 0;
6115 X = B; Y = D; Z = A;
6116 } else if (A == D) {
6117 X = B; Y = C; Z = A;
6118 } else if (B == C) {
6119 X = A; Y = D; Z = B;
6120 } else if (B == D) {
6121 X = A; Y = C; Z = B;
6124 if (X) { // Build (X^Y) & Z
6125 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
6126 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
6127 I.setOperand(0, Op1);
6128 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6133 return Changed ? &I : 0;
6136 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6137 // We only handle extending casts so far.
6139 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6140 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6141 Value *LHSCIOp = LHSCI->getOperand(0);
6142 const Type *SrcTy = LHSCIOp->getType();
6143 const Type *DestTy = LHSCI->getType();
6146 // We only handle extension cast instructions, so far. Enforce this.
6147 if (LHSCI->getOpcode() != Instruction::ZExt &&
6148 LHSCI->getOpcode() != Instruction::SExt)
6151 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6152 bool isSignedCmp = ICI.isSignedPredicate();
6154 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6155 // Not an extension from the same type?
6156 RHSCIOp = CI->getOperand(0);
6157 if (RHSCIOp->getType() != LHSCIOp->getType())
6160 // If the signedness of the two compares doesn't agree (i.e. one is a sext
6161 // and the other is a zext), then we can't handle this.
6162 if (CI->getOpcode() != LHSCI->getOpcode())
6165 // Likewise, if the signedness of the [sz]exts and the compare don't match,
6166 // then we can't handle this.
6167 if (isSignedExt != isSignedCmp && !ICI.isEquality())
6170 // Okay, just insert a compare of the reduced operands now!
6171 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6174 // If we aren't dealing with a constant on the RHS, exit early
6175 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6179 // Compute the constant that would happen if we truncated to SrcTy then
6180 // reextended to DestTy.
6181 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6182 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6184 // If the re-extended constant didn't change...
6186 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6187 // For example, we might have:
6188 // %A = sext short %X to uint
6189 // %B = icmp ugt uint %A, 1330
6190 // It is incorrect to transform this into
6191 // %B = icmp ugt short %X, 1330
6192 // because %A may have negative value.
6194 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6195 // OR operation is EQ/NE.
6196 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6197 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6202 // The re-extended constant changed so the constant cannot be represented
6203 // in the shorter type. Consequently, we cannot emit a simple comparison.
6205 // First, handle some easy cases. We know the result cannot be equal at this
6206 // point so handle the ICI.isEquality() cases
6207 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6208 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6209 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6210 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6212 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6213 // should have been folded away previously and not enter in here.
6216 // We're performing a signed comparison.
6217 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
6218 Result = ConstantInt::getFalse(); // X < (small) --> false
6220 Result = ConstantInt::getTrue(); // X < (large) --> true
6222 // We're performing an unsigned comparison.
6224 // We're performing an unsigned comp with a sign extended value.
6225 // This is true if the input is >= 0. [aka >s -1]
6226 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6227 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6228 NegOne, ICI.getName()), ICI);
6230 // Unsigned extend & unsigned compare -> always true.
6231 Result = ConstantInt::getTrue();
6235 // Finally, return the value computed.
6236 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6237 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6238 return ReplaceInstUsesWith(ICI, Result);
6240 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6241 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6242 "ICmp should be folded!");
6243 if (Constant *CI = dyn_cast<Constant>(Result))
6244 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6246 return BinaryOperator::createNot(Result);
6250 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6251 return commonShiftTransforms(I);
6254 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6255 return commonShiftTransforms(I);
6258 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6259 return commonShiftTransforms(I);
6262 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6263 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6266 // shl X, 0 == X and shr X, 0 == X
6267 // shl 0, X == 0 and shr 0, X == 0
6268 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6269 Op0 == Constant::getNullValue(Op0->getType()))
6270 return ReplaceInstUsesWith(I, Op0);
6272 if (isa<UndefValue>(Op0)) {
6273 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6274 return ReplaceInstUsesWith(I, Op0);
6275 else // undef << X -> 0, undef >>u X -> 0
6276 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6278 if (isa<UndefValue>(Op1)) {
6279 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6280 return ReplaceInstUsesWith(I, Op0);
6281 else // X << undef, X >>u undef -> 0
6282 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6285 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6286 if (I.getOpcode() == Instruction::AShr)
6287 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6288 if (CSI->isAllOnesValue())
6289 return ReplaceInstUsesWith(I, CSI);
6291 // Try to fold constant and into select arguments.
6292 if (isa<Constant>(Op0))
6293 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6294 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6297 // See if we can turn a signed shr into an unsigned shr.
6298 if (I.isArithmeticShift()) {
6299 if (MaskedValueIsZero(Op0,
6300 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
6301 return BinaryOperator::createLShr(Op0, Op1, I.getName());
6305 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6306 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6311 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6312 BinaryOperator &I) {
6313 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6315 // See if we can simplify any instructions used by the instruction whose sole
6316 // purpose is to compute bits we don't care about.
6317 uint64_t KnownZero, KnownOne;
6318 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
6319 KnownZero, KnownOne))
6322 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6323 // of a signed value.
6325 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6326 if (Op1->getZExtValue() >= TypeBits) {
6327 if (I.getOpcode() != Instruction::AShr)
6328 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6330 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6335 // ((X*C1) << C2) == (X * (C1 << C2))
6336 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6337 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6338 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6339 return BinaryOperator::createMul(BO->getOperand(0),
6340 ConstantExpr::getShl(BOOp, Op1));
6342 // Try to fold constant and into select arguments.
6343 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6344 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6346 if (isa<PHINode>(Op0))
6347 if (Instruction *NV = FoldOpIntoPhi(I))
6350 if (Op0->hasOneUse()) {
6351 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6352 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6355 switch (Op0BO->getOpcode()) {
6357 case Instruction::Add:
6358 case Instruction::And:
6359 case Instruction::Or:
6360 case Instruction::Xor: {
6361 // These operators commute.
6362 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6363 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6364 match(Op0BO->getOperand(1),
6365 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6366 Instruction *YS = BinaryOperator::createShl(
6367 Op0BO->getOperand(0), Op1,
6369 InsertNewInstBefore(YS, I); // (Y << C)
6371 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6372 Op0BO->getOperand(1)->getName());
6373 InsertNewInstBefore(X, I); // (X + (Y << C))
6374 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
6375 C2 = ConstantExpr::getShl(C2, Op1);
6376 return BinaryOperator::createAnd(X, C2);
6379 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6380 Value *Op0BOOp1 = Op0BO->getOperand(1);
6381 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6383 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6384 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6386 Instruction *YS = BinaryOperator::createShl(
6387 Op0BO->getOperand(0), Op1,
6389 InsertNewInstBefore(YS, I); // (Y << C)
6391 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6392 V1->getName()+".mask");
6393 InsertNewInstBefore(XM, I); // X & (CC << C)
6395 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6400 case Instruction::Sub: {
6401 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6402 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6403 match(Op0BO->getOperand(0),
6404 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6405 Instruction *YS = BinaryOperator::createShl(
6406 Op0BO->getOperand(1), Op1,
6408 InsertNewInstBefore(YS, I); // (Y << C)
6410 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6411 Op0BO->getOperand(0)->getName());
6412 InsertNewInstBefore(X, I); // (X + (Y << C))
6413 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
6414 C2 = ConstantExpr::getShl(C2, Op1);
6415 return BinaryOperator::createAnd(X, C2);
6418 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6419 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6420 match(Op0BO->getOperand(0),
6421 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6422 m_ConstantInt(CC))) && V2 == Op1 &&
6423 cast<BinaryOperator>(Op0BO->getOperand(0))
6424 ->getOperand(0)->hasOneUse()) {
6425 Instruction *YS = BinaryOperator::createShl(
6426 Op0BO->getOperand(1), Op1,
6428 InsertNewInstBefore(YS, I); // (Y << C)
6430 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6431 V1->getName()+".mask");
6432 InsertNewInstBefore(XM, I); // X & (CC << C)
6434 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6442 // If the operand is an bitwise operator with a constant RHS, and the
6443 // shift is the only use, we can pull it out of the shift.
6444 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6445 bool isValid = true; // Valid only for And, Or, Xor
6446 bool highBitSet = false; // Transform if high bit of constant set?
6448 switch (Op0BO->getOpcode()) {
6449 default: isValid = false; break; // Do not perform transform!
6450 case Instruction::Add:
6451 isValid = isLeftShift;
6453 case Instruction::Or:
6454 case Instruction::Xor:
6457 case Instruction::And:
6462 // If this is a signed shift right, and the high bit is modified
6463 // by the logical operation, do not perform the transformation.
6464 // The highBitSet boolean indicates the value of the high bit of
6465 // the constant which would cause it to be modified for this
6468 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
6469 uint64_t Val = Op0C->getZExtValue();
6470 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
6474 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6476 Instruction *NewShift =
6477 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6478 InsertNewInstBefore(NewShift, I);
6479 NewShift->takeName(Op0BO);
6481 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6488 // Find out if this is a shift of a shift by a constant.
6489 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6490 if (ShiftOp && !ShiftOp->isShift())
6493 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6494 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6495 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
6496 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
6497 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6498 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6499 Value *X = ShiftOp->getOperand(0);
6501 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6502 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
6503 AmtSum = I.getType()->getPrimitiveSizeInBits();
6505 const IntegerType *Ty = cast<IntegerType>(I.getType());
6507 // Check for (X << c1) << c2 and (X >> c1) >> c2
6508 if (I.getOpcode() == ShiftOp->getOpcode()) {
6509 return BinaryOperator::create(I.getOpcode(), X,
6510 ConstantInt::get(Ty, AmtSum));
6511 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6512 I.getOpcode() == Instruction::AShr) {
6513 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6514 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6515 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6516 I.getOpcode() == Instruction::LShr) {
6517 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6518 Instruction *Shift =
6519 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6520 InsertNewInstBefore(Shift, I);
6522 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6523 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6526 // Okay, if we get here, one shift must be left, and the other shift must be
6527 // right. See if the amounts are equal.
6528 if (ShiftAmt1 == ShiftAmt2) {
6529 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6530 if (I.getOpcode() == Instruction::Shl) {
6531 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
6532 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6534 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6535 if (I.getOpcode() == Instruction::LShr) {
6536 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
6537 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6539 // We can simplify ((X << C) >>s C) into a trunc + sext.
6540 // NOTE: we could do this for any C, but that would make 'unusual' integer
6541 // types. For now, just stick to ones well-supported by the code
6543 const Type *SExtType = 0;
6544 switch (Ty->getBitWidth() - ShiftAmt1) {
6545 case 8 : SExtType = Type::Int8Ty; break;
6546 case 16: SExtType = Type::Int16Ty; break;
6547 case 32: SExtType = Type::Int32Ty; break;
6551 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6552 InsertNewInstBefore(NewTrunc, I);
6553 return new SExtInst(NewTrunc, Ty);
6555 // Otherwise, we can't handle it yet.
6556 } else if (ShiftAmt1 < ShiftAmt2) {
6557 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
6559 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6560 if (I.getOpcode() == Instruction::Shl) {
6561 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6562 ShiftOp->getOpcode() == Instruction::AShr);
6563 Instruction *Shift =
6564 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6565 InsertNewInstBefore(Shift, I);
6567 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
6568 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6571 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6572 if (I.getOpcode() == Instruction::LShr) {
6573 assert(ShiftOp->getOpcode() == Instruction::Shl);
6574 Instruction *Shift =
6575 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6576 InsertNewInstBefore(Shift, I);
6578 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6579 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6582 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6584 assert(ShiftAmt2 < ShiftAmt1);
6585 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
6587 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6588 if (I.getOpcode() == Instruction::Shl) {
6589 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6590 ShiftOp->getOpcode() == Instruction::AShr);
6591 Instruction *Shift =
6592 BinaryOperator::create(ShiftOp->getOpcode(), X,
6593 ConstantInt::get(Ty, ShiftDiff));
6594 InsertNewInstBefore(Shift, I);
6596 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
6597 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6600 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6601 if (I.getOpcode() == Instruction::LShr) {
6602 assert(ShiftOp->getOpcode() == Instruction::Shl);
6603 Instruction *Shift =
6604 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6605 InsertNewInstBefore(Shift, I);
6607 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6608 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6611 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6618 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6619 /// expression. If so, decompose it, returning some value X, such that Val is
6622 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6624 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6625 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6626 Offset = CI->getZExtValue();
6628 return ConstantInt::get(Type::Int32Ty, 0);
6629 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6630 if (I->getNumOperands() == 2) {
6631 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6632 if (I->getOpcode() == Instruction::Shl) {
6633 // This is a value scaled by '1 << the shift amt'.
6634 Scale = 1U << CUI->getZExtValue();
6636 return I->getOperand(0);
6637 } else if (I->getOpcode() == Instruction::Mul) {
6638 // This value is scaled by 'CUI'.
6639 Scale = CUI->getZExtValue();
6641 return I->getOperand(0);
6642 } else if (I->getOpcode() == Instruction::Add) {
6643 // We have X+C. Check to see if we really have (X*C2)+C1,
6644 // where C1 is divisible by C2.
6647 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6648 Offset += CUI->getZExtValue();
6649 if (SubScale > 1 && (Offset % SubScale == 0)) {
6658 // Otherwise, we can't look past this.
6665 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6666 /// try to eliminate the cast by moving the type information into the alloc.
6667 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6668 AllocationInst &AI) {
6669 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
6670 if (!PTy) return 0; // Not casting the allocation to a pointer type.
6672 // Remove any uses of AI that are dead.
6673 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6675 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6676 Instruction *User = cast<Instruction>(*UI++);
6677 if (isInstructionTriviallyDead(User)) {
6678 while (UI != E && *UI == User)
6679 ++UI; // If this instruction uses AI more than once, don't break UI.
6682 DOUT << "IC: DCE: " << *User;
6683 EraseInstFromFunction(*User);
6687 // Get the type really allocated and the type casted to.
6688 const Type *AllocElTy = AI.getAllocatedType();
6689 const Type *CastElTy = PTy->getElementType();
6690 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6692 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6693 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6694 if (CastElTyAlign < AllocElTyAlign) return 0;
6696 // If the allocation has multiple uses, only promote it if we are strictly
6697 // increasing the alignment of the resultant allocation. If we keep it the
6698 // same, we open the door to infinite loops of various kinds.
6699 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6701 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6702 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
6703 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6705 // See if we can satisfy the modulus by pulling a scale out of the array
6707 unsigned ArraySizeScale, ArrayOffset;
6708 Value *NumElements = // See if the array size is a decomposable linear expr.
6709 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6711 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6713 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6714 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6716 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6721 // If the allocation size is constant, form a constant mul expression
6722 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6723 if (isa<ConstantInt>(NumElements))
6724 Amt = ConstantExpr::getMul(
6725 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6726 // otherwise multiply the amount and the number of elements
6727 else if (Scale != 1) {
6728 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6729 Amt = InsertNewInstBefore(Tmp, AI);
6733 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6734 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
6735 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6736 Amt = InsertNewInstBefore(Tmp, AI);
6739 AllocationInst *New;
6740 if (isa<MallocInst>(AI))
6741 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6743 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6744 InsertNewInstBefore(New, AI);
6747 // If the allocation has multiple uses, insert a cast and change all things
6748 // that used it to use the new cast. This will also hack on CI, but it will
6750 if (!AI.hasOneUse()) {
6751 AddUsesToWorkList(AI);
6752 // New is the allocation instruction, pointer typed. AI is the original
6753 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6754 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6755 InsertNewInstBefore(NewCast, AI);
6756 AI.replaceAllUsesWith(NewCast);
6758 return ReplaceInstUsesWith(CI, New);
6761 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6762 /// and return it as type Ty without inserting any new casts and without
6763 /// changing the computed value. This is used by code that tries to decide
6764 /// whether promoting or shrinking integer operations to wider or smaller types
6765 /// will allow us to eliminate a truncate or extend.
6767 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6768 /// extension operation if Ty is larger.
6769 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6770 int &NumCastsRemoved) {
6771 // We can always evaluate constants in another type.
6772 if (isa<ConstantInt>(V))
6775 Instruction *I = dyn_cast<Instruction>(V);
6776 if (!I) return false;
6778 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6780 switch (I->getOpcode()) {
6781 case Instruction::Add:
6782 case Instruction::Sub:
6783 case Instruction::And:
6784 case Instruction::Or:
6785 case Instruction::Xor:
6786 if (!I->hasOneUse()) return false;
6787 // These operators can all arbitrarily be extended or truncated.
6788 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6789 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
6791 case Instruction::Shl:
6792 if (!I->hasOneUse()) return false;
6793 // If we are truncating the result of this SHL, and if it's a shift of a
6794 // constant amount, we can always perform a SHL in a smaller type.
6795 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6796 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6797 CI->getZExtValue() < Ty->getBitWidth())
6798 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6801 case Instruction::LShr:
6802 if (!I->hasOneUse()) return false;
6803 // If this is a truncate of a logical shr, we can truncate it to a smaller
6804 // lshr iff we know that the bits we would otherwise be shifting in are
6806 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6807 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6808 MaskedValueIsZero(I->getOperand(0),
6809 OrigTy->getBitMask() & ~Ty->getBitMask()) &&
6810 CI->getZExtValue() < Ty->getBitWidth()) {
6811 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6815 case Instruction::Trunc:
6816 case Instruction::ZExt:
6817 case Instruction::SExt:
6818 // If this is a cast from the destination type, we can trivially eliminate
6819 // it, and this will remove a cast overall.
6820 if (I->getOperand(0)->getType() == Ty) {
6821 // If the first operand is itself a cast, and is eliminable, do not count
6822 // this as an eliminable cast. We would prefer to eliminate those two
6824 if (isa<CastInst>(I->getOperand(0)))
6832 // TODO: Can handle more cases here.
6839 /// EvaluateInDifferentType - Given an expression that
6840 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6841 /// evaluate the expression.
6842 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6844 if (Constant *C = dyn_cast<Constant>(V))
6845 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6847 // Otherwise, it must be an instruction.
6848 Instruction *I = cast<Instruction>(V);
6849 Instruction *Res = 0;
6850 switch (I->getOpcode()) {
6851 case Instruction::Add:
6852 case Instruction::Sub:
6853 case Instruction::And:
6854 case Instruction::Or:
6855 case Instruction::Xor:
6856 case Instruction::AShr:
6857 case Instruction::LShr:
6858 case Instruction::Shl: {
6859 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6860 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6861 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6862 LHS, RHS, I->getName());
6865 case Instruction::Trunc:
6866 case Instruction::ZExt:
6867 case Instruction::SExt:
6868 case Instruction::BitCast:
6869 // If the source type of the cast is the type we're trying for then we can
6870 // just return the source. There's no need to insert it because its not new.
6871 if (I->getOperand(0)->getType() == Ty)
6872 return I->getOperand(0);
6874 // Some other kind of cast, which shouldn't happen, so just ..
6877 // TODO: Can handle more cases here.
6878 assert(0 && "Unreachable!");
6882 return InsertNewInstBefore(Res, *I);
6885 /// @brief Implement the transforms common to all CastInst visitors.
6886 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6887 Value *Src = CI.getOperand(0);
6889 // Casting undef to anything results in undef so might as just replace it and
6890 // get rid of the cast.
6891 if (isa<UndefValue>(Src)) // cast undef -> undef
6892 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6894 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6895 // eliminate it now.
6896 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6897 if (Instruction::CastOps opc =
6898 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6899 // The first cast (CSrc) is eliminable so we need to fix up or replace
6900 // the second cast (CI). CSrc will then have a good chance of being dead.
6901 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6905 // If casting the result of a getelementptr instruction with no offset, turn
6906 // this into a cast of the original pointer!
6908 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6909 bool AllZeroOperands = true;
6910 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6911 if (!isa<Constant>(GEP->getOperand(i)) ||
6912 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6913 AllZeroOperands = false;
6916 if (AllZeroOperands) {
6917 // Changing the cast operand is usually not a good idea but it is safe
6918 // here because the pointer operand is being replaced with another
6919 // pointer operand so the opcode doesn't need to change.
6920 CI.setOperand(0, GEP->getOperand(0));
6925 // If we are casting a malloc or alloca to a pointer to a type of the same
6926 // size, rewrite the allocation instruction to allocate the "right" type.
6927 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6928 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6931 // If we are casting a select then fold the cast into the select
6932 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6933 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6936 // If we are casting a PHI then fold the cast into the PHI
6937 if (isa<PHINode>(Src))
6938 if (Instruction *NV = FoldOpIntoPhi(CI))
6944 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6945 /// integer types. This function implements the common transforms for all those
6947 /// @brief Implement the transforms common to CastInst with integer operands
6948 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6949 if (Instruction *Result = commonCastTransforms(CI))
6952 Value *Src = CI.getOperand(0);
6953 const Type *SrcTy = Src->getType();
6954 const Type *DestTy = CI.getType();
6955 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6956 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6958 // See if we can simplify any instructions used by the LHS whose sole
6959 // purpose is to compute bits we don't care about.
6960 uint64_t KnownZero = 0, KnownOne = 0;
6961 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
6962 KnownZero, KnownOne))
6965 // If the source isn't an instruction or has more than one use then we
6966 // can't do anything more.
6967 Instruction *SrcI = dyn_cast<Instruction>(Src);
6968 if (!SrcI || !Src->hasOneUse())
6971 // Attempt to propagate the cast into the instruction for int->int casts.
6972 int NumCastsRemoved = 0;
6973 if (!isa<BitCastInst>(CI) &&
6974 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6976 // If this cast is a truncate, evaluting in a different type always
6977 // eliminates the cast, so it is always a win. If this is a noop-cast
6978 // this just removes a noop cast which isn't pointful, but simplifies
6979 // the code. If this is a zero-extension, we need to do an AND to
6980 // maintain the clear top-part of the computation, so we require that
6981 // the input have eliminated at least one cast. If this is a sign
6982 // extension, we insert two new casts (to do the extension) so we
6983 // require that two casts have been eliminated.
6985 switch (CI.getOpcode()) {
6987 // All the others use floating point so we shouldn't actually
6988 // get here because of the check above.
6989 assert(0 && "Unknown cast type");
6990 case Instruction::Trunc:
6993 case Instruction::ZExt:
6994 DoXForm = NumCastsRemoved >= 1;
6996 case Instruction::SExt:
6997 DoXForm = NumCastsRemoved >= 2;
6999 case Instruction::BitCast:
7005 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7006 CI.getOpcode() == Instruction::SExt);
7007 assert(Res->getType() == DestTy);
7008 switch (CI.getOpcode()) {
7009 default: assert(0 && "Unknown cast type!");
7010 case Instruction::Trunc:
7011 case Instruction::BitCast:
7012 // Just replace this cast with the result.
7013 return ReplaceInstUsesWith(CI, Res);
7014 case Instruction::ZExt: {
7015 // We need to emit an AND to clear the high bits.
7016 assert(SrcBitSize < DestBitSize && "Not a zext?");
7018 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
7019 if (DestBitSize < 64)
7020 C = ConstantExpr::getTrunc(C, DestTy);
7021 return BinaryOperator::createAnd(Res, C);
7023 case Instruction::SExt:
7024 // We need to emit a cast to truncate, then a cast to sext.
7025 return CastInst::create(Instruction::SExt,
7026 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7032 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7033 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7035 switch (SrcI->getOpcode()) {
7036 case Instruction::Add:
7037 case Instruction::Mul:
7038 case Instruction::And:
7039 case Instruction::Or:
7040 case Instruction::Xor:
7041 // If we are discarding information, or just changing the sign,
7043 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7044 // Don't insert two casts if they cannot be eliminated. We allow
7045 // two casts to be inserted if the sizes are the same. This could
7046 // only be converting signedness, which is a noop.
7047 if (DestBitSize == SrcBitSize ||
7048 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7049 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7050 Instruction::CastOps opcode = CI.getOpcode();
7051 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7052 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7053 return BinaryOperator::create(
7054 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7058 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7059 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7060 SrcI->getOpcode() == Instruction::Xor &&
7061 Op1 == ConstantInt::getTrue() &&
7062 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7063 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7064 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7067 case Instruction::SDiv:
7068 case Instruction::UDiv:
7069 case Instruction::SRem:
7070 case Instruction::URem:
7071 // If we are just changing the sign, rewrite.
7072 if (DestBitSize == SrcBitSize) {
7073 // Don't insert two casts if they cannot be eliminated. We allow
7074 // two casts to be inserted if the sizes are the same. This could
7075 // only be converting signedness, which is a noop.
7076 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7077 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7078 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7080 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7082 return BinaryOperator::create(
7083 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7088 case Instruction::Shl:
7089 // Allow changing the sign of the source operand. Do not allow
7090 // changing the size of the shift, UNLESS the shift amount is a
7091 // constant. We must not change variable sized shifts to a smaller
7092 // size, because it is undefined to shift more bits out than exist
7094 if (DestBitSize == SrcBitSize ||
7095 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7096 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7097 Instruction::BitCast : Instruction::Trunc);
7098 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7099 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7100 return BinaryOperator::createShl(Op0c, Op1c);
7103 case Instruction::AShr:
7104 // If this is a signed shr, and if all bits shifted in are about to be
7105 // truncated off, turn it into an unsigned shr to allow greater
7107 if (DestBitSize < SrcBitSize &&
7108 isa<ConstantInt>(Op1)) {
7109 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
7110 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7111 // Insert the new logical shift right.
7112 return BinaryOperator::createLShr(Op0, Op1);
7117 case Instruction::ICmp:
7118 // If we are just checking for a icmp eq of a single bit and casting it
7119 // to an integer, then shift the bit to the appropriate place and then
7120 // cast to integer to avoid the comparison.
7121 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
7122 uint64_t Op1CV = Op1C->getZExtValue();
7123 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
7124 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7125 // cast (X == 1) to int --> X iff X has only the low bit set.
7126 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
7127 // cast (X != 0) to int --> X iff X has only the low bit set.
7128 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
7129 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
7130 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7131 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
7132 // If Op1C some other power of two, convert:
7133 uint64_t KnownZero, KnownOne;
7134 uint64_t TypeMask = Op1C->getType()->getBitMask();
7135 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
7137 // This only works for EQ and NE
7138 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
7139 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
7142 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
7143 bool isNE = pred == ICmpInst::ICMP_NE;
7144 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
7145 // (X&4) == 2 --> false
7146 // (X&4) != 2 --> true
7147 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7148 Res = ConstantExpr::getZExt(Res, CI.getType());
7149 return ReplaceInstUsesWith(CI, Res);
7152 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
7155 // Perform a logical shr by shiftamt.
7156 // Insert the shift to put the result in the low bit.
7157 In = InsertNewInstBefore(
7158 BinaryOperator::createLShr(In,
7159 ConstantInt::get(In->getType(), ShiftAmt),
7160 In->getName()+".lobit"), CI);
7163 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7164 Constant *One = ConstantInt::get(In->getType(), 1);
7165 In = BinaryOperator::createXor(In, One, "tmp");
7166 InsertNewInstBefore(cast<Instruction>(In), CI);
7169 if (CI.getType() == In->getType())
7170 return ReplaceInstUsesWith(CI, In);
7172 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7181 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
7182 if (Instruction *Result = commonIntCastTransforms(CI))
7185 Value *Src = CI.getOperand(0);
7186 const Type *Ty = CI.getType();
7187 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
7189 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7190 switch (SrcI->getOpcode()) {
7192 case Instruction::LShr:
7193 // We can shrink lshr to something smaller if we know the bits shifted in
7194 // are already zeros.
7195 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7196 unsigned ShAmt = ShAmtV->getZExtValue();
7198 // Get a mask for the bits shifting in.
7199 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
7200 Value* SrcIOp0 = SrcI->getOperand(0);
7201 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7202 if (ShAmt >= DestBitWidth) // All zeros.
7203 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7205 // Okay, we can shrink this. Truncate the input, then return a new
7207 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7208 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7210 return BinaryOperator::createLShr(V1, V2);
7212 } else { // This is a variable shr.
7214 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7215 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7216 // loop-invariant and CSE'd.
7217 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7218 Value *One = ConstantInt::get(SrcI->getType(), 1);
7220 Value *V = InsertNewInstBefore(
7221 BinaryOperator::createShl(One, SrcI->getOperand(1),
7223 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7224 SrcI->getOperand(0),
7226 Value *Zero = Constant::getNullValue(V->getType());
7227 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7237 Instruction *InstCombiner::visitZExt(CastInst &CI) {
7238 // If one of the common conversion will work ..
7239 if (Instruction *Result = commonIntCastTransforms(CI))
7242 Value *Src = CI.getOperand(0);
7244 // If this is a cast of a cast
7245 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7246 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7247 // types and if the sizes are just right we can convert this into a logical
7248 // 'and' which will be much cheaper than the pair of casts.
7249 if (isa<TruncInst>(CSrc)) {
7250 // Get the sizes of the types involved
7251 Value *A = CSrc->getOperand(0);
7252 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
7253 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7254 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7255 // If we're actually extending zero bits and the trunc is a no-op
7256 if (MidSize < DstSize && SrcSize == DstSize) {
7257 // Replace both of the casts with an And of the type mask.
7258 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
7259 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
7261 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7262 // Unfortunately, if the type changed, we need to cast it back.
7263 if (And->getType() != CI.getType()) {
7264 And->setName(CSrc->getName()+".mask");
7265 InsertNewInstBefore(And, CI);
7266 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7276 Instruction *InstCombiner::visitSExt(CastInst &CI) {
7277 return commonIntCastTransforms(CI);
7280 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7281 return commonCastTransforms(CI);
7284 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7285 return commonCastTransforms(CI);
7288 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7289 return commonCastTransforms(CI);
7292 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7293 return commonCastTransforms(CI);
7296 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7297 return commonCastTransforms(CI);
7300 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7301 return commonCastTransforms(CI);
7304 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7305 return commonCastTransforms(CI);
7308 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7309 return commonCastTransforms(CI);
7312 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
7314 // If the operands are integer typed then apply the integer transforms,
7315 // otherwise just apply the common ones.
7316 Value *Src = CI.getOperand(0);
7317 const Type *SrcTy = Src->getType();
7318 const Type *DestTy = CI.getType();
7320 if (SrcTy->isInteger() && DestTy->isInteger()) {
7321 if (Instruction *Result = commonIntCastTransforms(CI))
7324 if (Instruction *Result = commonCastTransforms(CI))
7329 // Get rid of casts from one type to the same type. These are useless and can
7330 // be replaced by the operand.
7331 if (DestTy == Src->getType())
7332 return ReplaceInstUsesWith(CI, Src);
7334 // If the source and destination are pointers, and this cast is equivalent to
7335 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
7336 // This can enhance SROA and other transforms that want type-safe pointers.
7337 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7338 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
7339 const Type *DstElTy = DstPTy->getElementType();
7340 const Type *SrcElTy = SrcPTy->getElementType();
7342 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7343 unsigned NumZeros = 0;
7344 while (SrcElTy != DstElTy &&
7345 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7346 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7347 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7351 // If we found a path from the src to dest, create the getelementptr now.
7352 if (SrcElTy == DstElTy) {
7353 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7354 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
7359 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7360 if (SVI->hasOneUse()) {
7361 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7362 // a bitconvert to a vector with the same # elts.
7363 if (isa<VectorType>(DestTy) &&
7364 cast<VectorType>(DestTy)->getNumElements() ==
7365 SVI->getType()->getNumElements()) {
7367 // If either of the operands is a cast from CI.getType(), then
7368 // evaluating the shuffle in the casted destination's type will allow
7369 // us to eliminate at least one cast.
7370 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7371 Tmp->getOperand(0)->getType() == DestTy) ||
7372 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7373 Tmp->getOperand(0)->getType() == DestTy)) {
7374 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7375 SVI->getOperand(0), DestTy, &CI);
7376 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7377 SVI->getOperand(1), DestTy, &CI);
7378 // Return a new shuffle vector. Use the same element ID's, as we
7379 // know the vector types match #elts.
7380 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7388 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7390 /// %D = select %cond, %C, %A
7392 /// %C = select %cond, %B, 0
7395 /// Assuming that the specified instruction is an operand to the select, return
7396 /// a bitmask indicating which operands of this instruction are foldable if they
7397 /// equal the other incoming value of the select.
7399 static unsigned GetSelectFoldableOperands(Instruction *I) {
7400 switch (I->getOpcode()) {
7401 case Instruction::Add:
7402 case Instruction::Mul:
7403 case Instruction::And:
7404 case Instruction::Or:
7405 case Instruction::Xor:
7406 return 3; // Can fold through either operand.
7407 case Instruction::Sub: // Can only fold on the amount subtracted.
7408 case Instruction::Shl: // Can only fold on the shift amount.
7409 case Instruction::LShr:
7410 case Instruction::AShr:
7413 return 0; // Cannot fold
7417 /// GetSelectFoldableConstant - For the same transformation as the previous
7418 /// function, return the identity constant that goes into the select.
7419 static Constant *GetSelectFoldableConstant(Instruction *I) {
7420 switch (I->getOpcode()) {
7421 default: assert(0 && "This cannot happen!"); abort();
7422 case Instruction::Add:
7423 case Instruction::Sub:
7424 case Instruction::Or:
7425 case Instruction::Xor:
7426 case Instruction::Shl:
7427 case Instruction::LShr:
7428 case Instruction::AShr:
7429 return Constant::getNullValue(I->getType());
7430 case Instruction::And:
7431 return ConstantInt::getAllOnesValue(I->getType());
7432 case Instruction::Mul:
7433 return ConstantInt::get(I->getType(), 1);
7437 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7438 /// have the same opcode and only one use each. Try to simplify this.
7439 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7441 if (TI->getNumOperands() == 1) {
7442 // If this is a non-volatile load or a cast from the same type,
7445 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7448 return 0; // unknown unary op.
7451 // Fold this by inserting a select from the input values.
7452 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7453 FI->getOperand(0), SI.getName()+".v");
7454 InsertNewInstBefore(NewSI, SI);
7455 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7459 // Only handle binary operators here.
7460 if (!isa<BinaryOperator>(TI))
7463 // Figure out if the operations have any operands in common.
7464 Value *MatchOp, *OtherOpT, *OtherOpF;
7466 if (TI->getOperand(0) == FI->getOperand(0)) {
7467 MatchOp = TI->getOperand(0);
7468 OtherOpT = TI->getOperand(1);
7469 OtherOpF = FI->getOperand(1);
7470 MatchIsOpZero = true;
7471 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7472 MatchOp = TI->getOperand(1);
7473 OtherOpT = TI->getOperand(0);
7474 OtherOpF = FI->getOperand(0);
7475 MatchIsOpZero = false;
7476 } else if (!TI->isCommutative()) {
7478 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7479 MatchOp = TI->getOperand(0);
7480 OtherOpT = TI->getOperand(1);
7481 OtherOpF = FI->getOperand(0);
7482 MatchIsOpZero = true;
7483 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7484 MatchOp = TI->getOperand(1);
7485 OtherOpT = TI->getOperand(0);
7486 OtherOpF = FI->getOperand(1);
7487 MatchIsOpZero = true;
7492 // If we reach here, they do have operations in common.
7493 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7494 OtherOpF, SI.getName()+".v");
7495 InsertNewInstBefore(NewSI, SI);
7497 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7499 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7501 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7503 assert(0 && "Shouldn't get here");
7507 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7508 Value *CondVal = SI.getCondition();
7509 Value *TrueVal = SI.getTrueValue();
7510 Value *FalseVal = SI.getFalseValue();
7512 // select true, X, Y -> X
7513 // select false, X, Y -> Y
7514 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7515 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7517 // select C, X, X -> X
7518 if (TrueVal == FalseVal)
7519 return ReplaceInstUsesWith(SI, TrueVal);
7521 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7522 return ReplaceInstUsesWith(SI, FalseVal);
7523 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7524 return ReplaceInstUsesWith(SI, TrueVal);
7525 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7526 if (isa<Constant>(TrueVal))
7527 return ReplaceInstUsesWith(SI, TrueVal);
7529 return ReplaceInstUsesWith(SI, FalseVal);
7532 if (SI.getType() == Type::Int1Ty) {
7533 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7534 if (C->getZExtValue()) {
7535 // Change: A = select B, true, C --> A = or B, C
7536 return BinaryOperator::createOr(CondVal, FalseVal);
7538 // Change: A = select B, false, C --> A = and !B, C
7540 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7541 "not."+CondVal->getName()), SI);
7542 return BinaryOperator::createAnd(NotCond, FalseVal);
7544 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7545 if (C->getZExtValue() == false) {
7546 // Change: A = select B, C, false --> A = and B, C
7547 return BinaryOperator::createAnd(CondVal, TrueVal);
7549 // Change: A = select B, C, true --> A = or !B, C
7551 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7552 "not."+CondVal->getName()), SI);
7553 return BinaryOperator::createOr(NotCond, TrueVal);
7558 // Selecting between two integer constants?
7559 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7560 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7561 // select C, 1, 0 -> cast C to int
7562 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
7563 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7564 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
7565 // select C, 0, 1 -> cast !C to int
7567 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7568 "not."+CondVal->getName()), SI);
7569 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7572 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7574 // (x <s 0) ? -1 : 0 -> ashr x, 31
7575 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
7576 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
7577 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7578 bool CanXForm = false;
7579 if (IC->isSignedPredicate())
7580 CanXForm = CmpCst->isNullValue() &&
7581 IC->getPredicate() == ICmpInst::ICMP_SLT;
7583 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
7584 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
7585 IC->getPredicate() == ICmpInst::ICMP_UGT;
7589 // The comparison constant and the result are not neccessarily the
7590 // same width. Make an all-ones value by inserting a AShr.
7591 Value *X = IC->getOperand(0);
7592 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
7593 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7594 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7596 InsertNewInstBefore(SRA, SI);
7598 // Finally, convert to the type of the select RHS. We figure out
7599 // if this requires a SExt, Trunc or BitCast based on the sizes.
7600 Instruction::CastOps opc = Instruction::BitCast;
7601 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
7602 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
7603 if (SRASize < SISize)
7604 opc = Instruction::SExt;
7605 else if (SRASize > SISize)
7606 opc = Instruction::Trunc;
7607 return CastInst::create(opc, SRA, SI.getType());
7612 // If one of the constants is zero (we know they can't both be) and we
7613 // have a fcmp instruction with zero, and we have an 'and' with the
7614 // non-constant value, eliminate this whole mess. This corresponds to
7615 // cases like this: ((X & 27) ? 27 : 0)
7616 if (TrueValC->isNullValue() || FalseValC->isNullValue())
7617 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7618 cast<Constant>(IC->getOperand(1))->isNullValue())
7619 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7620 if (ICA->getOpcode() == Instruction::And &&
7621 isa<ConstantInt>(ICA->getOperand(1)) &&
7622 (ICA->getOperand(1) == TrueValC ||
7623 ICA->getOperand(1) == FalseValC) &&
7624 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7625 // Okay, now we know that everything is set up, we just don't
7626 // know whether we have a icmp_ne or icmp_eq and whether the
7627 // true or false val is the zero.
7628 bool ShouldNotVal = !TrueValC->isNullValue();
7629 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7632 V = InsertNewInstBefore(BinaryOperator::create(
7633 Instruction::Xor, V, ICA->getOperand(1)), SI);
7634 return ReplaceInstUsesWith(SI, V);
7639 // See if we are selecting two values based on a comparison of the two values.
7640 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7641 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7642 // Transform (X == Y) ? X : Y -> Y
7643 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7644 return ReplaceInstUsesWith(SI, FalseVal);
7645 // Transform (X != Y) ? X : Y -> X
7646 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7647 return ReplaceInstUsesWith(SI, TrueVal);
7648 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7650 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7651 // Transform (X == Y) ? Y : X -> X
7652 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7653 return ReplaceInstUsesWith(SI, FalseVal);
7654 // Transform (X != Y) ? Y : X -> Y
7655 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7656 return ReplaceInstUsesWith(SI, TrueVal);
7657 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7661 // See if we are selecting two values based on a comparison of the two values.
7662 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7663 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7664 // Transform (X == Y) ? X : Y -> Y
7665 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7666 return ReplaceInstUsesWith(SI, FalseVal);
7667 // Transform (X != Y) ? X : Y -> X
7668 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7669 return ReplaceInstUsesWith(SI, TrueVal);
7670 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7672 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7673 // Transform (X == Y) ? Y : X -> X
7674 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7675 return ReplaceInstUsesWith(SI, FalseVal);
7676 // Transform (X != Y) ? Y : X -> Y
7677 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7678 return ReplaceInstUsesWith(SI, TrueVal);
7679 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7683 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7684 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7685 if (TI->hasOneUse() && FI->hasOneUse()) {
7686 Instruction *AddOp = 0, *SubOp = 0;
7688 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7689 if (TI->getOpcode() == FI->getOpcode())
7690 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7693 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7694 // even legal for FP.
7695 if (TI->getOpcode() == Instruction::Sub &&
7696 FI->getOpcode() == Instruction::Add) {
7697 AddOp = FI; SubOp = TI;
7698 } else if (FI->getOpcode() == Instruction::Sub &&
7699 TI->getOpcode() == Instruction::Add) {
7700 AddOp = TI; SubOp = FI;
7704 Value *OtherAddOp = 0;
7705 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7706 OtherAddOp = AddOp->getOperand(1);
7707 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7708 OtherAddOp = AddOp->getOperand(0);
7712 // So at this point we know we have (Y -> OtherAddOp):
7713 // select C, (add X, Y), (sub X, Z)
7714 Value *NegVal; // Compute -Z
7715 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7716 NegVal = ConstantExpr::getNeg(C);
7718 NegVal = InsertNewInstBefore(
7719 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7722 Value *NewTrueOp = OtherAddOp;
7723 Value *NewFalseOp = NegVal;
7725 std::swap(NewTrueOp, NewFalseOp);
7726 Instruction *NewSel =
7727 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7729 NewSel = InsertNewInstBefore(NewSel, SI);
7730 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7735 // See if we can fold the select into one of our operands.
7736 if (SI.getType()->isInteger()) {
7737 // See the comment above GetSelectFoldableOperands for a description of the
7738 // transformation we are doing here.
7739 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7740 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7741 !isa<Constant>(FalseVal))
7742 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7743 unsigned OpToFold = 0;
7744 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7746 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7751 Constant *C = GetSelectFoldableConstant(TVI);
7752 Instruction *NewSel =
7753 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7754 InsertNewInstBefore(NewSel, SI);
7755 NewSel->takeName(TVI);
7756 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7757 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7759 assert(0 && "Unknown instruction!!");
7764 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7765 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7766 !isa<Constant>(TrueVal))
7767 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7768 unsigned OpToFold = 0;
7769 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7771 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7776 Constant *C = GetSelectFoldableConstant(FVI);
7777 Instruction *NewSel =
7778 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7779 InsertNewInstBefore(NewSel, SI);
7780 NewSel->takeName(FVI);
7781 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7782 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7784 assert(0 && "Unknown instruction!!");
7789 if (BinaryOperator::isNot(CondVal)) {
7790 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7791 SI.setOperand(1, FalseVal);
7792 SI.setOperand(2, TrueVal);
7799 /// GetKnownAlignment - If the specified pointer has an alignment that we can
7800 /// determine, return it, otherwise return 0.
7801 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7802 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7803 unsigned Align = GV->getAlignment();
7804 if (Align == 0 && TD)
7805 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7807 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7808 unsigned Align = AI->getAlignment();
7809 if (Align == 0 && TD) {
7810 if (isa<AllocaInst>(AI))
7811 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7812 else if (isa<MallocInst>(AI)) {
7813 // Malloc returns maximally aligned memory.
7814 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7817 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7820 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7824 } else if (isa<BitCastInst>(V) ||
7825 (isa<ConstantExpr>(V) &&
7826 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7827 User *CI = cast<User>(V);
7828 if (isa<PointerType>(CI->getOperand(0)->getType()))
7829 return GetKnownAlignment(CI->getOperand(0), TD);
7831 } else if (isa<GetElementPtrInst>(V) ||
7832 (isa<ConstantExpr>(V) &&
7833 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7834 User *GEPI = cast<User>(V);
7835 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7836 if (BaseAlignment == 0) return 0;
7838 // If all indexes are zero, it is just the alignment of the base pointer.
7839 bool AllZeroOperands = true;
7840 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7841 if (!isa<Constant>(GEPI->getOperand(i)) ||
7842 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7843 AllZeroOperands = false;
7846 if (AllZeroOperands)
7847 return BaseAlignment;
7849 // Otherwise, if the base alignment is >= the alignment we expect for the
7850 // base pointer type, then we know that the resultant pointer is aligned at
7851 // least as much as its type requires.
7854 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7855 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7856 if (TD->getABITypeAlignment(PtrTy->getElementType())
7858 const Type *GEPTy = GEPI->getType();
7859 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7860 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
7868 /// visitCallInst - CallInst simplification. This mostly only handles folding
7869 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7870 /// the heavy lifting.
7872 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7873 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7874 if (!II) return visitCallSite(&CI);
7876 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7878 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7879 bool Changed = false;
7881 // memmove/cpy/set of zero bytes is a noop.
7882 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7883 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7885 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7886 if (CI->getZExtValue() == 1) {
7887 // Replace the instruction with just byte operations. We would
7888 // transform other cases to loads/stores, but we don't know if
7889 // alignment is sufficient.
7893 // If we have a memmove and the source operation is a constant global,
7894 // then the source and dest pointers can't alias, so we can change this
7895 // into a call to memcpy.
7896 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7897 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7898 if (GVSrc->isConstant()) {
7899 Module *M = CI.getParent()->getParent()->getParent();
7901 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
7903 Name = "llvm.memcpy.i32";
7905 Name = "llvm.memcpy.i64";
7906 Constant *MemCpy = M->getOrInsertFunction(Name,
7907 CI.getCalledFunction()->getFunctionType());
7908 CI.setOperand(0, MemCpy);
7913 // If we can determine a pointer alignment that is bigger than currently
7914 // set, update the alignment.
7915 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7916 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7917 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7918 unsigned Align = std::min(Alignment1, Alignment2);
7919 if (MI->getAlignment()->getZExtValue() < Align) {
7920 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7923 } else if (isa<MemSetInst>(MI)) {
7924 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7925 if (MI->getAlignment()->getZExtValue() < Alignment) {
7926 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7931 if (Changed) return II;
7933 switch (II->getIntrinsicID()) {
7935 case Intrinsic::ppc_altivec_lvx:
7936 case Intrinsic::ppc_altivec_lvxl:
7937 case Intrinsic::x86_sse_loadu_ps:
7938 case Intrinsic::x86_sse2_loadu_pd:
7939 case Intrinsic::x86_sse2_loadu_dq:
7940 // Turn PPC lvx -> load if the pointer is known aligned.
7941 // Turn X86 loadups -> load if the pointer is known aligned.
7942 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7943 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7944 PointerType::get(II->getType()), CI);
7945 return new LoadInst(Ptr);
7948 case Intrinsic::ppc_altivec_stvx:
7949 case Intrinsic::ppc_altivec_stvxl:
7950 // Turn stvx -> store if the pointer is known aligned.
7951 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7952 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7953 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7955 return new StoreInst(II->getOperand(1), Ptr);
7958 case Intrinsic::x86_sse_storeu_ps:
7959 case Intrinsic::x86_sse2_storeu_pd:
7960 case Intrinsic::x86_sse2_storeu_dq:
7961 case Intrinsic::x86_sse2_storel_dq:
7962 // Turn X86 storeu -> store if the pointer is known aligned.
7963 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7964 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7965 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7967 return new StoreInst(II->getOperand(2), Ptr);
7971 case Intrinsic::x86_sse_cvttss2si: {
7972 // These intrinsics only demands the 0th element of its input vector. If
7973 // we can simplify the input based on that, do so now.
7975 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7977 II->setOperand(1, V);
7983 case Intrinsic::ppc_altivec_vperm:
7984 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7985 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7986 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7988 // Check that all of the elements are integer constants or undefs.
7989 bool AllEltsOk = true;
7990 for (unsigned i = 0; i != 16; ++i) {
7991 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7992 !isa<UndefValue>(Mask->getOperand(i))) {
7999 // Cast the input vectors to byte vectors.
8000 Value *Op0 = InsertCastBefore(Instruction::BitCast,
8001 II->getOperand(1), Mask->getType(), CI);
8002 Value *Op1 = InsertCastBefore(Instruction::BitCast,
8003 II->getOperand(2), Mask->getType(), CI);
8004 Value *Result = UndefValue::get(Op0->getType());
8006 // Only extract each element once.
8007 Value *ExtractedElts[32];
8008 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8010 for (unsigned i = 0; i != 16; ++i) {
8011 if (isa<UndefValue>(Mask->getOperand(i)))
8013 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8014 Idx &= 31; // Match the hardware behavior.
8016 if (ExtractedElts[Idx] == 0) {
8018 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8019 InsertNewInstBefore(Elt, CI);
8020 ExtractedElts[Idx] = Elt;
8023 // Insert this value into the result vector.
8024 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8025 InsertNewInstBefore(cast<Instruction>(Result), CI);
8027 return CastInst::create(Instruction::BitCast, Result, CI.getType());
8032 case Intrinsic::stackrestore: {
8033 // If the save is right next to the restore, remove the restore. This can
8034 // happen when variable allocas are DCE'd.
8035 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8036 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8037 BasicBlock::iterator BI = SS;
8039 return EraseInstFromFunction(CI);
8043 // If the stack restore is in a return/unwind block and if there are no
8044 // allocas or calls between the restore and the return, nuke the restore.
8045 TerminatorInst *TI = II->getParent()->getTerminator();
8046 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8047 BasicBlock::iterator BI = II;
8048 bool CannotRemove = false;
8049 for (++BI; &*BI != TI; ++BI) {
8050 if (isa<AllocaInst>(BI) ||
8051 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8052 CannotRemove = true;
8057 return EraseInstFromFunction(CI);
8064 return visitCallSite(II);
8067 // InvokeInst simplification
8069 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8070 return visitCallSite(&II);
8073 // visitCallSite - Improvements for call and invoke instructions.
8075 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8076 bool Changed = false;
8078 // If the callee is a constexpr cast of a function, attempt to move the cast
8079 // to the arguments of the call/invoke.
8080 if (transformConstExprCastCall(CS)) return 0;
8082 Value *Callee = CS.getCalledValue();
8084 if (Function *CalleeF = dyn_cast<Function>(Callee))
8085 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8086 Instruction *OldCall = CS.getInstruction();
8087 // If the call and callee calling conventions don't match, this call must
8088 // be unreachable, as the call is undefined.
8089 new StoreInst(ConstantInt::getTrue(),
8090 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
8091 if (!OldCall->use_empty())
8092 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8093 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8094 return EraseInstFromFunction(*OldCall);
8098 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8099 // This instruction is not reachable, just remove it. We insert a store to
8100 // undef so that we know that this code is not reachable, despite the fact
8101 // that we can't modify the CFG here.
8102 new StoreInst(ConstantInt::getTrue(),
8103 UndefValue::get(PointerType::get(Type::Int1Ty)),
8104 CS.getInstruction());
8106 if (!CS.getInstruction()->use_empty())
8107 CS.getInstruction()->
8108 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8110 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8111 // Don't break the CFG, insert a dummy cond branch.
8112 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8113 ConstantInt::getTrue(), II);
8115 return EraseInstFromFunction(*CS.getInstruction());
8118 const PointerType *PTy = cast<PointerType>(Callee->getType());
8119 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8120 if (FTy->isVarArg()) {
8121 // See if we can optimize any arguments passed through the varargs area of
8123 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8124 E = CS.arg_end(); I != E; ++I)
8125 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8126 // If this cast does not effect the value passed through the varargs
8127 // area, we can eliminate the use of the cast.
8128 Value *Op = CI->getOperand(0);
8129 if (CI->isLosslessCast()) {
8136 return Changed ? CS.getInstruction() : 0;
8139 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8140 // attempt to move the cast to the arguments of the call/invoke.
8142 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8143 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8144 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8145 if (CE->getOpcode() != Instruction::BitCast ||
8146 !isa<Function>(CE->getOperand(0)))
8148 Function *Callee = cast<Function>(CE->getOperand(0));
8149 Instruction *Caller = CS.getInstruction();
8151 // Okay, this is a cast from a function to a different type. Unless doing so
8152 // would cause a type conversion of one of our arguments, change this call to
8153 // be a direct call with arguments casted to the appropriate types.
8155 const FunctionType *FT = Callee->getFunctionType();
8156 const Type *OldRetTy = Caller->getType();
8158 // Check to see if we are changing the return type...
8159 if (OldRetTy != FT->getReturnType()) {
8160 if (Callee->isDeclaration() && !Caller->use_empty() &&
8161 // Conversion is ok if changing from pointer to int of same size.
8162 !(isa<PointerType>(FT->getReturnType()) &&
8163 TD->getIntPtrType() == OldRetTy))
8164 return false; // Cannot transform this return value.
8166 // If the callsite is an invoke instruction, and the return value is used by
8167 // a PHI node in a successor, we cannot change the return type of the call
8168 // because there is no place to put the cast instruction (without breaking
8169 // the critical edge). Bail out in this case.
8170 if (!Caller->use_empty())
8171 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8172 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8174 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8175 if (PN->getParent() == II->getNormalDest() ||
8176 PN->getParent() == II->getUnwindDest())
8180 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8181 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8183 CallSite::arg_iterator AI = CS.arg_begin();
8184 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8185 const Type *ParamTy = FT->getParamType(i);
8186 const Type *ActTy = (*AI)->getType();
8187 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8188 //Either we can cast directly, or we can upconvert the argument
8189 bool isConvertible = ActTy == ParamTy ||
8190 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8191 (ParamTy->isInteger() && ActTy->isInteger() &&
8192 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8193 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8194 && c->getSExtValue() > 0);
8195 if (Callee->isDeclaration() && !isConvertible) return false;
8198 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8199 Callee->isDeclaration())
8200 return false; // Do not delete arguments unless we have a function body...
8202 // Okay, we decided that this is a safe thing to do: go ahead and start
8203 // inserting cast instructions as necessary...
8204 std::vector<Value*> Args;
8205 Args.reserve(NumActualArgs);
8207 AI = CS.arg_begin();
8208 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8209 const Type *ParamTy = FT->getParamType(i);
8210 if ((*AI)->getType() == ParamTy) {
8211 Args.push_back(*AI);
8213 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8214 false, ParamTy, false);
8215 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8216 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8220 // If the function takes more arguments than the call was taking, add them
8222 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8223 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8225 // If we are removing arguments to the function, emit an obnoxious warning...
8226 if (FT->getNumParams() < NumActualArgs)
8227 if (!FT->isVarArg()) {
8228 cerr << "WARNING: While resolving call to function '"
8229 << Callee->getName() << "' arguments were dropped!\n";
8231 // Add all of the arguments in their promoted form to the arg list...
8232 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8233 const Type *PTy = getPromotedType((*AI)->getType());
8234 if (PTy != (*AI)->getType()) {
8235 // Must promote to pass through va_arg area!
8236 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8238 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8239 InsertNewInstBefore(Cast, *Caller);
8240 Args.push_back(Cast);
8242 Args.push_back(*AI);
8247 if (FT->getReturnType() == Type::VoidTy)
8248 Caller->setName(""); // Void type should not have a name.
8251 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8252 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8253 &Args[0], Args.size(), Caller->getName(), Caller);
8254 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
8256 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
8257 if (cast<CallInst>(Caller)->isTailCall())
8258 cast<CallInst>(NC)->setTailCall();
8259 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8262 // Insert a cast of the return type as necessary.
8264 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8265 if (NV->getType() != Type::VoidTy) {
8266 const Type *CallerTy = Caller->getType();
8267 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
8269 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
8271 // If this is an invoke instruction, we should insert it after the first
8272 // non-phi, instruction in the normal successor block.
8273 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8274 BasicBlock::iterator I = II->getNormalDest()->begin();
8275 while (isa<PHINode>(I)) ++I;
8276 InsertNewInstBefore(NC, *I);
8278 // Otherwise, it's a call, just insert cast right after the call instr
8279 InsertNewInstBefore(NC, *Caller);
8281 AddUsersToWorkList(*Caller);
8283 NV = UndefValue::get(Caller->getType());
8287 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8288 Caller->replaceAllUsesWith(NV);
8289 Caller->eraseFromParent();
8290 RemoveFromWorkList(Caller);
8294 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8295 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8296 /// and a single binop.
8297 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8298 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8299 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8300 isa<CmpInst>(FirstInst));
8301 unsigned Opc = FirstInst->getOpcode();
8302 Value *LHSVal = FirstInst->getOperand(0);
8303 Value *RHSVal = FirstInst->getOperand(1);
8305 const Type *LHSType = LHSVal->getType();
8306 const Type *RHSType = RHSVal->getType();
8308 // Scan to see if all operands are the same opcode, all have one use, and all
8309 // kill their operands (i.e. the operands have one use).
8310 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8311 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8312 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8313 // Verify type of the LHS matches so we don't fold cmp's of different
8314 // types or GEP's with different index types.
8315 I->getOperand(0)->getType() != LHSType ||
8316 I->getOperand(1)->getType() != RHSType)
8319 // If they are CmpInst instructions, check their predicates
8320 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8321 if (cast<CmpInst>(I)->getPredicate() !=
8322 cast<CmpInst>(FirstInst)->getPredicate())
8325 // Keep track of which operand needs a phi node.
8326 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8327 if (I->getOperand(1) != RHSVal) RHSVal = 0;
8330 // Otherwise, this is safe to transform, determine if it is profitable.
8332 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8333 // Indexes are often folded into load/store instructions, so we don't want to
8334 // hide them behind a phi.
8335 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8338 Value *InLHS = FirstInst->getOperand(0);
8339 Value *InRHS = FirstInst->getOperand(1);
8340 PHINode *NewLHS = 0, *NewRHS = 0;
8342 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8343 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8344 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8345 InsertNewInstBefore(NewLHS, PN);
8350 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8351 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8352 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8353 InsertNewInstBefore(NewRHS, PN);
8357 // Add all operands to the new PHIs.
8358 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8360 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8361 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8364 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8365 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8369 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8370 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8371 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8372 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8375 assert(isa<GetElementPtrInst>(FirstInst));
8376 return new GetElementPtrInst(LHSVal, RHSVal);
8380 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8381 /// of the block that defines it. This means that it must be obvious the value
8382 /// of the load is not changed from the point of the load to the end of the
8385 /// Finally, it is safe, but not profitable, to sink a load targetting a
8386 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
8388 static bool isSafeToSinkLoad(LoadInst *L) {
8389 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8391 for (++BBI; BBI != E; ++BBI)
8392 if (BBI->mayWriteToMemory())
8395 // Check for non-address taken alloca. If not address-taken already, it isn't
8396 // profitable to do this xform.
8397 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8398 bool isAddressTaken = false;
8399 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8401 if (isa<LoadInst>(UI)) continue;
8402 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8403 // If storing TO the alloca, then the address isn't taken.
8404 if (SI->getOperand(1) == AI) continue;
8406 isAddressTaken = true;
8410 if (!isAddressTaken)
8418 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8419 // operator and they all are only used by the PHI, PHI together their
8420 // inputs, and do the operation once, to the result of the PHI.
8421 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8422 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8424 // Scan the instruction, looking for input operations that can be folded away.
8425 // If all input operands to the phi are the same instruction (e.g. a cast from
8426 // the same type or "+42") we can pull the operation through the PHI, reducing
8427 // code size and simplifying code.
8428 Constant *ConstantOp = 0;
8429 const Type *CastSrcTy = 0;
8430 bool isVolatile = false;
8431 if (isa<CastInst>(FirstInst)) {
8432 CastSrcTy = FirstInst->getOperand(0)->getType();
8433 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8434 // Can fold binop, compare or shift here if the RHS is a constant,
8435 // otherwise call FoldPHIArgBinOpIntoPHI.
8436 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8437 if (ConstantOp == 0)
8438 return FoldPHIArgBinOpIntoPHI(PN);
8439 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8440 isVolatile = LI->isVolatile();
8441 // We can't sink the load if the loaded value could be modified between the
8442 // load and the PHI.
8443 if (LI->getParent() != PN.getIncomingBlock(0) ||
8444 !isSafeToSinkLoad(LI))
8446 } else if (isa<GetElementPtrInst>(FirstInst)) {
8447 if (FirstInst->getNumOperands() == 2)
8448 return FoldPHIArgBinOpIntoPHI(PN);
8449 // Can't handle general GEPs yet.
8452 return 0; // Cannot fold this operation.
8455 // Check to see if all arguments are the same operation.
8456 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8457 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8458 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8459 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8462 if (I->getOperand(0)->getType() != CastSrcTy)
8463 return 0; // Cast operation must match.
8464 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8465 // We can't sink the load if the loaded value could be modified between
8466 // the load and the PHI.
8467 if (LI->isVolatile() != isVolatile ||
8468 LI->getParent() != PN.getIncomingBlock(i) ||
8469 !isSafeToSinkLoad(LI))
8471 } else if (I->getOperand(1) != ConstantOp) {
8476 // Okay, they are all the same operation. Create a new PHI node of the
8477 // correct type, and PHI together all of the LHS's of the instructions.
8478 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8479 PN.getName()+".in");
8480 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8482 Value *InVal = FirstInst->getOperand(0);
8483 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8485 // Add all operands to the new PHI.
8486 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8487 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8488 if (NewInVal != InVal)
8490 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8495 // The new PHI unions all of the same values together. This is really
8496 // common, so we handle it intelligently here for compile-time speed.
8500 InsertNewInstBefore(NewPN, PN);
8504 // Insert and return the new operation.
8505 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8506 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8507 else if (isa<LoadInst>(FirstInst))
8508 return new LoadInst(PhiVal, "", isVolatile);
8509 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8510 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8511 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8512 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8513 PhiVal, ConstantOp);
8515 assert(0 && "Unknown operation");
8519 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8521 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
8522 if (PN->use_empty()) return true;
8523 if (!PN->hasOneUse()) return false;
8525 // Remember this node, and if we find the cycle, return.
8526 if (!PotentiallyDeadPHIs.insert(PN).second)
8529 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8530 return DeadPHICycle(PU, PotentiallyDeadPHIs);
8535 // PHINode simplification
8537 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8538 // If LCSSA is around, don't mess with Phi nodes
8539 if (MustPreserveLCSSA) return 0;
8541 if (Value *V = PN.hasConstantValue())
8542 return ReplaceInstUsesWith(PN, V);
8544 // If all PHI operands are the same operation, pull them through the PHI,
8545 // reducing code size.
8546 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8547 PN.getIncomingValue(0)->hasOneUse())
8548 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8551 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8552 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8553 // PHI)... break the cycle.
8554 if (PN.hasOneUse()) {
8555 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8556 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8557 std::set<PHINode*> PotentiallyDeadPHIs;
8558 PotentiallyDeadPHIs.insert(&PN);
8559 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8560 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8563 // If this phi has a single use, and if that use just computes a value for
8564 // the next iteration of a loop, delete the phi. This occurs with unused
8565 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8566 // common case here is good because the only other things that catch this
8567 // are induction variable analysis (sometimes) and ADCE, which is only run
8569 if (PHIUser->hasOneUse() &&
8570 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8571 PHIUser->use_back() == &PN) {
8572 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8579 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8580 Instruction *InsertPoint,
8582 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8583 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8584 // We must cast correctly to the pointer type. Ensure that we
8585 // sign extend the integer value if it is smaller as this is
8586 // used for address computation.
8587 Instruction::CastOps opcode =
8588 (VTySize < PtrSize ? Instruction::SExt :
8589 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8590 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8594 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8595 Value *PtrOp = GEP.getOperand(0);
8596 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
8597 // If so, eliminate the noop.
8598 if (GEP.getNumOperands() == 1)
8599 return ReplaceInstUsesWith(GEP, PtrOp);
8601 if (isa<UndefValue>(GEP.getOperand(0)))
8602 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8604 bool HasZeroPointerIndex = false;
8605 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8606 HasZeroPointerIndex = C->isNullValue();
8608 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8609 return ReplaceInstUsesWith(GEP, PtrOp);
8611 // Eliminate unneeded casts for indices.
8612 bool MadeChange = false;
8613 gep_type_iterator GTI = gep_type_begin(GEP);
8614 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8615 if (isa<SequentialType>(*GTI)) {
8616 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8617 if (CI->getOpcode() == Instruction::ZExt ||
8618 CI->getOpcode() == Instruction::SExt) {
8619 const Type *SrcTy = CI->getOperand(0)->getType();
8620 // We can eliminate a cast from i32 to i64 iff the target
8621 // is a 32-bit pointer target.
8622 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8624 GEP.setOperand(i, CI->getOperand(0));
8628 // If we are using a wider index than needed for this platform, shrink it
8629 // to what we need. If the incoming value needs a cast instruction,
8630 // insert it. This explicit cast can make subsequent optimizations more
8632 Value *Op = GEP.getOperand(i);
8633 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
8634 if (Constant *C = dyn_cast<Constant>(Op)) {
8635 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8638 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8640 GEP.setOperand(i, Op);
8644 if (MadeChange) return &GEP;
8646 // Combine Indices - If the source pointer to this getelementptr instruction
8647 // is a getelementptr instruction, combine the indices of the two
8648 // getelementptr instructions into a single instruction.
8650 SmallVector<Value*, 8> SrcGEPOperands;
8651 if (User *Src = dyn_castGetElementPtr(PtrOp))
8652 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8654 if (!SrcGEPOperands.empty()) {
8655 // Note that if our source is a gep chain itself that we wait for that
8656 // chain to be resolved before we perform this transformation. This
8657 // avoids us creating a TON of code in some cases.
8659 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8660 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8661 return 0; // Wait until our source is folded to completion.
8663 SmallVector<Value*, 8> Indices;
8665 // Find out whether the last index in the source GEP is a sequential idx.
8666 bool EndsWithSequential = false;
8667 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8668 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8669 EndsWithSequential = !isa<StructType>(*I);
8671 // Can we combine the two pointer arithmetics offsets?
8672 if (EndsWithSequential) {
8673 // Replace: gep (gep %P, long B), long A, ...
8674 // With: T = long A+B; gep %P, T, ...
8676 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8677 if (SO1 == Constant::getNullValue(SO1->getType())) {
8679 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8682 // If they aren't the same type, convert both to an integer of the
8683 // target's pointer size.
8684 if (SO1->getType() != GO1->getType()) {
8685 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8686 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8687 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8688 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8690 unsigned PS = TD->getPointerSize();
8691 if (TD->getTypeSize(SO1->getType()) == PS) {
8692 // Convert GO1 to SO1's type.
8693 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8695 } else if (TD->getTypeSize(GO1->getType()) == PS) {
8696 // Convert SO1 to GO1's type.
8697 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8699 const Type *PT = TD->getIntPtrType();
8700 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8701 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8705 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8706 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8708 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8709 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8713 // Recycle the GEP we already have if possible.
8714 if (SrcGEPOperands.size() == 2) {
8715 GEP.setOperand(0, SrcGEPOperands[0]);
8716 GEP.setOperand(1, Sum);
8719 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8720 SrcGEPOperands.end()-1);
8721 Indices.push_back(Sum);
8722 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8724 } else if (isa<Constant>(*GEP.idx_begin()) &&
8725 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8726 SrcGEPOperands.size() != 1) {
8727 // Otherwise we can do the fold if the first index of the GEP is a zero
8728 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8729 SrcGEPOperands.end());
8730 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8733 if (!Indices.empty())
8734 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8735 Indices.size(), GEP.getName());
8737 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8738 // GEP of global variable. If all of the indices for this GEP are
8739 // constants, we can promote this to a constexpr instead of an instruction.
8741 // Scan for nonconstants...
8742 SmallVector<Constant*, 8> Indices;
8743 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8744 for (; I != E && isa<Constant>(*I); ++I)
8745 Indices.push_back(cast<Constant>(*I));
8747 if (I == E) { // If they are all constants...
8748 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8749 &Indices[0],Indices.size());
8751 // Replace all uses of the GEP with the new constexpr...
8752 return ReplaceInstUsesWith(GEP, CE);
8754 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
8755 if (!isa<PointerType>(X->getType())) {
8756 // Not interesting. Source pointer must be a cast from pointer.
8757 } else if (HasZeroPointerIndex) {
8758 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8759 // into : GEP [10 x ubyte]* X, long 0, ...
8761 // This occurs when the program declares an array extern like "int X[];"
8763 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8764 const PointerType *XTy = cast<PointerType>(X->getType());
8765 if (const ArrayType *XATy =
8766 dyn_cast<ArrayType>(XTy->getElementType()))
8767 if (const ArrayType *CATy =
8768 dyn_cast<ArrayType>(CPTy->getElementType()))
8769 if (CATy->getElementType() == XATy->getElementType()) {
8770 // At this point, we know that the cast source type is a pointer
8771 // to an array of the same type as the destination pointer
8772 // array. Because the array type is never stepped over (there
8773 // is a leading zero) we can fold the cast into this GEP.
8774 GEP.setOperand(0, X);
8777 } else if (GEP.getNumOperands() == 2) {
8778 // Transform things like:
8779 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8780 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
8781 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8782 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8783 if (isa<ArrayType>(SrcElTy) &&
8784 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8785 TD->getTypeSize(ResElTy)) {
8786 Value *V = InsertNewInstBefore(
8787 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8788 GEP.getOperand(1), GEP.getName()), GEP);
8789 // V and GEP are both pointer types --> BitCast
8790 return new BitCastInst(V, GEP.getType());
8793 // Transform things like:
8794 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8795 // (where tmp = 8*tmp2) into:
8796 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8798 if (isa<ArrayType>(SrcElTy) &&
8799 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
8800 uint64_t ArrayEltSize =
8801 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8803 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8804 // allow either a mul, shift, or constant here.
8806 ConstantInt *Scale = 0;
8807 if (ArrayEltSize == 1) {
8808 NewIdx = GEP.getOperand(1);
8809 Scale = ConstantInt::get(NewIdx->getType(), 1);
8810 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
8811 NewIdx = ConstantInt::get(CI->getType(), 1);
8813 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8814 if (Inst->getOpcode() == Instruction::Shl &&
8815 isa<ConstantInt>(Inst->getOperand(1))) {
8817 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
8818 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
8819 NewIdx = Inst->getOperand(0);
8820 } else if (Inst->getOpcode() == Instruction::Mul &&
8821 isa<ConstantInt>(Inst->getOperand(1))) {
8822 Scale = cast<ConstantInt>(Inst->getOperand(1));
8823 NewIdx = Inst->getOperand(0);
8827 // If the index will be to exactly the right offset with the scale taken
8828 // out, perform the transformation.
8829 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8830 if (isa<ConstantInt>(Scale))
8831 Scale = ConstantInt::get(Scale->getType(),
8832 Scale->getZExtValue() / ArrayEltSize);
8833 if (Scale->getZExtValue() != 1) {
8834 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8836 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8837 NewIdx = InsertNewInstBefore(Sc, GEP);
8840 // Insert the new GEP instruction.
8841 Instruction *NewGEP =
8842 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8843 NewIdx, GEP.getName());
8844 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8845 // The NewGEP must be pointer typed, so must the old one -> BitCast
8846 return new BitCastInst(NewGEP, GEP.getType());
8855 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8856 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8857 if (AI.isArrayAllocation()) // Check C != 1
8858 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8860 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8861 AllocationInst *New = 0;
8863 // Create and insert the replacement instruction...
8864 if (isa<MallocInst>(AI))
8865 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8867 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8868 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8871 InsertNewInstBefore(New, AI);
8873 // Scan to the end of the allocation instructions, to skip over a block of
8874 // allocas if possible...
8876 BasicBlock::iterator It = New;
8877 while (isa<AllocationInst>(*It)) ++It;
8879 // Now that I is pointing to the first non-allocation-inst in the block,
8880 // insert our getelementptr instruction...
8882 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8883 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8884 New->getName()+".sub", It);
8886 // Now make everything use the getelementptr instead of the original
8888 return ReplaceInstUsesWith(AI, V);
8889 } else if (isa<UndefValue>(AI.getArraySize())) {
8890 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8893 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8894 // Note that we only do this for alloca's, because malloc should allocate and
8895 // return a unique pointer, even for a zero byte allocation.
8896 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8897 TD->getTypeSize(AI.getAllocatedType()) == 0)
8898 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8903 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8904 Value *Op = FI.getOperand(0);
8906 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8907 if (CastInst *CI = dyn_cast<CastInst>(Op))
8908 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8909 FI.setOperand(0, CI->getOperand(0));
8913 // free undef -> unreachable.
8914 if (isa<UndefValue>(Op)) {
8915 // Insert a new store to null because we cannot modify the CFG here.
8916 new StoreInst(ConstantInt::getTrue(),
8917 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8918 return EraseInstFromFunction(FI);
8921 // If we have 'free null' delete the instruction. This can happen in stl code
8922 // when lots of inlining happens.
8923 if (isa<ConstantPointerNull>(Op))
8924 return EraseInstFromFunction(FI);
8930 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8931 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8932 User *CI = cast<User>(LI.getOperand(0));
8933 Value *CastOp = CI->getOperand(0);
8935 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8936 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8937 const Type *SrcPTy = SrcTy->getElementType();
8939 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
8940 isa<VectorType>(DestPTy)) {
8941 // If the source is an array, the code below will not succeed. Check to
8942 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8944 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8945 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8946 if (ASrcTy->getNumElements() != 0) {
8948 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8949 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8950 SrcTy = cast<PointerType>(CastOp->getType());
8951 SrcPTy = SrcTy->getElementType();
8954 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
8955 isa<VectorType>(SrcPTy)) &&
8956 // Do not allow turning this into a load of an integer, which is then
8957 // casted to a pointer, this pessimizes pointer analysis a lot.
8958 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8959 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8960 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8962 // Okay, we are casting from one integer or pointer type to another of
8963 // the same size. Instead of casting the pointer before the load, cast
8964 // the result of the loaded value.
8965 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8967 LI.isVolatile()),LI);
8968 // Now cast the result of the load.
8969 return new BitCastInst(NewLoad, LI.getType());
8976 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8977 /// from this value cannot trap. If it is not obviously safe to load from the
8978 /// specified pointer, we do a quick local scan of the basic block containing
8979 /// ScanFrom, to determine if the address is already accessed.
8980 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8981 // If it is an alloca or global variable, it is always safe to load from.
8982 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8984 // Otherwise, be a little bit agressive by scanning the local block where we
8985 // want to check to see if the pointer is already being loaded or stored
8986 // from/to. If so, the previous load or store would have already trapped,
8987 // so there is no harm doing an extra load (also, CSE will later eliminate
8988 // the load entirely).
8989 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8994 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8995 if (LI->getOperand(0) == V) return true;
8996 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8997 if (SI->getOperand(1) == V) return true;
9003 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9004 Value *Op = LI.getOperand(0);
9006 // load (cast X) --> cast (load X) iff safe
9007 if (isa<CastInst>(Op))
9008 if (Instruction *Res = InstCombineLoadCast(*this, LI))
9011 // None of the following transforms are legal for volatile loads.
9012 if (LI.isVolatile()) return 0;
9014 if (&LI.getParent()->front() != &LI) {
9015 BasicBlock::iterator BBI = &LI; --BBI;
9016 // If the instruction immediately before this is a store to the same
9017 // address, do a simple form of store->load forwarding.
9018 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9019 if (SI->getOperand(1) == LI.getOperand(0))
9020 return ReplaceInstUsesWith(LI, SI->getOperand(0));
9021 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9022 if (LIB->getOperand(0) == LI.getOperand(0))
9023 return ReplaceInstUsesWith(LI, LIB);
9026 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
9027 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
9028 isa<UndefValue>(GEPI->getOperand(0))) {
9029 // Insert a new store to null instruction before the load to indicate
9030 // that this code is not reachable. We do this instead of inserting
9031 // an unreachable instruction directly because we cannot modify the
9033 new StoreInst(UndefValue::get(LI.getType()),
9034 Constant::getNullValue(Op->getType()), &LI);
9035 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9038 if (Constant *C = dyn_cast<Constant>(Op)) {
9039 // load null/undef -> undef
9040 if ((C->isNullValue() || isa<UndefValue>(C))) {
9041 // Insert a new store to null instruction before the load to indicate that
9042 // this code is not reachable. We do this instead of inserting an
9043 // unreachable instruction directly because we cannot modify the CFG.
9044 new StoreInst(UndefValue::get(LI.getType()),
9045 Constant::getNullValue(Op->getType()), &LI);
9046 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9049 // Instcombine load (constant global) into the value loaded.
9050 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9051 if (GV->isConstant() && !GV->isDeclaration())
9052 return ReplaceInstUsesWith(LI, GV->getInitializer());
9054 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9055 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9056 if (CE->getOpcode() == Instruction::GetElementPtr) {
9057 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9058 if (GV->isConstant() && !GV->isDeclaration())
9060 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9061 return ReplaceInstUsesWith(LI, V);
9062 if (CE->getOperand(0)->isNullValue()) {
9063 // Insert a new store to null instruction before the load to indicate
9064 // that this code is not reachable. We do this instead of inserting
9065 // an unreachable instruction directly because we cannot modify the
9067 new StoreInst(UndefValue::get(LI.getType()),
9068 Constant::getNullValue(Op->getType()), &LI);
9069 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9072 } else if (CE->isCast()) {
9073 if (Instruction *Res = InstCombineLoadCast(*this, LI))
9078 if (Op->hasOneUse()) {
9079 // Change select and PHI nodes to select values instead of addresses: this
9080 // helps alias analysis out a lot, allows many others simplifications, and
9081 // exposes redundancy in the code.
9083 // Note that we cannot do the transformation unless we know that the
9084 // introduced loads cannot trap! Something like this is valid as long as
9085 // the condition is always false: load (select bool %C, int* null, int* %G),
9086 // but it would not be valid if we transformed it to load from null
9089 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9090 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
9091 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9092 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9093 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9094 SI->getOperand(1)->getName()+".val"), LI);
9095 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9096 SI->getOperand(2)->getName()+".val"), LI);
9097 return new SelectInst(SI->getCondition(), V1, V2);
9100 // load (select (cond, null, P)) -> load P
9101 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9102 if (C->isNullValue()) {
9103 LI.setOperand(0, SI->getOperand(2));
9107 // load (select (cond, P, null)) -> load P
9108 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9109 if (C->isNullValue()) {
9110 LI.setOperand(0, SI->getOperand(1));
9118 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9120 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9121 User *CI = cast<User>(SI.getOperand(1));
9122 Value *CastOp = CI->getOperand(0);
9124 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9125 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9126 const Type *SrcPTy = SrcTy->getElementType();
9128 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9129 // If the source is an array, the code below will not succeed. Check to
9130 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9132 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9133 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9134 if (ASrcTy->getNumElements() != 0) {
9136 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9137 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9138 SrcTy = cast<PointerType>(CastOp->getType());
9139 SrcPTy = SrcTy->getElementType();
9142 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9143 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9144 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9146 // Okay, we are casting from one integer or pointer type to another of
9147 // the same size. Instead of casting the pointer before
9148 // the store, cast the value to be stored.
9150 Value *SIOp0 = SI.getOperand(0);
9151 Instruction::CastOps opcode = Instruction::BitCast;
9152 const Type* CastSrcTy = SIOp0->getType();
9153 const Type* CastDstTy = SrcPTy;
9154 if (isa<PointerType>(CastDstTy)) {
9155 if (CastSrcTy->isInteger())
9156 opcode = Instruction::IntToPtr;
9157 } else if (isa<IntegerType>(CastDstTy)) {
9158 if (isa<PointerType>(SIOp0->getType()))
9159 opcode = Instruction::PtrToInt;
9161 if (Constant *C = dyn_cast<Constant>(SIOp0))
9162 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9164 NewCast = IC.InsertNewInstBefore(
9165 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9167 return new StoreInst(NewCast, CastOp);
9174 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9175 Value *Val = SI.getOperand(0);
9176 Value *Ptr = SI.getOperand(1);
9178 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
9179 EraseInstFromFunction(SI);
9184 // If the RHS is an alloca with a single use, zapify the store, making the
9186 if (Ptr->hasOneUse()) {
9187 if (isa<AllocaInst>(Ptr)) {
9188 EraseInstFromFunction(SI);
9193 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9194 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9195 GEP->getOperand(0)->hasOneUse()) {
9196 EraseInstFromFunction(SI);
9202 // Do really simple DSE, to catch cases where there are several consequtive
9203 // stores to the same location, separated by a few arithmetic operations. This
9204 // situation often occurs with bitfield accesses.
9205 BasicBlock::iterator BBI = &SI;
9206 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9210 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9211 // Prev store isn't volatile, and stores to the same location?
9212 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9215 EraseInstFromFunction(*PrevSI);
9221 // If this is a load, we have to stop. However, if the loaded value is from
9222 // the pointer we're loading and is producing the pointer we're storing,
9223 // then *this* store is dead (X = load P; store X -> P).
9224 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9225 if (LI == Val && LI->getOperand(0) == Ptr) {
9226 EraseInstFromFunction(SI);
9230 // Otherwise, this is a load from some other location. Stores before it
9235 // Don't skip over loads or things that can modify memory.
9236 if (BBI->mayWriteToMemory())
9241 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
9243 // store X, null -> turns into 'unreachable' in SimplifyCFG
9244 if (isa<ConstantPointerNull>(Ptr)) {
9245 if (!isa<UndefValue>(Val)) {
9246 SI.setOperand(0, UndefValue::get(Val->getType()));
9247 if (Instruction *U = dyn_cast<Instruction>(Val))
9248 AddToWorkList(U); // Dropped a use.
9251 return 0; // Do not modify these!
9254 // store undef, Ptr -> noop
9255 if (isa<UndefValue>(Val)) {
9256 EraseInstFromFunction(SI);
9261 // If the pointer destination is a cast, see if we can fold the cast into the
9263 if (isa<CastInst>(Ptr))
9264 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9266 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9268 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9272 // If this store is the last instruction in the basic block, and if the block
9273 // ends with an unconditional branch, try to move it to the successor block.
9275 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9276 if (BI->isUnconditional()) {
9277 // Check to see if the successor block has exactly two incoming edges. If
9278 // so, see if the other predecessor contains a store to the same location.
9279 // if so, insert a PHI node (if needed) and move the stores down.
9280 BasicBlock *Dest = BI->getSuccessor(0);
9282 pred_iterator PI = pred_begin(Dest);
9283 BasicBlock *Other = 0;
9284 if (*PI != BI->getParent())
9287 if (PI != pred_end(Dest)) {
9288 if (*PI != BI->getParent())
9293 if (++PI != pred_end(Dest))
9296 if (Other) { // If only one other pred...
9297 BBI = Other->getTerminator();
9298 // Make sure this other block ends in an unconditional branch and that
9299 // there is an instruction before the branch.
9300 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
9301 BBI != Other->begin()) {
9303 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
9305 // If this instruction is a store to the same location.
9306 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
9307 // Okay, we know we can perform this transformation. Insert a PHI
9308 // node now if we need it.
9309 Value *MergedVal = OtherStore->getOperand(0);
9310 if (MergedVal != SI.getOperand(0)) {
9311 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9312 PN->reserveOperandSpace(2);
9313 PN->addIncoming(SI.getOperand(0), SI.getParent());
9314 PN->addIncoming(OtherStore->getOperand(0), Other);
9315 MergedVal = InsertNewInstBefore(PN, Dest->front());
9318 // Advance to a place where it is safe to insert the new store and
9320 BBI = Dest->begin();
9321 while (isa<PHINode>(BBI)) ++BBI;
9322 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9323 OtherStore->isVolatile()), *BBI);
9325 // Nuke the old stores.
9326 EraseInstFromFunction(SI);
9327 EraseInstFromFunction(*OtherStore);
9339 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9340 // Change br (not X), label True, label False to: br X, label False, True
9342 BasicBlock *TrueDest;
9343 BasicBlock *FalseDest;
9344 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9345 !isa<Constant>(X)) {
9346 // Swap Destinations and condition...
9348 BI.setSuccessor(0, FalseDest);
9349 BI.setSuccessor(1, TrueDest);
9353 // Cannonicalize fcmp_one -> fcmp_oeq
9354 FCmpInst::Predicate FPred; Value *Y;
9355 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9356 TrueDest, FalseDest)))
9357 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9358 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9359 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9360 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9361 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9362 NewSCC->takeName(I);
9363 // Swap Destinations and condition...
9364 BI.setCondition(NewSCC);
9365 BI.setSuccessor(0, FalseDest);
9366 BI.setSuccessor(1, TrueDest);
9367 RemoveFromWorkList(I);
9368 I->eraseFromParent();
9369 AddToWorkList(NewSCC);
9373 // Cannonicalize icmp_ne -> icmp_eq
9374 ICmpInst::Predicate IPred;
9375 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9376 TrueDest, FalseDest)))
9377 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9378 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9379 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9380 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9381 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9382 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9383 NewSCC->takeName(I);
9384 // Swap Destinations and condition...
9385 BI.setCondition(NewSCC);
9386 BI.setSuccessor(0, FalseDest);
9387 BI.setSuccessor(1, TrueDest);
9388 RemoveFromWorkList(I);
9389 I->eraseFromParent();;
9390 AddToWorkList(NewSCC);
9397 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9398 Value *Cond = SI.getCondition();
9399 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9400 if (I->getOpcode() == Instruction::Add)
9401 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9402 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9403 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9404 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9406 SI.setOperand(0, I->getOperand(0));
9414 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9415 /// is to leave as a vector operation.
9416 static bool CheapToScalarize(Value *V, bool isConstant) {
9417 if (isa<ConstantAggregateZero>(V))
9419 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9420 if (isConstant) return true;
9421 // If all elts are the same, we can extract.
9422 Constant *Op0 = C->getOperand(0);
9423 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9424 if (C->getOperand(i) != Op0)
9428 Instruction *I = dyn_cast<Instruction>(V);
9429 if (!I) return false;
9431 // Insert element gets simplified to the inserted element or is deleted if
9432 // this is constant idx extract element and its a constant idx insertelt.
9433 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9434 isa<ConstantInt>(I->getOperand(2)))
9436 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9438 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9439 if (BO->hasOneUse() &&
9440 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9441 CheapToScalarize(BO->getOperand(1), isConstant)))
9443 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9444 if (CI->hasOneUse() &&
9445 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9446 CheapToScalarize(CI->getOperand(1), isConstant)))
9452 /// Read and decode a shufflevector mask.
9454 /// It turns undef elements into values that are larger than the number of
9455 /// elements in the input.
9456 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9457 unsigned NElts = SVI->getType()->getNumElements();
9458 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9459 return std::vector<unsigned>(NElts, 0);
9460 if (isa<UndefValue>(SVI->getOperand(2)))
9461 return std::vector<unsigned>(NElts, 2*NElts);
9463 std::vector<unsigned> Result;
9464 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9465 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9466 if (isa<UndefValue>(CP->getOperand(i)))
9467 Result.push_back(NElts*2); // undef -> 8
9469 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9473 /// FindScalarElement - Given a vector and an element number, see if the scalar
9474 /// value is already around as a register, for example if it were inserted then
9475 /// extracted from the vector.
9476 static Value *FindScalarElement(Value *V, unsigned EltNo) {
9477 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9478 const VectorType *PTy = cast<VectorType>(V->getType());
9479 unsigned Width = PTy->getNumElements();
9480 if (EltNo >= Width) // Out of range access.
9481 return UndefValue::get(PTy->getElementType());
9483 if (isa<UndefValue>(V))
9484 return UndefValue::get(PTy->getElementType());
9485 else if (isa<ConstantAggregateZero>(V))
9486 return Constant::getNullValue(PTy->getElementType());
9487 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9488 return CP->getOperand(EltNo);
9489 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9490 // If this is an insert to a variable element, we don't know what it is.
9491 if (!isa<ConstantInt>(III->getOperand(2)))
9493 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9495 // If this is an insert to the element we are looking for, return the
9498 return III->getOperand(1);
9500 // Otherwise, the insertelement doesn't modify the value, recurse on its
9502 return FindScalarElement(III->getOperand(0), EltNo);
9503 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
9504 unsigned InEl = getShuffleMask(SVI)[EltNo];
9506 return FindScalarElement(SVI->getOperand(0), InEl);
9507 else if (InEl < Width*2)
9508 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9510 return UndefValue::get(PTy->getElementType());
9513 // Otherwise, we don't know.
9517 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
9519 // If packed val is undef, replace extract with scalar undef.
9520 if (isa<UndefValue>(EI.getOperand(0)))
9521 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9523 // If packed val is constant 0, replace extract with scalar 0.
9524 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9525 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9527 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
9528 // If packed val is constant with uniform operands, replace EI
9529 // with that operand
9530 Constant *op0 = C->getOperand(0);
9531 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9532 if (C->getOperand(i) != op0) {
9537 return ReplaceInstUsesWith(EI, op0);
9540 // If extracting a specified index from the vector, see if we can recursively
9541 // find a previously computed scalar that was inserted into the vector.
9542 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9543 // This instruction only demands the single element from the input vector.
9544 // If the input vector has a single use, simplify it based on this use
9546 uint64_t IndexVal = IdxC->getZExtValue();
9547 if (EI.getOperand(0)->hasOneUse()) {
9549 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
9552 EI.setOperand(0, V);
9557 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
9558 return ReplaceInstUsesWith(EI, Elt);
9561 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
9562 if (I->hasOneUse()) {
9563 // Push extractelement into predecessor operation if legal and
9564 // profitable to do so
9565 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9566 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9567 if (CheapToScalarize(BO, isConstantElt)) {
9568 ExtractElementInst *newEI0 =
9569 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9570 EI.getName()+".lhs");
9571 ExtractElementInst *newEI1 =
9572 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9573 EI.getName()+".rhs");
9574 InsertNewInstBefore(newEI0, EI);
9575 InsertNewInstBefore(newEI1, EI);
9576 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9578 } else if (isa<LoadInst>(I)) {
9579 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
9580 PointerType::get(EI.getType()), EI);
9581 GetElementPtrInst *GEP =
9582 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
9583 InsertNewInstBefore(GEP, EI);
9584 return new LoadInst(GEP);
9587 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9588 // Extracting the inserted element?
9589 if (IE->getOperand(2) == EI.getOperand(1))
9590 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9591 // If the inserted and extracted elements are constants, they must not
9592 // be the same value, extract from the pre-inserted value instead.
9593 if (isa<Constant>(IE->getOperand(2)) &&
9594 isa<Constant>(EI.getOperand(1))) {
9595 AddUsesToWorkList(EI);
9596 EI.setOperand(0, IE->getOperand(0));
9599 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9600 // If this is extracting an element from a shufflevector, figure out where
9601 // it came from and extract from the appropriate input element instead.
9602 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9603 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
9605 if (SrcIdx < SVI->getType()->getNumElements())
9606 Src = SVI->getOperand(0);
9607 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9608 SrcIdx -= SVI->getType()->getNumElements();
9609 Src = SVI->getOperand(1);
9611 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9613 return new ExtractElementInst(Src, SrcIdx);
9620 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9621 /// elements from either LHS or RHS, return the shuffle mask and true.
9622 /// Otherwise, return false.
9623 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9624 std::vector<Constant*> &Mask) {
9625 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9626 "Invalid CollectSingleShuffleElements");
9627 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9629 if (isa<UndefValue>(V)) {
9630 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9632 } else if (V == LHS) {
9633 for (unsigned i = 0; i != NumElts; ++i)
9634 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9636 } else if (V == RHS) {
9637 for (unsigned i = 0; i != NumElts; ++i)
9638 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
9640 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9641 // If this is an insert of an extract from some other vector, include it.
9642 Value *VecOp = IEI->getOperand(0);
9643 Value *ScalarOp = IEI->getOperand(1);
9644 Value *IdxOp = IEI->getOperand(2);
9646 if (!isa<ConstantInt>(IdxOp))
9648 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9650 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9651 // Okay, we can handle this if the vector we are insertinting into is
9653 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9654 // If so, update the mask to reflect the inserted undef.
9655 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
9658 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9659 if (isa<ConstantInt>(EI->getOperand(1)) &&
9660 EI->getOperand(0)->getType() == V->getType()) {
9661 unsigned ExtractedIdx =
9662 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9664 // This must be extracting from either LHS or RHS.
9665 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9666 // Okay, we can handle this if the vector we are insertinting into is
9668 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9669 // If so, update the mask to reflect the inserted value.
9670 if (EI->getOperand(0) == LHS) {
9671 Mask[InsertedIdx & (NumElts-1)] =
9672 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9674 assert(EI->getOperand(0) == RHS);
9675 Mask[InsertedIdx & (NumElts-1)] =
9676 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
9685 // TODO: Handle shufflevector here!
9690 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9691 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9692 /// that computes V and the LHS value of the shuffle.
9693 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
9695 assert(isa<VectorType>(V->getType()) &&
9696 (RHS == 0 || V->getType() == RHS->getType()) &&
9697 "Invalid shuffle!");
9698 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9700 if (isa<UndefValue>(V)) {
9701 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9703 } else if (isa<ConstantAggregateZero>(V)) {
9704 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
9706 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9707 // If this is an insert of an extract from some other vector, include it.
9708 Value *VecOp = IEI->getOperand(0);
9709 Value *ScalarOp = IEI->getOperand(1);
9710 Value *IdxOp = IEI->getOperand(2);
9712 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9713 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9714 EI->getOperand(0)->getType() == V->getType()) {
9715 unsigned ExtractedIdx =
9716 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9717 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9719 // Either the extracted from or inserted into vector must be RHSVec,
9720 // otherwise we'd end up with a shuffle of three inputs.
9721 if (EI->getOperand(0) == RHS || RHS == 0) {
9722 RHS = EI->getOperand(0);
9723 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
9724 Mask[InsertedIdx & (NumElts-1)] =
9725 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
9730 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
9731 // Everything but the extracted element is replaced with the RHS.
9732 for (unsigned i = 0; i != NumElts; ++i) {
9733 if (i != InsertedIdx)
9734 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
9739 // If this insertelement is a chain that comes from exactly these two
9740 // vectors, return the vector and the effective shuffle.
9741 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9742 return EI->getOperand(0);
9747 // TODO: Handle shufflevector here!
9749 // Otherwise, can't do anything fancy. Return an identity vector.
9750 for (unsigned i = 0; i != NumElts; ++i)
9751 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9755 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9756 Value *VecOp = IE.getOperand(0);
9757 Value *ScalarOp = IE.getOperand(1);
9758 Value *IdxOp = IE.getOperand(2);
9760 // If the inserted element was extracted from some other vector, and if the
9761 // indexes are constant, try to turn this into a shufflevector operation.
9762 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9763 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9764 EI->getOperand(0)->getType() == IE.getType()) {
9765 unsigned NumVectorElts = IE.getType()->getNumElements();
9766 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9767 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9769 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9770 return ReplaceInstUsesWith(IE, VecOp);
9772 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9773 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9775 // If we are extracting a value from a vector, then inserting it right
9776 // back into the same place, just use the input vector.
9777 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9778 return ReplaceInstUsesWith(IE, VecOp);
9780 // We could theoretically do this for ANY input. However, doing so could
9781 // turn chains of insertelement instructions into a chain of shufflevector
9782 // instructions, and right now we do not merge shufflevectors. As such,
9783 // only do this in a situation where it is clear that there is benefit.
9784 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9785 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9786 // the values of VecOp, except then one read from EIOp0.
9787 // Build a new shuffle mask.
9788 std::vector<Constant*> Mask;
9789 if (isa<UndefValue>(VecOp))
9790 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
9792 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
9793 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
9796 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9797 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
9798 ConstantVector::get(Mask));
9801 // If this insertelement isn't used by some other insertelement, turn it
9802 // (and any insertelements it points to), into one big shuffle.
9803 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9804 std::vector<Constant*> Mask;
9806 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9807 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9808 // We now have a shuffle of LHS, RHS, Mask.
9809 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
9818 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9819 Value *LHS = SVI.getOperand(0);
9820 Value *RHS = SVI.getOperand(1);
9821 std::vector<unsigned> Mask = getShuffleMask(&SVI);
9823 bool MadeChange = false;
9825 // Undefined shuffle mask -> undefined value.
9826 if (isa<UndefValue>(SVI.getOperand(2)))
9827 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9829 // If we have shuffle(x, undef, mask) and any elements of mask refer to
9830 // the undef, change them to undefs.
9831 if (isa<UndefValue>(SVI.getOperand(1))) {
9832 // Scan to see if there are any references to the RHS. If so, replace them
9833 // with undef element refs and set MadeChange to true.
9834 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9835 if (Mask[i] >= e && Mask[i] != 2*e) {
9842 // Remap any references to RHS to use LHS.
9843 std::vector<Constant*> Elts;
9844 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9846 Elts.push_back(UndefValue::get(Type::Int32Ty));
9848 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9850 SVI.setOperand(2, ConstantVector::get(Elts));
9854 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9855 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9856 if (LHS == RHS || isa<UndefValue>(LHS)) {
9857 if (isa<UndefValue>(LHS) && LHS == RHS) {
9858 // shuffle(undef,undef,mask) -> undef.
9859 return ReplaceInstUsesWith(SVI, LHS);
9862 // Remap any references to RHS to use LHS.
9863 std::vector<Constant*> Elts;
9864 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9866 Elts.push_back(UndefValue::get(Type::Int32Ty));
9868 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9869 (Mask[i] < e && isa<UndefValue>(LHS)))
9870 Mask[i] = 2*e; // Turn into undef.
9872 Mask[i] &= (e-1); // Force to LHS.
9873 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9876 SVI.setOperand(0, SVI.getOperand(1));
9877 SVI.setOperand(1, UndefValue::get(RHS->getType()));
9878 SVI.setOperand(2, ConstantVector::get(Elts));
9879 LHS = SVI.getOperand(0);
9880 RHS = SVI.getOperand(1);
9884 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9885 bool isLHSID = true, isRHSID = true;
9887 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9888 if (Mask[i] >= e*2) continue; // Ignore undef values.
9889 // Is this an identity shuffle of the LHS value?
9890 isLHSID &= (Mask[i] == i);
9892 // Is this an identity shuffle of the RHS value?
9893 isRHSID &= (Mask[i]-e == i);
9896 // Eliminate identity shuffles.
9897 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9898 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9900 // If the LHS is a shufflevector itself, see if we can combine it with this
9901 // one without producing an unusual shuffle. Here we are really conservative:
9902 // we are absolutely afraid of producing a shuffle mask not in the input
9903 // program, because the code gen may not be smart enough to turn a merged
9904 // shuffle into two specific shuffles: it may produce worse code. As such,
9905 // we only merge two shuffles if the result is one of the two input shuffle
9906 // masks. In this case, merging the shuffles just removes one instruction,
9907 // which we know is safe. This is good for things like turning:
9908 // (splat(splat)) -> splat.
9909 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9910 if (isa<UndefValue>(RHS)) {
9911 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9913 std::vector<unsigned> NewMask;
9914 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9916 NewMask.push_back(2*e);
9918 NewMask.push_back(LHSMask[Mask[i]]);
9920 // If the result mask is equal to the src shuffle or this shuffle mask, do
9922 if (NewMask == LHSMask || NewMask == Mask) {
9923 std::vector<Constant*> Elts;
9924 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9925 if (NewMask[i] >= e*2) {
9926 Elts.push_back(UndefValue::get(Type::Int32Ty));
9928 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9931 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9932 LHSSVI->getOperand(1),
9933 ConstantVector::get(Elts));
9938 return MadeChange ? &SVI : 0;
9944 /// TryToSinkInstruction - Try to move the specified instruction from its
9945 /// current block into the beginning of DestBlock, which can only happen if it's
9946 /// safe to move the instruction past all of the instructions between it and the
9947 /// end of its block.
9948 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9949 assert(I->hasOneUse() && "Invariants didn't hold!");
9951 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9952 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9954 // Do not sink alloca instructions out of the entry block.
9955 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9958 // We can only sink load instructions if there is nothing between the load and
9959 // the end of block that could change the value.
9960 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9961 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9963 if (Scan->mayWriteToMemory())
9967 BasicBlock::iterator InsertPos = DestBlock->begin();
9968 while (isa<PHINode>(InsertPos)) ++InsertPos;
9970 I->moveBefore(InsertPos);
9976 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9977 /// all reachable code to the worklist.
9979 /// This has a couple of tricks to make the code faster and more powerful. In
9980 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9981 /// them to the worklist (this significantly speeds up instcombine on code where
9982 /// many instructions are dead or constant). Additionally, if we find a branch
9983 /// whose condition is a known constant, we only visit the reachable successors.
9985 static void AddReachableCodeToWorklist(BasicBlock *BB,
9986 SmallPtrSet<BasicBlock*, 64> &Visited,
9988 const TargetData *TD) {
9989 // We have now visited this block! If we've already been here, bail out.
9990 if (!Visited.insert(BB)) return;
9992 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9993 Instruction *Inst = BBI++;
9995 // DCE instruction if trivially dead.
9996 if (isInstructionTriviallyDead(Inst)) {
9998 DOUT << "IC: DCE: " << *Inst;
9999 Inst->eraseFromParent();
10003 // ConstantProp instruction if trivially constant.
10004 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10005 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10006 Inst->replaceAllUsesWith(C);
10008 Inst->eraseFromParent();
10012 IC.AddToWorkList(Inst);
10015 // Recursively visit successors. If this is a branch or switch on a constant,
10016 // only visit the reachable successor.
10017 TerminatorInst *TI = BB->getTerminator();
10018 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10019 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10020 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10021 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
10024 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10025 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10026 // See if this is an explicit destination.
10027 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10028 if (SI->getCaseValue(i) == Cond) {
10029 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
10033 // Otherwise it is the default destination.
10034 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
10039 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10040 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
10043 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10044 bool Changed = false;
10045 TD = &getAnalysis<TargetData>();
10047 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10048 << F.getNameStr() << "\n");
10051 // Do a depth-first traversal of the function, populate the worklist with
10052 // the reachable instructions. Ignore blocks that are not reachable. Keep
10053 // track of which blocks we visit.
10054 SmallPtrSet<BasicBlock*, 64> Visited;
10055 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10057 // Do a quick scan over the function. If we find any blocks that are
10058 // unreachable, remove any instructions inside of them. This prevents
10059 // the instcombine code from having to deal with some bad special cases.
10060 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10061 if (!Visited.count(BB)) {
10062 Instruction *Term = BB->getTerminator();
10063 while (Term != BB->begin()) { // Remove instrs bottom-up
10064 BasicBlock::iterator I = Term; --I;
10066 DOUT << "IC: DCE: " << *I;
10069 if (!I->use_empty())
10070 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10071 I->eraseFromParent();
10076 while (!Worklist.empty()) {
10077 Instruction *I = RemoveOneFromWorkList();
10078 if (I == 0) continue; // skip null values.
10080 // Check to see if we can DCE the instruction.
10081 if (isInstructionTriviallyDead(I)) {
10082 // Add operands to the worklist.
10083 if (I->getNumOperands() < 4)
10084 AddUsesToWorkList(*I);
10087 DOUT << "IC: DCE: " << *I;
10089 I->eraseFromParent();
10090 RemoveFromWorkList(I);
10094 // Instruction isn't dead, see if we can constant propagate it.
10095 if (Constant *C = ConstantFoldInstruction(I, TD)) {
10096 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10098 // Add operands to the worklist.
10099 AddUsesToWorkList(*I);
10100 ReplaceInstUsesWith(*I, C);
10103 I->eraseFromParent();
10104 RemoveFromWorkList(I);
10108 // See if we can trivially sink this instruction to a successor basic block.
10109 if (I->hasOneUse()) {
10110 BasicBlock *BB = I->getParent();
10111 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10112 if (UserParent != BB) {
10113 bool UserIsSuccessor = false;
10114 // See if the user is one of our successors.
10115 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10116 if (*SI == UserParent) {
10117 UserIsSuccessor = true;
10121 // If the user is one of our immediate successors, and if that successor
10122 // only has us as a predecessors (we'd have to split the critical edge
10123 // otherwise), we can keep going.
10124 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10125 next(pred_begin(UserParent)) == pred_end(UserParent))
10126 // Okay, the CFG is simple enough, try to sink this instruction.
10127 Changed |= TryToSinkInstruction(I, UserParent);
10131 // Now that we have an instruction, try combining it to simplify it...
10132 if (Instruction *Result = visit(*I)) {
10134 // Should we replace the old instruction with a new one?
10136 DOUT << "IC: Old = " << *I
10137 << " New = " << *Result;
10139 // Everything uses the new instruction now.
10140 I->replaceAllUsesWith(Result);
10142 // Push the new instruction and any users onto the worklist.
10143 AddToWorkList(Result);
10144 AddUsersToWorkList(*Result);
10146 // Move the name to the new instruction first.
10147 Result->takeName(I);
10149 // Insert the new instruction into the basic block...
10150 BasicBlock *InstParent = I->getParent();
10151 BasicBlock::iterator InsertPos = I;
10153 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10154 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10157 InstParent->getInstList().insert(InsertPos, Result);
10159 // Make sure that we reprocess all operands now that we reduced their
10161 AddUsesToWorkList(*I);
10163 // Instructions can end up on the worklist more than once. Make sure
10164 // we do not process an instruction that has been deleted.
10165 RemoveFromWorkList(I);
10167 // Erase the old instruction.
10168 InstParent->getInstList().erase(I);
10170 DOUT << "IC: MOD = " << *I;
10172 // If the instruction was modified, it's possible that it is now dead.
10173 // if so, remove it.
10174 if (isInstructionTriviallyDead(I)) {
10175 // Make sure we process all operands now that we are reducing their
10177 AddUsesToWorkList(*I);
10179 // Instructions may end up in the worklist more than once. Erase all
10180 // occurrences of this instruction.
10181 RemoveFromWorkList(I);
10182 I->eraseFromParent();
10185 AddUsersToWorkList(*I);
10192 assert(WorklistMap.empty() && "Worklist empty, but map not?");
10197 bool InstCombiner::runOnFunction(Function &F) {
10198 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10200 bool EverMadeChange = false;
10202 // Iterate while there is work to do.
10203 unsigned Iteration = 0;
10204 while (DoOneIteration(F, Iteration++))
10205 EverMadeChange = true;
10206 return EverMadeChange;
10209 FunctionPass *llvm::createInstructionCombiningPass() {
10210 return new InstCombiner();