1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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
12 // algebraic 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/ConstantRange.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/GetElementPtrTypeIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/STLExtras.h"
63 using namespace llvm::PatternMatch;
65 STATISTIC(NumCombined , "Number of insts combined");
66 STATISTIC(NumConstProp, "Number of constant folds");
67 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69 STATISTIC(NumSunkInst , "Number of instructions sunk");
72 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
75 // Worklist of all of the instructions that need to be simplified.
76 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
79 bool MustPreserveLCSSA;
81 static char ID; // Pass identification, replacement for typeid
82 InstCombiner() : FunctionPass((intptr_t)&ID) {}
84 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
99 WorklistMap.erase(It);
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
105 WorklistMap.erase(I);
110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
114 void AddUsersToWorkList(Value &I) {
115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117 AddToWorkList(cast<Instruction>(*UI));
120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
133 /// Return the specified operand before it is turned into an undef.
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
149 virtual bool runOnFunction(Function &F);
151 bool DoOneIteration(Function &F, unsigned ItNum);
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequired<TargetData>();
155 AU.addPreservedID(LCSSAID);
156 AU.setPreservesCFG();
159 TargetData &getTargetData() const { return *TD; }
161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
164 // null - No change was made
165 // I - Change was made, I is still valid, I may be dead though
166 // otherwise - Change was made, replace I with returned instruction
168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
188 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190 Instruction *visitFCmpInst(FCmpInst &I);
191 Instruction *visitICmpInst(ICmpInst &I);
192 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
193 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
196 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197 ConstantInt *DivRHS);
199 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200 ICmpInst::Predicate Cond, Instruction &I);
201 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
203 Instruction *commonCastTransforms(CastInst &CI);
204 Instruction *commonIntCastTransforms(CastInst &CI);
205 Instruction *commonPointerCastTransforms(CastInst &CI);
206 Instruction *visitTrunc(TruncInst &CI);
207 Instruction *visitZExt(ZExtInst &CI);
208 Instruction *visitSExt(SExtInst &CI);
209 Instruction *visitFPTrunc(FPTruncInst &CI);
210 Instruction *visitFPExt(CastInst &CI);
211 Instruction *visitFPToUI(FPToUIInst &FI);
212 Instruction *visitFPToSI(FPToSIInst &FI);
213 Instruction *visitUIToFP(CastInst &CI);
214 Instruction *visitSIToFP(CastInst &CI);
215 Instruction *visitPtrToInt(CastInst &CI);
216 Instruction *visitIntToPtr(IntToPtrInst &CI);
217 Instruction *visitBitCast(BitCastInst &CI);
218 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220 Instruction *visitSelectInst(SelectInst &CI);
221 Instruction *visitCallInst(CallInst &CI);
222 Instruction *visitInvokeInst(InvokeInst &II);
223 Instruction *visitPHINode(PHINode &PN);
224 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
225 Instruction *visitAllocationInst(AllocationInst &AI);
226 Instruction *visitFreeInst(FreeInst &FI);
227 Instruction *visitLoadInst(LoadInst &LI);
228 Instruction *visitStoreInst(StoreInst &SI);
229 Instruction *visitBranchInst(BranchInst &BI);
230 Instruction *visitSwitchInst(SwitchInst &SI);
231 Instruction *visitInsertElementInst(InsertElementInst &IE);
232 Instruction *visitExtractElementInst(ExtractElementInst &EI);
233 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235 // visitInstruction - Specify what to return for unhandled instructions...
236 Instruction *visitInstruction(Instruction &I) { return 0; }
239 Instruction *visitCallSite(CallSite CS);
240 bool transformConstExprCastCall(CallSite CS);
241 Instruction *transformCallThroughTrampoline(CallSite CS);
242 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243 bool DoXform = true);
244 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
247 // InsertNewInstBefore - insert an instruction New before instruction Old
248 // in the program. Add the new instruction to the worklist.
250 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
251 assert(New && New->getParent() == 0 &&
252 "New instruction already inserted into a basic block!");
253 BasicBlock *BB = Old.getParent();
254 BB->getInstList().insert(&Old, New); // Insert inst
259 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
260 /// This also adds the cast to the worklist. Finally, this returns the
262 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
264 if (V->getType() == Ty) return V;
266 if (Constant *CV = dyn_cast<Constant>(V))
267 return ConstantExpr::getCast(opc, CV, Ty);
269 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
274 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
275 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
279 // ReplaceInstUsesWith - This method is to be used when an instruction is
280 // found to be dead, replacable with another preexisting expression. Here
281 // we add all uses of I to the worklist, replace all uses of I with the new
282 // value, then return I, so that the inst combiner will know that I was
285 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
286 AddUsersToWorkList(I); // Add all modified instrs to worklist
288 I.replaceAllUsesWith(V);
291 // If we are replacing the instruction with itself, this must be in a
292 // segment of unreachable code, so just clobber the instruction.
293 I.replaceAllUsesWith(UndefValue::get(I.getType()));
298 // UpdateValueUsesWith - This method is to be used when an value is
299 // found to be replacable with another preexisting expression or was
300 // updated. Here we add all uses of I to the worklist, replace all uses of
301 // I with the new value (unless the instruction was just updated), then
302 // return true, so that the inst combiner will know that I was modified.
304 bool UpdateValueUsesWith(Value *Old, Value *New) {
305 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
307 Old->replaceAllUsesWith(New);
308 if (Instruction *I = dyn_cast<Instruction>(Old))
310 if (Instruction *I = dyn_cast<Instruction>(New))
315 // EraseInstFromFunction - When dealing with an instruction that has side
316 // effects or produces a void value, we can't rely on DCE to delete the
317 // instruction. Instead, visit methods should return the value returned by
319 Instruction *EraseInstFromFunction(Instruction &I) {
320 assert(I.use_empty() && "Cannot erase instruction that is used!");
321 AddUsesToWorkList(I);
322 RemoveFromWorkList(&I);
324 return 0; // Don't do anything with FI
328 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
329 /// InsertBefore instruction. This is specialized a bit to avoid inserting
330 /// casts that are known to not do anything...
332 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
333 Value *V, const Type *DestTy,
334 Instruction *InsertBefore);
336 /// SimplifyCommutative - This performs a few simplifications for
337 /// commutative operators.
338 bool SimplifyCommutative(BinaryOperator &I);
340 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341 /// most-complex to least-complex order.
342 bool SimplifyCompare(CmpInst &I);
344 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
345 /// on the demanded bits.
346 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
347 APInt& KnownZero, APInt& KnownOne,
350 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
351 uint64_t &UndefElts, unsigned Depth = 0);
353 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
354 // PHI node as operand #0, see if we can fold the instruction into the PHI
355 // (which is only possible if all operands to the PHI are constants).
356 Instruction *FoldOpIntoPhi(Instruction &I);
358 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
359 // operator and they all are only used by the PHI, PHI together their
360 // inputs, and do the operation once, to the result of the PHI.
361 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
362 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
365 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
366 ConstantInt *AndRHS, BinaryOperator &TheAnd);
368 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
369 bool isSub, Instruction &I);
370 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
371 bool isSigned, bool Inside, Instruction &IB);
372 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
373 Instruction *MatchBSwap(BinaryOperator &I);
374 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
375 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
376 Instruction *SimplifyMemSet(MemSetInst *MI);
379 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
381 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
382 APInt& KnownOne, unsigned Depth = 0) const;
383 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
384 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const;
385 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
387 int &NumCastsRemoved);
388 unsigned GetOrEnforceKnownAlignment(Value *V,
389 unsigned PrefAlign = 0);
393 char InstCombiner::ID = 0;
394 static RegisterPass<InstCombiner>
395 X("instcombine", "Combine redundant instructions");
397 // getComplexity: Assign a complexity or rank value to LLVM Values...
398 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
399 static unsigned getComplexity(Value *V) {
400 if (isa<Instruction>(V)) {
401 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
405 if (isa<Argument>(V)) return 3;
406 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
409 // isOnlyUse - Return true if this instruction will be deleted if we stop using
411 static bool isOnlyUse(Value *V) {
412 return V->hasOneUse() || isa<Constant>(V);
415 // getPromotedType - Return the specified type promoted as it would be to pass
416 // though a va_arg area...
417 static const Type *getPromotedType(const Type *Ty) {
418 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
419 if (ITy->getBitWidth() < 32)
420 return Type::Int32Ty;
425 /// getBitCastOperand - If the specified operand is a CastInst or a constant
426 /// expression bitcast, return the operand value, otherwise return null.
427 static Value *getBitCastOperand(Value *V) {
428 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
429 return I->getOperand(0);
430 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
431 if (CE->getOpcode() == Instruction::BitCast)
432 return CE->getOperand(0);
436 /// This function is a wrapper around CastInst::isEliminableCastPair. It
437 /// simply extracts arguments and returns what that function returns.
438 static Instruction::CastOps
439 isEliminableCastPair(
440 const CastInst *CI, ///< The first cast instruction
441 unsigned opcode, ///< The opcode of the second cast instruction
442 const Type *DstTy, ///< The target type for the second cast instruction
443 TargetData *TD ///< The target data for pointer size
446 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
447 const Type *MidTy = CI->getType(); // B from above
449 // Get the opcodes of the two Cast instructions
450 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
451 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
453 return Instruction::CastOps(
454 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
455 DstTy, TD->getIntPtrType()));
458 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
459 /// in any code being generated. It does not require codegen if V is simple
460 /// enough or if the cast can be folded into other casts.
461 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
462 const Type *Ty, TargetData *TD) {
463 if (V->getType() == Ty || isa<Constant>(V)) return false;
465 // If this is another cast that can be eliminated, it isn't codegen either.
466 if (const CastInst *CI = dyn_cast<CastInst>(V))
467 if (isEliminableCastPair(CI, opcode, Ty, TD))
472 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
473 /// InsertBefore instruction. This is specialized a bit to avoid inserting
474 /// casts that are known to not do anything...
476 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
477 Value *V, const Type *DestTy,
478 Instruction *InsertBefore) {
479 if (V->getType() == DestTy) return V;
480 if (Constant *C = dyn_cast<Constant>(V))
481 return ConstantExpr::getCast(opcode, C, DestTy);
483 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
486 // SimplifyCommutative - This performs a few simplifications for commutative
489 // 1. Order operands such that they are listed from right (least complex) to
490 // left (most complex). This puts constants before unary operators before
493 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
494 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
496 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
497 bool Changed = false;
498 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
499 Changed = !I.swapOperands();
501 if (!I.isAssociative()) return Changed;
502 Instruction::BinaryOps Opcode = I.getOpcode();
503 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
504 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
505 if (isa<Constant>(I.getOperand(1))) {
506 Constant *Folded = ConstantExpr::get(I.getOpcode(),
507 cast<Constant>(I.getOperand(1)),
508 cast<Constant>(Op->getOperand(1)));
509 I.setOperand(0, Op->getOperand(0));
510 I.setOperand(1, Folded);
512 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
513 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
514 isOnlyUse(Op) && isOnlyUse(Op1)) {
515 Constant *C1 = cast<Constant>(Op->getOperand(1));
516 Constant *C2 = cast<Constant>(Op1->getOperand(1));
518 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
519 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
520 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
524 I.setOperand(0, New);
525 I.setOperand(1, Folded);
532 /// SimplifyCompare - For a CmpInst this function just orders the operands
533 /// so that theyare listed from right (least complex) to left (most complex).
534 /// This puts constants before unary operators before binary operators.
535 bool InstCombiner::SimplifyCompare(CmpInst &I) {
536 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
539 // Compare instructions are not associative so there's nothing else we can do.
543 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
544 // if the LHS is a constant zero (which is the 'negate' form).
546 static inline Value *dyn_castNegVal(Value *V) {
547 if (BinaryOperator::isNeg(V))
548 return BinaryOperator::getNegArgument(V);
550 // Constants can be considered to be negated values if they can be folded.
551 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
552 return ConstantExpr::getNeg(C);
554 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
555 if (C->getType()->getElementType()->isInteger())
556 return ConstantExpr::getNeg(C);
561 static inline Value *dyn_castNotVal(Value *V) {
562 if (BinaryOperator::isNot(V))
563 return BinaryOperator::getNotArgument(V);
565 // Constants can be considered to be not'ed values...
566 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
567 return ConstantInt::get(~C->getValue());
571 // dyn_castFoldableMul - If this value is a multiply that can be folded into
572 // other computations (because it has a constant operand), return the
573 // non-constant operand of the multiply, and set CST to point to the multiplier.
574 // Otherwise, return null.
576 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
577 if (V->hasOneUse() && V->getType()->isInteger())
578 if (Instruction *I = dyn_cast<Instruction>(V)) {
579 if (I->getOpcode() == Instruction::Mul)
580 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
581 return I->getOperand(0);
582 if (I->getOpcode() == Instruction::Shl)
583 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
584 // The multiplier is really 1 << CST.
585 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
586 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
587 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
588 return I->getOperand(0);
594 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
595 /// expression, return it.
596 static User *dyn_castGetElementPtr(Value *V) {
597 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
599 if (CE->getOpcode() == Instruction::GetElementPtr)
600 return cast<User>(V);
604 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
605 /// opcode value. Otherwise return UserOp1.
606 static unsigned getOpcode(Value *V) {
607 if (Instruction *I = dyn_cast<Instruction>(V))
608 return I->getOpcode();
609 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
610 return CE->getOpcode();
611 // Use UserOp1 to mean there's no opcode.
612 return Instruction::UserOp1;
615 /// AddOne - Add one to a ConstantInt
616 static ConstantInt *AddOne(ConstantInt *C) {
617 APInt Val(C->getValue());
618 return ConstantInt::get(++Val);
620 /// SubOne - Subtract one from a ConstantInt
621 static ConstantInt *SubOne(ConstantInt *C) {
622 APInt Val(C->getValue());
623 return ConstantInt::get(--Val);
625 /// Add - Add two ConstantInts together
626 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
627 return ConstantInt::get(C1->getValue() + C2->getValue());
629 /// And - Bitwise AND two ConstantInts together
630 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
631 return ConstantInt::get(C1->getValue() & C2->getValue());
633 /// Subtract - Subtract one ConstantInt from another
634 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() - C2->getValue());
637 /// Multiply - Multiply two ConstantInts together
638 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() * C2->getValue());
641 /// MultiplyOverflows - True if the multiply can not be expressed in an int
643 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654 APInt MulExt = LHSExt * RHSExt;
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
664 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
665 /// known to be either zero or one and return them in the KnownZero/KnownOne
666 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
668 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
669 /// we cannot optimize based on the assumption that it is zero without changing
670 /// it to be an explicit zero. If we don't change it to zero, other code could
671 /// optimized based on the contradictory assumption that it is non-zero.
672 /// Because instcombine aggressively folds operations with undef args anyway,
673 /// this won't lose us code quality.
674 void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
675 APInt& KnownZero, APInt& KnownOne,
676 unsigned Depth) const {
677 assert(V && "No Value?");
678 assert(Depth <= 6 && "Limit Search Depth");
679 uint32_t BitWidth = Mask.getBitWidth();
680 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
681 "Not integer or pointer type!");
682 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
683 (!isa<IntegerType>(V->getType()) ||
684 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
685 KnownZero.getBitWidth() == BitWidth &&
686 KnownOne.getBitWidth() == BitWidth &&
687 "V, Mask, KnownOne and KnownZero should have same BitWidth");
689 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
690 // We know all of the bits for a constant!
691 KnownOne = CI->getValue() & Mask;
692 KnownZero = ~KnownOne & Mask;
695 // Null is all-zeros.
696 if (isa<ConstantPointerNull>(V)) {
701 // The address of an aligned GlobalValue has trailing zeros.
702 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
703 unsigned Align = GV->getAlignment();
704 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
705 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
707 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
708 CountTrailingZeros_32(Align));
715 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
717 if (Depth == 6 || Mask == 0)
718 return; // Limit search depth.
720 User *I = dyn_cast<User>(V);
723 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
724 switch (getOpcode(I)) {
726 case Instruction::And: {
727 // If either the LHS or the RHS are Zero, the result is zero.
728 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
729 APInt Mask2(Mask & ~KnownZero);
730 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
731 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
732 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
734 // Output known-1 bits are only known if set in both the LHS & RHS.
735 KnownOne &= KnownOne2;
736 // Output known-0 are known to be clear if zero in either the LHS | RHS.
737 KnownZero |= KnownZero2;
740 case Instruction::Or: {
741 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
742 APInt Mask2(Mask & ~KnownOne);
743 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
744 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
747 // Output known-0 bits are only known if clear in both the LHS & RHS.
748 KnownZero &= KnownZero2;
749 // Output known-1 are known to be set if set in either the LHS | RHS.
750 KnownOne |= KnownOne2;
753 case Instruction::Xor: {
754 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
755 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
759 // Output known-0 bits are known if clear or set in both the LHS & RHS.
760 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
761 // Output known-1 are known to be set if set in only one of the LHS, RHS.
762 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
763 KnownZero = KnownZeroOut;
766 case Instruction::Mul: {
767 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
768 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
769 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
771 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
773 // If low bits are zero in either operand, output low known-0 bits.
774 // Also compute a conserative estimate for high known-0 bits.
775 // More trickiness is possible, but this is sufficient for the
776 // interesting case of alignment computation.
778 unsigned TrailZ = KnownZero.countTrailingOnes() +
779 KnownZero2.countTrailingOnes();
780 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
781 KnownZero2.countLeadingOnes(),
782 BitWidth) - BitWidth;
784 TrailZ = std::min(TrailZ, BitWidth);
785 LeadZ = std::min(LeadZ, BitWidth);
786 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
787 APInt::getHighBitsSet(BitWidth, LeadZ);
791 case Instruction::UDiv: {
792 // For the purposes of computing leading zeros we can conservatively
793 // treat a udiv as a logical right shift by the power of 2 known to
794 // be less than the denominator.
795 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
796 ComputeMaskedBits(I->getOperand(0),
797 AllOnes, KnownZero2, KnownOne2, Depth+1);
798 unsigned LeadZ = KnownZero2.countLeadingOnes();
802 ComputeMaskedBits(I->getOperand(1),
803 AllOnes, KnownZero2, KnownOne2, Depth+1);
804 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
805 if (RHSUnknownLeadingOnes != BitWidth)
806 LeadZ = std::min(BitWidth,
807 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
809 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
812 case Instruction::Select:
813 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
814 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
815 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
816 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
818 // Only known if known in both the LHS and RHS.
819 KnownOne &= KnownOne2;
820 KnownZero &= KnownZero2;
822 case Instruction::FPTrunc:
823 case Instruction::FPExt:
824 case Instruction::FPToUI:
825 case Instruction::FPToSI:
826 case Instruction::SIToFP:
827 case Instruction::UIToFP:
828 return; // Can't work with floating point.
829 case Instruction::PtrToInt:
830 case Instruction::IntToPtr:
831 // We can't handle these if we don't know the pointer size.
833 // FALL THROUGH and handle them the same as zext/trunc.
834 case Instruction::ZExt:
835 case Instruction::Trunc: {
836 // Note that we handle pointer operands here because of inttoptr/ptrtoint
837 // which fall through here.
838 const Type *SrcTy = I->getOperand(0)->getType();
839 uint32_t SrcBitWidth = TD ?
840 TD->getTypeSizeInBits(SrcTy) :
841 SrcTy->getPrimitiveSizeInBits();
843 MaskIn.zextOrTrunc(SrcBitWidth);
844 KnownZero.zextOrTrunc(SrcBitWidth);
845 KnownOne.zextOrTrunc(SrcBitWidth);
846 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
847 KnownZero.zextOrTrunc(BitWidth);
848 KnownOne.zextOrTrunc(BitWidth);
849 // Any top bits are known to be zero.
850 if (BitWidth > SrcBitWidth)
851 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
854 case Instruction::BitCast: {
855 const Type *SrcTy = I->getOperand(0)->getType();
856 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
857 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
862 case Instruction::SExt: {
863 // Compute the bits in the result that are not present in the input.
864 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
865 uint32_t SrcBitWidth = SrcTy->getBitWidth();
868 MaskIn.trunc(SrcBitWidth);
869 KnownZero.trunc(SrcBitWidth);
870 KnownOne.trunc(SrcBitWidth);
871 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
872 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
873 KnownZero.zext(BitWidth);
874 KnownOne.zext(BitWidth);
876 // If the sign bit of the input is known set or clear, then we know the
877 // top bits of the result.
878 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
879 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
880 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
881 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
884 case Instruction::Shl:
885 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
886 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
887 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
888 APInt Mask2(Mask.lshr(ShiftAmt));
889 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
890 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
891 KnownZero <<= ShiftAmt;
892 KnownOne <<= ShiftAmt;
893 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
897 case Instruction::LShr:
898 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
899 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
900 // Compute the new bits that are at the top now.
901 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
903 // Unsigned shift right.
904 APInt Mask2(Mask.shl(ShiftAmt));
905 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
906 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
907 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
908 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
909 // high bits known zero.
910 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
914 case Instruction::AShr:
915 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
916 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
917 // Compute the new bits that are at the top now.
918 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
920 // Signed shift right.
921 APInt Mask2(Mask.shl(ShiftAmt));
922 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
923 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
924 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
925 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
927 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
928 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
929 KnownZero |= HighBits;
930 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
931 KnownOne |= HighBits;
935 case Instruction::Sub: {
936 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
937 // We know that the top bits of C-X are clear if X contains less bits
938 // than C (i.e. no wrap-around can happen). For example, 20-X is
939 // positive if we can prove that X is >= 0 and < 16.
940 if (!CLHS->getValue().isNegative()) {
941 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
942 // NLZ can't be BitWidth with no sign bit
943 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
944 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
947 // If all of the MaskV bits are known to be zero, then we know the
948 // output top bits are zero, because we now know that the output is
950 if ((KnownZero2 & MaskV) == MaskV) {
951 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
952 // Top bits known zero.
953 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
959 case Instruction::Add: {
960 // Output known-0 bits are known if clear or set in both the low clear bits
961 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
963 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
964 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
965 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
966 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
968 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
969 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
970 KnownZeroOut = std::min(KnownZeroOut,
971 KnownZero2.countTrailingOnes());
973 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
976 case Instruction::SRem:
977 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
978 APInt RA = Rem->getValue();
979 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
980 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
981 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
982 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
984 // The sign of a remainder is equal to the sign of the first
985 // operand (zero being positive).
986 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
987 KnownZero2 |= ~LowBits;
988 else if (KnownOne2[BitWidth-1])
989 KnownOne2 |= ~LowBits;
991 KnownZero |= KnownZero2 & Mask;
992 KnownOne |= KnownOne2 & Mask;
994 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
998 case Instruction::URem: {
999 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000 APInt RA = Rem->getValue();
1001 if (RA.isPowerOf2()) {
1002 APInt LowBits = (RA - 1);
1003 APInt Mask2 = LowBits & Mask;
1004 KnownZero |= ~LowBits & Mask;
1005 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1006 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1011 // Since the result is less than or equal to either operand, any leading
1012 // zero bits in either operand must also exist in the result.
1013 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1014 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1016 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1019 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1020 KnownZero2.countLeadingOnes());
1022 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1026 case Instruction::Alloca:
1027 case Instruction::Malloc: {
1028 AllocationInst *AI = cast<AllocationInst>(V);
1029 unsigned Align = AI->getAlignment();
1030 if (Align == 0 && TD) {
1031 if (isa<AllocaInst>(AI))
1032 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1033 else if (isa<MallocInst>(AI)) {
1034 // Malloc returns maximally aligned memory.
1035 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1038 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1041 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1046 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1047 CountTrailingZeros_32(Align));
1050 case Instruction::GetElementPtr: {
1051 // Analyze all of the subscripts of this getelementptr instruction
1052 // to determine if we can prove known low zero bits.
1053 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1054 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1055 ComputeMaskedBits(I->getOperand(0), LocalMask,
1056 LocalKnownZero, LocalKnownOne, Depth+1);
1057 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1059 gep_type_iterator GTI = gep_type_begin(I);
1060 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1061 Value *Index = I->getOperand(i);
1062 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1063 // Handle struct member offset arithmetic.
1065 const StructLayout *SL = TD->getStructLayout(STy);
1066 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1067 uint64_t Offset = SL->getElementOffset(Idx);
1068 TrailZ = std::min(TrailZ,
1069 CountTrailingZeros_64(Offset));
1071 // Handle array index arithmetic.
1072 const Type *IndexedTy = GTI.getIndexedType();
1073 if (!IndexedTy->isSized()) return;
1074 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1075 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1076 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1077 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1078 ComputeMaskedBits(Index, LocalMask,
1079 LocalKnownZero, LocalKnownOne, Depth+1);
1080 TrailZ = std::min(TrailZ,
1081 CountTrailingZeros_64(TypeSize) +
1082 LocalKnownZero.countTrailingOnes());
1086 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1089 case Instruction::PHI: {
1090 PHINode *P = cast<PHINode>(I);
1091 // Handle the case of a simple two-predecessor recurrence PHI.
1092 // There's a lot more that could theoretically be done here, but
1093 // this is sufficient to catch some interesting cases.
1094 if (P->getNumIncomingValues() == 2) {
1095 for (unsigned i = 0; i != 2; ++i) {
1096 Value *L = P->getIncomingValue(i);
1097 Value *R = P->getIncomingValue(!i);
1098 User *LU = dyn_cast<User>(L);
1101 unsigned Opcode = getOpcode(LU);
1102 // Check for operations that have the property that if
1103 // both their operands have low zero bits, the result
1104 // will have low zero bits.
1105 if (Opcode == Instruction::Add ||
1106 Opcode == Instruction::Sub ||
1107 Opcode == Instruction::And ||
1108 Opcode == Instruction::Or ||
1109 Opcode == Instruction::Mul) {
1110 Value *LL = LU->getOperand(0);
1111 Value *LR = LU->getOperand(1);
1112 // Find a recurrence.
1119 // Ok, we have a PHI of the form L op= R. Check for low
1121 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1122 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1123 Mask2 = APInt::getLowBitsSet(BitWidth,
1124 KnownZero2.countTrailingOnes());
1127 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1129 APInt::getLowBitsSet(BitWidth,
1130 KnownZero2.countTrailingOnes());
1137 case Instruction::Call:
1138 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1139 switch (II->getIntrinsicID()) {
1141 case Intrinsic::ctpop:
1142 case Intrinsic::ctlz:
1143 case Intrinsic::cttz: {
1144 unsigned LowBits = Log2_32(BitWidth)+1;
1145 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1154 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1155 /// this predicate to simplify operations downstream. Mask is known to be zero
1156 /// for bits that V cannot have.
1157 bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1159 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1160 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1161 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1162 return (KnownZero & Mask) == Mask;
1165 /// ShrinkDemandedConstant - Check to see if the specified operand of the
1166 /// specified instruction is a constant integer. If so, check to see if there
1167 /// are any bits set in the constant that are not demanded. If so, shrink the
1168 /// constant and return true.
1169 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1171 assert(I && "No instruction?");
1172 assert(OpNo < I->getNumOperands() && "Operand index too large");
1174 // If the operand is not a constant integer, nothing to do.
1175 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1176 if (!OpC) return false;
1178 // If there are no bits set that aren't demanded, nothing to do.
1179 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1180 if ((~Demanded & OpC->getValue()) == 0)
1183 // This instruction is producing bits that are not demanded. Shrink the RHS.
1184 Demanded &= OpC->getValue();
1185 I->setOperand(OpNo, ConstantInt::get(Demanded));
1189 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1190 // set of known zero and one bits, compute the maximum and minimum values that
1191 // could have the specified known zero and known one bits, returning them in
1193 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1194 const APInt& KnownZero,
1195 const APInt& KnownOne,
1196 APInt& Min, APInt& Max) {
1197 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1198 assert(KnownZero.getBitWidth() == BitWidth &&
1199 KnownOne.getBitWidth() == BitWidth &&
1200 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1201 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1202 APInt UnknownBits = ~(KnownZero|KnownOne);
1204 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1205 // bit if it is unknown.
1207 Max = KnownOne|UnknownBits;
1209 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1210 Min.set(BitWidth-1);
1211 Max.clear(BitWidth-1);
1215 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1216 // a set of known zero and one bits, compute the maximum and minimum values that
1217 // could have the specified known zero and known one bits, returning them in
1219 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1220 const APInt &KnownZero,
1221 const APInt &KnownOne,
1222 APInt &Min, APInt &Max) {
1223 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
1224 assert(KnownZero.getBitWidth() == BitWidth &&
1225 KnownOne.getBitWidth() == BitWidth &&
1226 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1227 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1228 APInt UnknownBits = ~(KnownZero|KnownOne);
1230 // The minimum value is when the unknown bits are all zeros.
1232 // The maximum value is when the unknown bits are all ones.
1233 Max = KnownOne|UnknownBits;
1236 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1237 /// value based on the demanded bits. When this function is called, it is known
1238 /// that only the bits set in DemandedMask of the result of V are ever used
1239 /// downstream. Consequently, depending on the mask and V, it may be possible
1240 /// to replace V with a constant or one of its operands. In such cases, this
1241 /// function does the replacement and returns true. In all other cases, it
1242 /// returns false after analyzing the expression and setting KnownOne and known
1243 /// to be one in the expression. KnownZero contains all the bits that are known
1244 /// to be zero in the expression. These are provided to potentially allow the
1245 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1246 /// the expression. KnownOne and KnownZero always follow the invariant that
1247 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1248 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1249 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1250 /// and KnownOne must all be the same.
1251 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1252 APInt& KnownZero, APInt& KnownOne,
1254 assert(V != 0 && "Null pointer of Value???");
1255 assert(Depth <= 6 && "Limit Search Depth");
1256 uint32_t BitWidth = DemandedMask.getBitWidth();
1257 const IntegerType *VTy = cast<IntegerType>(V->getType());
1258 assert(VTy->getBitWidth() == BitWidth &&
1259 KnownZero.getBitWidth() == BitWidth &&
1260 KnownOne.getBitWidth() == BitWidth &&
1261 "Value *V, DemandedMask, KnownZero and KnownOne \
1262 must have same BitWidth");
1263 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1264 // We know all of the bits for a constant!
1265 KnownOne = CI->getValue() & DemandedMask;
1266 KnownZero = ~KnownOne & DemandedMask;
1272 if (!V->hasOneUse()) { // Other users may use these bits.
1273 if (Depth != 0) { // Not at the root.
1274 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1275 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1278 // If this is the root being simplified, allow it to have multiple uses,
1279 // just set the DemandedMask to all bits.
1280 DemandedMask = APInt::getAllOnesValue(BitWidth);
1281 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1282 if (V != UndefValue::get(VTy))
1283 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1285 } else if (Depth == 6) { // Limit search depth.
1289 Instruction *I = dyn_cast<Instruction>(V);
1290 if (!I) return false; // Only analyze instructions.
1292 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1293 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1294 switch (I->getOpcode()) {
1296 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1298 case Instruction::And:
1299 // If either the LHS or the RHS are Zero, the result is zero.
1300 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1301 RHSKnownZero, RHSKnownOne, Depth+1))
1303 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1304 "Bits known to be one AND zero?");
1306 // If something is known zero on the RHS, the bits aren't demanded on the
1308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1309 LHSKnownZero, LHSKnownOne, Depth+1))
1311 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1312 "Bits known to be one AND zero?");
1314 // If all of the demanded bits are known 1 on one side, return the other.
1315 // These bits cannot contribute to the result of the 'and'.
1316 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1317 (DemandedMask & ~LHSKnownZero))
1318 return UpdateValueUsesWith(I, I->getOperand(0));
1319 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1320 (DemandedMask & ~RHSKnownZero))
1321 return UpdateValueUsesWith(I, I->getOperand(1));
1323 // If all of the demanded bits in the inputs are known zeros, return zero.
1324 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1325 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1327 // If the RHS is a constant, see if we can simplify it.
1328 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1329 return UpdateValueUsesWith(I, I);
1331 // Output known-1 bits are only known if set in both the LHS & RHS.
1332 RHSKnownOne &= LHSKnownOne;
1333 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1334 RHSKnownZero |= LHSKnownZero;
1336 case Instruction::Or:
1337 // If either the LHS or the RHS are One, the result is One.
1338 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1339 RHSKnownZero, RHSKnownOne, Depth+1))
1341 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1342 "Bits known to be one AND zero?");
1343 // If something is known one on the RHS, the bits aren't demanded on the
1345 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1346 LHSKnownZero, LHSKnownOne, Depth+1))
1348 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1349 "Bits known to be one AND zero?");
1351 // If all of the demanded bits are known zero on one side, return the other.
1352 // These bits cannot contribute to the result of the 'or'.
1353 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1354 (DemandedMask & ~LHSKnownOne))
1355 return UpdateValueUsesWith(I, I->getOperand(0));
1356 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1357 (DemandedMask & ~RHSKnownOne))
1358 return UpdateValueUsesWith(I, I->getOperand(1));
1360 // If all of the potentially set bits on one side are known to be set on
1361 // the other side, just use the 'other' side.
1362 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1363 (DemandedMask & (~RHSKnownZero)))
1364 return UpdateValueUsesWith(I, I->getOperand(0));
1365 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1366 (DemandedMask & (~LHSKnownZero)))
1367 return UpdateValueUsesWith(I, I->getOperand(1));
1369 // If the RHS is a constant, see if we can simplify it.
1370 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1371 return UpdateValueUsesWith(I, I);
1373 // Output known-0 bits are only known if clear in both the LHS & RHS.
1374 RHSKnownZero &= LHSKnownZero;
1375 // Output known-1 are known to be set if set in either the LHS | RHS.
1376 RHSKnownOne |= LHSKnownOne;
1378 case Instruction::Xor: {
1379 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1380 RHSKnownZero, RHSKnownOne, Depth+1))
1382 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1383 "Bits known to be one AND zero?");
1384 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1385 LHSKnownZero, LHSKnownOne, Depth+1))
1387 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1388 "Bits known to be one AND zero?");
1390 // If all of the demanded bits are known zero on one side, return the other.
1391 // These bits cannot contribute to the result of the 'xor'.
1392 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1393 return UpdateValueUsesWith(I, I->getOperand(0));
1394 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1395 return UpdateValueUsesWith(I, I->getOperand(1));
1397 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1398 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1399 (RHSKnownOne & LHSKnownOne);
1400 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1401 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1402 (RHSKnownOne & LHSKnownZero);
1404 // If all of the demanded bits are known to be zero on one side or the
1405 // other, turn this into an *inclusive* or.
1406 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1407 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1409 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1411 InsertNewInstBefore(Or, *I);
1412 return UpdateValueUsesWith(I, Or);
1415 // If all of the demanded bits on one side are known, and all of the set
1416 // bits on that side are also known to be set on the other side, turn this
1417 // into an AND, as we know the bits will be cleared.
1418 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1419 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1421 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1422 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1424 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1425 InsertNewInstBefore(And, *I);
1426 return UpdateValueUsesWith(I, And);
1430 // If the RHS is a constant, see if we can simplify it.
1431 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1432 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1433 return UpdateValueUsesWith(I, I);
1435 RHSKnownZero = KnownZeroOut;
1436 RHSKnownOne = KnownOneOut;
1439 case Instruction::Select:
1440 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1441 RHSKnownZero, RHSKnownOne, Depth+1))
1443 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1444 LHSKnownZero, LHSKnownOne, Depth+1))
1446 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1447 "Bits known to be one AND zero?");
1448 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1449 "Bits known to be one AND zero?");
1451 // If the operands are constants, see if we can simplify them.
1452 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1453 return UpdateValueUsesWith(I, I);
1454 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1455 return UpdateValueUsesWith(I, I);
1457 // Only known if known in both the LHS and RHS.
1458 RHSKnownOne &= LHSKnownOne;
1459 RHSKnownZero &= LHSKnownZero;
1461 case Instruction::Trunc: {
1463 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1464 DemandedMask.zext(truncBf);
1465 RHSKnownZero.zext(truncBf);
1466 RHSKnownOne.zext(truncBf);
1467 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1468 RHSKnownZero, RHSKnownOne, Depth+1))
1470 DemandedMask.trunc(BitWidth);
1471 RHSKnownZero.trunc(BitWidth);
1472 RHSKnownOne.trunc(BitWidth);
1473 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1474 "Bits known to be one AND zero?");
1477 case Instruction::BitCast:
1478 if (!I->getOperand(0)->getType()->isInteger())
1481 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1482 RHSKnownZero, RHSKnownOne, Depth+1))
1484 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1485 "Bits known to be one AND zero?");
1487 case Instruction::ZExt: {
1488 // Compute the bits in the result that are not present in the input.
1489 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1490 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1492 DemandedMask.trunc(SrcBitWidth);
1493 RHSKnownZero.trunc(SrcBitWidth);
1494 RHSKnownOne.trunc(SrcBitWidth);
1495 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1496 RHSKnownZero, RHSKnownOne, Depth+1))
1498 DemandedMask.zext(BitWidth);
1499 RHSKnownZero.zext(BitWidth);
1500 RHSKnownOne.zext(BitWidth);
1501 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1502 "Bits known to be one AND zero?");
1503 // The top bits are known to be zero.
1504 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1507 case Instruction::SExt: {
1508 // Compute the bits in the result that are not present in the input.
1509 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1510 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1512 APInt InputDemandedBits = DemandedMask &
1513 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1515 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1516 // If any of the sign extended bits are demanded, we know that the sign
1518 if ((NewBits & DemandedMask) != 0)
1519 InputDemandedBits.set(SrcBitWidth-1);
1521 InputDemandedBits.trunc(SrcBitWidth);
1522 RHSKnownZero.trunc(SrcBitWidth);
1523 RHSKnownOne.trunc(SrcBitWidth);
1524 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1525 RHSKnownZero, RHSKnownOne, Depth+1))
1527 InputDemandedBits.zext(BitWidth);
1528 RHSKnownZero.zext(BitWidth);
1529 RHSKnownOne.zext(BitWidth);
1530 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1531 "Bits known to be one AND zero?");
1533 // If the sign bit of the input is known set or clear, then we know the
1534 // top bits of the result.
1536 // If the input sign bit is known zero, or if the NewBits are not demanded
1537 // convert this into a zero extension.
1538 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1540 // Convert to ZExt cast
1541 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1542 return UpdateValueUsesWith(I, NewCast);
1543 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1544 RHSKnownOne |= NewBits;
1548 case Instruction::Add: {
1549 // Figure out what the input bits are. If the top bits of the and result
1550 // are not demanded, then the add doesn't demand them from its input
1552 uint32_t NLZ = DemandedMask.countLeadingZeros();
1554 // If there is a constant on the RHS, there are a variety of xformations
1556 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1557 // If null, this should be simplified elsewhere. Some of the xforms here
1558 // won't work if the RHS is zero.
1562 // If the top bit of the output is demanded, demand everything from the
1563 // input. Otherwise, we demand all the input bits except NLZ top bits.
1564 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1566 // Find information about known zero/one bits in the input.
1567 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1568 LHSKnownZero, LHSKnownOne, Depth+1))
1571 // If the RHS of the add has bits set that can't affect the input, reduce
1573 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1574 return UpdateValueUsesWith(I, I);
1576 // Avoid excess work.
1577 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1580 // Turn it into OR if input bits are zero.
1581 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1583 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1585 InsertNewInstBefore(Or, *I);
1586 return UpdateValueUsesWith(I, Or);
1589 // We can say something about the output known-zero and known-one bits,
1590 // depending on potential carries from the input constant and the
1591 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1592 // bits set and the RHS constant is 0x01001, then we know we have a known
1593 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1595 // To compute this, we first compute the potential carry bits. These are
1596 // the bits which may be modified. I'm not aware of a better way to do
1598 const APInt& RHSVal = RHS->getValue();
1599 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1601 // Now that we know which bits have carries, compute the known-1/0 sets.
1603 // Bits are known one if they are known zero in one operand and one in the
1604 // other, and there is no input carry.
1605 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1606 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1608 // Bits are known zero if they are known zero in both operands and there
1609 // is no input carry.
1610 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1612 // If the high-bits of this ADD are not demanded, then it does not demand
1613 // the high bits of its LHS or RHS.
1614 if (DemandedMask[BitWidth-1] == 0) {
1615 // Right fill the mask of bits for this ADD to demand the most
1616 // significant bit and all those below it.
1617 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1618 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1619 LHSKnownZero, LHSKnownOne, Depth+1))
1621 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1622 LHSKnownZero, LHSKnownOne, Depth+1))
1628 case Instruction::Sub:
1629 // If the high-bits of this SUB are not demanded, then it does not demand
1630 // the high bits of its LHS or RHS.
1631 if (DemandedMask[BitWidth-1] == 0) {
1632 // Right fill the mask of bits for this SUB to demand the most
1633 // significant bit and all those below it.
1634 uint32_t NLZ = DemandedMask.countLeadingZeros();
1635 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1636 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1637 LHSKnownZero, LHSKnownOne, Depth+1))
1639 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1640 LHSKnownZero, LHSKnownOne, Depth+1))
1643 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1644 // the known zeros and ones.
1645 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1647 case Instruction::Shl:
1648 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1649 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1650 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1651 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1652 RHSKnownZero, RHSKnownOne, Depth+1))
1654 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1655 "Bits known to be one AND zero?");
1656 RHSKnownZero <<= ShiftAmt;
1657 RHSKnownOne <<= ShiftAmt;
1658 // low bits known zero.
1660 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1663 case Instruction::LShr:
1664 // For a logical shift right
1665 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1666 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1668 // Unsigned shift right.
1669 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1670 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1671 RHSKnownZero, RHSKnownOne, Depth+1))
1673 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1674 "Bits known to be one AND zero?");
1675 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1676 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1678 // Compute the new bits that are at the top now.
1679 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1680 RHSKnownZero |= HighBits; // high bits known zero.
1684 case Instruction::AShr:
1685 // If this is an arithmetic shift right and only the low-bit is set, we can
1686 // always convert this into a logical shr, even if the shift amount is
1687 // variable. The low bit of the shift cannot be an input sign bit unless
1688 // the shift amount is >= the size of the datatype, which is undefined.
1689 if (DemandedMask == 1) {
1690 // Perform the logical shift right.
1691 Value *NewVal = BinaryOperator::CreateLShr(
1692 I->getOperand(0), I->getOperand(1), I->getName());
1693 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1694 return UpdateValueUsesWith(I, NewVal);
1697 // If the sign bit is the only bit demanded by this ashr, then there is no
1698 // need to do it, the shift doesn't change the high bit.
1699 if (DemandedMask.isSignBit())
1700 return UpdateValueUsesWith(I, I->getOperand(0));
1702 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1703 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1705 // Signed shift right.
1706 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1707 // If any of the "high bits" are demanded, we should set the sign bit as
1709 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1710 DemandedMaskIn.set(BitWidth-1);
1711 if (SimplifyDemandedBits(I->getOperand(0),
1713 RHSKnownZero, RHSKnownOne, Depth+1))
1715 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1716 "Bits known to be one AND zero?");
1717 // Compute the new bits that are at the top now.
1718 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1719 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1720 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1722 // Handle the sign bits.
1723 APInt SignBit(APInt::getSignBit(BitWidth));
1724 // Adjust to where it is now in the mask.
1725 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1727 // If the input sign bit is known to be zero, or if none of the top bits
1728 // are demanded, turn this into an unsigned shift right.
1729 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1730 (HighBits & ~DemandedMask) == HighBits) {
1731 // Perform the logical shift right.
1732 Value *NewVal = BinaryOperator::CreateLShr(
1733 I->getOperand(0), SA, I->getName());
1734 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1735 return UpdateValueUsesWith(I, NewVal);
1736 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1737 RHSKnownOne |= HighBits;
1741 case Instruction::SRem:
1742 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1743 APInt RA = Rem->getValue();
1744 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1745 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1746 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1747 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1748 LHSKnownZero, LHSKnownOne, Depth+1))
1751 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1752 LHSKnownZero |= ~LowBits;
1753 else if (LHSKnownOne[BitWidth-1])
1754 LHSKnownOne |= ~LowBits;
1756 KnownZero |= LHSKnownZero & DemandedMask;
1757 KnownOne |= LHSKnownOne & DemandedMask;
1759 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1763 case Instruction::URem: {
1764 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1765 APInt RA = Rem->getValue();
1766 if (RA.isPowerOf2()) {
1767 APInt LowBits = (RA - 1);
1768 APInt Mask2 = LowBits & DemandedMask;
1769 KnownZero |= ~LowBits & DemandedMask;
1770 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1771 KnownZero, KnownOne, Depth+1))
1774 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1779 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1780 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1781 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1782 KnownZero2, KnownOne2, Depth+1))
1785 uint32_t Leaders = KnownZero2.countLeadingOnes();
1786 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1787 KnownZero2, KnownOne2, Depth+1))
1790 Leaders = std::max(Leaders,
1791 KnownZero2.countLeadingOnes());
1792 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1797 // If the client is only demanding bits that we know, return the known
1799 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1800 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1805 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1806 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1807 /// actually used by the caller. This method analyzes which elements of the
1808 /// operand are undef and returns that information in UndefElts.
1810 /// If the information about demanded elements can be used to simplify the
1811 /// operation, the operation is simplified, then the resultant value is
1812 /// returned. This returns null if no change was made.
1813 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1814 uint64_t &UndefElts,
1816 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1817 assert(VWidth <= 64 && "Vector too wide to analyze!");
1818 uint64_t EltMask = ~0ULL >> (64-VWidth);
1819 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1820 "Invalid DemandedElts!");
1822 if (isa<UndefValue>(V)) {
1823 // If the entire vector is undefined, just return this info.
1824 UndefElts = EltMask;
1826 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1827 UndefElts = EltMask;
1828 return UndefValue::get(V->getType());
1832 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1833 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1834 Constant *Undef = UndefValue::get(EltTy);
1836 std::vector<Constant*> Elts;
1837 for (unsigned i = 0; i != VWidth; ++i)
1838 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1839 Elts.push_back(Undef);
1840 UndefElts |= (1ULL << i);
1841 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1842 Elts.push_back(Undef);
1843 UndefElts |= (1ULL << i);
1844 } else { // Otherwise, defined.
1845 Elts.push_back(CP->getOperand(i));
1848 // If we changed the constant, return it.
1849 Constant *NewCP = ConstantVector::get(Elts);
1850 return NewCP != CP ? NewCP : 0;
1851 } else if (isa<ConstantAggregateZero>(V)) {
1852 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1854 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1855 Constant *Zero = Constant::getNullValue(EltTy);
1856 Constant *Undef = UndefValue::get(EltTy);
1857 std::vector<Constant*> Elts;
1858 for (unsigned i = 0; i != VWidth; ++i)
1859 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1860 UndefElts = DemandedElts ^ EltMask;
1861 return ConstantVector::get(Elts);
1864 if (!V->hasOneUse()) { // Other users may use these bits.
1865 if (Depth != 0) { // Not at the root.
1866 // TODO: Just compute the UndefElts information recursively.
1870 } else if (Depth == 10) { // Limit search depth.
1874 Instruction *I = dyn_cast<Instruction>(V);
1875 if (!I) return false; // Only analyze instructions.
1877 bool MadeChange = false;
1878 uint64_t UndefElts2;
1880 switch (I->getOpcode()) {
1883 case Instruction::InsertElement: {
1884 // If this is a variable index, we don't know which element it overwrites.
1885 // demand exactly the same input as we produce.
1886 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1888 // Note that we can't propagate undef elt info, because we don't know
1889 // which elt is getting updated.
1890 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1891 UndefElts2, Depth+1);
1892 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1896 // If this is inserting an element that isn't demanded, remove this
1898 unsigned IdxNo = Idx->getZExtValue();
1899 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1900 return AddSoonDeadInstToWorklist(*I, 0);
1902 // Otherwise, the element inserted overwrites whatever was there, so the
1903 // input demanded set is simpler than the output set.
1904 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1905 DemandedElts & ~(1ULL << IdxNo),
1906 UndefElts, Depth+1);
1907 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1909 // The inserted element is defined.
1910 UndefElts |= 1ULL << IdxNo;
1913 case Instruction::BitCast: {
1914 // Vector->vector casts only.
1915 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1917 unsigned InVWidth = VTy->getNumElements();
1918 uint64_t InputDemandedElts = 0;
1921 if (VWidth == InVWidth) {
1922 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1923 // elements as are demanded of us.
1925 InputDemandedElts = DemandedElts;
1926 } else if (VWidth > InVWidth) {
1930 // If there are more elements in the result than there are in the source,
1931 // then an input element is live if any of the corresponding output
1932 // elements are live.
1933 Ratio = VWidth/InVWidth;
1934 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1935 if (DemandedElts & (1ULL << OutIdx))
1936 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1942 // If there are more elements in the source than there are in the result,
1943 // then an input element is live if the corresponding output element is
1945 Ratio = InVWidth/VWidth;
1946 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1947 if (DemandedElts & (1ULL << InIdx/Ratio))
1948 InputDemandedElts |= 1ULL << InIdx;
1951 // div/rem demand all inputs, because they don't want divide by zero.
1952 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1953 UndefElts2, Depth+1);
1955 I->setOperand(0, TmpV);
1959 UndefElts = UndefElts2;
1960 if (VWidth > InVWidth) {
1961 assert(0 && "Unimp");
1962 // If there are more elements in the result than there are in the source,
1963 // then an output element is undef if the corresponding input element is
1965 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1966 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1967 UndefElts |= 1ULL << OutIdx;
1968 } else if (VWidth < InVWidth) {
1969 assert(0 && "Unimp");
1970 // If there are more elements in the source than there are in the result,
1971 // then a result element is undef if all of the corresponding input
1972 // elements are undef.
1973 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1974 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1975 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1976 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1980 case Instruction::And:
1981 case Instruction::Or:
1982 case Instruction::Xor:
1983 case Instruction::Add:
1984 case Instruction::Sub:
1985 case Instruction::Mul:
1986 // div/rem demand all inputs, because they don't want divide by zero.
1987 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1988 UndefElts, Depth+1);
1989 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1990 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1991 UndefElts2, Depth+1);
1992 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1994 // Output elements are undefined if both are undefined. Consider things
1995 // like undef&0. The result is known zero, not undef.
1996 UndefElts &= UndefElts2;
1999 case Instruction::Call: {
2000 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2002 switch (II->getIntrinsicID()) {
2005 // Binary vector operations that work column-wise. A dest element is a
2006 // function of the corresponding input elements from the two inputs.
2007 case Intrinsic::x86_sse_sub_ss:
2008 case Intrinsic::x86_sse_mul_ss:
2009 case Intrinsic::x86_sse_min_ss:
2010 case Intrinsic::x86_sse_max_ss:
2011 case Intrinsic::x86_sse2_sub_sd:
2012 case Intrinsic::x86_sse2_mul_sd:
2013 case Intrinsic::x86_sse2_min_sd:
2014 case Intrinsic::x86_sse2_max_sd:
2015 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2016 UndefElts, Depth+1);
2017 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2018 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2019 UndefElts2, Depth+1);
2020 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2022 // If only the low elt is demanded and this is a scalarizable intrinsic,
2023 // scalarize it now.
2024 if (DemandedElts == 1) {
2025 switch (II->getIntrinsicID()) {
2027 case Intrinsic::x86_sse_sub_ss:
2028 case Intrinsic::x86_sse_mul_ss:
2029 case Intrinsic::x86_sse2_sub_sd:
2030 case Intrinsic::x86_sse2_mul_sd:
2031 // TODO: Lower MIN/MAX/ABS/etc
2032 Value *LHS = II->getOperand(1);
2033 Value *RHS = II->getOperand(2);
2034 // Extract the element as scalars.
2035 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2036 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2038 switch (II->getIntrinsicID()) {
2039 default: assert(0 && "Case stmts out of sync!");
2040 case Intrinsic::x86_sse_sub_ss:
2041 case Intrinsic::x86_sse2_sub_sd:
2042 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
2043 II->getName()), *II);
2045 case Intrinsic::x86_sse_mul_ss:
2046 case Intrinsic::x86_sse2_mul_sd:
2047 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
2048 II->getName()), *II);
2053 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2055 InsertNewInstBefore(New, *II);
2056 AddSoonDeadInstToWorklist(*II, 0);
2061 // Output elements are undefined if both are undefined. Consider things
2062 // like undef&0. The result is known zero, not undef.
2063 UndefElts &= UndefElts2;
2069 return MadeChange ? I : 0;
2072 /// ComputeNumSignBits - Return the number of times the sign bit of the
2073 /// register is replicated into the other bits. We know that at least 1 bit
2074 /// is always equal to the sign bit (itself), but other cases can give us
2075 /// information. For example, immediately after an "ashr X, 2", we know that
2076 /// the top 3 bits are all equal to each other, so we return 3.
2078 unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2079 const IntegerType *Ty = cast<IntegerType>(V->getType());
2080 unsigned TyBits = Ty->getBitWidth();
2082 unsigned FirstAnswer = 1;
2085 return 1; // Limit search depth.
2087 User *U = dyn_cast<User>(V);
2088 switch (getOpcode(V)) {
2090 case Instruction::SExt:
2091 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2092 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2094 case Instruction::AShr:
2095 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2096 // ashr X, C -> adds C sign bits.
2097 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2098 Tmp += C->getZExtValue();
2099 if (Tmp > TyBits) Tmp = TyBits;
2102 case Instruction::Shl:
2103 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2104 // shl destroys sign bits.
2105 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2106 if (C->getZExtValue() >= TyBits || // Bad shift.
2107 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2108 return Tmp - C->getZExtValue();
2111 case Instruction::And:
2112 case Instruction::Or:
2113 case Instruction::Xor: // NOT is handled here.
2114 // Logical binary ops preserve the number of sign bits at the worst.
2115 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2117 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2118 FirstAnswer = std::min(Tmp, Tmp2);
2119 // We computed what we know about the sign bits as our first
2120 // answer. Now proceed to the generic code that uses
2121 // ComputeMaskedBits, and pick whichever answer is better.
2125 case Instruction::Select:
2126 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
2127 if (Tmp == 1) return 1; // Early out.
2128 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
2129 return std::min(Tmp, Tmp2);
2131 case Instruction::Add:
2132 // Add can have at most one carry bit. Thus we know that the output
2133 // is, at worst, one more bit than the inputs.
2134 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2135 if (Tmp == 1) return 1; // Early out.
2137 // Special case decrementing a value (ADD X, -1):
2138 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2139 if (CRHS->isAllOnesValue()) {
2140 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2141 APInt Mask = APInt::getAllOnesValue(TyBits);
2142 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2144 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2146 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2149 // If we are subtracting one from a positive number, there is no carry
2150 // out of the result.
2151 if (KnownZero.isNegative())
2155 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2156 if (Tmp2 == 1) return 1;
2157 return std::min(Tmp, Tmp2)-1;
2160 case Instruction::Sub:
2161 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2162 if (Tmp2 == 1) return 1;
2165 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2166 if (CLHS->isNullValue()) {
2167 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2168 APInt Mask = APInt::getAllOnesValue(TyBits);
2169 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2170 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2172 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2175 // If the input is known to be positive (the sign bit is known clear),
2176 // the output of the NEG has the same number of sign bits as the input.
2177 if (KnownZero.isNegative())
2180 // Otherwise, we treat this like a SUB.
2183 // Sub can have at most one carry bit. Thus we know that the output
2184 // is, at worst, one more bit than the inputs.
2185 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2186 if (Tmp == 1) return 1; // Early out.
2187 return std::min(Tmp, Tmp2)-1;
2189 case Instruction::Trunc:
2190 // FIXME: it's tricky to do anything useful for this, but it is an important
2191 // case for targets like X86.
2195 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2196 // use this information.
2197 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2198 APInt Mask = APInt::getAllOnesValue(TyBits);
2199 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2201 if (KnownZero.isNegative()) { // sign bit is 0
2203 } else if (KnownOne.isNegative()) { // sign bit is 1;
2210 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2211 // the number of identical bits in the top of the input value.
2213 Mask <<= Mask.getBitWidth()-TyBits;
2214 // Return # leading zeros. We use 'min' here in case Val was zero before
2215 // shifting. We don't want to return '64' as for an i32 "0".
2216 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2220 /// AssociativeOpt - Perform an optimization on an associative operator. This
2221 /// function is designed to check a chain of associative operators for a
2222 /// potential to apply a certain optimization. Since the optimization may be
2223 /// applicable if the expression was reassociated, this checks the chain, then
2224 /// reassociates the expression as necessary to expose the optimization
2225 /// opportunity. This makes use of a special Functor, which must define
2226 /// 'shouldApply' and 'apply' methods.
2228 template<typename Functor>
2229 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2230 unsigned Opcode = Root.getOpcode();
2231 Value *LHS = Root.getOperand(0);
2233 // Quick check, see if the immediate LHS matches...
2234 if (F.shouldApply(LHS))
2235 return F.apply(Root);
2237 // Otherwise, if the LHS is not of the same opcode as the root, return.
2238 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2239 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2240 // Should we apply this transform to the RHS?
2241 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2243 // If not to the RHS, check to see if we should apply to the LHS...
2244 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2245 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2249 // If the functor wants to apply the optimization to the RHS of LHSI,
2250 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2252 BasicBlock *BB = Root.getParent();
2254 // Now all of the instructions are in the current basic block, go ahead
2255 // and perform the reassociation.
2256 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2258 // First move the selected RHS to the LHS of the root...
2259 Root.setOperand(0, LHSI->getOperand(1));
2261 // Make what used to be the LHS of the root be the user of the root...
2262 Value *ExtraOperand = TmpLHSI->getOperand(1);
2263 if (&Root == TmpLHSI) {
2264 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2267 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
2268 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
2269 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2270 BasicBlock::iterator ARI = &Root; ++ARI;
2271 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2274 // Now propagate the ExtraOperand down the chain of instructions until we
2276 while (TmpLHSI != LHSI) {
2277 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2278 // Move the instruction to immediately before the chain we are
2279 // constructing to avoid breaking dominance properties.
2280 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2281 BB->getInstList().insert(ARI, NextLHSI);
2284 Value *NextOp = NextLHSI->getOperand(1);
2285 NextLHSI->setOperand(1, ExtraOperand);
2287 ExtraOperand = NextOp;
2290 // Now that the instructions are reassociated, have the functor perform
2291 // the transformation...
2292 return F.apply(Root);
2295 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2302 // AddRHS - Implements: X + X --> X << 1
2305 AddRHS(Value *rhs) : RHS(rhs) {}
2306 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2307 Instruction *apply(BinaryOperator &Add) const {
2308 return BinaryOperator::CreateShl(Add.getOperand(0),
2309 ConstantInt::get(Add.getType(), 1));
2313 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2315 struct AddMaskingAnd {
2317 AddMaskingAnd(Constant *c) : C2(c) {}
2318 bool shouldApply(Value *LHS) const {
2320 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2321 ConstantExpr::getAnd(C1, C2)->isNullValue();
2323 Instruction *apply(BinaryOperator &Add) const {
2324 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
2330 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2332 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2333 if (Constant *SOC = dyn_cast<Constant>(SO))
2334 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2336 return IC->InsertNewInstBefore(CastInst::Create(
2337 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2340 // Figure out if the constant is the left or the right argument.
2341 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2342 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2344 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2346 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2347 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2350 Value *Op0 = SO, *Op1 = ConstOperand;
2352 std::swap(Op0, Op1);
2354 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2355 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2356 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2357 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2358 SO->getName()+".cmp");
2360 assert(0 && "Unknown binary instruction type!");
2363 return IC->InsertNewInstBefore(New, I);
2366 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2367 // constant as the other operand, try to fold the binary operator into the
2368 // select arguments. This also works for Cast instructions, which obviously do
2369 // not have a second operand.
2370 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2372 // Don't modify shared select instructions
2373 if (!SI->hasOneUse()) return 0;
2374 Value *TV = SI->getOperand(1);
2375 Value *FV = SI->getOperand(2);
2377 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2378 // Bool selects with constant operands can be folded to logical ops.
2379 if (SI->getType() == Type::Int1Ty) return 0;
2381 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2382 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2384 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2391 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2392 /// node as operand #0, see if we can fold the instruction into the PHI (which
2393 /// is only possible if all operands to the PHI are constants).
2394 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2395 PHINode *PN = cast<PHINode>(I.getOperand(0));
2396 unsigned NumPHIValues = PN->getNumIncomingValues();
2397 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2399 // Check to see if all of the operands of the PHI are constants. If there is
2400 // one non-constant value, remember the BB it is. If there is more than one
2401 // or if *it* is a PHI, bail out.
2402 BasicBlock *NonConstBB = 0;
2403 for (unsigned i = 0; i != NumPHIValues; ++i)
2404 if (!isa<Constant>(PN->getIncomingValue(i))) {
2405 if (NonConstBB) return 0; // More than one non-const value.
2406 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2407 NonConstBB = PN->getIncomingBlock(i);
2409 // If the incoming non-constant value is in I's block, we have an infinite
2411 if (NonConstBB == I.getParent())
2415 // If there is exactly one non-constant value, we can insert a copy of the
2416 // operation in that block. However, if this is a critical edge, we would be
2417 // inserting the computation one some other paths (e.g. inside a loop). Only
2418 // do this if the pred block is unconditionally branching into the phi block.
2420 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2421 if (!BI || !BI->isUnconditional()) return 0;
2424 // Okay, we can do the transformation: create the new PHI node.
2425 PHINode *NewPN = PHINode::Create(I.getType(), "");
2426 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2427 InsertNewInstBefore(NewPN, *PN);
2428 NewPN->takeName(PN);
2430 // Next, add all of the operands to the PHI.
2431 if (I.getNumOperands() == 2) {
2432 Constant *C = cast<Constant>(I.getOperand(1));
2433 for (unsigned i = 0; i != NumPHIValues; ++i) {
2435 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2436 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2437 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2439 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2441 assert(PN->getIncomingBlock(i) == NonConstBB);
2442 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2443 InV = BinaryOperator::Create(BO->getOpcode(),
2444 PN->getIncomingValue(i), C, "phitmp",
2445 NonConstBB->getTerminator());
2446 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2447 InV = CmpInst::Create(CI->getOpcode(),
2449 PN->getIncomingValue(i), C, "phitmp",
2450 NonConstBB->getTerminator());
2452 assert(0 && "Unknown binop!");
2454 AddToWorkList(cast<Instruction>(InV));
2456 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2459 CastInst *CI = cast<CastInst>(&I);
2460 const Type *RetTy = CI->getType();
2461 for (unsigned i = 0; i != NumPHIValues; ++i) {
2463 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2464 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2466 assert(PN->getIncomingBlock(i) == NonConstBB);
2467 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2468 I.getType(), "phitmp",
2469 NonConstBB->getTerminator());
2470 AddToWorkList(cast<Instruction>(InV));
2472 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2475 return ReplaceInstUsesWith(I, NewPN);
2479 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
2480 /// value is never equal to -0.0.
2482 /// Note that this function will need to be revisited when we support nondefault
2485 static bool CannotBeNegativeZero(const Value *V) {
2486 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2487 return !CFP->getValueAPF().isNegZero();
2489 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2490 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2491 if (I->getOpcode() == Instruction::Add &&
2492 isa<ConstantFP>(I->getOperand(1)) &&
2493 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2496 // sitofp and uitofp turn into +0.0 for zero.
2497 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2500 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2501 if (II->getIntrinsicID() == Intrinsic::sqrt)
2502 return CannotBeNegativeZero(II->getOperand(1));
2504 if (const CallInst *CI = dyn_cast<CallInst>(I))
2505 if (const Function *F = CI->getCalledFunction()) {
2506 if (F->isDeclaration()) {
2507 switch (F->getNameLen()) {
2508 case 3: // abs(x) != -0.0
2509 if (!strcmp(F->getNameStart(), "abs")) return true;
2511 case 4: // abs[lf](x) != -0.0
2512 if (!strcmp(F->getNameStart(), "absf")) return true;
2513 if (!strcmp(F->getNameStart(), "absl")) return true;
2523 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2524 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2525 /// This basically requires proving that the add in the original type would not
2526 /// overflow to change the sign bit or have a carry out.
2527 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2528 // There are different heuristics we can use for this. Here are some simple
2531 // Add has the property that adding any two 2's complement numbers can only
2532 // have one carry bit which can change a sign. As such, if LHS and RHS each
2533 // have at least two sign bits, we know that the addition of the two values will
2534 // sign extend fine.
2535 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2539 // If one of the operands only has one non-zero bit, and if the other operand
2540 // has a known-zero bit in a more significant place than it (not including the
2541 // sign bit) the ripple may go up to and fill the zero, but won't change the
2542 // sign. For example, (X & ~4) + 1.
2550 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2551 bool Changed = SimplifyCommutative(I);
2552 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2554 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2555 // X + undef -> undef
2556 if (isa<UndefValue>(RHS))
2557 return ReplaceInstUsesWith(I, RHS);
2560 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2561 if (RHSC->isNullValue())
2562 return ReplaceInstUsesWith(I, LHS);
2563 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2564 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2565 (I.getType())->getValueAPF()))
2566 return ReplaceInstUsesWith(I, LHS);
2569 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2570 // X + (signbit) --> X ^ signbit
2571 const APInt& Val = CI->getValue();
2572 uint32_t BitWidth = Val.getBitWidth();
2573 if (Val == APInt::getSignBit(BitWidth))
2574 return BinaryOperator::CreateXor(LHS, RHS);
2576 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2577 // (X & 254)+1 -> (X&254)|1
2578 if (!isa<VectorType>(I.getType())) {
2579 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2580 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2581 KnownZero, KnownOne))
2586 if (isa<PHINode>(LHS))
2587 if (Instruction *NV = FoldOpIntoPhi(I))
2590 ConstantInt *XorRHS = 0;
2592 if (isa<ConstantInt>(RHSC) &&
2593 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2594 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2595 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2597 uint32_t Size = TySizeBits / 2;
2598 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2599 APInt CFF80Val(-C0080Val);
2601 if (TySizeBits > Size) {
2602 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2603 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2604 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2605 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2606 // This is a sign extend if the top bits are known zero.
2607 if (!MaskedValueIsZero(XorLHS,
2608 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2609 Size = 0; // Not a sign ext, but can't be any others either.
2614 C0080Val = APIntOps::lshr(C0080Val, Size);
2615 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2616 } while (Size >= 1);
2618 // FIXME: This shouldn't be necessary. When the backends can handle types
2619 // with funny bit widths then this switch statement should be removed. It
2620 // is just here to get the size of the "middle" type back up to something
2621 // that the back ends can handle.
2622 const Type *MiddleType = 0;
2625 case 32: MiddleType = Type::Int32Ty; break;
2626 case 16: MiddleType = Type::Int16Ty; break;
2627 case 8: MiddleType = Type::Int8Ty; break;
2630 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2631 InsertNewInstBefore(NewTrunc, I);
2632 return new SExtInst(NewTrunc, I.getType(), I.getName());
2638 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2639 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2641 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2642 if (RHSI->getOpcode() == Instruction::Sub)
2643 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2644 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2646 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2647 if (LHSI->getOpcode() == Instruction::Sub)
2648 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2649 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2654 // -A + -B --> -(A + B)
2655 if (Value *LHSV = dyn_castNegVal(LHS)) {
2656 if (LHS->getType()->isIntOrIntVector()) {
2657 if (Value *RHSV = dyn_castNegVal(RHS)) {
2658 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2659 InsertNewInstBefore(NewAdd, I);
2660 return BinaryOperator::CreateNeg(NewAdd);
2664 return BinaryOperator::CreateSub(RHS, LHSV);
2668 if (!isa<Constant>(RHS))
2669 if (Value *V = dyn_castNegVal(RHS))
2670 return BinaryOperator::CreateSub(LHS, V);
2674 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2675 if (X == RHS) // X*C + X --> X * (C+1)
2676 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2678 // X*C1 + X*C2 --> X * (C1+C2)
2680 if (X == dyn_castFoldableMul(RHS, C1))
2681 return BinaryOperator::CreateMul(X, Add(C1, C2));
2684 // X + X*C --> X * (C+1)
2685 if (dyn_castFoldableMul(RHS, C2) == LHS)
2686 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2688 // X + ~X --> -1 since ~X = -X-1
2689 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2690 return ReplaceInstUsesWith(I, Constant::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 // A+B --> A|B iff A and B have no bits set in common.
2699 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2700 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2701 APInt LHSKnownOne(IT->getBitWidth(), 0);
2702 APInt LHSKnownZero(IT->getBitWidth(), 0);
2703 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2704 if (LHSKnownZero != 0) {
2705 APInt RHSKnownOne(IT->getBitWidth(), 0);
2706 APInt RHSKnownZero(IT->getBitWidth(), 0);
2707 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2709 // No bits in common -> bitwise or.
2710 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2711 return BinaryOperator::CreateOr(LHS, RHS);
2715 // W*X + Y*Z --> W * (X+Z) iff W == Y
2716 if (I.getType()->isIntOrIntVector()) {
2717 Value *W, *X, *Y, *Z;
2718 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2719 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2723 } else if (Y == X) {
2725 } else if (X == Z) {
2732 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2733 LHS->getName()), I);
2734 return BinaryOperator::CreateMul(W, NewAdd);
2739 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2741 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2742 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2744 // (X & FF00) + xx00 -> (X+xx00) & FF00
2745 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2746 Constant *Anded = And(CRHS, C2);
2747 if (Anded == CRHS) {
2748 // See if all bits from the first bit set in the Add RHS up are included
2749 // in the mask. First, get the rightmost bit.
2750 const APInt& AddRHSV = CRHS->getValue();
2752 // Form a mask of all bits from the lowest bit added through the top.
2753 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2755 // See if the and mask includes all of these bits.
2756 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2758 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2759 // Okay, the xform is safe. Insert the new add pronto.
2760 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2761 LHS->getName()), I);
2762 return BinaryOperator::CreateAnd(NewAdd, C2);
2767 // Try to fold constant add into select arguments.
2768 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2769 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2773 // add (cast *A to intptrtype) B ->
2774 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
2776 CastInst *CI = dyn_cast<CastInst>(LHS);
2779 CI = dyn_cast<CastInst>(RHS);
2782 if (CI && CI->getType()->isSized() &&
2783 (CI->getType()->getPrimitiveSizeInBits() ==
2784 TD->getIntPtrType()->getPrimitiveSizeInBits())
2785 && isa<PointerType>(CI->getOperand(0)->getType())) {
2787 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2788 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2789 PointerType::get(Type::Int8Ty, AS), I);
2790 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2791 return new PtrToIntInst(I2, CI->getType());
2795 // add (select X 0 (sub n A)) A --> select X A n
2797 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2800 SI = dyn_cast<SelectInst>(RHS);
2803 if (SI && SI->hasOneUse()) {
2804 Value *TV = SI->getTrueValue();
2805 Value *FV = SI->getFalseValue();
2808 // Can we fold the add into the argument of the select?
2809 // We check both true and false select arguments for a matching subtract.
2810 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2811 A == Other) // Fold the add into the true select value.
2812 return SelectInst::Create(SI->getCondition(), N, A);
2813 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2814 A == Other) // Fold the add into the false select value.
2815 return SelectInst::Create(SI->getCondition(), A, N);
2819 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2820 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2821 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2822 return ReplaceInstUsesWith(I, LHS);
2824 // Check for (add (sext x), y), see if we can merge this into an
2825 // integer add followed by a sext.
2826 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2827 // (add (sext x), cst) --> (sext (add x, cst'))
2828 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2830 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2831 if (LHSConv->hasOneUse() &&
2832 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2833 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2834 // Insert the new, smaller add.
2835 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2837 InsertNewInstBefore(NewAdd, I);
2838 return new SExtInst(NewAdd, I.getType());
2842 // (add (sext x), (sext y)) --> (sext (add int x, y))
2843 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2844 // Only do this if x/y have the same type, if at last one of them has a
2845 // single use (so we don't increase the number of sexts), and if the
2846 // integer add will not overflow.
2847 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2848 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2849 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2850 RHSConv->getOperand(0))) {
2851 // Insert the new integer add.
2852 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2853 RHSConv->getOperand(0),
2855 InsertNewInstBefore(NewAdd, I);
2856 return new SExtInst(NewAdd, I.getType());
2861 // Check for (add double (sitofp x), y), see if we can merge this into an
2862 // integer add followed by a promotion.
2863 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2864 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2865 // ... if the constant fits in the integer value. This is useful for things
2866 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2867 // requires a constant pool load, and generally allows the add to be better
2869 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2871 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2872 if (LHSConv->hasOneUse() &&
2873 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2874 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2875 // Insert the new integer add.
2876 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2878 InsertNewInstBefore(NewAdd, I);
2879 return new SIToFPInst(NewAdd, I.getType());
2883 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2884 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2885 // Only do this if x/y have the same type, if at last one of them has a
2886 // single use (so we don't increase the number of int->fp conversions),
2887 // and if the integer add will not overflow.
2888 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2889 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2890 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2891 RHSConv->getOperand(0))) {
2892 // Insert the new integer add.
2893 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2894 RHSConv->getOperand(0),
2896 InsertNewInstBefore(NewAdd, I);
2897 return new SIToFPInst(NewAdd, I.getType());
2902 return Changed ? &I : 0;
2905 // isSignBit - Return true if the value represented by the constant only has the
2906 // highest order bit set.
2907 static bool isSignBit(ConstantInt *CI) {
2908 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2909 return CI->getValue() == APInt::getSignBit(NumBits);
2912 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2913 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2915 if (Op0 == Op1) // sub X, X -> 0
2916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2918 // If this is a 'B = x-(-A)', change to B = x+A...
2919 if (Value *V = dyn_castNegVal(Op1))
2920 return BinaryOperator::CreateAdd(Op0, V);
2922 if (isa<UndefValue>(Op0))
2923 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2924 if (isa<UndefValue>(Op1))
2925 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2927 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2928 // Replace (-1 - A) with (~A)...
2929 if (C->isAllOnesValue())
2930 return BinaryOperator::CreateNot(Op1);
2932 // C - ~X == X + (1+C)
2934 if (match(Op1, m_Not(m_Value(X))))
2935 return BinaryOperator::CreateAdd(X, AddOne(C));
2937 // -(X >>u 31) -> (X >>s 31)
2938 // -(X >>s 31) -> (X >>u 31)
2940 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2941 if (SI->getOpcode() == Instruction::LShr) {
2942 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2943 // Check to see if we are shifting out everything but the sign bit.
2944 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2945 SI->getType()->getPrimitiveSizeInBits()-1) {
2946 // Ok, the transformation is safe. Insert AShr.
2947 return BinaryOperator::Create(Instruction::AShr,
2948 SI->getOperand(0), CU, SI->getName());
2952 else if (SI->getOpcode() == Instruction::AShr) {
2953 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2954 // Check to see if we are shifting out everything but the sign bit.
2955 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2956 SI->getType()->getPrimitiveSizeInBits()-1) {
2957 // Ok, the transformation is safe. Insert LShr.
2958 return BinaryOperator::CreateLShr(
2959 SI->getOperand(0), CU, SI->getName());
2966 // Try to fold constant sub into select arguments.
2967 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2968 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2971 if (isa<PHINode>(Op0))
2972 if (Instruction *NV = FoldOpIntoPhi(I))
2976 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2977 if (Op1I->getOpcode() == Instruction::Add &&
2978 !Op0->getType()->isFPOrFPVector()) {
2979 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2980 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2981 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2982 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2983 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2984 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2985 // C1-(X+C2) --> (C1-C2)-X
2986 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
2987 Op1I->getOperand(0));
2991 if (Op1I->hasOneUse()) {
2992 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2993 // is not used by anyone else...
2995 if (Op1I->getOpcode() == Instruction::Sub &&
2996 !Op1I->getType()->isFPOrFPVector()) {
2997 // Swap the two operands of the subexpr...
2998 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2999 Op1I->setOperand(0, IIOp1);
3000 Op1I->setOperand(1, IIOp0);
3002 // Create the new top level add instruction...
3003 return BinaryOperator::CreateAdd(Op0, Op1);
3006 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3008 if (Op1I->getOpcode() == Instruction::And &&
3009 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3010 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3013 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3014 return BinaryOperator::CreateAnd(Op0, NewNot);
3017 // 0 - (X sdiv C) -> (X sdiv -C)
3018 if (Op1I->getOpcode() == Instruction::SDiv)
3019 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3021 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
3022 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
3023 ConstantExpr::getNeg(DivRHS));
3025 // X - X*C --> X * (1-C)
3026 ConstantInt *C2 = 0;
3027 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
3028 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
3029 return BinaryOperator::CreateMul(Op0, CP1);
3032 // X - ((X / Y) * Y) --> X % Y
3033 if (Op1I->getOpcode() == Instruction::Mul)
3034 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3035 if (Op0 == I->getOperand(0) &&
3036 Op1I->getOperand(1) == I->getOperand(1)) {
3037 if (I->getOpcode() == Instruction::SDiv)
3038 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
3039 if (I->getOpcode() == Instruction::UDiv)
3040 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
3045 if (!Op0->getType()->isFPOrFPVector())
3046 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3047 if (Op0I->getOpcode() == Instruction::Add) {
3048 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3049 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3050 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3051 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3052 } else if (Op0I->getOpcode() == Instruction::Sub) {
3053 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
3054 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
3059 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
3060 if (X == Op1) // X*C - X --> X * (C-1)
3061 return BinaryOperator::CreateMul(Op1, SubOne(C1));
3063 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3064 if (X == dyn_castFoldableMul(Op1, C2))
3065 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
3070 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
3071 /// comparison only checks the sign bit. If it only checks the sign bit, set
3072 /// TrueIfSigned if the result of the comparison is true when the input value is
3074 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3075 bool &TrueIfSigned) {
3077 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3078 TrueIfSigned = true;
3079 return RHS->isZero();
3080 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3081 TrueIfSigned = true;
3082 return RHS->isAllOnesValue();
3083 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3084 TrueIfSigned = false;
3085 return RHS->isAllOnesValue();
3086 case ICmpInst::ICMP_UGT:
3087 // True if LHS u> RHS and RHS == high-bit-mask - 1
3088 TrueIfSigned = true;
3089 return RHS->getValue() ==
3090 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3091 case ICmpInst::ICMP_UGE:
3092 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3093 TrueIfSigned = true;
3094 return RHS->getValue() ==
3095 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
3101 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3102 bool Changed = SimplifyCommutative(I);
3103 Value *Op0 = I.getOperand(0);
3105 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3106 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3108 // Simplify mul instructions with a constant RHS...
3109 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3112 // ((X << C1)*C2) == (X * (C2 << C1))
3113 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3114 if (SI->getOpcode() == Instruction::Shl)
3115 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
3116 return BinaryOperator::CreateMul(SI->getOperand(0),
3117 ConstantExpr::getShl(CI, ShOp));
3120 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3121 if (CI->equalsInt(1)) // X * 1 == X
3122 return ReplaceInstUsesWith(I, Op0);
3123 if (CI->isAllOnesValue()) // X * -1 == 0 - X
3124 return BinaryOperator::CreateNeg(Op0, I.getName());
3126 const APInt& Val = cast<ConstantInt>(CI)->getValue();
3127 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
3128 return BinaryOperator::CreateShl(Op0,
3129 ConstantInt::get(Op0->getType(), Val.logBase2()));
3131 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
3132 if (Op1F->isNullValue())
3133 return ReplaceInstUsesWith(I, Op1);
3135 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3136 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3137 // We need a better interface for long double here.
3138 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3139 if (Op1F->isExactlyValue(1.0))
3140 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
3143 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3144 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3145 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
3146 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3147 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
3149 InsertNewInstBefore(Add, I);
3150 Value *C1C2 = ConstantExpr::getMul(Op1,
3151 cast<Constant>(Op0I->getOperand(1)));
3152 return BinaryOperator::CreateAdd(Add, C1C2);
3156 // Try to fold constant mul into select arguments.
3157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3161 if (isa<PHINode>(Op0))
3162 if (Instruction *NV = FoldOpIntoPhi(I))
3166 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3167 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
3168 return BinaryOperator::CreateMul(Op0v, Op1v);
3170 // If one of the operands of the multiply is a cast from a boolean value, then
3171 // we know the bool is either zero or one, so this is a 'masking' multiply.
3172 // See if we can simplify things based on how the boolean was originally
3174 CastInst *BoolCast = 0;
3175 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
3176 if (CI->getOperand(0)->getType() == Type::Int1Ty)
3179 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
3180 if (CI->getOperand(0)->getType() == Type::Int1Ty)
3183 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
3184 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3185 const Type *SCOpTy = SCIOp0->getType();
3188 // If the icmp is true iff the sign bit of X is set, then convert this
3189 // multiply into a shift/and combination.
3190 if (isa<ConstantInt>(SCIOp1) &&
3191 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3193 // Shift the X value right to turn it into "all signbits".
3194 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
3195 SCOpTy->getPrimitiveSizeInBits()-1);
3197 InsertNewInstBefore(
3198 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
3199 BoolCast->getOperand(0)->getName()+
3202 // If the multiply type is not the same as the source type, sign extend
3203 // or truncate to the multiply type.
3204 if (I.getType() != V->getType()) {
3205 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3206 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
3207 Instruction::CastOps opcode =
3208 (SrcBits == DstBits ? Instruction::BitCast :
3209 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3210 V = InsertCastBefore(opcode, V, I.getType(), I);
3213 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
3214 return BinaryOperator::CreateAnd(V, OtherOp);
3219 return Changed ? &I : 0;
3222 /// This function implements the transforms on div instructions that work
3223 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3224 /// used by the visitors to those instructions.
3225 /// @brief Transforms common to all three div instructions
3226 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3229 // undef / X -> 0 for integer.
3230 // undef / X -> undef for FP (the undef could be a snan).
3231 if (isa<UndefValue>(Op0)) {
3232 if (Op0->getType()->isFPOrFPVector())
3233 return ReplaceInstUsesWith(I, Op0);
3234 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3237 // X / undef -> undef
3238 if (isa<UndefValue>(Op1))
3239 return ReplaceInstUsesWith(I, Op1);
3241 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3242 // This does not apply for fdiv.
3243 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3244 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3245 // the same basic block, then we replace the select with Y, and the
3246 // condition of the select with false (if the cond value is in the same BB).
3247 // If the select has uses other than the div, this allows them to be
3248 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3249 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
3250 if (ST->isNullValue()) {
3251 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3252 if (CondI && CondI->getParent() == I.getParent())
3253 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3254 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3255 I.setOperand(1, SI->getOperand(2));
3257 UpdateValueUsesWith(SI, SI->getOperand(2));
3261 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3262 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
3263 if (ST->isNullValue()) {
3264 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3265 if (CondI && CondI->getParent() == I.getParent())
3266 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3267 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3268 I.setOperand(1, SI->getOperand(1));
3270 UpdateValueUsesWith(SI, SI->getOperand(1));
3278 /// This function implements the transforms common to both integer division
3279 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3280 /// division instructions.
3281 /// @brief Common integer divide transforms
3282 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3285 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3287 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3288 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3289 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3290 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3293 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3294 return ReplaceInstUsesWith(I, CI);
3297 if (Instruction *Common = commonDivTransforms(I))
3300 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3302 if (RHS->equalsInt(1))
3303 return ReplaceInstUsesWith(I, Op0);
3305 // (X / C1) / C2 -> X / (C1*C2)
3306 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3307 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3308 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3309 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3310 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3312 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3313 Multiply(RHS, LHSRHS));
3316 if (!RHS->isZero()) { // avoid X udiv 0
3317 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3318 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3320 if (isa<PHINode>(Op0))
3321 if (Instruction *NV = FoldOpIntoPhi(I))
3326 // 0 / X == 0, we don't need to preserve faults!
3327 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3328 if (LHS->equalsInt(0))
3329 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3334 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3337 // Handle the integer div common cases
3338 if (Instruction *Common = commonIDivTransforms(I))
3341 // X udiv C^2 -> X >> C
3342 // Check to see if this is an unsigned division with an exact power of 2,
3343 // if so, convert to a right shift.
3344 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3345 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3346 return BinaryOperator::CreateLShr(Op0,
3347 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3350 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3351 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3352 if (RHSI->getOpcode() == Instruction::Shl &&
3353 isa<ConstantInt>(RHSI->getOperand(0))) {
3354 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3355 if (C1.isPowerOf2()) {
3356 Value *N = RHSI->getOperand(1);
3357 const Type *NTy = N->getType();
3358 if (uint32_t C2 = C1.logBase2()) {
3359 Constant *C2V = ConstantInt::get(NTy, C2);
3360 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3362 return BinaryOperator::CreateLShr(Op0, N);
3367 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3368 // where C1&C2 are powers of two.
3369 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3370 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3371 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3372 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3373 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3374 // Compute the shift amounts
3375 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3376 // Construct the "on true" case of the select
3377 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3378 Instruction *TSI = BinaryOperator::CreateLShr(
3379 Op0, TC, SI->getName()+".t");
3380 TSI = InsertNewInstBefore(TSI, I);
3382 // Construct the "on false" case of the select
3383 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3384 Instruction *FSI = BinaryOperator::CreateLShr(
3385 Op0, FC, SI->getName()+".f");
3386 FSI = InsertNewInstBefore(FSI, I);
3388 // construct the select instruction and return it.
3389 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3395 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3396 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3398 // Handle the integer div common cases
3399 if (Instruction *Common = commonIDivTransforms(I))
3402 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3404 if (RHS->isAllOnesValue())
3405 return BinaryOperator::CreateNeg(Op0);
3408 if (Value *LHSNeg = dyn_castNegVal(Op0))
3409 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3412 // If the sign bits of both operands are zero (i.e. we can prove they are
3413 // unsigned inputs), turn this into a udiv.
3414 if (I.getType()->isInteger()) {
3415 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3416 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3417 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3418 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3425 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3426 return commonDivTransforms(I);
3429 /// This function implements the transforms on rem instructions that work
3430 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3431 /// is used by the visitors to those instructions.
3432 /// @brief Transforms common to all three rem instructions
3433 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3434 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3436 // 0 % X == 0 for integer, we don't need to preserve faults!
3437 if (Constant *LHS = dyn_cast<Constant>(Op0))
3438 if (LHS->isNullValue())
3439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3441 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3442 if (I.getType()->isFPOrFPVector())
3443 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3444 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3446 if (isa<UndefValue>(Op1))
3447 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3449 // Handle cases involving: rem X, (select Cond, Y, Z)
3450 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3451 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3452 // the same basic block, then we replace the select with Y, and the
3453 // condition of the select with false (if the cond value is in the same
3454 // BB). If the select has uses other than the div, this allows them to be
3456 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3457 if (ST->isNullValue()) {
3458 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3459 if (CondI && CondI->getParent() == I.getParent())
3460 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3461 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3462 I.setOperand(1, SI->getOperand(2));
3464 UpdateValueUsesWith(SI, SI->getOperand(2));
3467 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3468 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3469 if (ST->isNullValue()) {
3470 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3471 if (CondI && CondI->getParent() == I.getParent())
3472 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3473 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3474 I.setOperand(1, SI->getOperand(1));
3476 UpdateValueUsesWith(SI, SI->getOperand(1));
3484 /// This function implements the transforms common to both integer remainder
3485 /// instructions (urem and srem). It is called by the visitors to those integer
3486 /// remainder instructions.
3487 /// @brief Common integer remainder transforms
3488 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3489 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3491 if (Instruction *common = commonRemTransforms(I))
3494 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3495 // X % 0 == undef, we don't need to preserve faults!
3496 if (RHS->equalsInt(0))
3497 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3499 if (RHS->equalsInt(1)) // X % 1 == 0
3500 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3502 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3503 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3504 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3506 } else if (isa<PHINode>(Op0I)) {
3507 if (Instruction *NV = FoldOpIntoPhi(I))
3511 // See if we can fold away this rem instruction.
3512 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3513 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3514 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3515 KnownZero, KnownOne))
3523 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3524 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3526 if (Instruction *common = commonIRemTransforms(I))
3529 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3530 // X urem C^2 -> X and C
3531 // Check to see if this is an unsigned remainder with an exact power of 2,
3532 // if so, convert to a bitwise and.
3533 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3534 if (C->getValue().isPowerOf2())
3535 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3538 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3539 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3540 if (RHSI->getOpcode() == Instruction::Shl &&
3541 isa<ConstantInt>(RHSI->getOperand(0))) {
3542 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3543 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3544 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3546 return BinaryOperator::CreateAnd(Op0, Add);
3551 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3552 // where C1&C2 are powers of two.
3553 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3554 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3555 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3556 // STO == 0 and SFO == 0 handled above.
3557 if ((STO->getValue().isPowerOf2()) &&
3558 (SFO->getValue().isPowerOf2())) {
3559 Value *TrueAnd = InsertNewInstBefore(
3560 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3561 Value *FalseAnd = InsertNewInstBefore(
3562 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3563 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3571 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3572 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3574 // Handle the integer rem common cases
3575 if (Instruction *common = commonIRemTransforms(I))
3578 if (Value *RHSNeg = dyn_castNegVal(Op1))
3579 if (!isa<ConstantInt>(RHSNeg) ||
3580 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3582 AddUsesToWorkList(I);
3583 I.setOperand(1, RHSNeg);
3587 // If the sign bits of both operands are zero (i.e. we can prove they are
3588 // unsigned inputs), turn this into a urem.
3589 if (I.getType()->isInteger()) {
3590 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3591 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3592 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3593 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3600 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3601 return commonRemTransforms(I);
3604 // isMaxValueMinusOne - return true if this is Max-1
3605 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3606 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3608 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3609 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3612 // isMinValuePlusOne - return true if this is Min+1
3613 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3615 return C->getValue() == 1; // unsigned
3617 // Calculate 1111111111000000000000
3618 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3619 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3622 // isOneBitSet - Return true if there is exactly one bit set in the specified
3624 static bool isOneBitSet(const ConstantInt *CI) {
3625 return CI->getValue().isPowerOf2();
3628 // isHighOnes - Return true if the constant is of the form 1+0+.
3629 // This is the same as lowones(~X).
3630 static bool isHighOnes(const ConstantInt *CI) {
3631 return (~CI->getValue() + 1).isPowerOf2();
3634 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3635 /// are carefully arranged to allow folding of expressions such as:
3637 /// (A < B) | (A > B) --> (A != B)
3639 /// Note that this is only valid if the first and second predicates have the
3640 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3642 /// Three bits are used to represent the condition, as follows:
3647 /// <=> Value Definition
3648 /// 000 0 Always false
3655 /// 111 7 Always true
3657 static unsigned getICmpCode(const ICmpInst *ICI) {
3658 switch (ICI->getPredicate()) {
3660 case ICmpInst::ICMP_UGT: return 1; // 001
3661 case ICmpInst::ICMP_SGT: return 1; // 001
3662 case ICmpInst::ICMP_EQ: return 2; // 010
3663 case ICmpInst::ICMP_UGE: return 3; // 011
3664 case ICmpInst::ICMP_SGE: return 3; // 011
3665 case ICmpInst::ICMP_ULT: return 4; // 100
3666 case ICmpInst::ICMP_SLT: return 4; // 100
3667 case ICmpInst::ICMP_NE: return 5; // 101
3668 case ICmpInst::ICMP_ULE: return 6; // 110
3669 case ICmpInst::ICMP_SLE: return 6; // 110
3672 assert(0 && "Invalid ICmp predicate!");
3677 /// getICmpValue - This is the complement of getICmpCode, which turns an
3678 /// opcode and two operands into either a constant true or false, or a brand
3679 /// new ICmp instruction. The sign is passed in to determine which kind
3680 /// of predicate to use in new icmp instructions.
3681 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3683 default: assert(0 && "Illegal ICmp code!");
3684 case 0: return ConstantInt::getFalse();
3687 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3689 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3690 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3693 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3695 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3698 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3700 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3701 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3704 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3706 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3707 case 7: return ConstantInt::getTrue();
3711 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3712 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3713 (ICmpInst::isSignedPredicate(p1) &&
3714 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3715 (ICmpInst::isSignedPredicate(p2) &&
3716 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3720 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3721 struct FoldICmpLogical {
3724 ICmpInst::Predicate pred;
3725 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3726 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3727 pred(ICI->getPredicate()) {}
3728 bool shouldApply(Value *V) const {
3729 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3730 if (PredicatesFoldable(pred, ICI->getPredicate()))
3731 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3732 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3735 Instruction *apply(Instruction &Log) const {
3736 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3737 if (ICI->getOperand(0) != LHS) {
3738 assert(ICI->getOperand(1) == LHS);
3739 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3742 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3743 unsigned LHSCode = getICmpCode(ICI);
3744 unsigned RHSCode = getICmpCode(RHSICI);
3746 switch (Log.getOpcode()) {
3747 case Instruction::And: Code = LHSCode & RHSCode; break;
3748 case Instruction::Or: Code = LHSCode | RHSCode; break;
3749 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3750 default: assert(0 && "Illegal logical opcode!"); return 0;
3753 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3754 ICmpInst::isSignedPredicate(ICI->getPredicate());
3756 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3757 if (Instruction *I = dyn_cast<Instruction>(RV))
3759 // Otherwise, it's a constant boolean value...
3760 return IC.ReplaceInstUsesWith(Log, RV);
3763 } // end anonymous namespace
3765 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3766 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3767 // guaranteed to be a binary operator.
3768 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3770 ConstantInt *AndRHS,
3771 BinaryOperator &TheAnd) {
3772 Value *X = Op->getOperand(0);
3773 Constant *Together = 0;
3775 Together = And(AndRHS, OpRHS);
3777 switch (Op->getOpcode()) {
3778 case Instruction::Xor:
3779 if (Op->hasOneUse()) {
3780 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3781 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3782 InsertNewInstBefore(And, TheAnd);
3784 return BinaryOperator::CreateXor(And, Together);
3787 case Instruction::Or:
3788 if (Together == AndRHS) // (X | C) & C --> C
3789 return ReplaceInstUsesWith(TheAnd, AndRHS);
3791 if (Op->hasOneUse() && Together != OpRHS) {
3792 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3793 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3794 InsertNewInstBefore(Or, TheAnd);
3796 return BinaryOperator::CreateAnd(Or, AndRHS);
3799 case Instruction::Add:
3800 if (Op->hasOneUse()) {
3801 // Adding a one to a single bit bit-field should be turned into an XOR
3802 // of the bit. First thing to check is to see if this AND is with a
3803 // single bit constant.
3804 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3806 // If there is only one bit set...
3807 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3808 // Ok, at this point, we know that we are masking the result of the
3809 // ADD down to exactly one bit. If the constant we are adding has
3810 // no bits set below this bit, then we can eliminate the ADD.
3811 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3813 // Check to see if any bits below the one bit set in AndRHSV are set.
3814 if ((AddRHS & (AndRHSV-1)) == 0) {
3815 // If not, the only thing that can effect the output of the AND is
3816 // the bit specified by AndRHSV. If that bit is set, the effect of
3817 // the XOR is to toggle the bit. If it is clear, then the ADD has
3819 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3820 TheAnd.setOperand(0, X);
3823 // Pull the XOR out of the AND.
3824 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3825 InsertNewInstBefore(NewAnd, TheAnd);
3826 NewAnd->takeName(Op);
3827 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3834 case Instruction::Shl: {
3835 // We know that the AND will not produce any of the bits shifted in, so if
3836 // the anded constant includes them, clear them now!
3838 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3839 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3840 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3841 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3843 if (CI->getValue() == ShlMask) {
3844 // Masking out bits that the shift already masks
3845 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3846 } else if (CI != AndRHS) { // Reducing bits set in and.
3847 TheAnd.setOperand(1, CI);
3852 case Instruction::LShr:
3854 // We know that the AND will not produce any of the bits shifted in, so if
3855 // the anded constant includes them, clear them now! This only applies to
3856 // unsigned shifts, because a signed shr may bring in set bits!
3858 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3859 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3860 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3861 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3863 if (CI->getValue() == ShrMask) {
3864 // Masking out bits that the shift already masks.
3865 return ReplaceInstUsesWith(TheAnd, Op);
3866 } else if (CI != AndRHS) {
3867 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3872 case Instruction::AShr:
3874 // See if this is shifting in some sign extension, then masking it out
3876 if (Op->hasOneUse()) {
3877 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3878 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3879 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3880 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3881 if (C == AndRHS) { // Masking out bits shifted in.
3882 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3883 // Make the argument unsigned.
3884 Value *ShVal = Op->getOperand(0);
3885 ShVal = InsertNewInstBefore(
3886 BinaryOperator::CreateLShr(ShVal, OpRHS,
3887 Op->getName()), TheAnd);
3888 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3897 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3898 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3899 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3900 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3901 /// insert new instructions.
3902 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3903 bool isSigned, bool Inside,
3905 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3906 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3907 "Lo is not <= Hi in range emission code!");
3910 if (Lo == Hi) // Trivially false.
3911 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3913 // V >= Min && V < Hi --> V < Hi
3914 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3915 ICmpInst::Predicate pred = (isSigned ?
3916 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3917 return new ICmpInst(pred, V, Hi);
3920 // Emit V-Lo <u Hi-Lo
3921 Constant *NegLo = ConstantExpr::getNeg(Lo);
3922 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3923 InsertNewInstBefore(Add, IB);
3924 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3925 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3928 if (Lo == Hi) // Trivially true.
3929 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3931 // V < Min || V >= Hi -> V > Hi-1
3932 Hi = SubOne(cast<ConstantInt>(Hi));
3933 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3934 ICmpInst::Predicate pred = (isSigned ?
3935 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3936 return new ICmpInst(pred, V, Hi);
3939 // Emit V-Lo >u Hi-1-Lo
3940 // Note that Hi has already had one subtracted from it, above.
3941 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3942 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3943 InsertNewInstBefore(Add, IB);
3944 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3945 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3948 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3949 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3950 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3951 // not, since all 1s are not contiguous.
3952 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3953 const APInt& V = Val->getValue();
3954 uint32_t BitWidth = Val->getType()->getBitWidth();
3955 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3957 // look for the first zero bit after the run of ones
3958 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3959 // look for the first non-zero bit
3960 ME = V.getActiveBits();
3964 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3965 /// where isSub determines whether the operator is a sub. If we can fold one of
3966 /// the following xforms:
3968 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3969 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3970 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3972 /// return (A +/- B).
3974 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3975 ConstantInt *Mask, bool isSub,
3977 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3978 if (!LHSI || LHSI->getNumOperands() != 2 ||
3979 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3981 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3983 switch (LHSI->getOpcode()) {
3985 case Instruction::And:
3986 if (And(N, Mask) == Mask) {
3987 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3988 if ((Mask->getValue().countLeadingZeros() +
3989 Mask->getValue().countPopulation()) ==
3990 Mask->getValue().getBitWidth())
3993 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3994 // part, we don't need any explicit masks to take them out of A. If that
3995 // is all N is, ignore it.
3996 uint32_t MB = 0, ME = 0;
3997 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3998 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3999 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4000 if (MaskedValueIsZero(RHS, Mask))
4005 case Instruction::Or:
4006 case Instruction::Xor:
4007 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4008 if ((Mask->getValue().countLeadingZeros() +
4009 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4010 && And(N, Mask)->isZero())
4017 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
4019 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
4020 return InsertNewInstBefore(New, I);
4023 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4024 bool Changed = SimplifyCommutative(I);
4025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4027 if (isa<UndefValue>(Op1)) // X & undef -> 0
4028 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4032 return ReplaceInstUsesWith(I, Op1);
4034 // See if we can simplify any instructions used by the instruction whose sole
4035 // purpose is to compute bits we don't care about.
4036 if (!isa<VectorType>(I.getType())) {
4037 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4038 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4039 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4040 KnownZero, KnownOne))
4043 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4044 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4045 return ReplaceInstUsesWith(I, I.getOperand(0));
4046 } else if (isa<ConstantAggregateZero>(Op1)) {
4047 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4051 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4052 const APInt& AndRHSMask = AndRHS->getValue();
4053 APInt NotAndRHS(~AndRHSMask);
4055 // Optimize a variety of ((val OP C1) & C2) combinations...
4056 if (isa<BinaryOperator>(Op0)) {
4057 Instruction *Op0I = cast<Instruction>(Op0);
4058 Value *Op0LHS = Op0I->getOperand(0);
4059 Value *Op0RHS = Op0I->getOperand(1);
4060 switch (Op0I->getOpcode()) {
4061 case Instruction::Xor:
4062 case Instruction::Or:
4063 // If the mask is only needed on one incoming arm, push it up.
4064 if (Op0I->hasOneUse()) {
4065 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4066 // Not masking anything out for the LHS, move to RHS.
4067 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4068 Op0RHS->getName()+".masked");
4069 InsertNewInstBefore(NewRHS, I);
4070 return BinaryOperator::Create(
4071 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4073 if (!isa<Constant>(Op0RHS) &&
4074 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4075 // Not masking anything out for the RHS, move to LHS.
4076 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4077 Op0LHS->getName()+".masked");
4078 InsertNewInstBefore(NewLHS, I);
4079 return BinaryOperator::Create(
4080 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4085 case Instruction::Add:
4086 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4087 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4088 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4089 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4090 return BinaryOperator::CreateAnd(V, AndRHS);
4091 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4092 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4095 case Instruction::Sub:
4096 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4097 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4098 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4099 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4100 return BinaryOperator::CreateAnd(V, AndRHS);
4104 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4105 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4107 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4108 // If this is an integer truncation or change from signed-to-unsigned, and
4109 // if the source is an and/or with immediate, transform it. This
4110 // frequently occurs for bitfield accesses.
4111 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4112 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4113 CastOp->getNumOperands() == 2)
4114 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4115 if (CastOp->getOpcode() == Instruction::And) {
4116 // Change: and (cast (and X, C1) to T), C2
4117 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4118 // This will fold the two constants together, which may allow
4119 // other simplifications.
4120 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4121 CastOp->getOperand(0), I.getType(),
4122 CastOp->getName()+".shrunk");
4123 NewCast = InsertNewInstBefore(NewCast, I);
4124 // trunc_or_bitcast(C1)&C2
4125 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4126 C3 = ConstantExpr::getAnd(C3, AndRHS);
4127 return BinaryOperator::CreateAnd(NewCast, C3);
4128 } else if (CastOp->getOpcode() == Instruction::Or) {
4129 // Change: and (cast (or X, C1) to T), C2
4130 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4131 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4132 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4133 return ReplaceInstUsesWith(I, AndRHS);
4139 // Try to fold constant and into select arguments.
4140 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4141 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4143 if (isa<PHINode>(Op0))
4144 if (Instruction *NV = FoldOpIntoPhi(I))
4148 Value *Op0NotVal = dyn_castNotVal(Op0);
4149 Value *Op1NotVal = dyn_castNotVal(Op1);
4151 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4152 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4154 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4155 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4156 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4157 I.getName()+".demorgan");
4158 InsertNewInstBefore(Or, I);
4159 return BinaryOperator::CreateNot(Or);
4163 Value *A = 0, *B = 0, *C = 0, *D = 0;
4164 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4165 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4166 return ReplaceInstUsesWith(I, Op1);
4168 // (A|B) & ~(A&B) -> A^B
4169 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4170 if ((A == C && B == D) || (A == D && B == C))
4171 return BinaryOperator::CreateXor(A, B);
4175 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4176 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4177 return ReplaceInstUsesWith(I, Op0);
4179 // ~(A&B) & (A|B) -> A^B
4180 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4181 if ((A == C && B == D) || (A == D && B == C))
4182 return BinaryOperator::CreateXor(A, B);
4186 if (Op0->hasOneUse() &&
4187 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4188 if (A == Op1) { // (A^B)&A -> A&(A^B)
4189 I.swapOperands(); // Simplify below
4190 std::swap(Op0, Op1);
4191 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4192 cast<BinaryOperator>(Op0)->swapOperands();
4193 I.swapOperands(); // Simplify below
4194 std::swap(Op0, Op1);
4197 if (Op1->hasOneUse() &&
4198 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4199 if (B == Op0) { // B&(A^B) -> B&(B^A)
4200 cast<BinaryOperator>(Op1)->swapOperands();
4203 if (A == Op0) { // A&(A^B) -> A & ~B
4204 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4205 InsertNewInstBefore(NotB, I);
4206 return BinaryOperator::CreateAnd(A, NotB);
4211 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4212 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4213 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4216 Value *LHSVal, *RHSVal;
4217 ConstantInt *LHSCst, *RHSCst;
4218 ICmpInst::Predicate LHSCC, RHSCC;
4219 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4220 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4221 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4222 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4223 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4224 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4225 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4226 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4228 // Don't try to fold ICMP_SLT + ICMP_ULT.
4229 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4230 ICmpInst::isSignedPredicate(LHSCC) ==
4231 ICmpInst::isSignedPredicate(RHSCC))) {
4232 // Ensure that the larger constant is on the RHS.
4233 ICmpInst::Predicate GT;
4234 if (ICmpInst::isSignedPredicate(LHSCC) ||
4235 (ICmpInst::isEquality(LHSCC) &&
4236 ICmpInst::isSignedPredicate(RHSCC)))
4237 GT = ICmpInst::ICMP_SGT;
4239 GT = ICmpInst::ICMP_UGT;
4241 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4242 ICmpInst *LHS = cast<ICmpInst>(Op0);
4243 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4244 std::swap(LHS, RHS);
4245 std::swap(LHSCst, RHSCst);
4246 std::swap(LHSCC, RHSCC);
4249 // At this point, we know we have have two icmp instructions
4250 // comparing a value against two constants and and'ing the result
4251 // together. Because of the above check, we know that we only have
4252 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4253 // (from the FoldICmpLogical check above), that the two constants
4254 // are not equal and that the larger constant is on the RHS
4255 assert(LHSCst != RHSCst && "Compares not folded above?");
4258 default: assert(0 && "Unknown integer condition code!");
4259 case ICmpInst::ICMP_EQ:
4261 default: assert(0 && "Unknown integer condition code!");
4262 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4263 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4264 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
4265 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4266 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4267 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4268 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4269 return ReplaceInstUsesWith(I, LHS);
4271 case ICmpInst::ICMP_NE:
4273 default: assert(0 && "Unknown integer condition code!");
4274 case ICmpInst::ICMP_ULT:
4275 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4276 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4277 break; // (X != 13 & X u< 15) -> no change
4278 case ICmpInst::ICMP_SLT:
4279 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4280 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4281 break; // (X != 13 & X s< 15) -> no change
4282 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4283 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4284 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4285 return ReplaceInstUsesWith(I, RHS);
4286 case ICmpInst::ICMP_NE:
4287 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4288 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4289 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4290 LHSVal->getName()+".off");
4291 InsertNewInstBefore(Add, I);
4292 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4293 ConstantInt::get(Add->getType(), 1));
4295 break; // (X != 13 & X != 15) -> no change
4298 case ICmpInst::ICMP_ULT:
4300 default: assert(0 && "Unknown integer condition code!");
4301 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4302 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
4303 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4304 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4306 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4307 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4308 return ReplaceInstUsesWith(I, LHS);
4309 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4313 case ICmpInst::ICMP_SLT:
4315 default: assert(0 && "Unknown integer condition code!");
4316 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4317 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
4318 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4319 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4321 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4322 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4323 return ReplaceInstUsesWith(I, LHS);
4324 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4328 case ICmpInst::ICMP_UGT:
4330 default: assert(0 && "Unknown integer condition code!");
4331 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4332 return ReplaceInstUsesWith(I, LHS);
4333 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4334 return ReplaceInstUsesWith(I, RHS);
4335 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4337 case ICmpInst::ICMP_NE:
4338 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4339 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4340 break; // (X u> 13 & X != 15) -> no change
4341 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4342 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4344 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4348 case ICmpInst::ICMP_SGT:
4350 default: assert(0 && "Unknown integer condition code!");
4351 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4352 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4353 return ReplaceInstUsesWith(I, RHS);
4354 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4356 case ICmpInst::ICMP_NE:
4357 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4358 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4359 break; // (X s> 13 & X != 15) -> no change
4360 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4361 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4363 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4371 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4372 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4373 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4374 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4375 const Type *SrcTy = Op0C->getOperand(0)->getType();
4376 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4377 // Only do this if the casts both really cause code to be generated.
4378 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4380 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4382 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4383 Op1C->getOperand(0),
4385 InsertNewInstBefore(NewOp, I);
4386 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4390 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4391 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4392 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4393 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4394 SI0->getOperand(1) == SI1->getOperand(1) &&
4395 (SI0->hasOneUse() || SI1->hasOneUse())) {
4396 Instruction *NewOp =
4397 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4399 SI0->getName()), I);
4400 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4401 SI1->getOperand(1));
4405 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4406 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4407 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4408 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4409 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4410 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4411 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4412 // If either of the constants are nans, then the whole thing returns
4414 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4415 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4416 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4417 RHS->getOperand(0));
4422 return Changed ? &I : 0;
4425 /// CollectBSwapParts - Look to see if the specified value defines a single byte
4426 /// in the result. If it does, and if the specified byte hasn't been filled in
4427 /// yet, fill it in and return false.
4428 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4429 Instruction *I = dyn_cast<Instruction>(V);
4430 if (I == 0) return true;
4432 // If this is an or instruction, it is an inner node of the bswap.
4433 if (I->getOpcode() == Instruction::Or)
4434 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4435 CollectBSwapParts(I->getOperand(1), ByteValues);
4437 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4438 // If this is a shift by a constant int, and it is "24", then its operand
4439 // defines a byte. We only handle unsigned types here.
4440 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4441 // Not shifting the entire input by N-1 bytes?
4442 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4443 8*(ByteValues.size()-1))
4447 if (I->getOpcode() == Instruction::Shl) {
4448 // X << 24 defines the top byte with the lowest of the input bytes.
4449 DestNo = ByteValues.size()-1;
4451 // X >>u 24 defines the low byte with the highest of the input bytes.
4455 // If the destination byte value is already defined, the values are or'd
4456 // together, which isn't a bswap (unless it's an or of the same bits).
4457 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4459 ByteValues[DestNo] = I->getOperand(0);
4463 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4465 Value *Shift = 0, *ShiftLHS = 0;
4466 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4467 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4468 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4470 Instruction *SI = cast<Instruction>(Shift);
4472 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4473 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4474 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4477 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4479 if (AndAmt->getValue().getActiveBits() > 64)
4481 uint64_t AndAmtVal = AndAmt->getZExtValue();
4482 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4483 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4485 // Unknown mask for bswap.
4486 if (DestByte == ByteValues.size()) return true;
4488 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4490 if (SI->getOpcode() == Instruction::Shl)
4491 SrcByte = DestByte - ShiftBytes;
4493 SrcByte = DestByte + ShiftBytes;
4495 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4496 if (SrcByte != ByteValues.size()-DestByte-1)
4499 // If the destination byte value is already defined, the values are or'd
4500 // together, which isn't a bswap (unless it's an or of the same bits).
4501 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4503 ByteValues[DestByte] = SI->getOperand(0);
4507 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4508 /// If so, insert the new bswap intrinsic and return it.
4509 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4510 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4511 if (!ITy || ITy->getBitWidth() % 16)
4512 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4514 /// ByteValues - For each byte of the result, we keep track of which value
4515 /// defines each byte.
4516 SmallVector<Value*, 8> ByteValues;
4517 ByteValues.resize(ITy->getBitWidth()/8);
4519 // Try to find all the pieces corresponding to the bswap.
4520 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4521 CollectBSwapParts(I.getOperand(1), ByteValues))
4524 // Check to see if all of the bytes come from the same value.
4525 Value *V = ByteValues[0];
4526 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4528 // Check to make sure that all of the bytes come from the same value.
4529 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4530 if (ByteValues[i] != V)
4532 const Type *Tys[] = { ITy };
4533 Module *M = I.getParent()->getParent()->getParent();
4534 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4535 return CallInst::Create(F, V);
4539 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4540 bool Changed = SimplifyCommutative(I);
4541 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4543 if (isa<UndefValue>(Op1)) // X | undef -> -1
4544 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4548 return ReplaceInstUsesWith(I, Op0);
4550 // See if we can simplify any instructions used by the instruction whose sole
4551 // purpose is to compute bits we don't care about.
4552 if (!isa<VectorType>(I.getType())) {
4553 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4554 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4555 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4556 KnownZero, KnownOne))
4558 } else if (isa<ConstantAggregateZero>(Op1)) {
4559 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4560 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4561 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4562 return ReplaceInstUsesWith(I, I.getOperand(1));
4568 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4569 ConstantInt *C1 = 0; Value *X = 0;
4570 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4571 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4572 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4573 InsertNewInstBefore(Or, I);
4575 return BinaryOperator::CreateAnd(Or,
4576 ConstantInt::get(RHS->getValue() | C1->getValue()));
4579 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4580 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4581 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4582 InsertNewInstBefore(Or, I);
4584 return BinaryOperator::CreateXor(Or,
4585 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4588 // Try to fold constant and into select arguments.
4589 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4590 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4592 if (isa<PHINode>(Op0))
4593 if (Instruction *NV = FoldOpIntoPhi(I))
4597 Value *A = 0, *B = 0;
4598 ConstantInt *C1 = 0, *C2 = 0;
4600 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4601 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4602 return ReplaceInstUsesWith(I, Op1);
4603 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4604 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4605 return ReplaceInstUsesWith(I, Op0);
4607 // (A | B) | C and A | (B | C) -> bswap if possible.
4608 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4609 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4610 match(Op1, m_Or(m_Value(), m_Value())) ||
4611 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4612 match(Op1, m_Shift(m_Value(), m_Value())))) {
4613 if (Instruction *BSwap = MatchBSwap(I))
4617 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4618 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4619 MaskedValueIsZero(Op1, C1->getValue())) {
4620 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4621 InsertNewInstBefore(NOr, I);
4623 return BinaryOperator::CreateXor(NOr, C1);
4626 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4627 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4628 MaskedValueIsZero(Op0, C1->getValue())) {
4629 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4630 InsertNewInstBefore(NOr, I);
4632 return BinaryOperator::CreateXor(NOr, C1);
4636 Value *C = 0, *D = 0;
4637 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4638 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4639 Value *V1 = 0, *V2 = 0, *V3 = 0;
4640 C1 = dyn_cast<ConstantInt>(C);
4641 C2 = dyn_cast<ConstantInt>(D);
4642 if (C1 && C2) { // (A & C1)|(B & C2)
4643 // If we have: ((V + N) & C1) | (V & C2)
4644 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4645 // replace with V+N.
4646 if (C1->getValue() == ~C2->getValue()) {
4647 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4648 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4649 // Add commutes, try both ways.
4650 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4651 return ReplaceInstUsesWith(I, A);
4652 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4653 return ReplaceInstUsesWith(I, A);
4655 // Or commutes, try both ways.
4656 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4657 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4658 // Add commutes, try both ways.
4659 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4660 return ReplaceInstUsesWith(I, B);
4661 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4662 return ReplaceInstUsesWith(I, B);
4665 V1 = 0; V2 = 0; V3 = 0;
4668 // Check to see if we have any common things being and'ed. If so, find the
4669 // terms for V1 & (V2|V3).
4670 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4671 if (A == B) // (A & C)|(A & D) == A & (C|D)
4672 V1 = A, V2 = C, V3 = D;
4673 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4674 V1 = A, V2 = B, V3 = C;
4675 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4676 V1 = C, V2 = A, V3 = D;
4677 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4678 V1 = C, V2 = A, V3 = B;
4682 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4683 return BinaryOperator::CreateAnd(V1, Or);
4688 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4689 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4690 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4691 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4692 SI0->getOperand(1) == SI1->getOperand(1) &&
4693 (SI0->hasOneUse() || SI1->hasOneUse())) {
4694 Instruction *NewOp =
4695 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4697 SI0->getName()), I);
4698 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4699 SI1->getOperand(1));
4703 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4704 if (A == Op1) // ~A | A == -1
4705 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4709 // Note, A is still live here!
4710 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4712 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4714 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4715 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4716 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4717 I.getName()+".demorgan"), I);
4718 return BinaryOperator::CreateNot(And);
4722 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4723 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4724 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4727 Value *LHSVal, *RHSVal;
4728 ConstantInt *LHSCst, *RHSCst;
4729 ICmpInst::Predicate LHSCC, RHSCC;
4730 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4731 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4732 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4733 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4734 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4735 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4736 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4737 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4738 // We can't fold (ugt x, C) | (sgt x, C2).
4739 PredicatesFoldable(LHSCC, RHSCC)) {
4740 // Ensure that the larger constant is on the RHS.
4741 ICmpInst *LHS = cast<ICmpInst>(Op0);
4743 if (ICmpInst::isSignedPredicate(LHSCC))
4744 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4746 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4749 std::swap(LHS, RHS);
4750 std::swap(LHSCst, RHSCst);
4751 std::swap(LHSCC, RHSCC);
4754 // At this point, we know we have have two icmp instructions
4755 // comparing a value against two constants and or'ing the result
4756 // together. Because of the above check, we know that we only have
4757 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4758 // FoldICmpLogical check above), that the two constants are not
4760 assert(LHSCst != RHSCst && "Compares not folded above?");
4763 default: assert(0 && "Unknown integer condition code!");
4764 case ICmpInst::ICMP_EQ:
4766 default: assert(0 && "Unknown integer condition code!");
4767 case ICmpInst::ICMP_EQ:
4768 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4769 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4770 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4771 LHSVal->getName()+".off");
4772 InsertNewInstBefore(Add, I);
4773 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4774 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4776 break; // (X == 13 | X == 15) -> no change
4777 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4778 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4780 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4781 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4782 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4783 return ReplaceInstUsesWith(I, RHS);
4786 case ICmpInst::ICMP_NE:
4788 default: assert(0 && "Unknown integer condition code!");
4789 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4790 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4791 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4792 return ReplaceInstUsesWith(I, LHS);
4793 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4794 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4795 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4796 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4799 case ICmpInst::ICMP_ULT:
4801 default: assert(0 && "Unknown integer condition code!");
4802 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4804 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4805 // If RHSCst is [us]MAXINT, it is always false. Not handling
4806 // this can cause overflow.
4807 if (RHSCst->isMaxValue(false))
4808 return ReplaceInstUsesWith(I, LHS);
4809 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4811 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4813 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4814 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4815 return ReplaceInstUsesWith(I, RHS);
4816 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4820 case ICmpInst::ICMP_SLT:
4822 default: assert(0 && "Unknown integer condition code!");
4823 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4825 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4826 // If RHSCst is [us]MAXINT, it is always false. Not handling
4827 // this can cause overflow.
4828 if (RHSCst->isMaxValue(true))
4829 return ReplaceInstUsesWith(I, LHS);
4830 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4832 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4834 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4835 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4836 return ReplaceInstUsesWith(I, RHS);
4837 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4841 case ICmpInst::ICMP_UGT:
4843 default: assert(0 && "Unknown integer condition code!");
4844 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4845 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4846 return ReplaceInstUsesWith(I, LHS);
4847 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4849 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4850 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4851 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4852 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4856 case ICmpInst::ICMP_SGT:
4858 default: assert(0 && "Unknown integer condition code!");
4859 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4860 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4861 return ReplaceInstUsesWith(I, LHS);
4862 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4864 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4865 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4866 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4867 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4875 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4876 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4877 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4878 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4879 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4880 !isa<ICmpInst>(Op1C->getOperand(0))) {
4881 const Type *SrcTy = Op0C->getOperand(0)->getType();
4882 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4883 // Only do this if the casts both really cause code to be
4885 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4887 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4889 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4890 Op1C->getOperand(0),
4892 InsertNewInstBefore(NewOp, I);
4893 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4900 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4901 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4902 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4903 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4904 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4905 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4906 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4907 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4908 // If either of the constants are nans, then the whole thing returns
4910 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4911 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4913 // Otherwise, no need to compare the two constants, compare the
4915 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4916 RHS->getOperand(0));
4921 return Changed ? &I : 0;
4926 // XorSelf - Implements: X ^ X --> 0
4929 XorSelf(Value *rhs) : RHS(rhs) {}
4930 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4931 Instruction *apply(BinaryOperator &Xor) const {
4938 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4939 bool Changed = SimplifyCommutative(I);
4940 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4942 if (isa<UndefValue>(Op1)) {
4943 if (isa<UndefValue>(Op0))
4944 // Handle undef ^ undef -> 0 special case. This is a common
4946 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4947 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4950 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4951 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4952 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4953 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4956 // See if we can simplify any instructions used by the instruction whose sole
4957 // purpose is to compute bits we don't care about.
4958 if (!isa<VectorType>(I.getType())) {
4959 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4960 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4961 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4962 KnownZero, KnownOne))
4964 } else if (isa<ConstantAggregateZero>(Op1)) {
4965 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4968 // Is this a ~ operation?
4969 if (Value *NotOp = dyn_castNotVal(&I)) {
4970 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4971 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4972 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4973 if (Op0I->getOpcode() == Instruction::And ||
4974 Op0I->getOpcode() == Instruction::Or) {
4975 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4976 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4978 BinaryOperator::CreateNot(Op0I->getOperand(1),
4979 Op0I->getOperand(1)->getName()+".not");
4980 InsertNewInstBefore(NotY, I);
4981 if (Op0I->getOpcode() == Instruction::And)
4982 return BinaryOperator::CreateOr(Op0NotVal, NotY);
4984 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4991 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4992 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4993 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4994 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4995 return new ICmpInst(ICI->getInversePredicate(),
4996 ICI->getOperand(0), ICI->getOperand(1));
4998 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4999 return new FCmpInst(FCI->getInversePredicate(),
5000 FCI->getOperand(0), FCI->getOperand(1));
5003 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5004 // ~(c-X) == X-c-1 == X+(-c-1)
5005 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5006 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5007 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5008 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5009 ConstantInt::get(I.getType(), 1));
5010 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5013 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5014 if (Op0I->getOpcode() == Instruction::Add) {
5015 // ~(X-c) --> (-c-1)-X
5016 if (RHS->isAllOnesValue()) {
5017 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5018 return BinaryOperator::CreateSub(
5019 ConstantExpr::getSub(NegOp0CI,
5020 ConstantInt::get(I.getType(), 1)),
5021 Op0I->getOperand(0));
5022 } else if (RHS->getValue().isSignBit()) {
5023 // (X + C) ^ signbit -> (X + C + signbit)
5024 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
5025 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5028 } else if (Op0I->getOpcode() == Instruction::Or) {
5029 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5030 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5031 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5032 // Anything in both C1 and C2 is known to be zero, remove it from
5034 Constant *CommonBits = And(Op0CI, RHS);
5035 NewRHS = ConstantExpr::getAnd(NewRHS,
5036 ConstantExpr::getNot(CommonBits));
5037 AddToWorkList(Op0I);
5038 I.setOperand(0, Op0I->getOperand(0));
5039 I.setOperand(1, NewRHS);
5046 // Try to fold constant and into select arguments.
5047 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5048 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5050 if (isa<PHINode>(Op0))
5051 if (Instruction *NV = FoldOpIntoPhi(I))
5055 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5057 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5059 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5061 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5064 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5067 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5068 if (A == Op0) { // B^(B|A) == (A|B)^B
5069 Op1I->swapOperands();
5071 std::swap(Op0, Op1);
5072 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5073 I.swapOperands(); // Simplified below.
5074 std::swap(Op0, Op1);
5076 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5077 if (Op0 == A) // A^(A^B) == B
5078 return ReplaceInstUsesWith(I, B);
5079 else if (Op0 == B) // A^(B^A) == B
5080 return ReplaceInstUsesWith(I, A);
5081 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5082 if (A == Op0) { // A^(A&B) -> A^(B&A)
5083 Op1I->swapOperands();
5086 if (B == Op0) { // A^(B&A) -> (B&A)^A
5087 I.swapOperands(); // Simplified below.
5088 std::swap(Op0, Op1);
5093 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5096 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5097 if (A == Op1) // (B|A)^B == (A|B)^B
5099 if (B == Op1) { // (A|B)^B == A & ~B
5101 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5102 return BinaryOperator::CreateAnd(A, NotB);
5104 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5105 if (Op1 == A) // (A^B)^A == B
5106 return ReplaceInstUsesWith(I, B);
5107 else if (Op1 == B) // (B^A)^A == B
5108 return ReplaceInstUsesWith(I, A);
5109 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5110 if (A == Op1) // (A&B)^A -> (B&A)^A
5112 if (B == Op1 && // (B&A)^A == ~B & A
5113 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5115 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5116 return BinaryOperator::CreateAnd(N, Op1);
5121 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5122 if (Op0I && Op1I && Op0I->isShift() &&
5123 Op0I->getOpcode() == Op1I->getOpcode() &&
5124 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5125 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5126 Instruction *NewOp =
5127 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5128 Op1I->getOperand(0),
5129 Op0I->getName()), I);
5130 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5131 Op1I->getOperand(1));
5135 Value *A, *B, *C, *D;
5136 // (A & B)^(A | B) -> A ^ B
5137 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5138 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5139 if ((A == C && B == D) || (A == D && B == C))
5140 return BinaryOperator::CreateXor(A, B);
5142 // (A | B)^(A & B) -> A ^ B
5143 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5144 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5145 if ((A == C && B == D) || (A == D && B == C))
5146 return BinaryOperator::CreateXor(A, B);
5150 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5151 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5152 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5153 // (X & Y)^(X & Y) -> (Y^Z) & X
5154 Value *X = 0, *Y = 0, *Z = 0;
5156 X = A, Y = B, Z = D;
5158 X = A, Y = B, Z = C;
5160 X = B, Y = A, Z = D;
5162 X = B, Y = A, Z = C;
5165 Instruction *NewOp =
5166 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5167 return BinaryOperator::CreateAnd(NewOp, X);
5172 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5173 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5174 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5177 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5178 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5179 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5180 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5181 const Type *SrcTy = Op0C->getOperand(0)->getType();
5182 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5183 // Only do this if the casts both really cause code to be generated.
5184 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5186 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5188 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5189 Op1C->getOperand(0),
5191 InsertNewInstBefore(NewOp, I);
5192 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5196 return Changed ? &I : 0;
5199 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5200 /// overflowed for this type.
5201 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5202 ConstantInt *In2, bool IsSigned = false) {
5203 Result = cast<ConstantInt>(Add(In1, In2));
5206 if (In2->getValue().isNegative())
5207 return Result->getValue().sgt(In1->getValue());
5209 return Result->getValue().slt(In1->getValue());
5211 return Result->getValue().ult(In1->getValue());
5214 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5215 /// code necessary to compute the offset from the base pointer (without adding
5216 /// in the base pointer). Return the result as a signed integer of intptr size.
5217 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5218 TargetData &TD = IC.getTargetData();
5219 gep_type_iterator GTI = gep_type_begin(GEP);
5220 const Type *IntPtrTy = TD.getIntPtrType();
5221 Value *Result = Constant::getNullValue(IntPtrTy);
5223 // Build a mask for high order bits.
5224 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5225 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5227 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5228 Value *Op = GEP->getOperand(i);
5229 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5230 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5231 if (OpC->isZero()) continue;
5233 // Handle a struct index, which adds its field offset to the pointer.
5234 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5235 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5237 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5238 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5240 Result = IC.InsertNewInstBefore(
5241 BinaryOperator::CreateAdd(Result,
5242 ConstantInt::get(IntPtrTy, Size),
5243 GEP->getName()+".offs"), I);
5247 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5248 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5249 Scale = ConstantExpr::getMul(OC, Scale);
5250 if (Constant *RC = dyn_cast<Constant>(Result))
5251 Result = ConstantExpr::getAdd(RC, Scale);
5253 // Emit an add instruction.
5254 Result = IC.InsertNewInstBefore(
5255 BinaryOperator::CreateAdd(Result, Scale,
5256 GEP->getName()+".offs"), I);
5260 // Convert to correct type.
5261 if (Op->getType() != IntPtrTy) {
5262 if (Constant *OpC = dyn_cast<Constant>(Op))
5263 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5265 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5266 Op->getName()+".c"), I);
5269 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5270 if (Constant *OpC = dyn_cast<Constant>(Op))
5271 Op = ConstantExpr::getMul(OpC, Scale);
5272 else // We'll let instcombine(mul) convert this to a shl if possible.
5273 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5274 GEP->getName()+".idx"), I);
5277 // Emit an add instruction.
5278 if (isa<Constant>(Op) && isa<Constant>(Result))
5279 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5280 cast<Constant>(Result));
5282 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5283 GEP->getName()+".offs"), I);
5289 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5290 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5291 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5292 /// complex, and scales are involved. The above expression would also be legal
5293 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5294 /// later form is less amenable to optimization though, and we are allowed to
5295 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5297 /// If we can't emit an optimized form for this expression, this returns null.
5299 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5301 TargetData &TD = IC.getTargetData();
5302 gep_type_iterator GTI = gep_type_begin(GEP);
5304 // Check to see if this gep only has a single variable index. If so, and if
5305 // any constant indices are a multiple of its scale, then we can compute this
5306 // in terms of the scale of the variable index. For example, if the GEP
5307 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5308 // because the expression will cross zero at the same point.
5309 unsigned i, e = GEP->getNumOperands();
5311 for (i = 1; i != e; ++i, ++GTI) {
5312 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5313 // Compute the aggregate offset of constant indices.
5314 if (CI->isZero()) continue;
5316 // Handle a struct index, which adds its field offset to the pointer.
5317 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5318 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5320 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5321 Offset += Size*CI->getSExtValue();
5324 // Found our variable index.
5329 // If there are no variable indices, we must have a constant offset, just
5330 // evaluate it the general way.
5331 if (i == e) return 0;
5333 Value *VariableIdx = GEP->getOperand(i);
5334 // Determine the scale factor of the variable element. For example, this is
5335 // 4 if the variable index is into an array of i32.
5336 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5338 // Verify that there are no other variable indices. If so, emit the hard way.
5339 for (++i, ++GTI; i != e; ++i, ++GTI) {
5340 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5343 // Compute the aggregate offset of constant indices.
5344 if (CI->isZero()) continue;
5346 // Handle a struct index, which adds its field offset to the pointer.
5347 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5348 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5350 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5351 Offset += Size*CI->getSExtValue();
5355 // Okay, we know we have a single variable index, which must be a
5356 // pointer/array/vector index. If there is no offset, life is simple, return
5358 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5360 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5361 // we don't need to bother extending: the extension won't affect where the
5362 // computation crosses zero.
5363 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5364 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5365 VariableIdx->getNameStart(), &I);
5369 // Otherwise, there is an index. The computation we will do will be modulo
5370 // the pointer size, so get it.
5371 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5373 Offset &= PtrSizeMask;
5374 VariableScale &= PtrSizeMask;
5376 // To do this transformation, any constant index must be a multiple of the
5377 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5378 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5379 // multiple of the variable scale.
5380 int64_t NewOffs = Offset / (int64_t)VariableScale;
5381 if (Offset != NewOffs*(int64_t)VariableScale)
5384 // Okay, we can do this evaluation. Start by converting the index to intptr.
5385 const Type *IntPtrTy = TD.getIntPtrType();
5386 if (VariableIdx->getType() != IntPtrTy)
5387 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5389 VariableIdx->getNameStart(), &I);
5390 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5391 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5395 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5396 /// else. At this point we know that the GEP is on the LHS of the comparison.
5397 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5398 ICmpInst::Predicate Cond,
5400 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5402 // Look through bitcasts.
5403 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5404 RHS = BCI->getOperand(0);
5406 Value *PtrBase = GEPLHS->getOperand(0);
5407 if (PtrBase == RHS) {
5408 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5409 // This transformation (ignoring the base and scales) is valid because we
5410 // know pointers can't overflow. See if we can output an optimized form.
5411 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5413 // If not, synthesize the offset the hard way.
5415 Offset = EmitGEPOffset(GEPLHS, I, *this);
5416 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5417 Constant::getNullValue(Offset->getType()));
5418 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5419 // If the base pointers are different, but the indices are the same, just
5420 // compare the base pointer.
5421 if (PtrBase != GEPRHS->getOperand(0)) {
5422 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5423 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5424 GEPRHS->getOperand(0)->getType();
5426 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5427 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5428 IndicesTheSame = false;
5432 // If all indices are the same, just compare the base pointers.
5434 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5435 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5437 // Otherwise, the base pointers are different and the indices are
5438 // different, bail out.
5442 // If one of the GEPs has all zero indices, recurse.
5443 bool AllZeros = true;
5444 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5445 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5446 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5451 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5452 ICmpInst::getSwappedPredicate(Cond), I);
5454 // If the other GEP has all zero indices, recurse.
5456 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5457 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5458 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5463 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5465 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5466 // If the GEPs only differ by one index, compare it.
5467 unsigned NumDifferences = 0; // Keep track of # differences.
5468 unsigned DiffOperand = 0; // The operand that differs.
5469 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5470 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5471 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5472 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5473 // Irreconcilable differences.
5477 if (NumDifferences++) break;
5482 if (NumDifferences == 0) // SAME GEP?
5483 return ReplaceInstUsesWith(I, // No comparison is needed here.
5484 ConstantInt::get(Type::Int1Ty,
5485 ICmpInst::isTrueWhenEqual(Cond)));
5487 else if (NumDifferences == 1) {
5488 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5489 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5490 // Make sure we do a signed comparison here.
5491 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5495 // Only lower this if the icmp is the only user of the GEP or if we expect
5496 // the result to fold to a constant!
5497 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5498 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5499 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5500 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5501 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5502 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5508 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5510 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5513 if (!isa<ConstantFP>(RHSC)) return 0;
5514 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5516 // Get the width of the mantissa. We don't want to hack on conversions that
5517 // might lose information from the integer, e.g. "i64 -> float"
5518 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5519 if (MantissaWidth == -1) return 0; // Unknown.
5521 // Check to see that the input is converted from an integer type that is small
5522 // enough that preserves all bits. TODO: check here for "known" sign bits.
5523 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5524 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5526 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5527 if (isa<UIToFPInst>(LHSI))
5530 // If the conversion would lose info, don't hack on this.
5531 if ((int)InputSize > MantissaWidth)
5534 // Otherwise, we can potentially simplify the comparison. We know that it
5535 // will always come through as an integer value and we know the constant is
5536 // not a NAN (it would have been previously simplified).
5537 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5539 ICmpInst::Predicate Pred;
5540 switch (I.getPredicate()) {
5541 default: assert(0 && "Unexpected predicate!");
5542 case FCmpInst::FCMP_UEQ:
5543 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5544 case FCmpInst::FCMP_UGT:
5545 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5546 case FCmpInst::FCMP_UGE:
5547 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5548 case FCmpInst::FCMP_ULT:
5549 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5550 case FCmpInst::FCMP_ULE:
5551 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5552 case FCmpInst::FCMP_UNE:
5553 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5554 case FCmpInst::FCMP_ORD:
5555 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5556 case FCmpInst::FCMP_UNO:
5557 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5560 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5562 // Now we know that the APFloat is a normal number, zero or inf.
5564 // See if the FP constant is too large for the integer. For example,
5565 // comparing an i8 to 300.0.
5566 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5568 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5569 // and large values.
5570 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5571 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5572 APFloat::rmNearestTiesToEven);
5573 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5574 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5575 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5576 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5579 // See if the RHS value is < SignedMin.
5580 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5581 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5582 APFloat::rmNearestTiesToEven);
5583 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5584 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5585 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5586 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5589 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5590 // it may still be fractional. See if it is fractional by casting the FP
5591 // value to the integer value and back, checking for equality. Don't do this
5592 // for zero, because -0.0 is not fractional.
5593 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5594 if (!RHS.isZero() &&
5595 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5596 // If we had a comparison against a fractional value, we have to adjust
5597 // the compare predicate and sometimes the value. RHSC is rounded towards
5598 // zero at this point.
5600 default: assert(0 && "Unexpected integer comparison!");
5601 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5602 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5603 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5604 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5605 case ICmpInst::ICMP_SLE:
5606 // (float)int <= 4.4 --> int <= 4
5607 // (float)int <= -4.4 --> int < -4
5608 if (RHS.isNegative())
5609 Pred = ICmpInst::ICMP_SLT;
5611 case ICmpInst::ICMP_SLT:
5612 // (float)int < -4.4 --> int < -4
5613 // (float)int < 4.4 --> int <= 4
5614 if (!RHS.isNegative())
5615 Pred = ICmpInst::ICMP_SLE;
5617 case ICmpInst::ICMP_SGT:
5618 // (float)int > 4.4 --> int > 4
5619 // (float)int > -4.4 --> int >= -4
5620 if (RHS.isNegative())
5621 Pred = ICmpInst::ICMP_SGE;
5623 case ICmpInst::ICMP_SGE:
5624 // (float)int >= -4.4 --> int >= -4
5625 // (float)int >= 4.4 --> int > 4
5626 if (!RHS.isNegative())
5627 Pred = ICmpInst::ICMP_SGT;
5632 // Lower this FP comparison into an appropriate integer version of the
5634 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5637 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5638 bool Changed = SimplifyCompare(I);
5639 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5641 // Fold trivial predicates.
5642 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5643 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5644 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5645 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5647 // Simplify 'fcmp pred X, X'
5649 switch (I.getPredicate()) {
5650 default: assert(0 && "Unknown predicate!");
5651 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5652 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5653 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5654 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5655 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5656 case FCmpInst::FCMP_OLT: // True if ordered and less than
5657 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5658 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5660 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5661 case FCmpInst::FCMP_ULT: // True if unordered or less than
5662 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5663 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5664 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5665 I.setPredicate(FCmpInst::FCMP_UNO);
5666 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5669 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5670 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5671 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5672 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5673 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5674 I.setPredicate(FCmpInst::FCMP_ORD);
5675 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5680 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5681 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5683 // Handle fcmp with constant RHS
5684 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5685 // If the constant is a nan, see if we can fold the comparison based on it.
5686 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5687 if (CFP->getValueAPF().isNaN()) {
5688 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5689 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5690 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5691 "Comparison must be either ordered or unordered!");
5692 // True if unordered.
5693 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5697 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5698 switch (LHSI->getOpcode()) {
5699 case Instruction::PHI:
5700 if (Instruction *NV = FoldOpIntoPhi(I))
5703 case Instruction::SIToFP:
5704 case Instruction::UIToFP:
5705 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5708 case Instruction::Select:
5709 // If either operand of the select is a constant, we can fold the
5710 // comparison into the select arms, which will cause one to be
5711 // constant folded and the select turned into a bitwise or.
5712 Value *Op1 = 0, *Op2 = 0;
5713 if (LHSI->hasOneUse()) {
5714 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5715 // Fold the known value into the constant operand.
5716 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5717 // Insert a new FCmp of the other select operand.
5718 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5719 LHSI->getOperand(2), RHSC,
5721 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5722 // Fold the known value into the constant operand.
5723 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5724 // Insert a new FCmp of the other select operand.
5725 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5726 LHSI->getOperand(1), RHSC,
5732 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5737 return Changed ? &I : 0;
5740 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5741 bool Changed = SimplifyCompare(I);
5742 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5743 const Type *Ty = Op0->getType();
5747 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5748 I.isTrueWhenEqual()));
5750 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5751 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5753 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5754 // addresses never equal each other! We already know that Op0 != Op1.
5755 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5756 isa<ConstantPointerNull>(Op0)) &&
5757 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5758 isa<ConstantPointerNull>(Op1)))
5759 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5760 !I.isTrueWhenEqual()));
5762 // icmp's with boolean values can always be turned into bitwise operations
5763 if (Ty == Type::Int1Ty) {
5764 switch (I.getPredicate()) {
5765 default: assert(0 && "Invalid icmp instruction!");
5766 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
5767 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5768 InsertNewInstBefore(Xor, I);
5769 return BinaryOperator::CreateNot(Xor);
5771 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
5772 return BinaryOperator::CreateXor(Op0, Op1);
5774 case ICmpInst::ICMP_UGT:
5775 case ICmpInst::ICMP_SGT:
5776 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5778 case ICmpInst::ICMP_ULT:
5779 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
5780 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5781 InsertNewInstBefore(Not, I);
5782 return BinaryOperator::CreateAnd(Not, Op1);
5784 case ICmpInst::ICMP_UGE:
5785 case ICmpInst::ICMP_SGE:
5786 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5788 case ICmpInst::ICMP_ULE:
5789 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
5790 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5791 InsertNewInstBefore(Not, I);
5792 return BinaryOperator::CreateOr(Not, Op1);
5797 // See if we are doing a comparison between a constant and an instruction that
5798 // can be folded into the comparison.
5799 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5802 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5803 if (I.isEquality() && CI->isNullValue() &&
5804 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5805 // (icmp cond A B) if cond is equality
5806 return new ICmpInst(I.getPredicate(), A, B);
5809 switch (I.getPredicate()) {
5811 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5812 if (CI->isMinValue(false))
5813 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5814 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5815 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5816 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5817 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5818 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5819 if (CI->isMinValue(true))
5820 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5821 ConstantInt::getAllOnesValue(Op0->getType()));
5825 case ICmpInst::ICMP_SLT:
5826 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5827 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5828 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5829 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5830 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5831 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5834 case ICmpInst::ICMP_UGT:
5835 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5836 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5837 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5838 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5839 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5840 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5842 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5843 if (CI->isMaxValue(true))
5844 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5845 ConstantInt::getNullValue(Op0->getType()));
5848 case ICmpInst::ICMP_SGT:
5849 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5850 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5851 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5852 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5853 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5854 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5857 case ICmpInst::ICMP_ULE:
5858 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5859 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5860 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5861 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5862 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5863 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5866 case ICmpInst::ICMP_SLE:
5867 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5868 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5869 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5870 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5871 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5872 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5875 case ICmpInst::ICMP_UGE:
5876 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5877 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5878 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5879 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5880 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5881 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5884 case ICmpInst::ICMP_SGE:
5885 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5886 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5887 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5888 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5889 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5890 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5894 // If we still have a icmp le or icmp ge instruction, turn it into the
5895 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5896 // already been handled above, this requires little checking.
5898 switch (I.getPredicate()) {
5900 case ICmpInst::ICMP_ULE:
5901 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5902 case ICmpInst::ICMP_SLE:
5903 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5904 case ICmpInst::ICMP_UGE:
5905 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5906 case ICmpInst::ICMP_SGE:
5907 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5910 // See if we can fold the comparison based on bits known to be zero or one
5911 // in the input. If this comparison is a normal comparison, it demands all
5912 // bits, if it is a sign bit comparison, it only demands the sign bit.
5915 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5917 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5918 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5919 if (SimplifyDemandedBits(Op0,
5920 isSignBit ? APInt::getSignBit(BitWidth)
5921 : APInt::getAllOnesValue(BitWidth),
5922 KnownZero, KnownOne, 0))
5925 // Given the known and unknown bits, compute a range that the LHS could be
5927 if ((KnownOne | KnownZero) != 0) {
5928 // Compute the Min, Max and RHS values based on the known bits. For the
5929 // EQ and NE we use unsigned values.
5930 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5931 const APInt& RHSVal = CI->getValue();
5932 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5933 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5936 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5939 switch (I.getPredicate()) { // LE/GE have been folded already.
5940 default: assert(0 && "Unknown icmp opcode!");
5941 case ICmpInst::ICMP_EQ:
5942 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5943 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5945 case ICmpInst::ICMP_NE:
5946 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5947 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5949 case ICmpInst::ICMP_ULT:
5950 if (Max.ult(RHSVal))
5951 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5952 if (Min.uge(RHSVal))
5953 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5955 case ICmpInst::ICMP_UGT:
5956 if (Min.ugt(RHSVal))
5957 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5958 if (Max.ule(RHSVal))
5959 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5961 case ICmpInst::ICMP_SLT:
5962 if (Max.slt(RHSVal))
5963 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5964 if (Min.sgt(RHSVal))
5965 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5967 case ICmpInst::ICMP_SGT:
5968 if (Min.sgt(RHSVal))
5969 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5970 if (Max.sle(RHSVal))
5971 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5976 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5977 // instruction, see if that instruction also has constants so that the
5978 // instruction can be folded into the icmp
5979 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5980 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5984 // Handle icmp with constant (but not simple integer constant) RHS
5985 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5986 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5987 switch (LHSI->getOpcode()) {
5988 case Instruction::GetElementPtr:
5989 if (RHSC->isNullValue()) {
5990 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5991 bool isAllZeros = true;
5992 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5993 if (!isa<Constant>(LHSI->getOperand(i)) ||
5994 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5999 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6000 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6004 case Instruction::PHI:
6005 if (Instruction *NV = FoldOpIntoPhi(I))
6008 case Instruction::Select: {
6009 // If either operand of the select is a constant, we can fold the
6010 // comparison into the select arms, which will cause one to be
6011 // constant folded and the select turned into a bitwise or.
6012 Value *Op1 = 0, *Op2 = 0;
6013 if (LHSI->hasOneUse()) {
6014 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6015 // Fold the known value into the constant operand.
6016 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6017 // Insert a new ICmp of the other select operand.
6018 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6019 LHSI->getOperand(2), RHSC,
6021 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6022 // Fold the known value into the constant operand.
6023 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6024 // Insert a new ICmp of the other select operand.
6025 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6026 LHSI->getOperand(1), RHSC,
6032 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6035 case Instruction::Malloc:
6036 // If we have (malloc != null), and if the malloc has a single use, we
6037 // can assume it is successful and remove the malloc.
6038 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6039 AddToWorkList(LHSI);
6040 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6041 !I.isTrueWhenEqual()));
6047 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6048 if (User *GEP = dyn_castGetElementPtr(Op0))
6049 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6051 if (User *GEP = dyn_castGetElementPtr(Op1))
6052 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6053 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6056 // Test to see if the operands of the icmp are casted versions of other
6057 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6059 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6060 if (isa<PointerType>(Op0->getType()) &&
6061 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6062 // We keep moving the cast from the left operand over to the right
6063 // operand, where it can often be eliminated completely.
6064 Op0 = CI->getOperand(0);
6066 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6067 // so eliminate it as well.
6068 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6069 Op1 = CI2->getOperand(0);
6071 // If Op1 is a constant, we can fold the cast into the constant.
6072 if (Op0->getType() != Op1->getType()) {
6073 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6074 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6076 // Otherwise, cast the RHS right before the icmp
6077 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6080 return new ICmpInst(I.getPredicate(), Op0, Op1);
6084 if (isa<CastInst>(Op0)) {
6085 // Handle the special case of: icmp (cast bool to X), <cst>
6086 // This comes up when you have code like
6089 // For generality, we handle any zero-extension of any operand comparison
6090 // with a constant or another cast from the same type.
6091 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6092 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6096 // ~x < ~y --> y < x
6098 if (match(Op0, m_Not(m_Value(A))) &&
6099 match(Op1, m_Not(m_Value(B))))
6100 return new ICmpInst(I.getPredicate(), B, A);
6103 if (I.isEquality()) {
6104 Value *A, *B, *C, *D;
6106 // -x == -y --> x == y
6107 if (match(Op0, m_Neg(m_Value(A))) &&
6108 match(Op1, m_Neg(m_Value(B))))
6109 return new ICmpInst(I.getPredicate(), A, B);
6111 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6112 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6113 Value *OtherVal = A == Op1 ? B : A;
6114 return new ICmpInst(I.getPredicate(), OtherVal,
6115 Constant::getNullValue(A->getType()));
6118 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6119 // A^c1 == C^c2 --> A == C^(c1^c2)
6120 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6121 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6122 if (Op1->hasOneUse()) {
6123 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6124 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6125 return new ICmpInst(I.getPredicate(), A,
6126 InsertNewInstBefore(Xor, I));
6129 // A^B == A^D -> B == D
6130 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6131 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6132 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6133 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6137 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6138 (A == Op0 || B == Op0)) {
6139 // A == (A^B) -> B == 0
6140 Value *OtherVal = A == Op0 ? B : A;
6141 return new ICmpInst(I.getPredicate(), OtherVal,
6142 Constant::getNullValue(A->getType()));
6144 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6145 // (A-B) == A -> B == 0
6146 return new ICmpInst(I.getPredicate(), B,
6147 Constant::getNullValue(B->getType()));
6149 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6150 // A == (A-B) -> B == 0
6151 return new ICmpInst(I.getPredicate(), B,
6152 Constant::getNullValue(B->getType()));
6155 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6156 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6157 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6158 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6159 Value *X = 0, *Y = 0, *Z = 0;
6162 X = B; Y = D; Z = A;
6163 } else if (A == D) {
6164 X = B; Y = C; Z = A;
6165 } else if (B == C) {
6166 X = A; Y = D; Z = B;
6167 } else if (B == D) {
6168 X = A; Y = C; Z = B;
6171 if (X) { // Build (X^Y) & Z
6172 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6173 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6174 I.setOperand(0, Op1);
6175 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6180 return Changed ? &I : 0;
6184 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6185 /// and CmpRHS are both known to be integer constants.
6186 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6187 ConstantInt *DivRHS) {
6188 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6189 const APInt &CmpRHSV = CmpRHS->getValue();
6191 // FIXME: If the operand types don't match the type of the divide
6192 // then don't attempt this transform. The code below doesn't have the
6193 // logic to deal with a signed divide and an unsigned compare (and
6194 // vice versa). This is because (x /s C1) <s C2 produces different
6195 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6196 // (x /u C1) <u C2. Simply casting the operands and result won't
6197 // work. :( The if statement below tests that condition and bails
6199 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6200 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6202 if (DivRHS->isZero())
6203 return 0; // The ProdOV computation fails on divide by zero.
6205 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6206 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6207 // C2 (CI). By solving for X we can turn this into a range check
6208 // instead of computing a divide.
6209 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6211 // Determine if the product overflows by seeing if the product is
6212 // not equal to the divide. Make sure we do the same kind of divide
6213 // as in the LHS instruction that we're folding.
6214 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6215 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6217 // Get the ICmp opcode
6218 ICmpInst::Predicate Pred = ICI.getPredicate();
6220 // Figure out the interval that is being checked. For example, a comparison
6221 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6222 // Compute this interval based on the constants involved and the signedness of
6223 // the compare/divide. This computes a half-open interval, keeping track of
6224 // whether either value in the interval overflows. After analysis each
6225 // overflow variable is set to 0 if it's corresponding bound variable is valid
6226 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6227 int LoOverflow = 0, HiOverflow = 0;
6228 ConstantInt *LoBound = 0, *HiBound = 0;
6231 if (!DivIsSigned) { // udiv
6232 // e.g. X/5 op 3 --> [15, 20)
6234 HiOverflow = LoOverflow = ProdOV;
6236 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6237 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6238 if (CmpRHSV == 0) { // (X / pos) op 0
6239 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6240 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6242 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6243 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6244 HiOverflow = LoOverflow = ProdOV;
6246 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6247 } else { // (X / pos) op neg
6248 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6249 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6250 LoOverflow = AddWithOverflow(LoBound, Prod,
6251 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
6252 HiBound = AddOne(Prod);
6253 HiOverflow = ProdOV ? -1 : 0;
6255 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6256 if (CmpRHSV == 0) { // (X / neg) op 0
6257 // e.g. X/-5 op 0 --> [-4, 5)
6258 LoBound = AddOne(DivRHS);
6259 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6260 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6261 HiOverflow = 1; // [INTMIN+1, overflow)
6262 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6264 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6265 // e.g. X/-5 op 3 --> [-19, -14)
6266 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6268 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
6269 HiBound = AddOne(Prod);
6270 } else { // (X / neg) op neg
6271 // e.g. X/-5 op -3 --> [15, 20)
6273 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
6274 HiBound = Subtract(Prod, DivRHS);
6277 // Dividing by a negative swaps the condition. LT <-> GT
6278 Pred = ICmpInst::getSwappedPredicate(Pred);
6281 Value *X = DivI->getOperand(0);
6283 default: assert(0 && "Unhandled icmp opcode!");
6284 case ICmpInst::ICMP_EQ:
6285 if (LoOverflow && HiOverflow)
6286 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6287 else if (HiOverflow)
6288 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6289 ICmpInst::ICMP_UGE, X, LoBound);
6290 else if (LoOverflow)
6291 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6292 ICmpInst::ICMP_ULT, X, HiBound);
6294 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6295 case ICmpInst::ICMP_NE:
6296 if (LoOverflow && HiOverflow)
6297 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6298 else if (HiOverflow)
6299 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6300 ICmpInst::ICMP_ULT, X, LoBound);
6301 else if (LoOverflow)
6302 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6303 ICmpInst::ICMP_UGE, X, HiBound);
6305 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6306 case ICmpInst::ICMP_ULT:
6307 case ICmpInst::ICMP_SLT:
6308 if (LoOverflow == +1) // Low bound is greater than input range.
6309 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6310 if (LoOverflow == -1) // Low bound is less than input range.
6311 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6312 return new ICmpInst(Pred, X, LoBound);
6313 case ICmpInst::ICMP_UGT:
6314 case ICmpInst::ICMP_SGT:
6315 if (HiOverflow == +1) // High bound greater than input range.
6316 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6317 else if (HiOverflow == -1) // High bound less than input range.
6318 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6319 if (Pred == ICmpInst::ICMP_UGT)
6320 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6322 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6327 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6329 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6332 const APInt &RHSV = RHS->getValue();
6334 switch (LHSI->getOpcode()) {
6335 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6336 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6337 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6339 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6340 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6341 Value *CompareVal = LHSI->getOperand(0);
6343 // If the sign bit of the XorCST is not set, there is no change to
6344 // the operation, just stop using the Xor.
6345 if (!XorCST->getValue().isNegative()) {
6346 ICI.setOperand(0, CompareVal);
6347 AddToWorkList(LHSI);
6351 // Was the old condition true if the operand is positive?
6352 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6354 // If so, the new one isn't.
6355 isTrueIfPositive ^= true;
6357 if (isTrueIfPositive)
6358 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6360 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6364 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6365 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6366 LHSI->getOperand(0)->hasOneUse()) {
6367 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6369 // If the LHS is an AND of a truncating cast, we can widen the
6370 // and/compare to be the input width without changing the value
6371 // produced, eliminating a cast.
6372 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6373 // We can do this transformation if either the AND constant does not
6374 // have its sign bit set or if it is an equality comparison.
6375 // Extending a relational comparison when we're checking the sign
6376 // bit would not work.
6377 if (Cast->hasOneUse() &&
6378 (ICI.isEquality() ||
6379 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6381 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6382 APInt NewCST = AndCST->getValue();
6383 NewCST.zext(BitWidth);
6385 NewCI.zext(BitWidth);
6386 Instruction *NewAnd =
6387 BinaryOperator::CreateAnd(Cast->getOperand(0),
6388 ConstantInt::get(NewCST),LHSI->getName());
6389 InsertNewInstBefore(NewAnd, ICI);
6390 return new ICmpInst(ICI.getPredicate(), NewAnd,
6391 ConstantInt::get(NewCI));
6395 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6396 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6397 // happens a LOT in code produced by the C front-end, for bitfield
6399 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6400 if (Shift && !Shift->isShift())
6404 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6405 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6406 const Type *AndTy = AndCST->getType(); // Type of the and.
6408 // We can fold this as long as we can't shift unknown bits
6409 // into the mask. This can only happen with signed shift
6410 // rights, as they sign-extend.
6412 bool CanFold = Shift->isLogicalShift();
6414 // To test for the bad case of the signed shr, see if any
6415 // of the bits shifted in could be tested after the mask.
6416 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6417 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6419 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6420 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6421 AndCST->getValue()) == 0)
6427 if (Shift->getOpcode() == Instruction::Shl)
6428 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6430 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6432 // Check to see if we are shifting out any of the bits being
6434 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6435 // If we shifted bits out, the fold is not going to work out.
6436 // As a special case, check to see if this means that the
6437 // result is always true or false now.
6438 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6439 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6440 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6441 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6443 ICI.setOperand(1, NewCst);
6444 Constant *NewAndCST;
6445 if (Shift->getOpcode() == Instruction::Shl)
6446 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6448 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6449 LHSI->setOperand(1, NewAndCST);
6450 LHSI->setOperand(0, Shift->getOperand(0));
6451 AddToWorkList(Shift); // Shift is dead.
6452 AddUsesToWorkList(ICI);
6458 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6459 // preferable because it allows the C<<Y expression to be hoisted out
6460 // of a loop if Y is invariant and X is not.
6461 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6462 ICI.isEquality() && !Shift->isArithmeticShift() &&
6463 isa<Instruction>(Shift->getOperand(0))) {
6466 if (Shift->getOpcode() == Instruction::LShr) {
6467 NS = BinaryOperator::CreateShl(AndCST,
6468 Shift->getOperand(1), "tmp");
6470 // Insert a logical shift.
6471 NS = BinaryOperator::CreateLShr(AndCST,
6472 Shift->getOperand(1), "tmp");
6474 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6476 // Compute X & (C << Y).
6477 Instruction *NewAnd =
6478 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6479 InsertNewInstBefore(NewAnd, ICI);
6481 ICI.setOperand(0, NewAnd);
6487 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6488 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6491 uint32_t TypeBits = RHSV.getBitWidth();
6493 // Check that the shift amount is in range. If not, don't perform
6494 // undefined shifts. When the shift is visited it will be
6496 if (ShAmt->uge(TypeBits))
6499 if (ICI.isEquality()) {
6500 // If we are comparing against bits always shifted out, the
6501 // comparison cannot succeed.
6503 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6504 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6505 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6506 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6507 return ReplaceInstUsesWith(ICI, Cst);
6510 if (LHSI->hasOneUse()) {
6511 // Otherwise strength reduce the shift into an and.
6512 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6514 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6517 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6518 Mask, LHSI->getName()+".mask");
6519 Value *And = InsertNewInstBefore(AndI, ICI);
6520 return new ICmpInst(ICI.getPredicate(), And,
6521 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6525 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6526 bool TrueIfSigned = false;
6527 if (LHSI->hasOneUse() &&
6528 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6529 // (X << 31) <s 0 --> (X&1) != 0
6530 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6531 (TypeBits-ShAmt->getZExtValue()-1));
6533 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6534 Mask, LHSI->getName()+".mask");
6535 Value *And = InsertNewInstBefore(AndI, ICI);
6537 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6538 And, Constant::getNullValue(And->getType()));
6543 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6544 case Instruction::AShr: {
6545 // Only handle equality comparisons of shift-by-constant.
6546 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6547 if (!ShAmt || !ICI.isEquality()) break;
6549 // Check that the shift amount is in range. If not, don't perform
6550 // undefined shifts. When the shift is visited it will be
6552 uint32_t TypeBits = RHSV.getBitWidth();
6553 if (ShAmt->uge(TypeBits))
6556 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6558 // If we are comparing against bits always shifted out, the
6559 // comparison cannot succeed.
6560 APInt Comp = RHSV << ShAmtVal;
6561 if (LHSI->getOpcode() == Instruction::LShr)
6562 Comp = Comp.lshr(ShAmtVal);
6564 Comp = Comp.ashr(ShAmtVal);
6566 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6567 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6568 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6569 return ReplaceInstUsesWith(ICI, Cst);
6572 // Otherwise, check to see if the bits shifted out are known to be zero.
6573 // If so, we can compare against the unshifted value:
6574 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6575 if (LHSI->hasOneUse() &&
6576 MaskedValueIsZero(LHSI->getOperand(0),
6577 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6578 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6579 ConstantExpr::getShl(RHS, ShAmt));
6582 if (LHSI->hasOneUse()) {
6583 // Otherwise strength reduce the shift into an and.
6584 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6585 Constant *Mask = ConstantInt::get(Val);
6588 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6589 Mask, LHSI->getName()+".mask");
6590 Value *And = InsertNewInstBefore(AndI, ICI);
6591 return new ICmpInst(ICI.getPredicate(), And,
6592 ConstantExpr::getShl(RHS, ShAmt));
6597 case Instruction::SDiv:
6598 case Instruction::UDiv:
6599 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6600 // Fold this div into the comparison, producing a range check.
6601 // Determine, based on the divide type, what the range is being
6602 // checked. If there is an overflow on the low or high side, remember
6603 // it, otherwise compute the range [low, hi) bounding the new value.
6604 // See: InsertRangeTest above for the kinds of replacements possible.
6605 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6606 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6611 case Instruction::Add:
6612 // Fold: icmp pred (add, X, C1), C2
6614 if (!ICI.isEquality()) {
6615 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6617 const APInt &LHSV = LHSC->getValue();
6619 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6622 if (ICI.isSignedPredicate()) {
6623 if (CR.getLower().isSignBit()) {
6624 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6625 ConstantInt::get(CR.getUpper()));
6626 } else if (CR.getUpper().isSignBit()) {
6627 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6628 ConstantInt::get(CR.getLower()));
6631 if (CR.getLower().isMinValue()) {
6632 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6633 ConstantInt::get(CR.getUpper()));
6634 } else if (CR.getUpper().isMinValue()) {
6635 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6636 ConstantInt::get(CR.getLower()));
6643 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6644 if (ICI.isEquality()) {
6645 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6647 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6648 // the second operand is a constant, simplify a bit.
6649 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6650 switch (BO->getOpcode()) {
6651 case Instruction::SRem:
6652 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6653 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6654 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6655 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6656 Instruction *NewRem =
6657 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6659 InsertNewInstBefore(NewRem, ICI);
6660 return new ICmpInst(ICI.getPredicate(), NewRem,
6661 Constant::getNullValue(BO->getType()));
6665 case Instruction::Add:
6666 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6667 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6668 if (BO->hasOneUse())
6669 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6670 Subtract(RHS, BOp1C));
6671 } else if (RHSV == 0) {
6672 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6673 // efficiently invertible, or if the add has just this one use.
6674 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6676 if (Value *NegVal = dyn_castNegVal(BOp1))
6677 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6678 else if (Value *NegVal = dyn_castNegVal(BOp0))
6679 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6680 else if (BO->hasOneUse()) {
6681 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6682 InsertNewInstBefore(Neg, ICI);
6684 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6688 case Instruction::Xor:
6689 // For the xor case, we can xor two constants together, eliminating
6690 // the explicit xor.
6691 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6692 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6693 ConstantExpr::getXor(RHS, BOC));
6696 case Instruction::Sub:
6697 // Replace (([sub|xor] A, B) != 0) with (A != B)
6699 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6703 case Instruction::Or:
6704 // If bits are being or'd in that are not present in the constant we
6705 // are comparing against, then the comparison could never succeed!
6706 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6707 Constant *NotCI = ConstantExpr::getNot(RHS);
6708 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6709 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6714 case Instruction::And:
6715 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6716 // If bits are being compared against that are and'd out, then the
6717 // comparison can never succeed!
6718 if ((RHSV & ~BOC->getValue()) != 0)
6719 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6722 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6723 if (RHS == BOC && RHSV.isPowerOf2())
6724 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6725 ICmpInst::ICMP_NE, LHSI,
6726 Constant::getNullValue(RHS->getType()));
6728 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6729 if (isSignBit(BOC)) {
6730 Value *X = BO->getOperand(0);
6731 Constant *Zero = Constant::getNullValue(X->getType());
6732 ICmpInst::Predicate pred = isICMP_NE ?
6733 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6734 return new ICmpInst(pred, X, Zero);
6737 // ((X & ~7) == 0) --> X < 8
6738 if (RHSV == 0 && isHighOnes(BOC)) {
6739 Value *X = BO->getOperand(0);
6740 Constant *NegX = ConstantExpr::getNeg(BOC);
6741 ICmpInst::Predicate pred = isICMP_NE ?
6742 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6743 return new ICmpInst(pred, X, NegX);
6748 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6749 // Handle icmp {eq|ne} <intrinsic>, intcst.
6750 if (II->getIntrinsicID() == Intrinsic::bswap) {
6752 ICI.setOperand(0, II->getOperand(1));
6753 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6757 } else { // Not a ICMP_EQ/ICMP_NE
6758 // If the LHS is a cast from an integral value of the same size,
6759 // then since we know the RHS is a constant, try to simlify.
6760 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6761 Value *CastOp = Cast->getOperand(0);
6762 const Type *SrcTy = CastOp->getType();
6763 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6764 if (SrcTy->isInteger() &&
6765 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6766 // If this is an unsigned comparison, try to make the comparison use
6767 // smaller constant values.
6768 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6769 // X u< 128 => X s> -1
6770 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6771 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6772 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6773 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6774 // X u> 127 => X s< 0
6775 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6776 Constant::getNullValue(SrcTy));
6784 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6785 /// We only handle extending casts so far.
6787 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6788 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6789 Value *LHSCIOp = LHSCI->getOperand(0);
6790 const Type *SrcTy = LHSCIOp->getType();
6791 const Type *DestTy = LHSCI->getType();
6794 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6795 // integer type is the same size as the pointer type.
6796 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6797 getTargetData().getPointerSizeInBits() ==
6798 cast<IntegerType>(DestTy)->getBitWidth()) {
6800 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6801 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6802 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6803 RHSOp = RHSC->getOperand(0);
6804 // If the pointer types don't match, insert a bitcast.
6805 if (LHSCIOp->getType() != RHSOp->getType())
6806 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6810 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6813 // The code below only handles extension cast instructions, so far.
6815 if (LHSCI->getOpcode() != Instruction::ZExt &&
6816 LHSCI->getOpcode() != Instruction::SExt)
6819 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6820 bool isSignedCmp = ICI.isSignedPredicate();
6822 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6823 // Not an extension from the same type?
6824 RHSCIOp = CI->getOperand(0);
6825 if (RHSCIOp->getType() != LHSCIOp->getType())
6828 // If the signedness of the two casts doesn't agree (i.e. one is a sext
6829 // and the other is a zext), then we can't handle this.
6830 if (CI->getOpcode() != LHSCI->getOpcode())
6833 // Deal with equality cases early.
6834 if (ICI.isEquality())
6835 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6837 // A signed comparison of sign extended values simplifies into a
6838 // signed comparison.
6839 if (isSignedCmp && isSignedExt)
6840 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6842 // The other three cases all fold into an unsigned comparison.
6843 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6846 // If we aren't dealing with a constant on the RHS, exit early
6847 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6851 // Compute the constant that would happen if we truncated to SrcTy then
6852 // reextended to DestTy.
6853 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6854 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6856 // If the re-extended constant didn't change...
6858 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6859 // For example, we might have:
6860 // %A = sext short %X to uint
6861 // %B = icmp ugt uint %A, 1330
6862 // It is incorrect to transform this into
6863 // %B = icmp ugt short %X, 1330
6864 // because %A may have negative value.
6866 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6867 // OR operation is EQ/NE.
6868 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6869 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6874 // The re-extended constant changed so the constant cannot be represented
6875 // in the shorter type. Consequently, we cannot emit a simple comparison.
6877 // First, handle some easy cases. We know the result cannot be equal at this
6878 // point so handle the ICI.isEquality() cases
6879 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6880 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6881 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6882 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6884 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6885 // should have been folded away previously and not enter in here.
6888 // We're performing a signed comparison.
6889 if (cast<ConstantInt>(CI)->getValue().isNegative())
6890 Result = ConstantInt::getFalse(); // X < (small) --> false
6892 Result = ConstantInt::getTrue(); // X < (large) --> true
6894 // We're performing an unsigned comparison.
6896 // We're performing an unsigned comp with a sign extended value.
6897 // This is true if the input is >= 0. [aka >s -1]
6898 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6899 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6900 NegOne, ICI.getName()), ICI);
6902 // Unsigned extend & unsigned compare -> always true.
6903 Result = ConstantInt::getTrue();
6907 // Finally, return the value computed.
6908 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6909 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6910 return ReplaceInstUsesWith(ICI, Result);
6912 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6913 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6914 "ICmp should be folded!");
6915 if (Constant *CI = dyn_cast<Constant>(Result))
6916 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6918 return BinaryOperator::CreateNot(Result);
6922 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6923 return commonShiftTransforms(I);
6926 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6927 return commonShiftTransforms(I);
6930 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6931 if (Instruction *R = commonShiftTransforms(I))
6934 Value *Op0 = I.getOperand(0);
6936 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6937 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6938 if (CSI->isAllOnesValue())
6939 return ReplaceInstUsesWith(I, CSI);
6941 // See if we can turn a signed shr into an unsigned shr.
6942 if (MaskedValueIsZero(Op0,
6943 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6944 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6949 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6950 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6951 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6953 // shl X, 0 == X and shr X, 0 == X
6954 // shl 0, X == 0 and shr 0, X == 0
6955 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6956 Op0 == Constant::getNullValue(Op0->getType()))
6957 return ReplaceInstUsesWith(I, Op0);
6959 if (isa<UndefValue>(Op0)) {
6960 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6961 return ReplaceInstUsesWith(I, Op0);
6962 else // undef << X -> 0, undef >>u X -> 0
6963 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6965 if (isa<UndefValue>(Op1)) {
6966 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6967 return ReplaceInstUsesWith(I, Op0);
6968 else // X << undef, X >>u undef -> 0
6969 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6972 // Try to fold constant and into select arguments.
6973 if (isa<Constant>(Op0))
6974 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6975 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6978 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6979 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6984 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6985 BinaryOperator &I) {
6986 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6988 // See if we can simplify any instructions used by the instruction whose sole
6989 // purpose is to compute bits we don't care about.
6990 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6991 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6992 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6993 KnownZero, KnownOne))
6996 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6997 // of a signed value.
6999 if (Op1->uge(TypeBits)) {
7000 if (I.getOpcode() != Instruction::AShr)
7001 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7003 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7008 // ((X*C1) << C2) == (X * (C1 << C2))
7009 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7010 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7011 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7012 return BinaryOperator::CreateMul(BO->getOperand(0),
7013 ConstantExpr::getShl(BOOp, Op1));
7015 // Try to fold constant and into select arguments.
7016 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7017 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7019 if (isa<PHINode>(Op0))
7020 if (Instruction *NV = FoldOpIntoPhi(I))
7023 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7024 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7025 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7026 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7027 // place. Don't try to do this transformation in this case. Also, we
7028 // require that the input operand is a shift-by-constant so that we have
7029 // confidence that the shifts will get folded together. We could do this
7030 // xform in more cases, but it is unlikely to be profitable.
7031 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7032 isa<ConstantInt>(TrOp->getOperand(1))) {
7033 // Okay, we'll do this xform. Make the shift of shift.
7034 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7035 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7037 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7039 // For logical shifts, the truncation has the effect of making the high
7040 // part of the register be zeros. Emulate this by inserting an AND to
7041 // clear the top bits as needed. This 'and' will usually be zapped by
7042 // other xforms later if dead.
7043 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7044 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7045 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7047 // The mask we constructed says what the trunc would do if occurring
7048 // between the shifts. We want to know the effect *after* the second
7049 // shift. We know that it is a logical shift by a constant, so adjust the
7050 // mask as appropriate.
7051 if (I.getOpcode() == Instruction::Shl)
7052 MaskV <<= Op1->getZExtValue();
7054 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7055 MaskV = MaskV.lshr(Op1->getZExtValue());
7058 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7060 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7062 // Return the value truncated to the interesting size.
7063 return new TruncInst(And, I.getType());
7067 if (Op0->hasOneUse()) {
7068 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7069 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7072 switch (Op0BO->getOpcode()) {
7074 case Instruction::Add:
7075 case Instruction::And:
7076 case Instruction::Or:
7077 case Instruction::Xor: {
7078 // These operators commute.
7079 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7080 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7081 match(Op0BO->getOperand(1),
7082 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7083 Instruction *YS = BinaryOperator::CreateShl(
7084 Op0BO->getOperand(0), Op1,
7086 InsertNewInstBefore(YS, I); // (Y << C)
7088 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7089 Op0BO->getOperand(1)->getName());
7090 InsertNewInstBefore(X, I); // (X + (Y << C))
7091 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7092 return BinaryOperator::CreateAnd(X, ConstantInt::get(
7093 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7096 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7097 Value *Op0BOOp1 = Op0BO->getOperand(1);
7098 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7100 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
7101 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7103 Instruction *YS = BinaryOperator::CreateShl(
7104 Op0BO->getOperand(0), Op1,
7106 InsertNewInstBefore(YS, I); // (Y << C)
7108 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7109 V1->getName()+".mask");
7110 InsertNewInstBefore(XM, I); // X & (CC << C)
7112 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7117 case Instruction::Sub: {
7118 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7119 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7120 match(Op0BO->getOperand(0),
7121 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7122 Instruction *YS = BinaryOperator::CreateShl(
7123 Op0BO->getOperand(1), Op1,
7125 InsertNewInstBefore(YS, I); // (Y << C)
7127 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7128 Op0BO->getOperand(0)->getName());
7129 InsertNewInstBefore(X, I); // (X + (Y << C))
7130 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7131 return BinaryOperator::CreateAnd(X, ConstantInt::get(
7132 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7135 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7136 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7137 match(Op0BO->getOperand(0),
7138 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7139 m_ConstantInt(CC))) && V2 == Op1 &&
7140 cast<BinaryOperator>(Op0BO->getOperand(0))
7141 ->getOperand(0)->hasOneUse()) {
7142 Instruction *YS = BinaryOperator::CreateShl(
7143 Op0BO->getOperand(1), Op1,
7145 InsertNewInstBefore(YS, I); // (Y << C)
7147 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7148 V1->getName()+".mask");
7149 InsertNewInstBefore(XM, I); // X & (CC << C)
7151 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7159 // If the operand is an bitwise operator with a constant RHS, and the
7160 // shift is the only use, we can pull it out of the shift.
7161 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7162 bool isValid = true; // Valid only for And, Or, Xor
7163 bool highBitSet = false; // Transform if high bit of constant set?
7165 switch (Op0BO->getOpcode()) {
7166 default: isValid = false; break; // Do not perform transform!
7167 case Instruction::Add:
7168 isValid = isLeftShift;
7170 case Instruction::Or:
7171 case Instruction::Xor:
7174 case Instruction::And:
7179 // If this is a signed shift right, and the high bit is modified
7180 // by the logical operation, do not perform the transformation.
7181 // The highBitSet boolean indicates the value of the high bit of
7182 // the constant which would cause it to be modified for this
7185 if (isValid && I.getOpcode() == Instruction::AShr)
7186 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7189 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7191 Instruction *NewShift =
7192 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7193 InsertNewInstBefore(NewShift, I);
7194 NewShift->takeName(Op0BO);
7196 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7203 // Find out if this is a shift of a shift by a constant.
7204 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7205 if (ShiftOp && !ShiftOp->isShift())
7208 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7209 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7210 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7211 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7212 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7213 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7214 Value *X = ShiftOp->getOperand(0);
7216 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7217 if (AmtSum > TypeBits)
7220 const IntegerType *Ty = cast<IntegerType>(I.getType());
7222 // Check for (X << c1) << c2 and (X >> c1) >> c2
7223 if (I.getOpcode() == ShiftOp->getOpcode()) {
7224 return BinaryOperator::Create(I.getOpcode(), X,
7225 ConstantInt::get(Ty, AmtSum));
7226 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7227 I.getOpcode() == Instruction::AShr) {
7228 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7229 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7230 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7231 I.getOpcode() == Instruction::LShr) {
7232 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7233 Instruction *Shift =
7234 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7235 InsertNewInstBefore(Shift, I);
7237 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7238 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7241 // Okay, if we get here, one shift must be left, and the other shift must be
7242 // right. See if the amounts are equal.
7243 if (ShiftAmt1 == ShiftAmt2) {
7244 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7245 if (I.getOpcode() == Instruction::Shl) {
7246 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7247 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7249 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7250 if (I.getOpcode() == Instruction::LShr) {
7251 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7252 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7254 // We can simplify ((X << C) >>s C) into a trunc + sext.
7255 // NOTE: we could do this for any C, but that would make 'unusual' integer
7256 // types. For now, just stick to ones well-supported by the code
7258 const Type *SExtType = 0;
7259 switch (Ty->getBitWidth() - ShiftAmt1) {
7266 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7271 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7272 InsertNewInstBefore(NewTrunc, I);
7273 return new SExtInst(NewTrunc, Ty);
7275 // Otherwise, we can't handle it yet.
7276 } else if (ShiftAmt1 < ShiftAmt2) {
7277 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7279 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7280 if (I.getOpcode() == Instruction::Shl) {
7281 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7282 ShiftOp->getOpcode() == Instruction::AShr);
7283 Instruction *Shift =
7284 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7285 InsertNewInstBefore(Shift, I);
7287 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7288 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7291 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7292 if (I.getOpcode() == Instruction::LShr) {
7293 assert(ShiftOp->getOpcode() == Instruction::Shl);
7294 Instruction *Shift =
7295 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7296 InsertNewInstBefore(Shift, I);
7298 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7299 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7302 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7304 assert(ShiftAmt2 < ShiftAmt1);
7305 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7307 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7308 if (I.getOpcode() == Instruction::Shl) {
7309 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7310 ShiftOp->getOpcode() == Instruction::AShr);
7311 Instruction *Shift =
7312 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7313 ConstantInt::get(Ty, ShiftDiff));
7314 InsertNewInstBefore(Shift, I);
7316 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7317 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7320 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7321 if (I.getOpcode() == Instruction::LShr) {
7322 assert(ShiftOp->getOpcode() == Instruction::Shl);
7323 Instruction *Shift =
7324 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7325 InsertNewInstBefore(Shift, I);
7327 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7328 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7331 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7338 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7339 /// expression. If so, decompose it, returning some value X, such that Val is
7342 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7344 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7345 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7346 Offset = CI->getZExtValue();
7348 return ConstantInt::get(Type::Int32Ty, 0);
7349 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7350 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7351 if (I->getOpcode() == Instruction::Shl) {
7352 // This is a value scaled by '1 << the shift amt'.
7353 Scale = 1U << RHS->getZExtValue();
7355 return I->getOperand(0);
7356 } else if (I->getOpcode() == Instruction::Mul) {
7357 // This value is scaled by 'RHS'.
7358 Scale = RHS->getZExtValue();
7360 return I->getOperand(0);
7361 } else if (I->getOpcode() == Instruction::Add) {
7362 // We have X+C. Check to see if we really have (X*C2)+C1,
7363 // where C1 is divisible by C2.
7366 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7367 Offset += RHS->getZExtValue();
7374 // Otherwise, we can't look past this.
7381 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7382 /// try to eliminate the cast by moving the type information into the alloc.
7383 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7384 AllocationInst &AI) {
7385 const PointerType *PTy = cast<PointerType>(CI.getType());
7387 // Remove any uses of AI that are dead.
7388 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7390 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7391 Instruction *User = cast<Instruction>(*UI++);
7392 if (isInstructionTriviallyDead(User)) {
7393 while (UI != E && *UI == User)
7394 ++UI; // If this instruction uses AI more than once, don't break UI.
7397 DOUT << "IC: DCE: " << *User;
7398 EraseInstFromFunction(*User);
7402 // Get the type really allocated and the type casted to.
7403 const Type *AllocElTy = AI.getAllocatedType();
7404 const Type *CastElTy = PTy->getElementType();
7405 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7407 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7408 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7409 if (CastElTyAlign < AllocElTyAlign) return 0;
7411 // If the allocation has multiple uses, only promote it if we are strictly
7412 // increasing the alignment of the resultant allocation. If we keep it the
7413 // same, we open the door to infinite loops of various kinds.
7414 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7416 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7417 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7418 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7420 // See if we can satisfy the modulus by pulling a scale out of the array
7422 unsigned ArraySizeScale;
7424 Value *NumElements = // See if the array size is a decomposable linear expr.
7425 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7427 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7429 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7430 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7432 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7437 // If the allocation size is constant, form a constant mul expression
7438 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7439 if (isa<ConstantInt>(NumElements))
7440 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7441 // otherwise multiply the amount and the number of elements
7442 else if (Scale != 1) {
7443 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7444 Amt = InsertNewInstBefore(Tmp, AI);
7448 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7449 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7450 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7451 Amt = InsertNewInstBefore(Tmp, AI);
7454 AllocationInst *New;
7455 if (isa<MallocInst>(AI))
7456 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7458 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7459 InsertNewInstBefore(New, AI);
7462 // If the allocation has multiple uses, insert a cast and change all things
7463 // that used it to use the new cast. This will also hack on CI, but it will
7465 if (!AI.hasOneUse()) {
7466 AddUsesToWorkList(AI);
7467 // New is the allocation instruction, pointer typed. AI is the original
7468 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7469 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7470 InsertNewInstBefore(NewCast, AI);
7471 AI.replaceAllUsesWith(NewCast);
7473 return ReplaceInstUsesWith(CI, New);
7476 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7477 /// and return it as type Ty without inserting any new casts and without
7478 /// changing the computed value. This is used by code that tries to decide
7479 /// whether promoting or shrinking integer operations to wider or smaller types
7480 /// will allow us to eliminate a truncate or extend.
7482 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7483 /// extension operation if Ty is larger.
7484 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7486 int &NumCastsRemoved) {
7487 // We can always evaluate constants in another type.
7488 if (isa<ConstantInt>(V))
7491 Instruction *I = dyn_cast<Instruction>(V);
7492 if (!I) return false;
7494 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7496 // If this is an extension or truncate, we can often eliminate it.
7497 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7498 // If this is a cast from the destination type, we can trivially eliminate
7499 // it, and this will remove a cast overall.
7500 if (I->getOperand(0)->getType() == Ty) {
7501 // If the first operand is itself a cast, and is eliminable, do not count
7502 // this as an eliminable cast. We would prefer to eliminate those two
7504 if (!isa<CastInst>(I->getOperand(0)))
7510 // We can't extend or shrink something that has multiple uses: doing so would
7511 // require duplicating the instruction in general, which isn't profitable.
7512 if (!I->hasOneUse()) return false;
7514 switch (I->getOpcode()) {
7515 case Instruction::Add:
7516 case Instruction::Sub:
7517 case Instruction::And:
7518 case Instruction::Or:
7519 case Instruction::Xor:
7520 // These operators can all arbitrarily be extended or truncated.
7521 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7523 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7526 case Instruction::Mul:
7527 // A multiply can be truncated by truncating its operands.
7528 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7529 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7531 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7534 case Instruction::Shl:
7535 // If we are truncating the result of this SHL, and if it's a shift of a
7536 // constant amount, we can always perform a SHL in a smaller type.
7537 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7538 uint32_t BitWidth = Ty->getBitWidth();
7539 if (BitWidth < OrigTy->getBitWidth() &&
7540 CI->getLimitedValue(BitWidth) < BitWidth)
7541 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7545 case Instruction::LShr:
7546 // If this is a truncate of a logical shr, we can truncate it to a smaller
7547 // lshr iff we know that the bits we would otherwise be shifting in are
7549 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7550 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7551 uint32_t BitWidth = Ty->getBitWidth();
7552 if (BitWidth < OrigBitWidth &&
7553 MaskedValueIsZero(I->getOperand(0),
7554 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7555 CI->getLimitedValue(BitWidth) < BitWidth) {
7556 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7561 case Instruction::ZExt:
7562 case Instruction::SExt:
7563 case Instruction::Trunc:
7564 // If this is the same kind of case as our original (e.g. zext+zext), we
7565 // can safely replace it. Note that replacing it does not reduce the number
7566 // of casts in the input.
7567 if (I->getOpcode() == CastOpc)
7572 // TODO: Can handle more cases here.
7579 /// EvaluateInDifferentType - Given an expression that
7580 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7581 /// evaluate the expression.
7582 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7584 if (Constant *C = dyn_cast<Constant>(V))
7585 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7587 // Otherwise, it must be an instruction.
7588 Instruction *I = cast<Instruction>(V);
7589 Instruction *Res = 0;
7590 switch (I->getOpcode()) {
7591 case Instruction::Add:
7592 case Instruction::Sub:
7593 case Instruction::Mul:
7594 case Instruction::And:
7595 case Instruction::Or:
7596 case Instruction::Xor:
7597 case Instruction::AShr:
7598 case Instruction::LShr:
7599 case Instruction::Shl: {
7600 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7601 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7602 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7603 LHS, RHS, I->getName());
7606 case Instruction::Trunc:
7607 case Instruction::ZExt:
7608 case Instruction::SExt:
7609 // If the source type of the cast is the type we're trying for then we can
7610 // just return the source. There's no need to insert it because it is not
7612 if (I->getOperand(0)->getType() == Ty)
7613 return I->getOperand(0);
7615 // Otherwise, must be the same type of case, so just reinsert a new one.
7616 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7620 // TODO: Can handle more cases here.
7621 assert(0 && "Unreachable!");
7625 return InsertNewInstBefore(Res, *I);
7628 /// @brief Implement the transforms common to all CastInst visitors.
7629 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7630 Value *Src = CI.getOperand(0);
7632 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7633 // eliminate it now.
7634 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7635 if (Instruction::CastOps opc =
7636 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7637 // The first cast (CSrc) is eliminable so we need to fix up or replace
7638 // the second cast (CI). CSrc will then have a good chance of being dead.
7639 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7643 // If we are casting a select then fold the cast into the select
7644 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7645 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7648 // If we are casting a PHI then fold the cast into the PHI
7649 if (isa<PHINode>(Src))
7650 if (Instruction *NV = FoldOpIntoPhi(CI))
7656 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7657 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7658 Value *Src = CI.getOperand(0);
7660 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7661 // If casting the result of a getelementptr instruction with no offset, turn
7662 // this into a cast of the original pointer!
7663 if (GEP->hasAllZeroIndices()) {
7664 // Changing the cast operand is usually not a good idea but it is safe
7665 // here because the pointer operand is being replaced with another
7666 // pointer operand so the opcode doesn't need to change.
7668 CI.setOperand(0, GEP->getOperand(0));
7672 // If the GEP has a single use, and the base pointer is a bitcast, and the
7673 // GEP computes a constant offset, see if we can convert these three
7674 // instructions into fewer. This typically happens with unions and other
7675 // non-type-safe code.
7676 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7677 if (GEP->hasAllConstantIndices()) {
7678 // We are guaranteed to get a constant from EmitGEPOffset.
7679 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7680 int64_t Offset = OffsetV->getSExtValue();
7682 // Get the base pointer input of the bitcast, and the type it points to.
7683 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7684 const Type *GEPIdxTy =
7685 cast<PointerType>(OrigBase->getType())->getElementType();
7686 if (GEPIdxTy->isSized()) {
7687 SmallVector<Value*, 8> NewIndices;
7689 // Start with the index over the outer type. Note that the type size
7690 // might be zero (even if the offset isn't zero) if the indexed type
7691 // is something like [0 x {int, int}]
7692 const Type *IntPtrTy = TD->getIntPtrType();
7693 int64_t FirstIdx = 0;
7694 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7695 FirstIdx = Offset/TySize;
7698 // Handle silly modulus not returning values values [0..TySize).
7702 assert(Offset >= 0);
7704 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7707 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7709 // Index into the types. If we fail, set OrigBase to null.
7711 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7712 const StructLayout *SL = TD->getStructLayout(STy);
7713 if (Offset < (int64_t)SL->getSizeInBytes()) {
7714 unsigned Elt = SL->getElementContainingOffset(Offset);
7715 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7717 Offset -= SL->getElementOffset(Elt);
7718 GEPIdxTy = STy->getElementType(Elt);
7720 // Otherwise, we can't index into this, bail out.
7724 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7725 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7726 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7727 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7730 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7732 GEPIdxTy = STy->getElementType();
7734 // Otherwise, we can't index into this, bail out.
7740 // If we were able to index down into an element, create the GEP
7741 // and bitcast the result. This eliminates one bitcast, potentially
7743 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7745 NewIndices.end(), "");
7746 InsertNewInstBefore(NGEP, CI);
7747 NGEP->takeName(GEP);
7749 if (isa<BitCastInst>(CI))
7750 return new BitCastInst(NGEP, CI.getType());
7751 assert(isa<PtrToIntInst>(CI));
7752 return new PtrToIntInst(NGEP, CI.getType());
7759 return commonCastTransforms(CI);
7764 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7765 /// integer types. This function implements the common transforms for all those
7767 /// @brief Implement the transforms common to CastInst with integer operands
7768 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7769 if (Instruction *Result = commonCastTransforms(CI))
7772 Value *Src = CI.getOperand(0);
7773 const Type *SrcTy = Src->getType();
7774 const Type *DestTy = CI.getType();
7775 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7776 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7778 // See if we can simplify any instructions used by the LHS whose sole
7779 // purpose is to compute bits we don't care about.
7780 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7781 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7782 KnownZero, KnownOne))
7785 // If the source isn't an instruction or has more than one use then we
7786 // can't do anything more.
7787 Instruction *SrcI = dyn_cast<Instruction>(Src);
7788 if (!SrcI || !Src->hasOneUse())
7791 // Attempt to propagate the cast into the instruction for int->int casts.
7792 int NumCastsRemoved = 0;
7793 if (!isa<BitCastInst>(CI) &&
7794 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7795 CI.getOpcode(), NumCastsRemoved)) {
7796 // If this cast is a truncate, evaluting in a different type always
7797 // eliminates the cast, so it is always a win. If this is a zero-extension,
7798 // we need to do an AND to maintain the clear top-part of the computation,
7799 // so we require that the input have eliminated at least one cast. If this
7800 // is a sign extension, we insert two new casts (to do the extension) so we
7801 // require that two casts have been eliminated.
7803 switch (CI.getOpcode()) {
7805 // All the others use floating point so we shouldn't actually
7806 // get here because of the check above.
7807 assert(0 && "Unknown cast type");
7808 case Instruction::Trunc:
7811 case Instruction::ZExt:
7812 DoXForm = NumCastsRemoved >= 1;
7814 case Instruction::SExt:
7815 DoXForm = NumCastsRemoved >= 2;
7820 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7821 CI.getOpcode() == Instruction::SExt);
7822 assert(Res->getType() == DestTy);
7823 switch (CI.getOpcode()) {
7824 default: assert(0 && "Unknown cast type!");
7825 case Instruction::Trunc:
7826 case Instruction::BitCast:
7827 // Just replace this cast with the result.
7828 return ReplaceInstUsesWith(CI, Res);
7829 case Instruction::ZExt: {
7830 // We need to emit an AND to clear the high bits.
7831 assert(SrcBitSize < DestBitSize && "Not a zext?");
7832 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7834 return BinaryOperator::CreateAnd(Res, C);
7836 case Instruction::SExt:
7837 // We need to emit a cast to truncate, then a cast to sext.
7838 return CastInst::Create(Instruction::SExt,
7839 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7845 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7846 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7848 switch (SrcI->getOpcode()) {
7849 case Instruction::Add:
7850 case Instruction::Mul:
7851 case Instruction::And:
7852 case Instruction::Or:
7853 case Instruction::Xor:
7854 // If we are discarding information, rewrite.
7855 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7856 // Don't insert two casts if they cannot be eliminated. We allow
7857 // two casts to be inserted if the sizes are the same. This could
7858 // only be converting signedness, which is a noop.
7859 if (DestBitSize == SrcBitSize ||
7860 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7861 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7862 Instruction::CastOps opcode = CI.getOpcode();
7863 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7864 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7865 return BinaryOperator::Create(
7866 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7870 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7871 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7872 SrcI->getOpcode() == Instruction::Xor &&
7873 Op1 == ConstantInt::getTrue() &&
7874 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7875 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7876 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7879 case Instruction::SDiv:
7880 case Instruction::UDiv:
7881 case Instruction::SRem:
7882 case Instruction::URem:
7883 // If we are just changing the sign, rewrite.
7884 if (DestBitSize == SrcBitSize) {
7885 // Don't insert two casts if they cannot be eliminated. We allow
7886 // two casts to be inserted if the sizes are the same. This could
7887 // only be converting signedness, which is a noop.
7888 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7889 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7890 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7892 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7894 return BinaryOperator::Create(
7895 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7900 case Instruction::Shl:
7901 // Allow changing the sign of the source operand. Do not allow
7902 // changing the size of the shift, UNLESS the shift amount is a
7903 // constant. We must not change variable sized shifts to a smaller
7904 // size, because it is undefined to shift more bits out than exist
7906 if (DestBitSize == SrcBitSize ||
7907 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7908 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7909 Instruction::BitCast : Instruction::Trunc);
7910 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7911 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7912 return BinaryOperator::CreateShl(Op0c, Op1c);
7915 case Instruction::AShr:
7916 // If this is a signed shr, and if all bits shifted in are about to be
7917 // truncated off, turn it into an unsigned shr to allow greater
7919 if (DestBitSize < SrcBitSize &&
7920 isa<ConstantInt>(Op1)) {
7921 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7922 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7923 // Insert the new logical shift right.
7924 return BinaryOperator::CreateLShr(Op0, Op1);
7932 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7933 if (Instruction *Result = commonIntCastTransforms(CI))
7936 Value *Src = CI.getOperand(0);
7937 const Type *Ty = CI.getType();
7938 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7939 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7941 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7942 switch (SrcI->getOpcode()) {
7944 case Instruction::LShr:
7945 // We can shrink lshr to something smaller if we know the bits shifted in
7946 // are already zeros.
7947 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7948 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7950 // Get a mask for the bits shifting in.
7951 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7952 Value* SrcIOp0 = SrcI->getOperand(0);
7953 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7954 if (ShAmt >= DestBitWidth) // All zeros.
7955 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7957 // Okay, we can shrink this. Truncate the input, then return a new
7959 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7960 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7962 return BinaryOperator::CreateLShr(V1, V2);
7964 } else { // This is a variable shr.
7966 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7967 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7968 // loop-invariant and CSE'd.
7969 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7970 Value *One = ConstantInt::get(SrcI->getType(), 1);
7972 Value *V = InsertNewInstBefore(
7973 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7975 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7976 SrcI->getOperand(0),
7978 Value *Zero = Constant::getNullValue(V->getType());
7979 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7989 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7990 /// in order to eliminate the icmp.
7991 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7993 // If we are just checking for a icmp eq of a single bit and zext'ing it
7994 // to an integer, then shift the bit to the appropriate place and then
7995 // cast to integer to avoid the comparison.
7996 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7997 const APInt &Op1CV = Op1C->getValue();
7999 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8000 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8001 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8002 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8003 if (!DoXform) return ICI;
8005 Value *In = ICI->getOperand(0);
8006 Value *Sh = ConstantInt::get(In->getType(),
8007 In->getType()->getPrimitiveSizeInBits()-1);
8008 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8009 In->getName()+".lobit"),
8011 if (In->getType() != CI.getType())
8012 In = CastInst::CreateIntegerCast(In, CI.getType(),
8013 false/*ZExt*/, "tmp", &CI);
8015 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8016 Constant *One = ConstantInt::get(In->getType(), 1);
8017 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8018 In->getName()+".not"),
8022 return ReplaceInstUsesWith(CI, In);
8027 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8028 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8029 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8030 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8031 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8032 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8033 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8034 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8035 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8036 // This only works for EQ and NE
8037 ICI->isEquality()) {
8038 // If Op1C some other power of two, convert:
8039 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8040 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8041 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8042 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8044 APInt KnownZeroMask(~KnownZero);
8045 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8046 if (!DoXform) return ICI;
8048 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8049 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8050 // (X&4) == 2 --> false
8051 // (X&4) != 2 --> true
8052 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8053 Res = ConstantExpr::getZExt(Res, CI.getType());
8054 return ReplaceInstUsesWith(CI, Res);
8057 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8058 Value *In = ICI->getOperand(0);
8060 // Perform a logical shr by shiftamt.
8061 // Insert the shift to put the result in the low bit.
8062 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8063 ConstantInt::get(In->getType(), ShiftAmt),
8064 In->getName()+".lobit"), CI);
8067 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8068 Constant *One = ConstantInt::get(In->getType(), 1);
8069 In = BinaryOperator::CreateXor(In, One, "tmp");
8070 InsertNewInstBefore(cast<Instruction>(In), CI);
8073 if (CI.getType() == In->getType())
8074 return ReplaceInstUsesWith(CI, In);
8076 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8084 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8085 // If one of the common conversion will work ..
8086 if (Instruction *Result = commonIntCastTransforms(CI))
8089 Value *Src = CI.getOperand(0);
8091 // If this is a cast of a cast
8092 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8093 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8094 // types and if the sizes are just right we can convert this into a logical
8095 // 'and' which will be much cheaper than the pair of casts.
8096 if (isa<TruncInst>(CSrc)) {
8097 // Get the sizes of the types involved
8098 Value *A = CSrc->getOperand(0);
8099 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8100 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8101 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8102 // If we're actually extending zero bits and the trunc is a no-op
8103 if (MidSize < DstSize && SrcSize == DstSize) {
8104 // Replace both of the casts with an And of the type mask.
8105 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8106 Constant *AndConst = ConstantInt::get(AndValue);
8108 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8109 // Unfortunately, if the type changed, we need to cast it back.
8110 if (And->getType() != CI.getType()) {
8111 And->setName(CSrc->getName()+".mask");
8112 InsertNewInstBefore(And, CI);
8113 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8120 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8121 return transformZExtICmp(ICI, CI);
8123 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8124 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8125 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8126 // of the (zext icmp) will be transformed.
8127 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8128 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8129 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8130 (transformZExtICmp(LHS, CI, false) ||
8131 transformZExtICmp(RHS, CI, false))) {
8132 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8133 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8134 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8141 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8142 if (Instruction *I = commonIntCastTransforms(CI))
8145 Value *Src = CI.getOperand(0);
8147 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8148 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8149 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8150 // If we are just checking for a icmp eq of a single bit and zext'ing it
8151 // to an integer, then shift the bit to the appropriate place and then
8152 // cast to integer to avoid the comparison.
8153 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8154 const APInt &Op1CV = Op1C->getValue();
8156 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8157 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8158 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8159 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8160 Value *In = ICI->getOperand(0);
8161 Value *Sh = ConstantInt::get(In->getType(),
8162 In->getType()->getPrimitiveSizeInBits()-1);
8163 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8164 In->getName()+".lobit"),
8166 if (In->getType() != CI.getType())
8167 In = CastInst::CreateIntegerCast(In, CI.getType(),
8168 true/*SExt*/, "tmp", &CI);
8170 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
8171 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8172 In->getName()+".not"), CI);
8174 return ReplaceInstUsesWith(CI, In);
8179 // See if the value being truncated is already sign extended. If so, just
8180 // eliminate the trunc/sext pair.
8181 if (getOpcode(Src) == Instruction::Trunc) {
8182 Value *Op = cast<User>(Src)->getOperand(0);
8183 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8184 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8185 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8186 unsigned NumSignBits = ComputeNumSignBits(Op);
8188 if (OpBits == DestBits) {
8189 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8190 // bits, it is already ready.
8191 if (NumSignBits > DestBits-MidBits)
8192 return ReplaceInstUsesWith(CI, Op);
8193 } else if (OpBits < DestBits) {
8194 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8195 // bits, just sext from i32.
8196 if (NumSignBits > OpBits-MidBits)
8197 return new SExtInst(Op, CI.getType(), "tmp");
8199 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8200 // bits, just truncate to i32.
8201 if (NumSignBits > OpBits-MidBits)
8202 return new TruncInst(Op, CI.getType(), "tmp");
8209 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8210 /// in the specified FP type without changing its value.
8211 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8212 APFloat F = CFP->getValueAPF();
8213 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
8214 return ConstantFP::get(F);
8218 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8219 /// through it until we get the source value.
8220 static Value *LookThroughFPExtensions(Value *V) {
8221 if (Instruction *I = dyn_cast<Instruction>(V))
8222 if (I->getOpcode() == Instruction::FPExt)
8223 return LookThroughFPExtensions(I->getOperand(0));
8225 // If this value is a constant, return the constant in the smallest FP type
8226 // that can accurately represent it. This allows us to turn
8227 // (float)((double)X+2.0) into x+2.0f.
8228 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8229 if (CFP->getType() == Type::PPC_FP128Ty)
8230 return V; // No constant folding of this.
8231 // See if the value can be truncated to float and then reextended.
8232 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8234 if (CFP->getType() == Type::DoubleTy)
8235 return V; // Won't shrink.
8236 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8238 // Don't try to shrink to various long double types.
8244 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8245 if (Instruction *I = commonCastTransforms(CI))
8248 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8249 // smaller than the destination type, we can eliminate the truncate by doing
8250 // the add as the smaller type. This applies to add/sub/mul/div as well as
8251 // many builtins (sqrt, etc).
8252 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8253 if (OpI && OpI->hasOneUse()) {
8254 switch (OpI->getOpcode()) {
8256 case Instruction::Add:
8257 case Instruction::Sub:
8258 case Instruction::Mul:
8259 case Instruction::FDiv:
8260 case Instruction::FRem:
8261 const Type *SrcTy = OpI->getType();
8262 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8263 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8264 if (LHSTrunc->getType() != SrcTy &&
8265 RHSTrunc->getType() != SrcTy) {
8266 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8267 // If the source types were both smaller than the destination type of
8268 // the cast, do this xform.
8269 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8270 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8271 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8273 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8275 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8284 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8285 return commonCastTransforms(CI);
8288 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8289 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8290 // mantissa to accurately represent all values of X. For example, do not
8291 // do this with i64->float->i64.
8292 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8293 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8294 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8295 SrcI->getType()->getFPMantissaWidth())
8296 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8298 return commonCastTransforms(FI);
8301 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8302 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8303 // mantissa to accurately represent all values of X. For example, do not
8304 // do this with i64->float->i64.
8305 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8306 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8307 (int)FI.getType()->getPrimitiveSizeInBits() <=
8308 SrcI->getType()->getFPMantissaWidth())
8309 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8311 return commonCastTransforms(FI);
8314 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8315 return commonCastTransforms(CI);
8318 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8319 return commonCastTransforms(CI);
8322 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8323 return commonPointerCastTransforms(CI);
8326 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8327 if (Instruction *I = commonCastTransforms(CI))
8330 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8331 if (!DestPointee->isSized()) return 0;
8333 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8336 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8337 m_ConstantInt(Cst)))) {
8338 // If the source and destination operands have the same type, see if this
8339 // is a single-index GEP.
8340 if (X->getType() == CI.getType()) {
8341 // Get the size of the pointee type.
8342 uint64_t Size = TD->getABITypeSize(DestPointee);
8344 // Convert the constant to intptr type.
8345 APInt Offset = Cst->getValue();
8346 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8348 // If Offset is evenly divisible by Size, we can do this xform.
8349 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8350 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8351 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8354 // TODO: Could handle other cases, e.g. where add is indexing into field of
8356 } else if (CI.getOperand(0)->hasOneUse() &&
8357 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8358 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8359 // "inttoptr+GEP" instead of "add+intptr".
8361 // Get the size of the pointee type.
8362 uint64_t Size = TD->getABITypeSize(DestPointee);
8364 // Convert the constant to intptr type.
8365 APInt Offset = Cst->getValue();
8366 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8368 // If Offset is evenly divisible by Size, we can do this xform.
8369 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8370 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8372 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8374 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8380 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8381 // If the operands are integer typed then apply the integer transforms,
8382 // otherwise just apply the common ones.
8383 Value *Src = CI.getOperand(0);
8384 const Type *SrcTy = Src->getType();
8385 const Type *DestTy = CI.getType();
8387 if (SrcTy->isInteger() && DestTy->isInteger()) {
8388 if (Instruction *Result = commonIntCastTransforms(CI))
8390 } else if (isa<PointerType>(SrcTy)) {
8391 if (Instruction *I = commonPointerCastTransforms(CI))
8394 if (Instruction *Result = commonCastTransforms(CI))
8399 // Get rid of casts from one type to the same type. These are useless and can
8400 // be replaced by the operand.
8401 if (DestTy == Src->getType())
8402 return ReplaceInstUsesWith(CI, Src);
8404 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8405 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8406 const Type *DstElTy = DstPTy->getElementType();
8407 const Type *SrcElTy = SrcPTy->getElementType();
8409 // If the address spaces don't match, don't eliminate the bitcast, which is
8410 // required for changing types.
8411 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8414 // If we are casting a malloc or alloca to a pointer to a type of the same
8415 // size, rewrite the allocation instruction to allocate the "right" type.
8416 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8417 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8420 // If the source and destination are pointers, and this cast is equivalent
8421 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8422 // This can enhance SROA and other transforms that want type-safe pointers.
8423 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8424 unsigned NumZeros = 0;
8425 while (SrcElTy != DstElTy &&
8426 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8427 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8428 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8432 // If we found a path from the src to dest, create the getelementptr now.
8433 if (SrcElTy == DstElTy) {
8434 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8435 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8436 ((Instruction*) NULL));
8440 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8441 if (SVI->hasOneUse()) {
8442 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8443 // a bitconvert to a vector with the same # elts.
8444 if (isa<VectorType>(DestTy) &&
8445 cast<VectorType>(DestTy)->getNumElements() ==
8446 SVI->getType()->getNumElements()) {
8448 // If either of the operands is a cast from CI.getType(), then
8449 // evaluating the shuffle in the casted destination's type will allow
8450 // us to eliminate at least one cast.
8451 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8452 Tmp->getOperand(0)->getType() == DestTy) ||
8453 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8454 Tmp->getOperand(0)->getType() == DestTy)) {
8455 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8456 SVI->getOperand(0), DestTy, &CI);
8457 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8458 SVI->getOperand(1), DestTy, &CI);
8459 // Return a new shuffle vector. Use the same element ID's, as we
8460 // know the vector types match #elts.
8461 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8469 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8471 /// %D = select %cond, %C, %A
8473 /// %C = select %cond, %B, 0
8476 /// Assuming that the specified instruction is an operand to the select, return
8477 /// a bitmask indicating which operands of this instruction are foldable if they
8478 /// equal the other incoming value of the select.
8480 static unsigned GetSelectFoldableOperands(Instruction *I) {
8481 switch (I->getOpcode()) {
8482 case Instruction::Add:
8483 case Instruction::Mul:
8484 case Instruction::And:
8485 case Instruction::Or:
8486 case Instruction::Xor:
8487 return 3; // Can fold through either operand.
8488 case Instruction::Sub: // Can only fold on the amount subtracted.
8489 case Instruction::Shl: // Can only fold on the shift amount.
8490 case Instruction::LShr:
8491 case Instruction::AShr:
8494 return 0; // Cannot fold
8498 /// GetSelectFoldableConstant - For the same transformation as the previous
8499 /// function, return the identity constant that goes into the select.
8500 static Constant *GetSelectFoldableConstant(Instruction *I) {
8501 switch (I->getOpcode()) {
8502 default: assert(0 && "This cannot happen!"); abort();
8503 case Instruction::Add:
8504 case Instruction::Sub:
8505 case Instruction::Or:
8506 case Instruction::Xor:
8507 case Instruction::Shl:
8508 case Instruction::LShr:
8509 case Instruction::AShr:
8510 return Constant::getNullValue(I->getType());
8511 case Instruction::And:
8512 return Constant::getAllOnesValue(I->getType());
8513 case Instruction::Mul:
8514 return ConstantInt::get(I->getType(), 1);
8518 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8519 /// have the same opcode and only one use each. Try to simplify this.
8520 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8522 if (TI->getNumOperands() == 1) {
8523 // If this is a non-volatile load or a cast from the same type,
8526 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8529 return 0; // unknown unary op.
8532 // Fold this by inserting a select from the input values.
8533 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8534 FI->getOperand(0), SI.getName()+".v");
8535 InsertNewInstBefore(NewSI, SI);
8536 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
8540 // Only handle binary operators here.
8541 if (!isa<BinaryOperator>(TI))
8544 // Figure out if the operations have any operands in common.
8545 Value *MatchOp, *OtherOpT, *OtherOpF;
8547 if (TI->getOperand(0) == FI->getOperand(0)) {
8548 MatchOp = TI->getOperand(0);
8549 OtherOpT = TI->getOperand(1);
8550 OtherOpF = FI->getOperand(1);
8551 MatchIsOpZero = true;
8552 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8553 MatchOp = TI->getOperand(1);
8554 OtherOpT = TI->getOperand(0);
8555 OtherOpF = FI->getOperand(0);
8556 MatchIsOpZero = false;
8557 } else if (!TI->isCommutative()) {
8559 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8560 MatchOp = TI->getOperand(0);
8561 OtherOpT = TI->getOperand(1);
8562 OtherOpF = FI->getOperand(0);
8563 MatchIsOpZero = true;
8564 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8565 MatchOp = TI->getOperand(1);
8566 OtherOpT = TI->getOperand(0);
8567 OtherOpF = FI->getOperand(1);
8568 MatchIsOpZero = true;
8573 // If we reach here, they do have operations in common.
8574 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8575 OtherOpF, SI.getName()+".v");
8576 InsertNewInstBefore(NewSI, SI);
8578 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8580 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8582 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8584 assert(0 && "Shouldn't get here");
8588 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8589 Value *CondVal = SI.getCondition();
8590 Value *TrueVal = SI.getTrueValue();
8591 Value *FalseVal = SI.getFalseValue();
8593 // select true, X, Y -> X
8594 // select false, X, Y -> Y
8595 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8596 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8598 // select C, X, X -> X
8599 if (TrueVal == FalseVal)
8600 return ReplaceInstUsesWith(SI, TrueVal);
8602 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8603 return ReplaceInstUsesWith(SI, FalseVal);
8604 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8605 return ReplaceInstUsesWith(SI, TrueVal);
8606 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8607 if (isa<Constant>(TrueVal))
8608 return ReplaceInstUsesWith(SI, TrueVal);
8610 return ReplaceInstUsesWith(SI, FalseVal);
8613 if (SI.getType() == Type::Int1Ty) {
8614 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8615 if (C->getZExtValue()) {
8616 // Change: A = select B, true, C --> A = or B, C
8617 return BinaryOperator::CreateOr(CondVal, FalseVal);
8619 // Change: A = select B, false, C --> A = and !B, C
8621 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8622 "not."+CondVal->getName()), SI);
8623 return BinaryOperator::CreateAnd(NotCond, FalseVal);
8625 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8626 if (C->getZExtValue() == false) {
8627 // Change: A = select B, C, false --> A = and B, C
8628 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8630 // Change: A = select B, C, true --> A = or !B, C
8632 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8633 "not."+CondVal->getName()), SI);
8634 return BinaryOperator::CreateOr(NotCond, TrueVal);
8638 // select a, b, a -> a&b
8639 // select a, a, b -> a|b
8640 if (CondVal == TrueVal)
8641 return BinaryOperator::CreateOr(CondVal, FalseVal);
8642 else if (CondVal == FalseVal)
8643 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8646 // Selecting between two integer constants?
8647 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8648 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8649 // select C, 1, 0 -> zext C to int
8650 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8651 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8652 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8653 // select C, 0, 1 -> zext !C to int
8655 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8656 "not."+CondVal->getName()), SI);
8657 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8660 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8662 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8664 // (x <s 0) ? -1 : 0 -> ashr x, 31
8665 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8666 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8667 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8668 // The comparison constant and the result are not neccessarily the
8669 // same width. Make an all-ones value by inserting a AShr.
8670 Value *X = IC->getOperand(0);
8671 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8672 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8673 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8675 InsertNewInstBefore(SRA, SI);
8677 // Finally, convert to the type of the select RHS. We figure out
8678 // if this requires a SExt, Trunc or BitCast based on the sizes.
8679 Instruction::CastOps opc = Instruction::BitCast;
8680 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8681 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8682 if (SRASize < SISize)
8683 opc = Instruction::SExt;
8684 else if (SRASize > SISize)
8685 opc = Instruction::Trunc;
8686 return CastInst::Create(opc, SRA, SI.getType());
8691 // If one of the constants is zero (we know they can't both be) and we
8692 // have an icmp instruction with zero, and we have an 'and' with the
8693 // non-constant value, eliminate this whole mess. This corresponds to
8694 // cases like this: ((X & 27) ? 27 : 0)
8695 if (TrueValC->isZero() || FalseValC->isZero())
8696 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8697 cast<Constant>(IC->getOperand(1))->isNullValue())
8698 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8699 if (ICA->getOpcode() == Instruction::And &&
8700 isa<ConstantInt>(ICA->getOperand(1)) &&
8701 (ICA->getOperand(1) == TrueValC ||
8702 ICA->getOperand(1) == FalseValC) &&
8703 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8704 // Okay, now we know that everything is set up, we just don't
8705 // know whether we have a icmp_ne or icmp_eq and whether the
8706 // true or false val is the zero.
8707 bool ShouldNotVal = !TrueValC->isZero();
8708 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8711 V = InsertNewInstBefore(BinaryOperator::Create(
8712 Instruction::Xor, V, ICA->getOperand(1)), SI);
8713 return ReplaceInstUsesWith(SI, V);
8718 // See if we are selecting two values based on a comparison of the two values.
8719 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8720 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8721 // Transform (X == Y) ? X : Y -> Y
8722 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8723 // This is not safe in general for floating point:
8724 // consider X== -0, Y== +0.
8725 // It becomes safe if either operand is a nonzero constant.
8726 ConstantFP *CFPt, *CFPf;
8727 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8728 !CFPt->getValueAPF().isZero()) ||
8729 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8730 !CFPf->getValueAPF().isZero()))
8731 return ReplaceInstUsesWith(SI, FalseVal);
8733 // Transform (X != Y) ? X : Y -> X
8734 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8735 return ReplaceInstUsesWith(SI, TrueVal);
8736 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8738 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8739 // Transform (X == Y) ? Y : X -> X
8740 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8741 // This is not safe in general for floating point:
8742 // consider X== -0, Y== +0.
8743 // It becomes safe if either operand is a nonzero constant.
8744 ConstantFP *CFPt, *CFPf;
8745 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8746 !CFPt->getValueAPF().isZero()) ||
8747 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8748 !CFPf->getValueAPF().isZero()))
8749 return ReplaceInstUsesWith(SI, FalseVal);
8751 // Transform (X != Y) ? Y : X -> Y
8752 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8753 return ReplaceInstUsesWith(SI, TrueVal);
8754 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8758 // See if we are selecting two values based on a comparison of the two values.
8759 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8760 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8761 // Transform (X == Y) ? X : Y -> Y
8762 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8763 return ReplaceInstUsesWith(SI, FalseVal);
8764 // Transform (X != Y) ? X : Y -> X
8765 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8766 return ReplaceInstUsesWith(SI, TrueVal);
8767 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8769 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8770 // Transform (X == Y) ? Y : X -> X
8771 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8772 return ReplaceInstUsesWith(SI, FalseVal);
8773 // Transform (X != Y) ? Y : X -> Y
8774 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8775 return ReplaceInstUsesWith(SI, TrueVal);
8776 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8780 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8781 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8782 if (TI->hasOneUse() && FI->hasOneUse()) {
8783 Instruction *AddOp = 0, *SubOp = 0;
8785 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8786 if (TI->getOpcode() == FI->getOpcode())
8787 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8790 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8791 // even legal for FP.
8792 if (TI->getOpcode() == Instruction::Sub &&
8793 FI->getOpcode() == Instruction::Add) {
8794 AddOp = FI; SubOp = TI;
8795 } else if (FI->getOpcode() == Instruction::Sub &&
8796 TI->getOpcode() == Instruction::Add) {
8797 AddOp = TI; SubOp = FI;
8801 Value *OtherAddOp = 0;
8802 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8803 OtherAddOp = AddOp->getOperand(1);
8804 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8805 OtherAddOp = AddOp->getOperand(0);
8809 // So at this point we know we have (Y -> OtherAddOp):
8810 // select C, (add X, Y), (sub X, Z)
8811 Value *NegVal; // Compute -Z
8812 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8813 NegVal = ConstantExpr::getNeg(C);
8815 NegVal = InsertNewInstBefore(
8816 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8819 Value *NewTrueOp = OtherAddOp;
8820 Value *NewFalseOp = NegVal;
8822 std::swap(NewTrueOp, NewFalseOp);
8823 Instruction *NewSel =
8824 SelectInst::Create(CondVal, NewTrueOp,
8825 NewFalseOp, SI.getName() + ".p");
8827 NewSel = InsertNewInstBefore(NewSel, SI);
8828 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8833 // See if we can fold the select into one of our operands.
8834 if (SI.getType()->isInteger()) {
8835 // See the comment above GetSelectFoldableOperands for a description of the
8836 // transformation we are doing here.
8837 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8838 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8839 !isa<Constant>(FalseVal))
8840 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8841 unsigned OpToFold = 0;
8842 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8844 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8849 Constant *C = GetSelectFoldableConstant(TVI);
8850 Instruction *NewSel =
8851 SelectInst::Create(SI.getCondition(),
8852 TVI->getOperand(2-OpToFold), C);
8853 InsertNewInstBefore(NewSel, SI);
8854 NewSel->takeName(TVI);
8855 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8856 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8858 assert(0 && "Unknown instruction!!");
8863 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8864 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8865 !isa<Constant>(TrueVal))
8866 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8867 unsigned OpToFold = 0;
8868 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8870 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8875 Constant *C = GetSelectFoldableConstant(FVI);
8876 Instruction *NewSel =
8877 SelectInst::Create(SI.getCondition(), C,
8878 FVI->getOperand(2-OpToFold));
8879 InsertNewInstBefore(NewSel, SI);
8880 NewSel->takeName(FVI);
8881 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8882 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8884 assert(0 && "Unknown instruction!!");
8889 if (BinaryOperator::isNot(CondVal)) {
8890 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8891 SI.setOperand(1, FalseVal);
8892 SI.setOperand(2, TrueVal);
8899 /// EnforceKnownAlignment - If the specified pointer points to an object that
8900 /// we control, modify the object's alignment to PrefAlign. This isn't
8901 /// often possible though. If alignment is important, a more reliable approach
8902 /// is to simply align all global variables and allocation instructions to
8903 /// their preferred alignment from the beginning.
8905 static unsigned EnforceKnownAlignment(Value *V,
8906 unsigned Align, unsigned PrefAlign) {
8908 User *U = dyn_cast<User>(V);
8909 if (!U) return Align;
8911 switch (getOpcode(U)) {
8913 case Instruction::BitCast:
8914 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8915 case Instruction::GetElementPtr: {
8916 // If all indexes are zero, it is just the alignment of the base pointer.
8917 bool AllZeroOperands = true;
8918 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8919 if (!isa<Constant>(U->getOperand(i)) ||
8920 !cast<Constant>(U->getOperand(i))->isNullValue()) {
8921 AllZeroOperands = false;
8925 if (AllZeroOperands) {
8926 // Treat this like a bitcast.
8927 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8933 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8934 // If there is a large requested alignment and we can, bump up the alignment
8936 if (!GV->isDeclaration()) {
8937 GV->setAlignment(PrefAlign);
8940 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8941 // If there is a requested alignment and if this is an alloca, round up. We
8942 // don't do this for malloc, because some systems can't respect the request.
8943 if (isa<AllocaInst>(AI)) {
8944 AI->setAlignment(PrefAlign);
8952 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8953 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8954 /// and it is more than the alignment of the ultimate object, see if we can
8955 /// increase the alignment of the ultimate object, making this check succeed.
8956 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8957 unsigned PrefAlign) {
8958 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8959 sizeof(PrefAlign) * CHAR_BIT;
8960 APInt Mask = APInt::getAllOnesValue(BitWidth);
8961 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8962 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8963 unsigned TrailZ = KnownZero.countTrailingOnes();
8964 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8966 if (PrefAlign > Align)
8967 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8969 // We don't need to make any adjustment.
8973 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8974 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8975 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8976 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8977 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8979 if (CopyAlign < MinAlign) {
8980 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8984 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8986 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8987 if (MemOpLength == 0) return 0;
8989 // Source and destination pointer types are always "i8*" for intrinsic. See
8990 // if the size is something we can handle with a single primitive load/store.
8991 // A single load+store correctly handles overlapping memory in the memmove
8993 unsigned Size = MemOpLength->getZExtValue();
8994 if (Size == 0) return MI; // Delete this mem transfer.
8996 if (Size > 8 || (Size&(Size-1)))
8997 return 0; // If not 1/2/4/8 bytes, exit.
8999 // Use an integer load+store unless we can find something better.
9000 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9002 // Memcpy forces the use of i8* for the source and destination. That means
9003 // that if you're using memcpy to move one double around, you'll get a cast
9004 // from double* to i8*. We'd much rather use a double load+store rather than
9005 // an i64 load+store, here because this improves the odds that the source or
9006 // dest address will be promotable. See if we can find a better type than the
9007 // integer datatype.
9008 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9009 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9010 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9011 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9012 // down through these levels if so.
9013 while (!SrcETy->isSingleValueType()) {
9014 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9015 if (STy->getNumElements() == 1)
9016 SrcETy = STy->getElementType(0);
9019 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9020 if (ATy->getNumElements() == 1)
9021 SrcETy = ATy->getElementType();
9028 if (SrcETy->isSingleValueType())
9029 NewPtrTy = PointerType::getUnqual(SrcETy);
9034 // If the memcpy/memmove provides better alignment info than we can
9036 SrcAlign = std::max(SrcAlign, CopyAlign);
9037 DstAlign = std::max(DstAlign, CopyAlign);
9039 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9040 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9041 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9042 InsertNewInstBefore(L, *MI);
9043 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9045 // Set the size of the copy to 0, it will be deleted on the next iteration.
9046 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9050 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9051 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9052 if (MI->getAlignment()->getZExtValue() < Alignment) {
9053 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9057 // Extract the length and alignment and fill if they are constant.
9058 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9059 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9060 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9062 uint64_t Len = LenC->getZExtValue();
9063 Alignment = MI->getAlignment()->getZExtValue();
9065 // If the length is zero, this is a no-op
9066 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9068 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9069 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9070 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9072 Value *Dest = MI->getDest();
9073 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9075 // Alignment 0 is identity for alignment 1 for memset, but not store.
9076 if (Alignment == 0) Alignment = 1;
9078 // Extract the fill value and store.
9079 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9080 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9083 // Set the size of the copy to 0, it will be deleted on the next iteration.
9084 MI->setLength(Constant::getNullValue(LenC->getType()));
9092 /// visitCallInst - CallInst simplification. This mostly only handles folding
9093 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9094 /// the heavy lifting.
9096 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9097 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9098 if (!II) return visitCallSite(&CI);
9100 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9102 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9103 bool Changed = false;
9105 // memmove/cpy/set of zero bytes is a noop.
9106 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9107 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9109 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9110 if (CI->getZExtValue() == 1) {
9111 // Replace the instruction with just byte operations. We would
9112 // transform other cases to loads/stores, but we don't know if
9113 // alignment is sufficient.
9117 // If we have a memmove and the source operation is a constant global,
9118 // then the source and dest pointers can't alias, so we can change this
9119 // into a call to memcpy.
9120 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9121 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9122 if (GVSrc->isConstant()) {
9123 Module *M = CI.getParent()->getParent()->getParent();
9124 Intrinsic::ID MemCpyID;
9125 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9126 MemCpyID = Intrinsic::memcpy_i32;
9128 MemCpyID = Intrinsic::memcpy_i64;
9129 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
9134 // If we can determine a pointer alignment that is bigger than currently
9135 // set, update the alignment.
9136 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9137 if (Instruction *I = SimplifyMemTransfer(MI))
9139 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9140 if (Instruction *I = SimplifyMemSet(MSI))
9144 if (Changed) return II;
9146 switch (II->getIntrinsicID()) {
9148 case Intrinsic::ppc_altivec_lvx:
9149 case Intrinsic::ppc_altivec_lvxl:
9150 case Intrinsic::x86_sse_loadu_ps:
9151 case Intrinsic::x86_sse2_loadu_pd:
9152 case Intrinsic::x86_sse2_loadu_dq:
9153 // Turn PPC lvx -> load if the pointer is known aligned.
9154 // Turn X86 loadups -> load if the pointer is known aligned.
9155 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9156 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9157 PointerType::getUnqual(II->getType()),
9159 return new LoadInst(Ptr);
9162 case Intrinsic::ppc_altivec_stvx:
9163 case Intrinsic::ppc_altivec_stvxl:
9164 // Turn stvx -> store if the pointer is known aligned.
9165 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9166 const Type *OpPtrTy =
9167 PointerType::getUnqual(II->getOperand(1)->getType());
9168 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9169 return new StoreInst(II->getOperand(1), Ptr);
9172 case Intrinsic::x86_sse_storeu_ps:
9173 case Intrinsic::x86_sse2_storeu_pd:
9174 case Intrinsic::x86_sse2_storeu_dq:
9175 case Intrinsic::x86_sse2_storel_dq:
9176 // Turn X86 storeu -> store if the pointer is known aligned.
9177 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9178 const Type *OpPtrTy =
9179 PointerType::getUnqual(II->getOperand(2)->getType());
9180 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9181 return new StoreInst(II->getOperand(2), Ptr);
9185 case Intrinsic::x86_sse_cvttss2si: {
9186 // These intrinsics only demands the 0th element of its input vector. If
9187 // we can simplify the input based on that, do so now.
9189 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9191 II->setOperand(1, V);
9197 case Intrinsic::ppc_altivec_vperm:
9198 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9199 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9200 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9202 // Check that all of the elements are integer constants or undefs.
9203 bool AllEltsOk = true;
9204 for (unsigned i = 0; i != 16; ++i) {
9205 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9206 !isa<UndefValue>(Mask->getOperand(i))) {
9213 // Cast the input vectors to byte vectors.
9214 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9215 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9216 Value *Result = UndefValue::get(Op0->getType());
9218 // Only extract each element once.
9219 Value *ExtractedElts[32];
9220 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9222 for (unsigned i = 0; i != 16; ++i) {
9223 if (isa<UndefValue>(Mask->getOperand(i)))
9225 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9226 Idx &= 31; // Match the hardware behavior.
9228 if (ExtractedElts[Idx] == 0) {
9230 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9231 InsertNewInstBefore(Elt, CI);
9232 ExtractedElts[Idx] = Elt;
9235 // Insert this value into the result vector.
9236 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9238 InsertNewInstBefore(cast<Instruction>(Result), CI);
9240 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9245 case Intrinsic::stackrestore: {
9246 // If the save is right next to the restore, remove the restore. This can
9247 // happen when variable allocas are DCE'd.
9248 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9249 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9250 BasicBlock::iterator BI = SS;
9252 return EraseInstFromFunction(CI);
9256 // Scan down this block to see if there is another stack restore in the
9257 // same block without an intervening call/alloca.
9258 BasicBlock::iterator BI = II;
9259 TerminatorInst *TI = II->getParent()->getTerminator();
9260 bool CannotRemove = false;
9261 for (++BI; &*BI != TI; ++BI) {
9262 if (isa<AllocaInst>(BI)) {
9263 CannotRemove = true;
9266 if (isa<CallInst>(BI)) {
9267 if (!isa<IntrinsicInst>(BI)) {
9268 CannotRemove = true;
9271 // If there is a stackrestore below this one, remove this one.
9272 return EraseInstFromFunction(CI);
9276 // If the stack restore is in a return/unwind block and if there are no
9277 // allocas or calls between the restore and the return, nuke the restore.
9278 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9279 return EraseInstFromFunction(CI);
9285 return visitCallSite(II);
9288 // InvokeInst simplification
9290 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9291 return visitCallSite(&II);
9294 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9295 /// passed through the varargs area, we can eliminate the use of the cast.
9296 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9297 const CastInst * const CI,
9298 const TargetData * const TD,
9300 if (!CI->isLosslessCast())
9303 // The size of ByVal arguments is derived from the type, so we
9304 // can't change to a type with a different size. If the size were
9305 // passed explicitly we could avoid this check.
9306 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9310 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9311 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9312 if (!SrcTy->isSized() || !DstTy->isSized())
9314 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9319 // visitCallSite - Improvements for call and invoke instructions.
9321 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9322 bool Changed = false;
9324 // If the callee is a constexpr cast of a function, attempt to move the cast
9325 // to the arguments of the call/invoke.
9326 if (transformConstExprCastCall(CS)) return 0;
9328 Value *Callee = CS.getCalledValue();
9330 if (Function *CalleeF = dyn_cast<Function>(Callee))
9331 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9332 Instruction *OldCall = CS.getInstruction();
9333 // If the call and callee calling conventions don't match, this call must
9334 // be unreachable, as the call is undefined.
9335 new StoreInst(ConstantInt::getTrue(),
9336 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9338 if (!OldCall->use_empty())
9339 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9340 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9341 return EraseInstFromFunction(*OldCall);
9345 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9346 // This instruction is not reachable, just remove it. We insert a store to
9347 // undef so that we know that this code is not reachable, despite the fact
9348 // that we can't modify the CFG here.
9349 new StoreInst(ConstantInt::getTrue(),
9350 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9351 CS.getInstruction());
9353 if (!CS.getInstruction()->use_empty())
9354 CS.getInstruction()->
9355 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9357 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9358 // Don't break the CFG, insert a dummy cond branch.
9359 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9360 ConstantInt::getTrue(), II);
9362 return EraseInstFromFunction(*CS.getInstruction());
9365 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9366 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9367 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9368 return transformCallThroughTrampoline(CS);
9370 const PointerType *PTy = cast<PointerType>(Callee->getType());
9371 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9372 if (FTy->isVarArg()) {
9373 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9374 // See if we can optimize any arguments passed through the varargs area of
9376 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9377 E = CS.arg_end(); I != E; ++I, ++ix) {
9378 CastInst *CI = dyn_cast<CastInst>(*I);
9379 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9380 *I = CI->getOperand(0);
9386 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9387 // Inline asm calls cannot throw - mark them 'nounwind'.
9388 CS.setDoesNotThrow();
9392 return Changed ? CS.getInstruction() : 0;
9395 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9396 // attempt to move the cast to the arguments of the call/invoke.
9398 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9399 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9400 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9401 if (CE->getOpcode() != Instruction::BitCast ||
9402 !isa<Function>(CE->getOperand(0)))
9404 Function *Callee = cast<Function>(CE->getOperand(0));
9405 Instruction *Caller = CS.getInstruction();
9406 const PAListPtr &CallerPAL = CS.getParamAttrs();
9408 // Okay, this is a cast from a function to a different type. Unless doing so
9409 // would cause a type conversion of one of our arguments, change this call to
9410 // be a direct call with arguments casted to the appropriate types.
9412 const FunctionType *FT = Callee->getFunctionType();
9413 const Type *OldRetTy = Caller->getType();
9415 if (isa<StructType>(FT->getReturnType()))
9416 return false; // TODO: Handle multiple return values.
9418 // Check to see if we are changing the return type...
9419 if (OldRetTy != FT->getReturnType()) {
9420 if (Callee->isDeclaration() &&
9421 // Conversion is ok if changing from pointer to int of same size.
9422 !(isa<PointerType>(FT->getReturnType()) &&
9423 TD->getIntPtrType() == OldRetTy))
9424 return false; // Cannot transform this return value.
9426 if (!Caller->use_empty() &&
9427 // void -> non-void is handled specially
9428 FT->getReturnType() != Type::VoidTy &&
9429 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
9430 return false; // Cannot transform this return value.
9432 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9433 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9434 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9435 return false; // Attribute not compatible with transformed value.
9438 // If the callsite is an invoke instruction, and the return value is used by
9439 // a PHI node in a successor, we cannot change the return type of the call
9440 // because there is no place to put the cast instruction (without breaking
9441 // the critical edge). Bail out in this case.
9442 if (!Caller->use_empty())
9443 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9444 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9446 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9447 if (PN->getParent() == II->getNormalDest() ||
9448 PN->getParent() == II->getUnwindDest())
9452 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9453 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9455 CallSite::arg_iterator AI = CS.arg_begin();
9456 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9457 const Type *ParamTy = FT->getParamType(i);
9458 const Type *ActTy = (*AI)->getType();
9460 if (!CastInst::isCastable(ActTy, ParamTy))
9461 return false; // Cannot transform this parameter value.
9463 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9464 return false; // Attribute not compatible with transformed value.
9466 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
9467 // Some conversions are safe even if we do not have a body.
9468 // Either we can cast directly, or we can upconvert the argument
9469 bool isConvertible = ActTy == ParamTy ||
9470 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9471 (ParamTy->isInteger() && ActTy->isInteger() &&
9472 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9473 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9474 && c->getValue().isStrictlyPositive());
9475 if (Callee->isDeclaration() && !isConvertible) return false;
9478 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9479 Callee->isDeclaration())
9480 return false; // Do not delete arguments unless we have a function body.
9482 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9483 !CallerPAL.isEmpty())
9484 // In this case we have more arguments than the new function type, but we
9485 // won't be dropping them. Check that these extra arguments have attributes
9486 // that are compatible with being a vararg call argument.
9487 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9488 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9490 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9491 if (PAttrs & ParamAttr::VarArgsIncompatible)
9495 // Okay, we decided that this is a safe thing to do: go ahead and start
9496 // inserting cast instructions as necessary...
9497 std::vector<Value*> Args;
9498 Args.reserve(NumActualArgs);
9499 SmallVector<ParamAttrsWithIndex, 8> attrVec;
9500 attrVec.reserve(NumCommonArgs);
9502 // Get any return attributes.
9503 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9505 // If the return value is not being used, the type may not be compatible
9506 // with the existing attributes. Wipe out any problematic attributes.
9507 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
9509 // Add the new return attributes.
9511 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9513 AI = CS.arg_begin();
9514 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9515 const Type *ParamTy = FT->getParamType(i);
9516 if ((*AI)->getType() == ParamTy) {
9517 Args.push_back(*AI);
9519 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9520 false, ParamTy, false);
9521 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9522 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9525 // Add any parameter attributes.
9526 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9527 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9530 // If the function takes more arguments than the call was taking, add them
9532 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9533 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9535 // If we are removing arguments to the function, emit an obnoxious warning...
9536 if (FT->getNumParams() < NumActualArgs) {
9537 if (!FT->isVarArg()) {
9538 cerr << "WARNING: While resolving call to function '"
9539 << Callee->getName() << "' arguments were dropped!\n";
9541 // Add all of the arguments in their promoted form to the arg list...
9542 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9543 const Type *PTy = getPromotedType((*AI)->getType());
9544 if (PTy != (*AI)->getType()) {
9545 // Must promote to pass through va_arg area!
9546 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9548 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9549 InsertNewInstBefore(Cast, *Caller);
9550 Args.push_back(Cast);
9552 Args.push_back(*AI);
9555 // Add any parameter attributes.
9556 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9557 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9562 if (FT->getReturnType() == Type::VoidTy)
9563 Caller->setName(""); // Void type should not have a name.
9565 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9568 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9569 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9570 Args.begin(), Args.end(),
9571 Caller->getName(), Caller);
9572 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9573 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9575 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9576 Caller->getName(), Caller);
9577 CallInst *CI = cast<CallInst>(Caller);
9578 if (CI->isTailCall())
9579 cast<CallInst>(NC)->setTailCall();
9580 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9581 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9584 // Insert a cast of the return type as necessary.
9586 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9587 if (NV->getType() != Type::VoidTy) {
9588 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
9590 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9592 // If this is an invoke instruction, we should insert it after the first
9593 // non-phi, instruction in the normal successor block.
9594 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9595 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9596 InsertNewInstBefore(NC, *I);
9598 // Otherwise, it's a call, just insert cast right after the call instr
9599 InsertNewInstBefore(NC, *Caller);
9601 AddUsersToWorkList(*Caller);
9603 NV = UndefValue::get(Caller->getType());
9607 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9608 Caller->replaceAllUsesWith(NV);
9609 Caller->eraseFromParent();
9610 RemoveFromWorkList(Caller);
9614 // transformCallThroughTrampoline - Turn a call to a function created by the
9615 // init_trampoline intrinsic into a direct call to the underlying function.
9617 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9618 Value *Callee = CS.getCalledValue();
9619 const PointerType *PTy = cast<PointerType>(Callee->getType());
9620 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9621 const PAListPtr &Attrs = CS.getParamAttrs();
9623 // If the call already has the 'nest' attribute somewhere then give up -
9624 // otherwise 'nest' would occur twice after splicing in the chain.
9625 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9628 IntrinsicInst *Tramp =
9629 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9631 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9632 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9633 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9635 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9636 if (!NestAttrs.isEmpty()) {
9637 unsigned NestIdx = 1;
9638 const Type *NestTy = 0;
9639 ParameterAttributes NestAttr = ParamAttr::None;
9641 // Look for a parameter marked with the 'nest' attribute.
9642 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9643 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9644 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9645 // Record the parameter type and any other attributes.
9647 NestAttr = NestAttrs.getParamAttrs(NestIdx);
9652 Instruction *Caller = CS.getInstruction();
9653 std::vector<Value*> NewArgs;
9654 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9656 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9657 NewAttrs.reserve(Attrs.getNumSlots() + 1);
9659 // Insert the nest argument into the call argument list, which may
9660 // mean appending it. Likewise for attributes.
9662 // Add any function result attributes.
9663 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9664 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9668 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9670 if (Idx == NestIdx) {
9671 // Add the chain argument and attributes.
9672 Value *NestVal = Tramp->getOperand(3);
9673 if (NestVal->getType() != NestTy)
9674 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9675 NewArgs.push_back(NestVal);
9676 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9682 // Add the original argument and attributes.
9683 NewArgs.push_back(*I);
9684 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9686 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9692 // The trampoline may have been bitcast to a bogus type (FTy).
9693 // Handle this by synthesizing a new function type, equal to FTy
9694 // with the chain parameter inserted.
9696 std::vector<const Type*> NewTypes;
9697 NewTypes.reserve(FTy->getNumParams()+1);
9699 // Insert the chain's type into the list of parameter types, which may
9700 // mean appending it.
9703 FunctionType::param_iterator I = FTy->param_begin(),
9704 E = FTy->param_end();
9708 // Add the chain's type.
9709 NewTypes.push_back(NestTy);
9714 // Add the original type.
9715 NewTypes.push_back(*I);
9721 // Replace the trampoline call with a direct call. Let the generic
9722 // code sort out any function type mismatches.
9723 FunctionType *NewFTy =
9724 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9725 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9726 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9727 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9729 Instruction *NewCaller;
9730 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9731 NewCaller = InvokeInst::Create(NewCallee,
9732 II->getNormalDest(), II->getUnwindDest(),
9733 NewArgs.begin(), NewArgs.end(),
9734 Caller->getName(), Caller);
9735 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9736 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9738 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9739 Caller->getName(), Caller);
9740 if (cast<CallInst>(Caller)->isTailCall())
9741 cast<CallInst>(NewCaller)->setTailCall();
9742 cast<CallInst>(NewCaller)->
9743 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9744 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9746 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9747 Caller->replaceAllUsesWith(NewCaller);
9748 Caller->eraseFromParent();
9749 RemoveFromWorkList(Caller);
9754 // Replace the trampoline call with a direct call. Since there is no 'nest'
9755 // parameter, there is no need to adjust the argument list. Let the generic
9756 // code sort out any function type mismatches.
9757 Constant *NewCallee =
9758 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9759 CS.setCalledFunction(NewCallee);
9760 return CS.getInstruction();
9763 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9764 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9765 /// and a single binop.
9766 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9767 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9768 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9769 isa<CmpInst>(FirstInst));
9770 unsigned Opc = FirstInst->getOpcode();
9771 Value *LHSVal = FirstInst->getOperand(0);
9772 Value *RHSVal = FirstInst->getOperand(1);
9774 const Type *LHSType = LHSVal->getType();
9775 const Type *RHSType = RHSVal->getType();
9777 // Scan to see if all operands are the same opcode, all have one use, and all
9778 // kill their operands (i.e. the operands have one use).
9779 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9780 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9781 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9782 // Verify type of the LHS matches so we don't fold cmp's of different
9783 // types or GEP's with different index types.
9784 I->getOperand(0)->getType() != LHSType ||
9785 I->getOperand(1)->getType() != RHSType)
9788 // If they are CmpInst instructions, check their predicates
9789 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9790 if (cast<CmpInst>(I)->getPredicate() !=
9791 cast<CmpInst>(FirstInst)->getPredicate())
9794 // Keep track of which operand needs a phi node.
9795 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9796 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9799 // Otherwise, this is safe to transform, determine if it is profitable.
9801 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9802 // Indexes are often folded into load/store instructions, so we don't want to
9803 // hide them behind a phi.
9804 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9807 Value *InLHS = FirstInst->getOperand(0);
9808 Value *InRHS = FirstInst->getOperand(1);
9809 PHINode *NewLHS = 0, *NewRHS = 0;
9811 NewLHS = PHINode::Create(LHSType,
9812 FirstInst->getOperand(0)->getName() + ".pn");
9813 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9814 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9815 InsertNewInstBefore(NewLHS, PN);
9820 NewRHS = PHINode::Create(RHSType,
9821 FirstInst->getOperand(1)->getName() + ".pn");
9822 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9823 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9824 InsertNewInstBefore(NewRHS, PN);
9828 // Add all operands to the new PHIs.
9829 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9831 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9832 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9835 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9836 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9840 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9841 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9842 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9843 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9846 assert(isa<GetElementPtrInst>(FirstInst));
9847 return GetElementPtrInst::Create(LHSVal, RHSVal);
9851 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9852 /// of the block that defines it. This means that it must be obvious the value
9853 /// of the load is not changed from the point of the load to the end of the
9856 /// Finally, it is safe, but not profitable, to sink a load targetting a
9857 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
9859 static bool isSafeToSinkLoad(LoadInst *L) {
9860 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9862 for (++BBI; BBI != E; ++BBI)
9863 if (BBI->mayWriteToMemory())
9866 // Check for non-address taken alloca. If not address-taken already, it isn't
9867 // profitable to do this xform.
9868 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9869 bool isAddressTaken = false;
9870 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9872 if (isa<LoadInst>(UI)) continue;
9873 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9874 // If storing TO the alloca, then the address isn't taken.
9875 if (SI->getOperand(1) == AI) continue;
9877 isAddressTaken = true;
9881 if (!isAddressTaken)
9889 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9890 // operator and they all are only used by the PHI, PHI together their
9891 // inputs, and do the operation once, to the result of the PHI.
9892 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9893 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9895 // Scan the instruction, looking for input operations that can be folded away.
9896 // If all input operands to the phi are the same instruction (e.g. a cast from
9897 // the same type or "+42") we can pull the operation through the PHI, reducing
9898 // code size and simplifying code.
9899 Constant *ConstantOp = 0;
9900 const Type *CastSrcTy = 0;
9901 bool isVolatile = false;
9902 if (isa<CastInst>(FirstInst)) {
9903 CastSrcTy = FirstInst->getOperand(0)->getType();
9904 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9905 // Can fold binop, compare or shift here if the RHS is a constant,
9906 // otherwise call FoldPHIArgBinOpIntoPHI.
9907 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9908 if (ConstantOp == 0)
9909 return FoldPHIArgBinOpIntoPHI(PN);
9910 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9911 isVolatile = LI->isVolatile();
9912 // We can't sink the load if the loaded value could be modified between the
9913 // load and the PHI.
9914 if (LI->getParent() != PN.getIncomingBlock(0) ||
9915 !isSafeToSinkLoad(LI))
9917 } else if (isa<GetElementPtrInst>(FirstInst)) {
9918 if (FirstInst->getNumOperands() == 2)
9919 return FoldPHIArgBinOpIntoPHI(PN);
9920 // Can't handle general GEPs yet.
9923 return 0; // Cannot fold this operation.
9926 // Check to see if all arguments are the same operation.
9927 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9928 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9929 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9930 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9933 if (I->getOperand(0)->getType() != CastSrcTy)
9934 return 0; // Cast operation must match.
9935 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9936 // We can't sink the load if the loaded value could be modified between
9937 // the load and the PHI.
9938 if (LI->isVolatile() != isVolatile ||
9939 LI->getParent() != PN.getIncomingBlock(i) ||
9940 !isSafeToSinkLoad(LI))
9943 // If the PHI is volatile and its block has multiple successors, sinking
9944 // it would remove a load of the volatile value from the path through the
9947 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9951 } else if (I->getOperand(1) != ConstantOp) {
9956 // Okay, they are all the same operation. Create a new PHI node of the
9957 // correct type, and PHI together all of the LHS's of the instructions.
9958 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9959 PN.getName()+".in");
9960 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9962 Value *InVal = FirstInst->getOperand(0);
9963 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9965 // Add all operands to the new PHI.
9966 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9967 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9968 if (NewInVal != InVal)
9970 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9975 // The new PHI unions all of the same values together. This is really
9976 // common, so we handle it intelligently here for compile-time speed.
9980 InsertNewInstBefore(NewPN, PN);
9984 // Insert and return the new operation.
9985 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9986 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9987 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9988 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9989 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9990 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
9991 PhiVal, ConstantOp);
9992 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9994 // If this was a volatile load that we are merging, make sure to loop through
9995 // and mark all the input loads as non-volatile. If we don't do this, we will
9996 // insert a new volatile load and the old ones will not be deletable.
9998 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9999 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10001 return new LoadInst(PhiVal, "", isVolatile);
10004 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10006 static bool DeadPHICycle(PHINode *PN,
10007 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10008 if (PN->use_empty()) return true;
10009 if (!PN->hasOneUse()) return false;
10011 // Remember this node, and if we find the cycle, return.
10012 if (!PotentiallyDeadPHIs.insert(PN))
10015 // Don't scan crazily complex things.
10016 if (PotentiallyDeadPHIs.size() == 16)
10019 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10020 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10025 /// PHIsEqualValue - Return true if this phi node is always equal to
10026 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10027 /// z = some value; x = phi (y, z); y = phi (x, z)
10028 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10029 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10030 // See if we already saw this PHI node.
10031 if (!ValueEqualPHIs.insert(PN))
10034 // Don't scan crazily complex things.
10035 if (ValueEqualPHIs.size() == 16)
10038 // Scan the operands to see if they are either phi nodes or are equal to
10040 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10041 Value *Op = PN->getIncomingValue(i);
10042 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10043 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10045 } else if (Op != NonPhiInVal)
10053 // PHINode simplification
10055 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10056 // If LCSSA is around, don't mess with Phi nodes
10057 if (MustPreserveLCSSA) return 0;
10059 if (Value *V = PN.hasConstantValue())
10060 return ReplaceInstUsesWith(PN, V);
10062 // If all PHI operands are the same operation, pull them through the PHI,
10063 // reducing code size.
10064 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10065 PN.getIncomingValue(0)->hasOneUse())
10066 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10069 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10070 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10071 // PHI)... break the cycle.
10072 if (PN.hasOneUse()) {
10073 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10074 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10075 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10076 PotentiallyDeadPHIs.insert(&PN);
10077 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10078 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10081 // If this phi has a single use, and if that use just computes a value for
10082 // the next iteration of a loop, delete the phi. This occurs with unused
10083 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10084 // common case here is good because the only other things that catch this
10085 // are induction variable analysis (sometimes) and ADCE, which is only run
10087 if (PHIUser->hasOneUse() &&
10088 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10089 PHIUser->use_back() == &PN) {
10090 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10094 // We sometimes end up with phi cycles that non-obviously end up being the
10095 // same value, for example:
10096 // z = some value; x = phi (y, z); y = phi (x, z)
10097 // where the phi nodes don't necessarily need to be in the same block. Do a
10098 // quick check to see if the PHI node only contains a single non-phi value, if
10099 // so, scan to see if the phi cycle is actually equal to that value.
10101 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10102 // Scan for the first non-phi operand.
10103 while (InValNo != NumOperandVals &&
10104 isa<PHINode>(PN.getIncomingValue(InValNo)))
10107 if (InValNo != NumOperandVals) {
10108 Value *NonPhiInVal = PN.getOperand(InValNo);
10110 // Scan the rest of the operands to see if there are any conflicts, if so
10111 // there is no need to recursively scan other phis.
10112 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10113 Value *OpVal = PN.getIncomingValue(InValNo);
10114 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10118 // If we scanned over all operands, then we have one unique value plus
10119 // phi values. Scan PHI nodes to see if they all merge in each other or
10121 if (InValNo == NumOperandVals) {
10122 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10123 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10124 return ReplaceInstUsesWith(PN, NonPhiInVal);
10131 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10132 Instruction *InsertPoint,
10133 InstCombiner *IC) {
10134 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10135 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10136 // We must cast correctly to the pointer type. Ensure that we
10137 // sign extend the integer value if it is smaller as this is
10138 // used for address computation.
10139 Instruction::CastOps opcode =
10140 (VTySize < PtrSize ? Instruction::SExt :
10141 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10142 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10146 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10147 Value *PtrOp = GEP.getOperand(0);
10148 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10149 // If so, eliminate the noop.
10150 if (GEP.getNumOperands() == 1)
10151 return ReplaceInstUsesWith(GEP, PtrOp);
10153 if (isa<UndefValue>(GEP.getOperand(0)))
10154 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10156 bool HasZeroPointerIndex = false;
10157 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10158 HasZeroPointerIndex = C->isNullValue();
10160 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10161 return ReplaceInstUsesWith(GEP, PtrOp);
10163 // Eliminate unneeded casts for indices.
10164 bool MadeChange = false;
10166 gep_type_iterator GTI = gep_type_begin(GEP);
10167 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
10168 if (isa<SequentialType>(*GTI)) {
10169 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
10170 if (CI->getOpcode() == Instruction::ZExt ||
10171 CI->getOpcode() == Instruction::SExt) {
10172 const Type *SrcTy = CI->getOperand(0)->getType();
10173 // We can eliminate a cast from i32 to i64 iff the target
10174 // is a 32-bit pointer target.
10175 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10177 GEP.setOperand(i, CI->getOperand(0));
10181 // If we are using a wider index than needed for this platform, shrink it
10182 // to what we need. If the incoming value needs a cast instruction,
10183 // insert it. This explicit cast can make subsequent optimizations more
10185 Value *Op = GEP.getOperand(i);
10186 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10187 if (Constant *C = dyn_cast<Constant>(Op)) {
10188 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
10191 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10193 GEP.setOperand(i, Op);
10199 if (MadeChange) return &GEP;
10201 // If this GEP instruction doesn't move the pointer, and if the input operand
10202 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10203 // real input to the dest type.
10204 if (GEP.hasAllZeroIndices()) {
10205 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10206 // If the bitcast is of an allocation, and the allocation will be
10207 // converted to match the type of the cast, don't touch this.
10208 if (isa<AllocationInst>(BCI->getOperand(0))) {
10209 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10210 if (Instruction *I = visitBitCast(*BCI)) {
10213 BCI->getParent()->getInstList().insert(BCI, I);
10214 ReplaceInstUsesWith(*BCI, I);
10219 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10223 // Combine Indices - If the source pointer to this getelementptr instruction
10224 // is a getelementptr instruction, combine the indices of the two
10225 // getelementptr instructions into a single instruction.
10227 SmallVector<Value*, 8> SrcGEPOperands;
10228 if (User *Src = dyn_castGetElementPtr(PtrOp))
10229 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10231 if (!SrcGEPOperands.empty()) {
10232 // Note that if our source is a gep chain itself that we wait for that
10233 // chain to be resolved before we perform this transformation. This
10234 // avoids us creating a TON of code in some cases.
10236 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10237 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10238 return 0; // Wait until our source is folded to completion.
10240 SmallVector<Value*, 8> Indices;
10242 // Find out whether the last index in the source GEP is a sequential idx.
10243 bool EndsWithSequential = false;
10244 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10245 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10246 EndsWithSequential = !isa<StructType>(*I);
10248 // Can we combine the two pointer arithmetics offsets?
10249 if (EndsWithSequential) {
10250 // Replace: gep (gep %P, long B), long A, ...
10251 // With: T = long A+B; gep %P, T, ...
10253 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10254 if (SO1 == Constant::getNullValue(SO1->getType())) {
10256 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10259 // If they aren't the same type, convert both to an integer of the
10260 // target's pointer size.
10261 if (SO1->getType() != GO1->getType()) {
10262 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10263 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10264 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10265 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10267 unsigned PS = TD->getPointerSizeInBits();
10268 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10269 // Convert GO1 to SO1's type.
10270 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10272 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10273 // Convert SO1 to GO1's type.
10274 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10276 const Type *PT = TD->getIntPtrType();
10277 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10278 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10282 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10283 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10285 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10286 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10290 // Recycle the GEP we already have if possible.
10291 if (SrcGEPOperands.size() == 2) {
10292 GEP.setOperand(0, SrcGEPOperands[0]);
10293 GEP.setOperand(1, Sum);
10296 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10297 SrcGEPOperands.end()-1);
10298 Indices.push_back(Sum);
10299 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10301 } else if (isa<Constant>(*GEP.idx_begin()) &&
10302 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10303 SrcGEPOperands.size() != 1) {
10304 // Otherwise we can do the fold if the first index of the GEP is a zero
10305 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10306 SrcGEPOperands.end());
10307 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10310 if (!Indices.empty())
10311 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10312 Indices.end(), GEP.getName());
10314 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10315 // GEP of global variable. If all of the indices for this GEP are
10316 // constants, we can promote this to a constexpr instead of an instruction.
10318 // Scan for nonconstants...
10319 SmallVector<Constant*, 8> Indices;
10320 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10321 for (; I != E && isa<Constant>(*I); ++I)
10322 Indices.push_back(cast<Constant>(*I));
10324 if (I == E) { // If they are all constants...
10325 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10326 &Indices[0],Indices.size());
10328 // Replace all uses of the GEP with the new constexpr...
10329 return ReplaceInstUsesWith(GEP, CE);
10331 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10332 if (!isa<PointerType>(X->getType())) {
10333 // Not interesting. Source pointer must be a cast from pointer.
10334 } else if (HasZeroPointerIndex) {
10335 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10336 // into : GEP [10 x i8]* X, i32 0, ...
10338 // This occurs when the program declares an array extern like "int X[];"
10340 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10341 const PointerType *XTy = cast<PointerType>(X->getType());
10342 if (const ArrayType *XATy =
10343 dyn_cast<ArrayType>(XTy->getElementType()))
10344 if (const ArrayType *CATy =
10345 dyn_cast<ArrayType>(CPTy->getElementType()))
10346 if (CATy->getElementType() == XATy->getElementType()) {
10347 // At this point, we know that the cast source type is a pointer
10348 // to an array of the same type as the destination pointer
10349 // array. Because the array type is never stepped over (there
10350 // is a leading zero) we can fold the cast into this GEP.
10351 GEP.setOperand(0, X);
10354 } else if (GEP.getNumOperands() == 2) {
10355 // Transform things like:
10356 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10357 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10358 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10359 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10360 if (isa<ArrayType>(SrcElTy) &&
10361 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10362 TD->getABITypeSize(ResElTy)) {
10364 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10365 Idx[1] = GEP.getOperand(1);
10366 Value *V = InsertNewInstBefore(
10367 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10368 // V and GEP are both pointer types --> BitCast
10369 return new BitCastInst(V, GEP.getType());
10372 // Transform things like:
10373 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10374 // (where tmp = 8*tmp2) into:
10375 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10377 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10378 uint64_t ArrayEltSize =
10379 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10381 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10382 // allow either a mul, shift, or constant here.
10384 ConstantInt *Scale = 0;
10385 if (ArrayEltSize == 1) {
10386 NewIdx = GEP.getOperand(1);
10387 Scale = ConstantInt::get(NewIdx->getType(), 1);
10388 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10389 NewIdx = ConstantInt::get(CI->getType(), 1);
10391 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10392 if (Inst->getOpcode() == Instruction::Shl &&
10393 isa<ConstantInt>(Inst->getOperand(1))) {
10394 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10395 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10396 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10397 NewIdx = Inst->getOperand(0);
10398 } else if (Inst->getOpcode() == Instruction::Mul &&
10399 isa<ConstantInt>(Inst->getOperand(1))) {
10400 Scale = cast<ConstantInt>(Inst->getOperand(1));
10401 NewIdx = Inst->getOperand(0);
10405 // If the index will be to exactly the right offset with the scale taken
10406 // out, perform the transformation. Note, we don't know whether Scale is
10407 // signed or not. We'll use unsigned version of division/modulo
10408 // operation after making sure Scale doesn't have the sign bit set.
10409 if (Scale && Scale->getSExtValue() >= 0LL &&
10410 Scale->getZExtValue() % ArrayEltSize == 0) {
10411 Scale = ConstantInt::get(Scale->getType(),
10412 Scale->getZExtValue() / ArrayEltSize);
10413 if (Scale->getZExtValue() != 1) {
10414 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10416 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10417 NewIdx = InsertNewInstBefore(Sc, GEP);
10420 // Insert the new GEP instruction.
10422 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10424 Instruction *NewGEP =
10425 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10426 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10427 // The NewGEP must be pointer typed, so must the old one -> BitCast
10428 return new BitCastInst(NewGEP, GEP.getType());
10437 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10438 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10439 if (AI.isArrayAllocation()) { // Check C != 1
10440 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10441 const Type *NewTy =
10442 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10443 AllocationInst *New = 0;
10445 // Create and insert the replacement instruction...
10446 if (isa<MallocInst>(AI))
10447 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10449 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10450 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10453 InsertNewInstBefore(New, AI);
10455 // Scan to the end of the allocation instructions, to skip over a block of
10456 // allocas if possible...
10458 BasicBlock::iterator It = New;
10459 while (isa<AllocationInst>(*It)) ++It;
10461 // Now that I is pointing to the first non-allocation-inst in the block,
10462 // insert our getelementptr instruction...
10464 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10468 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10469 New->getName()+".sub", It);
10471 // Now make everything use the getelementptr instead of the original
10473 return ReplaceInstUsesWith(AI, V);
10474 } else if (isa<UndefValue>(AI.getArraySize())) {
10475 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10479 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10480 // Note that we only do this for alloca's, because malloc should allocate and
10481 // return a unique pointer, even for a zero byte allocation.
10482 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10483 TD->getABITypeSize(AI.getAllocatedType()) == 0)
10484 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10489 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10490 Value *Op = FI.getOperand(0);
10492 // free undef -> unreachable.
10493 if (isa<UndefValue>(Op)) {
10494 // Insert a new store to null because we cannot modify the CFG here.
10495 new StoreInst(ConstantInt::getTrue(),
10496 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10497 return EraseInstFromFunction(FI);
10500 // If we have 'free null' delete the instruction. This can happen in stl code
10501 // when lots of inlining happens.
10502 if (isa<ConstantPointerNull>(Op))
10503 return EraseInstFromFunction(FI);
10505 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10506 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10507 FI.setOperand(0, CI->getOperand(0));
10511 // Change free (gep X, 0,0,0,0) into free(X)
10512 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10513 if (GEPI->hasAllZeroIndices()) {
10514 AddToWorkList(GEPI);
10515 FI.setOperand(0, GEPI->getOperand(0));
10520 // Change free(malloc) into nothing, if the malloc has a single use.
10521 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10522 if (MI->hasOneUse()) {
10523 EraseInstFromFunction(FI);
10524 return EraseInstFromFunction(*MI);
10531 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10532 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10533 const TargetData *TD) {
10534 User *CI = cast<User>(LI.getOperand(0));
10535 Value *CastOp = CI->getOperand(0);
10537 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10538 // Instead of loading constant c string, use corresponding integer value
10539 // directly if string length is small enough.
10540 const std::string &Str = CE->getOperand(0)->getStringValue();
10541 if (!Str.empty()) {
10542 unsigned len = Str.length();
10543 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10544 unsigned numBits = Ty->getPrimitiveSizeInBits();
10545 // Replace LI with immediate integer store.
10546 if ((numBits >> 3) == len + 1) {
10547 APInt StrVal(numBits, 0);
10548 APInt SingleChar(numBits, 0);
10549 if (TD->isLittleEndian()) {
10550 for (signed i = len-1; i >= 0; i--) {
10551 SingleChar = (uint64_t) Str[i];
10552 StrVal = (StrVal << 8) | SingleChar;
10555 for (unsigned i = 0; i < len; i++) {
10556 SingleChar = (uint64_t) Str[i];
10557 StrVal = (StrVal << 8) | SingleChar;
10559 // Append NULL at the end.
10561 StrVal = (StrVal << 8) | SingleChar;
10563 Value *NL = ConstantInt::get(StrVal);
10564 return IC.ReplaceInstUsesWith(LI, NL);
10569 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10570 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10571 const Type *SrcPTy = SrcTy->getElementType();
10573 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10574 isa<VectorType>(DestPTy)) {
10575 // If the source is an array, the code below will not succeed. Check to
10576 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10578 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10579 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10580 if (ASrcTy->getNumElements() != 0) {
10582 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10583 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10584 SrcTy = cast<PointerType>(CastOp->getType());
10585 SrcPTy = SrcTy->getElementType();
10588 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10589 isa<VectorType>(SrcPTy)) &&
10590 // Do not allow turning this into a load of an integer, which is then
10591 // casted to a pointer, this pessimizes pointer analysis a lot.
10592 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10593 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10594 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10596 // Okay, we are casting from one integer or pointer type to another of
10597 // the same size. Instead of casting the pointer before the load, cast
10598 // the result of the loaded value.
10599 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10601 LI.isVolatile()),LI);
10602 // Now cast the result of the load.
10603 return new BitCastInst(NewLoad, LI.getType());
10610 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10611 /// from this value cannot trap. If it is not obviously safe to load from the
10612 /// specified pointer, we do a quick local scan of the basic block containing
10613 /// ScanFrom, to determine if the address is already accessed.
10614 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10615 // If it is an alloca it is always safe to load from.
10616 if (isa<AllocaInst>(V)) return true;
10618 // If it is a global variable it is mostly safe to load from.
10619 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10620 // Don't try to evaluate aliases. External weak GV can be null.
10621 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10623 // Otherwise, be a little bit agressive by scanning the local block where we
10624 // want to check to see if the pointer is already being loaded or stored
10625 // from/to. If so, the previous load or store would have already trapped,
10626 // so there is no harm doing an extra load (also, CSE will later eliminate
10627 // the load entirely).
10628 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10633 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10634 if (LI->getOperand(0) == V) return true;
10635 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10636 if (SI->getOperand(1) == V) return true;
10642 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10643 /// until we find the underlying object a pointer is referring to or something
10644 /// we don't understand. Note that the returned pointer may be offset from the
10645 /// input, because we ignore GEP indices.
10646 static Value *GetUnderlyingObject(Value *Ptr) {
10648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10649 if (CE->getOpcode() == Instruction::BitCast ||
10650 CE->getOpcode() == Instruction::GetElementPtr)
10651 Ptr = CE->getOperand(0);
10654 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10655 Ptr = BCI->getOperand(0);
10656 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10657 Ptr = GEP->getOperand(0);
10664 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10665 Value *Op = LI.getOperand(0);
10667 // Attempt to improve the alignment.
10668 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10670 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10671 LI.getAlignment()))
10672 LI.setAlignment(KnownAlign);
10674 // load (cast X) --> cast (load X) iff safe
10675 if (isa<CastInst>(Op))
10676 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10679 // None of the following transforms are legal for volatile loads.
10680 if (LI.isVolatile()) return 0;
10682 if (&LI.getParent()->front() != &LI) {
10683 BasicBlock::iterator BBI = &LI; --BBI;
10684 // If the instruction immediately before this is a store to the same
10685 // address, do a simple form of store->load forwarding.
10686 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10687 if (SI->getOperand(1) == LI.getOperand(0))
10688 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10689 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10690 if (LIB->getOperand(0) == LI.getOperand(0))
10691 return ReplaceInstUsesWith(LI, LIB);
10694 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10695 const Value *GEPI0 = GEPI->getOperand(0);
10696 // TODO: Consider a target hook for valid address spaces for this xform.
10697 if (isa<ConstantPointerNull>(GEPI0) &&
10698 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10699 // Insert a new store to null instruction before the load to indicate
10700 // that this code is not reachable. We do this instead of inserting
10701 // an unreachable instruction directly because we cannot modify the
10703 new StoreInst(UndefValue::get(LI.getType()),
10704 Constant::getNullValue(Op->getType()), &LI);
10705 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10709 if (Constant *C = dyn_cast<Constant>(Op)) {
10710 // load null/undef -> undef
10711 // TODO: Consider a target hook for valid address spaces for this xform.
10712 if (isa<UndefValue>(C) || (C->isNullValue() &&
10713 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10714 // Insert a new store to null instruction before the load to indicate that
10715 // this code is not reachable. We do this instead of inserting an
10716 // unreachable instruction directly because we cannot modify the CFG.
10717 new StoreInst(UndefValue::get(LI.getType()),
10718 Constant::getNullValue(Op->getType()), &LI);
10719 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10722 // Instcombine load (constant global) into the value loaded.
10723 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10724 if (GV->isConstant() && !GV->isDeclaration())
10725 return ReplaceInstUsesWith(LI, GV->getInitializer());
10727 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10728 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10729 if (CE->getOpcode() == Instruction::GetElementPtr) {
10730 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10731 if (GV->isConstant() && !GV->isDeclaration())
10733 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10734 return ReplaceInstUsesWith(LI, V);
10735 if (CE->getOperand(0)->isNullValue()) {
10736 // Insert a new store to null instruction before the load to indicate
10737 // that this code is not reachable. We do this instead of inserting
10738 // an unreachable instruction directly because we cannot modify the
10740 new StoreInst(UndefValue::get(LI.getType()),
10741 Constant::getNullValue(Op->getType()), &LI);
10742 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10745 } else if (CE->isCast()) {
10746 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10752 // If this load comes from anywhere in a constant global, and if the global
10753 // is all undef or zero, we know what it loads.
10754 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10755 if (GV->isConstant() && GV->hasInitializer()) {
10756 if (GV->getInitializer()->isNullValue())
10757 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10758 else if (isa<UndefValue>(GV->getInitializer()))
10759 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10763 if (Op->hasOneUse()) {
10764 // Change select and PHI nodes to select values instead of addresses: this
10765 // helps alias analysis out a lot, allows many others simplifications, and
10766 // exposes redundancy in the code.
10768 // Note that we cannot do the transformation unless we know that the
10769 // introduced loads cannot trap! Something like this is valid as long as
10770 // the condition is always false: load (select bool %C, int* null, int* %G),
10771 // but it would not be valid if we transformed it to load from null
10772 // unconditionally.
10774 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10775 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10776 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10777 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10778 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10779 SI->getOperand(1)->getName()+".val"), LI);
10780 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10781 SI->getOperand(2)->getName()+".val"), LI);
10782 return SelectInst::Create(SI->getCondition(), V1, V2);
10785 // load (select (cond, null, P)) -> load P
10786 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10787 if (C->isNullValue()) {
10788 LI.setOperand(0, SI->getOperand(2));
10792 // load (select (cond, P, null)) -> load P
10793 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10794 if (C->isNullValue()) {
10795 LI.setOperand(0, SI->getOperand(1));
10803 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10805 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10806 User *CI = cast<User>(SI.getOperand(1));
10807 Value *CastOp = CI->getOperand(0);
10809 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10810 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10811 const Type *SrcPTy = SrcTy->getElementType();
10813 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10814 // If the source is an array, the code below will not succeed. Check to
10815 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10817 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10818 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10819 if (ASrcTy->getNumElements() != 0) {
10821 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10822 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10823 SrcTy = cast<PointerType>(CastOp->getType());
10824 SrcPTy = SrcTy->getElementType();
10827 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10828 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10829 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10831 // Okay, we are casting from one integer or pointer type to another of
10832 // the same size. Instead of casting the pointer before
10833 // the store, cast the value to be stored.
10835 Value *SIOp0 = SI.getOperand(0);
10836 Instruction::CastOps opcode = Instruction::BitCast;
10837 const Type* CastSrcTy = SIOp0->getType();
10838 const Type* CastDstTy = SrcPTy;
10839 if (isa<PointerType>(CastDstTy)) {
10840 if (CastSrcTy->isInteger())
10841 opcode = Instruction::IntToPtr;
10842 } else if (isa<IntegerType>(CastDstTy)) {
10843 if (isa<PointerType>(SIOp0->getType()))
10844 opcode = Instruction::PtrToInt;
10846 if (Constant *C = dyn_cast<Constant>(SIOp0))
10847 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10849 NewCast = IC.InsertNewInstBefore(
10850 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10852 return new StoreInst(NewCast, CastOp);
10859 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10860 Value *Val = SI.getOperand(0);
10861 Value *Ptr = SI.getOperand(1);
10863 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10864 EraseInstFromFunction(SI);
10869 // If the RHS is an alloca with a single use, zapify the store, making the
10871 if (Ptr->hasOneUse() && !SI.isVolatile()) {
10872 if (isa<AllocaInst>(Ptr)) {
10873 EraseInstFromFunction(SI);
10878 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10879 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10880 GEP->getOperand(0)->hasOneUse()) {
10881 EraseInstFromFunction(SI);
10887 // Attempt to improve the alignment.
10888 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10890 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10891 SI.getAlignment()))
10892 SI.setAlignment(KnownAlign);
10894 // Do really simple DSE, to catch cases where there are several consequtive
10895 // stores to the same location, separated by a few arithmetic operations. This
10896 // situation often occurs with bitfield accesses.
10897 BasicBlock::iterator BBI = &SI;
10898 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10902 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10903 // Prev store isn't volatile, and stores to the same location?
10904 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10907 EraseInstFromFunction(*PrevSI);
10913 // If this is a load, we have to stop. However, if the loaded value is from
10914 // the pointer we're loading and is producing the pointer we're storing,
10915 // then *this* store is dead (X = load P; store X -> P).
10916 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10917 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10918 EraseInstFromFunction(SI);
10922 // Otherwise, this is a load from some other location. Stores before it
10923 // may not be dead.
10927 // Don't skip over loads or things that can modify memory.
10928 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10933 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10935 // store X, null -> turns into 'unreachable' in SimplifyCFG
10936 if (isa<ConstantPointerNull>(Ptr)) {
10937 if (!isa<UndefValue>(Val)) {
10938 SI.setOperand(0, UndefValue::get(Val->getType()));
10939 if (Instruction *U = dyn_cast<Instruction>(Val))
10940 AddToWorkList(U); // Dropped a use.
10943 return 0; // Do not modify these!
10946 // store undef, Ptr -> noop
10947 if (isa<UndefValue>(Val)) {
10948 EraseInstFromFunction(SI);
10953 // If the pointer destination is a cast, see if we can fold the cast into the
10955 if (isa<CastInst>(Ptr))
10956 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10958 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10960 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10964 // If this store is the last instruction in the basic block, and if the block
10965 // ends with an unconditional branch, try to move it to the successor block.
10967 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10968 if (BI->isUnconditional())
10969 if (SimplifyStoreAtEndOfBlock(SI))
10970 return 0; // xform done!
10975 /// SimplifyStoreAtEndOfBlock - Turn things like:
10976 /// if () { *P = v1; } else { *P = v2 }
10977 /// into a phi node with a store in the successor.
10979 /// Simplify things like:
10980 /// *P = v1; if () { *P = v2; }
10981 /// into a phi node with a store in the successor.
10983 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10984 BasicBlock *StoreBB = SI.getParent();
10986 // Check to see if the successor block has exactly two incoming edges. If
10987 // so, see if the other predecessor contains a store to the same location.
10988 // if so, insert a PHI node (if needed) and move the stores down.
10989 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10991 // Determine whether Dest has exactly two predecessors and, if so, compute
10992 // the other predecessor.
10993 pred_iterator PI = pred_begin(DestBB);
10994 BasicBlock *OtherBB = 0;
10995 if (*PI != StoreBB)
10998 if (PI == pred_end(DestBB))
11001 if (*PI != StoreBB) {
11006 if (++PI != pred_end(DestBB))
11010 // Verify that the other block ends in a branch and is not otherwise empty.
11011 BasicBlock::iterator BBI = OtherBB->getTerminator();
11012 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11013 if (!OtherBr || BBI == OtherBB->begin())
11016 // If the other block ends in an unconditional branch, check for the 'if then
11017 // else' case. there is an instruction before the branch.
11018 StoreInst *OtherStore = 0;
11019 if (OtherBr->isUnconditional()) {
11020 // If this isn't a store, or isn't a store to the same location, bail out.
11022 OtherStore = dyn_cast<StoreInst>(BBI);
11023 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11026 // Otherwise, the other block ended with a conditional branch. If one of the
11027 // destinations is StoreBB, then we have the if/then case.
11028 if (OtherBr->getSuccessor(0) != StoreBB &&
11029 OtherBr->getSuccessor(1) != StoreBB)
11032 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11033 // if/then triangle. See if there is a store to the same ptr as SI that
11034 // lives in OtherBB.
11036 // Check to see if we find the matching store.
11037 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11038 if (OtherStore->getOperand(1) != SI.getOperand(1))
11042 // If we find something that may be using the stored value, or if we run
11043 // out of instructions, we can't do the xform.
11044 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11045 BBI == OtherBB->begin())
11049 // In order to eliminate the store in OtherBr, we have to
11050 // make sure nothing reads the stored value in StoreBB.
11051 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11052 // FIXME: This should really be AA driven.
11053 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11058 // Insert a PHI node now if we need it.
11059 Value *MergedVal = OtherStore->getOperand(0);
11060 if (MergedVal != SI.getOperand(0)) {
11061 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11062 PN->reserveOperandSpace(2);
11063 PN->addIncoming(SI.getOperand(0), SI.getParent());
11064 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11065 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11068 // Advance to a place where it is safe to insert the new store and
11070 BBI = DestBB->getFirstNonPHI();
11071 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11072 OtherStore->isVolatile()), *BBI);
11074 // Nuke the old stores.
11075 EraseInstFromFunction(SI);
11076 EraseInstFromFunction(*OtherStore);
11082 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11083 // Change br (not X), label True, label False to: br X, label False, True
11085 BasicBlock *TrueDest;
11086 BasicBlock *FalseDest;
11087 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11088 !isa<Constant>(X)) {
11089 // Swap Destinations and condition...
11090 BI.setCondition(X);
11091 BI.setSuccessor(0, FalseDest);
11092 BI.setSuccessor(1, TrueDest);
11096 // Cannonicalize fcmp_one -> fcmp_oeq
11097 FCmpInst::Predicate FPred; Value *Y;
11098 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11099 TrueDest, FalseDest)))
11100 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11101 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11102 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11103 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11104 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11105 NewSCC->takeName(I);
11106 // Swap Destinations and condition...
11107 BI.setCondition(NewSCC);
11108 BI.setSuccessor(0, FalseDest);
11109 BI.setSuccessor(1, TrueDest);
11110 RemoveFromWorkList(I);
11111 I->eraseFromParent();
11112 AddToWorkList(NewSCC);
11116 // Cannonicalize icmp_ne -> icmp_eq
11117 ICmpInst::Predicate IPred;
11118 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11119 TrueDest, FalseDest)))
11120 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11121 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11122 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11123 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11124 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11125 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11126 NewSCC->takeName(I);
11127 // Swap Destinations and condition...
11128 BI.setCondition(NewSCC);
11129 BI.setSuccessor(0, FalseDest);
11130 BI.setSuccessor(1, TrueDest);
11131 RemoveFromWorkList(I);
11132 I->eraseFromParent();;
11133 AddToWorkList(NewSCC);
11140 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11141 Value *Cond = SI.getCondition();
11142 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11143 if (I->getOpcode() == Instruction::Add)
11144 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11145 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11146 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11147 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11149 SI.setOperand(0, I->getOperand(0));
11157 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11158 /// is to leave as a vector operation.
11159 static bool CheapToScalarize(Value *V, bool isConstant) {
11160 if (isa<ConstantAggregateZero>(V))
11162 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11163 if (isConstant) return true;
11164 // If all elts are the same, we can extract.
11165 Constant *Op0 = C->getOperand(0);
11166 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11167 if (C->getOperand(i) != Op0)
11171 Instruction *I = dyn_cast<Instruction>(V);
11172 if (!I) return false;
11174 // Insert element gets simplified to the inserted element or is deleted if
11175 // this is constant idx extract element and its a constant idx insertelt.
11176 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11177 isa<ConstantInt>(I->getOperand(2)))
11179 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11181 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11182 if (BO->hasOneUse() &&
11183 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11184 CheapToScalarize(BO->getOperand(1), isConstant)))
11186 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11187 if (CI->hasOneUse() &&
11188 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11189 CheapToScalarize(CI->getOperand(1), isConstant)))
11195 /// Read and decode a shufflevector mask.
11197 /// It turns undef elements into values that are larger than the number of
11198 /// elements in the input.
11199 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11200 unsigned NElts = SVI->getType()->getNumElements();
11201 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11202 return std::vector<unsigned>(NElts, 0);
11203 if (isa<UndefValue>(SVI->getOperand(2)))
11204 return std::vector<unsigned>(NElts, 2*NElts);
11206 std::vector<unsigned> Result;
11207 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11208 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11209 if (isa<UndefValue>(CP->getOperand(i)))
11210 Result.push_back(NElts*2); // undef -> 8
11212 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
11216 /// FindScalarElement - Given a vector and an element number, see if the scalar
11217 /// value is already around as a register, for example if it were inserted then
11218 /// extracted from the vector.
11219 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11220 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11221 const VectorType *PTy = cast<VectorType>(V->getType());
11222 unsigned Width = PTy->getNumElements();
11223 if (EltNo >= Width) // Out of range access.
11224 return UndefValue::get(PTy->getElementType());
11226 if (isa<UndefValue>(V))
11227 return UndefValue::get(PTy->getElementType());
11228 else if (isa<ConstantAggregateZero>(V))
11229 return Constant::getNullValue(PTy->getElementType());
11230 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11231 return CP->getOperand(EltNo);
11232 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11233 // If this is an insert to a variable element, we don't know what it is.
11234 if (!isa<ConstantInt>(III->getOperand(2)))
11236 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11238 // If this is an insert to the element we are looking for, return the
11240 if (EltNo == IIElt)
11241 return III->getOperand(1);
11243 // Otherwise, the insertelement doesn't modify the value, recurse on its
11245 return FindScalarElement(III->getOperand(0), EltNo);
11246 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11247 unsigned InEl = getShuffleMask(SVI)[EltNo];
11249 return FindScalarElement(SVI->getOperand(0), InEl);
11250 else if (InEl < Width*2)
11251 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11253 return UndefValue::get(PTy->getElementType());
11256 // Otherwise, we don't know.
11260 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11262 // If vector val is undef, replace extract with scalar undef.
11263 if (isa<UndefValue>(EI.getOperand(0)))
11264 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11266 // If vector val is constant 0, replace extract with scalar 0.
11267 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11268 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11270 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11271 // If vector val is constant with uniform operands, replace EI
11272 // with that operand
11273 Constant *op0 = C->getOperand(0);
11274 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11275 if (C->getOperand(i) != op0) {
11280 return ReplaceInstUsesWith(EI, op0);
11283 // If extracting a specified index from the vector, see if we can recursively
11284 // find a previously computed scalar that was inserted into the vector.
11285 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11286 unsigned IndexVal = IdxC->getZExtValue();
11287 unsigned VectorWidth =
11288 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11290 // If this is extracting an invalid index, turn this into undef, to avoid
11291 // crashing the code below.
11292 if (IndexVal >= VectorWidth)
11293 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11295 // This instruction only demands the single element from the input vector.
11296 // If the input vector has a single use, simplify it based on this use
11298 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11299 uint64_t UndefElts;
11300 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11303 EI.setOperand(0, V);
11308 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11309 return ReplaceInstUsesWith(EI, Elt);
11311 // If the this extractelement is directly using a bitcast from a vector of
11312 // the same number of elements, see if we can find the source element from
11313 // it. In this case, we will end up needing to bitcast the scalars.
11314 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11315 if (const VectorType *VT =
11316 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11317 if (VT->getNumElements() == VectorWidth)
11318 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11319 return new BitCastInst(Elt, EI.getType());
11323 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11324 if (I->hasOneUse()) {
11325 // Push extractelement into predecessor operation if legal and
11326 // profitable to do so
11327 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11328 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11329 if (CheapToScalarize(BO, isConstantElt)) {
11330 ExtractElementInst *newEI0 =
11331 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11332 EI.getName()+".lhs");
11333 ExtractElementInst *newEI1 =
11334 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11335 EI.getName()+".rhs");
11336 InsertNewInstBefore(newEI0, EI);
11337 InsertNewInstBefore(newEI1, EI);
11338 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11340 } else if (isa<LoadInst>(I)) {
11342 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11343 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11344 PointerType::get(EI.getType(), AS),EI);
11345 GetElementPtrInst *GEP =
11346 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11347 InsertNewInstBefore(GEP, EI);
11348 return new LoadInst(GEP);
11351 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11352 // Extracting the inserted element?
11353 if (IE->getOperand(2) == EI.getOperand(1))
11354 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11355 // If the inserted and extracted elements are constants, they must not
11356 // be the same value, extract from the pre-inserted value instead.
11357 if (isa<Constant>(IE->getOperand(2)) &&
11358 isa<Constant>(EI.getOperand(1))) {
11359 AddUsesToWorkList(EI);
11360 EI.setOperand(0, IE->getOperand(0));
11363 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11364 // If this is extracting an element from a shufflevector, figure out where
11365 // it came from and extract from the appropriate input element instead.
11366 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11367 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11369 if (SrcIdx < SVI->getType()->getNumElements())
11370 Src = SVI->getOperand(0);
11371 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11372 SrcIdx -= SVI->getType()->getNumElements();
11373 Src = SVI->getOperand(1);
11375 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11377 return new ExtractElementInst(Src, SrcIdx);
11384 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11385 /// elements from either LHS or RHS, return the shuffle mask and true.
11386 /// Otherwise, return false.
11387 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11388 std::vector<Constant*> &Mask) {
11389 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11390 "Invalid CollectSingleShuffleElements");
11391 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11393 if (isa<UndefValue>(V)) {
11394 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11396 } else if (V == LHS) {
11397 for (unsigned i = 0; i != NumElts; ++i)
11398 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11400 } else if (V == RHS) {
11401 for (unsigned i = 0; i != NumElts; ++i)
11402 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11404 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11405 // If this is an insert of an extract from some other vector, include it.
11406 Value *VecOp = IEI->getOperand(0);
11407 Value *ScalarOp = IEI->getOperand(1);
11408 Value *IdxOp = IEI->getOperand(2);
11410 if (!isa<ConstantInt>(IdxOp))
11412 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11414 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11415 // Okay, we can handle this if the vector we are insertinting into is
11416 // transitively ok.
11417 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11418 // If so, update the mask to reflect the inserted undef.
11419 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11422 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11423 if (isa<ConstantInt>(EI->getOperand(1)) &&
11424 EI->getOperand(0)->getType() == V->getType()) {
11425 unsigned ExtractedIdx =
11426 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11428 // This must be extracting from either LHS or RHS.
11429 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11430 // Okay, we can handle this if the vector we are insertinting into is
11431 // transitively ok.
11432 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11433 // If so, update the mask to reflect the inserted value.
11434 if (EI->getOperand(0) == LHS) {
11435 Mask[InsertedIdx & (NumElts-1)] =
11436 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11438 assert(EI->getOperand(0) == RHS);
11439 Mask[InsertedIdx & (NumElts-1)] =
11440 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11449 // TODO: Handle shufflevector here!
11454 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11455 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11456 /// that computes V and the LHS value of the shuffle.
11457 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11459 assert(isa<VectorType>(V->getType()) &&
11460 (RHS == 0 || V->getType() == RHS->getType()) &&
11461 "Invalid shuffle!");
11462 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11464 if (isa<UndefValue>(V)) {
11465 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11467 } else if (isa<ConstantAggregateZero>(V)) {
11468 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11470 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11471 // If this is an insert of an extract from some other vector, include it.
11472 Value *VecOp = IEI->getOperand(0);
11473 Value *ScalarOp = IEI->getOperand(1);
11474 Value *IdxOp = IEI->getOperand(2);
11476 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11477 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11478 EI->getOperand(0)->getType() == V->getType()) {
11479 unsigned ExtractedIdx =
11480 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11481 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11483 // Either the extracted from or inserted into vector must be RHSVec,
11484 // otherwise we'd end up with a shuffle of three inputs.
11485 if (EI->getOperand(0) == RHS || RHS == 0) {
11486 RHS = EI->getOperand(0);
11487 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11488 Mask[InsertedIdx & (NumElts-1)] =
11489 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11493 if (VecOp == RHS) {
11494 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11495 // Everything but the extracted element is replaced with the RHS.
11496 for (unsigned i = 0; i != NumElts; ++i) {
11497 if (i != InsertedIdx)
11498 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11503 // If this insertelement is a chain that comes from exactly these two
11504 // vectors, return the vector and the effective shuffle.
11505 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11506 return EI->getOperand(0);
11511 // TODO: Handle shufflevector here!
11513 // Otherwise, can't do anything fancy. Return an identity vector.
11514 for (unsigned i = 0; i != NumElts; ++i)
11515 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11519 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11520 Value *VecOp = IE.getOperand(0);
11521 Value *ScalarOp = IE.getOperand(1);
11522 Value *IdxOp = IE.getOperand(2);
11524 // Inserting an undef or into an undefined place, remove this.
11525 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11526 ReplaceInstUsesWith(IE, VecOp);
11528 // If the inserted element was extracted from some other vector, and if the
11529 // indexes are constant, try to turn this into a shufflevector operation.
11530 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11531 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11532 EI->getOperand(0)->getType() == IE.getType()) {
11533 unsigned NumVectorElts = IE.getType()->getNumElements();
11534 unsigned ExtractedIdx =
11535 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11536 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11538 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11539 return ReplaceInstUsesWith(IE, VecOp);
11541 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11542 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11544 // If we are extracting a value from a vector, then inserting it right
11545 // back into the same place, just use the input vector.
11546 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11547 return ReplaceInstUsesWith(IE, VecOp);
11549 // We could theoretically do this for ANY input. However, doing so could
11550 // turn chains of insertelement instructions into a chain of shufflevector
11551 // instructions, and right now we do not merge shufflevectors. As such,
11552 // only do this in a situation where it is clear that there is benefit.
11553 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11554 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11555 // the values of VecOp, except then one read from EIOp0.
11556 // Build a new shuffle mask.
11557 std::vector<Constant*> Mask;
11558 if (isa<UndefValue>(VecOp))
11559 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11561 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11562 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11565 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11566 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11567 ConstantVector::get(Mask));
11570 // If this insertelement isn't used by some other insertelement, turn it
11571 // (and any insertelements it points to), into one big shuffle.
11572 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11573 std::vector<Constant*> Mask;
11575 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11576 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11577 // We now have a shuffle of LHS, RHS, Mask.
11578 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11587 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11588 Value *LHS = SVI.getOperand(0);
11589 Value *RHS = SVI.getOperand(1);
11590 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11592 bool MadeChange = false;
11594 // Undefined shuffle mask -> undefined value.
11595 if (isa<UndefValue>(SVI.getOperand(2)))
11596 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11598 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11599 // the undef, change them to undefs.
11600 if (isa<UndefValue>(SVI.getOperand(1))) {
11601 // Scan to see if there are any references to the RHS. If so, replace them
11602 // with undef element refs and set MadeChange to true.
11603 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11604 if (Mask[i] >= e && Mask[i] != 2*e) {
11611 // Remap any references to RHS to use LHS.
11612 std::vector<Constant*> Elts;
11613 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11614 if (Mask[i] == 2*e)
11615 Elts.push_back(UndefValue::get(Type::Int32Ty));
11617 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11619 SVI.setOperand(2, ConstantVector::get(Elts));
11623 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11624 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11625 if (LHS == RHS || isa<UndefValue>(LHS)) {
11626 if (isa<UndefValue>(LHS) && LHS == RHS) {
11627 // shuffle(undef,undef,mask) -> undef.
11628 return ReplaceInstUsesWith(SVI, LHS);
11631 // Remap any references to RHS to use LHS.
11632 std::vector<Constant*> Elts;
11633 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11634 if (Mask[i] >= 2*e)
11635 Elts.push_back(UndefValue::get(Type::Int32Ty));
11637 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11638 (Mask[i] < e && isa<UndefValue>(LHS)))
11639 Mask[i] = 2*e; // Turn into undef.
11641 Mask[i] &= (e-1); // Force to LHS.
11642 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11645 SVI.setOperand(0, SVI.getOperand(1));
11646 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11647 SVI.setOperand(2, ConstantVector::get(Elts));
11648 LHS = SVI.getOperand(0);
11649 RHS = SVI.getOperand(1);
11653 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11654 bool isLHSID = true, isRHSID = true;
11656 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11657 if (Mask[i] >= e*2) continue; // Ignore undef values.
11658 // Is this an identity shuffle of the LHS value?
11659 isLHSID &= (Mask[i] == i);
11661 // Is this an identity shuffle of the RHS value?
11662 isRHSID &= (Mask[i]-e == i);
11665 // Eliminate identity shuffles.
11666 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11667 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11669 // If the LHS is a shufflevector itself, see if we can combine it with this
11670 // one without producing an unusual shuffle. Here we are really conservative:
11671 // we are absolutely afraid of producing a shuffle mask not in the input
11672 // program, because the code gen may not be smart enough to turn a merged
11673 // shuffle into two specific shuffles: it may produce worse code. As such,
11674 // we only merge two shuffles if the result is one of the two input shuffle
11675 // masks. In this case, merging the shuffles just removes one instruction,
11676 // which we know is safe. This is good for things like turning:
11677 // (splat(splat)) -> splat.
11678 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11679 if (isa<UndefValue>(RHS)) {
11680 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11682 std::vector<unsigned> NewMask;
11683 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11684 if (Mask[i] >= 2*e)
11685 NewMask.push_back(2*e);
11687 NewMask.push_back(LHSMask[Mask[i]]);
11689 // If the result mask is equal to the src shuffle or this shuffle mask, do
11690 // the replacement.
11691 if (NewMask == LHSMask || NewMask == Mask) {
11692 std::vector<Constant*> Elts;
11693 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11694 if (NewMask[i] >= e*2) {
11695 Elts.push_back(UndefValue::get(Type::Int32Ty));
11697 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11700 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11701 LHSSVI->getOperand(1),
11702 ConstantVector::get(Elts));
11707 return MadeChange ? &SVI : 0;
11713 /// TryToSinkInstruction - Try to move the specified instruction from its
11714 /// current block into the beginning of DestBlock, which can only happen if it's
11715 /// safe to move the instruction past all of the instructions between it and the
11716 /// end of its block.
11717 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11718 assert(I->hasOneUse() && "Invariants didn't hold!");
11720 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11721 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11724 // Do not sink alloca instructions out of the entry block.
11725 if (isa<AllocaInst>(I) && I->getParent() ==
11726 &DestBlock->getParent()->getEntryBlock())
11729 // We can only sink load instructions if there is nothing between the load and
11730 // the end of block that could change the value.
11731 if (I->mayReadFromMemory()) {
11732 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11734 if (Scan->mayWriteToMemory())
11738 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11740 I->moveBefore(InsertPos);
11746 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11747 /// all reachable code to the worklist.
11749 /// This has a couple of tricks to make the code faster and more powerful. In
11750 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11751 /// them to the worklist (this significantly speeds up instcombine on code where
11752 /// many instructions are dead or constant). Additionally, if we find a branch
11753 /// whose condition is a known constant, we only visit the reachable successors.
11755 static void AddReachableCodeToWorklist(BasicBlock *BB,
11756 SmallPtrSet<BasicBlock*, 64> &Visited,
11758 const TargetData *TD) {
11759 std::vector<BasicBlock*> Worklist;
11760 Worklist.push_back(BB);
11762 while (!Worklist.empty()) {
11763 BB = Worklist.back();
11764 Worklist.pop_back();
11766 // We have now visited this block! If we've already been here, ignore it.
11767 if (!Visited.insert(BB)) continue;
11769 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11770 Instruction *Inst = BBI++;
11772 // DCE instruction if trivially dead.
11773 if (isInstructionTriviallyDead(Inst)) {
11775 DOUT << "IC: DCE: " << *Inst;
11776 Inst->eraseFromParent();
11780 // ConstantProp instruction if trivially constant.
11781 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11782 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11783 Inst->replaceAllUsesWith(C);
11785 Inst->eraseFromParent();
11789 IC.AddToWorkList(Inst);
11792 // Recursively visit successors. If this is a branch or switch on a
11793 // constant, only visit the reachable successor.
11794 TerminatorInst *TI = BB->getTerminator();
11795 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11796 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11797 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11798 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11799 Worklist.push_back(ReachableBB);
11802 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11803 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11804 // See if this is an explicit destination.
11805 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11806 if (SI->getCaseValue(i) == Cond) {
11807 BasicBlock *ReachableBB = SI->getSuccessor(i);
11808 Worklist.push_back(ReachableBB);
11812 // Otherwise it is the default destination.
11813 Worklist.push_back(SI->getSuccessor(0));
11818 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11819 Worklist.push_back(TI->getSuccessor(i));
11823 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11824 bool Changed = false;
11825 TD = &getAnalysis<TargetData>();
11827 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11828 << F.getNameStr() << "\n");
11831 // Do a depth-first traversal of the function, populate the worklist with
11832 // the reachable instructions. Ignore blocks that are not reachable. Keep
11833 // track of which blocks we visit.
11834 SmallPtrSet<BasicBlock*, 64> Visited;
11835 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11837 // Do a quick scan over the function. If we find any blocks that are
11838 // unreachable, remove any instructions inside of them. This prevents
11839 // the instcombine code from having to deal with some bad special cases.
11840 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11841 if (!Visited.count(BB)) {
11842 Instruction *Term = BB->getTerminator();
11843 while (Term != BB->begin()) { // Remove instrs bottom-up
11844 BasicBlock::iterator I = Term; --I;
11846 DOUT << "IC: DCE: " << *I;
11849 if (!I->use_empty())
11850 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11851 I->eraseFromParent();
11856 while (!Worklist.empty()) {
11857 Instruction *I = RemoveOneFromWorkList();
11858 if (I == 0) continue; // skip null values.
11860 // Check to see if we can DCE the instruction.
11861 if (isInstructionTriviallyDead(I)) {
11862 // Add operands to the worklist.
11863 if (I->getNumOperands() < 4)
11864 AddUsesToWorkList(*I);
11867 DOUT << "IC: DCE: " << *I;
11869 I->eraseFromParent();
11870 RemoveFromWorkList(I);
11874 // Instruction isn't dead, see if we can constant propagate it.
11875 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11876 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11878 // Add operands to the worklist.
11879 AddUsesToWorkList(*I);
11880 ReplaceInstUsesWith(*I, C);
11883 I->eraseFromParent();
11884 RemoveFromWorkList(I);
11888 // See if we can trivially sink this instruction to a successor basic block.
11889 // FIXME: Remove GetResultInst test when first class support for aggregates
11891 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11892 BasicBlock *BB = I->getParent();
11893 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11894 if (UserParent != BB) {
11895 bool UserIsSuccessor = false;
11896 // See if the user is one of our successors.
11897 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11898 if (*SI == UserParent) {
11899 UserIsSuccessor = true;
11903 // If the user is one of our immediate successors, and if that successor
11904 // only has us as a predecessors (we'd have to split the critical edge
11905 // otherwise), we can keep going.
11906 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11907 next(pred_begin(UserParent)) == pred_end(UserParent))
11908 // Okay, the CFG is simple enough, try to sink this instruction.
11909 Changed |= TryToSinkInstruction(I, UserParent);
11913 // Now that we have an instruction, try combining it to simplify it...
11917 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11918 if (Instruction *Result = visit(*I)) {
11920 // Should we replace the old instruction with a new one?
11922 DOUT << "IC: Old = " << *I
11923 << " New = " << *Result;
11925 // Everything uses the new instruction now.
11926 I->replaceAllUsesWith(Result);
11928 // Push the new instruction and any users onto the worklist.
11929 AddToWorkList(Result);
11930 AddUsersToWorkList(*Result);
11932 // Move the name to the new instruction first.
11933 Result->takeName(I);
11935 // Insert the new instruction into the basic block...
11936 BasicBlock *InstParent = I->getParent();
11937 BasicBlock::iterator InsertPos = I;
11939 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11940 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11943 InstParent->getInstList().insert(InsertPos, Result);
11945 // Make sure that we reprocess all operands now that we reduced their
11947 AddUsesToWorkList(*I);
11949 // Instructions can end up on the worklist more than once. Make sure
11950 // we do not process an instruction that has been deleted.
11951 RemoveFromWorkList(I);
11953 // Erase the old instruction.
11954 InstParent->getInstList().erase(I);
11957 DOUT << "IC: Mod = " << OrigI
11958 << " New = " << *I;
11961 // If the instruction was modified, it's possible that it is now dead.
11962 // if so, remove it.
11963 if (isInstructionTriviallyDead(I)) {
11964 // Make sure we process all operands now that we are reducing their
11966 AddUsesToWorkList(*I);
11968 // Instructions may end up in the worklist more than once. Erase all
11969 // occurrences of this instruction.
11970 RemoveFromWorkList(I);
11971 I->eraseFromParent();
11974 AddUsersToWorkList(*I);
11981 assert(WorklistMap.empty() && "Worklist empty, but map not?");
11983 // Do an explicit clear, this shrinks the map if needed.
11984 WorklistMap.clear();
11989 bool InstCombiner::runOnFunction(Function &F) {
11990 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11992 bool EverMadeChange = false;
11994 // Iterate while there is work to do.
11995 unsigned Iteration = 0;
11996 while (DoOneIteration(F, Iteration++))
11997 EverMadeChange = true;
11998 return EverMadeChange;
12001 FunctionPass *llvm::createInstructionCombiningPass() {
12002 return new InstCombiner();