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/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
64 using namespace llvm::PatternMatch;
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
77 std::vector<Instruction*> Worklist;
78 DenseMap<Instruction*, unsigned> WorklistMap;
80 bool MustPreserveLCSSA;
82 static char ID; // Pass identification, replacement for typeid
83 InstCombiner() : FunctionPass((intptr_t)&ID) {}
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
88 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
89 Worklist.push_back(I);
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
100 WorklistMap.erase(It);
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
106 WorklistMap.erase(I);
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
118 AddToWorkList(cast<Instruction>(*UI));
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
124 void AddUsesToWorkList(Instruction &I) {
125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
134 /// Return the specified operand before it is turned into an undef.
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
142 // Set the operand to undef to drop the use.
143 *i = UndefValue::get(Op->getType());
150 virtual bool runOnFunction(Function &F);
152 bool DoOneIteration(Function &F, unsigned ItNum);
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
160 TargetData &getTargetData() const { return *TD; }
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
175 Instruction *commonRemTransforms(BinaryOperator &I);
176 Instruction *commonIRemTransforms(BinaryOperator &I);
177 Instruction *commonDivTransforms(BinaryOperator &I);
178 Instruction *commonIDivTransforms(BinaryOperator &I);
179 Instruction *visitUDiv(BinaryOperator &I);
180 Instruction *visitSDiv(BinaryOperator &I);
181 Instruction *visitFDiv(BinaryOperator &I);
182 Instruction *visitAnd(BinaryOperator &I);
183 Instruction *visitOr (BinaryOperator &I);
184 Instruction *visitXor(BinaryOperator &I);
185 Instruction *visitShl(BinaryOperator &I);
186 Instruction *visitAShr(BinaryOperator &I);
187 Instruction *visitLShr(BinaryOperator &I);
188 Instruction *commonShiftTransforms(BinaryOperator &I);
189 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
191 Instruction *visitFCmpInst(FCmpInst &I);
192 Instruction *visitICmpInst(ICmpInst &I);
193 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
194 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
197 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198 ConstantInt *DivRHS);
200 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201 ICmpInst::Predicate Cond, Instruction &I);
202 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
204 Instruction *commonCastTransforms(CastInst &CI);
205 Instruction *commonIntCastTransforms(CastInst &CI);
206 Instruction *commonPointerCastTransforms(CastInst &CI);
207 Instruction *visitTrunc(TruncInst &CI);
208 Instruction *visitZExt(ZExtInst &CI);
209 Instruction *visitSExt(SExtInst &CI);
210 Instruction *visitFPTrunc(FPTruncInst &CI);
211 Instruction *visitFPExt(CastInst &CI);
212 Instruction *visitFPToUI(FPToUIInst &FI);
213 Instruction *visitFPToSI(FPToSIInst &FI);
214 Instruction *visitUIToFP(CastInst &CI);
215 Instruction *visitSIToFP(CastInst &CI);
216 Instruction *visitPtrToInt(CastInst &CI);
217 Instruction *visitIntToPtr(IntToPtrInst &CI);
218 Instruction *visitBitCast(BitCastInst &CI);
219 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
221 Instruction *visitSelectInst(SelectInst &CI);
222 Instruction *visitCallInst(CallInst &CI);
223 Instruction *visitInvokeInst(InvokeInst &II);
224 Instruction *visitPHINode(PHINode &PN);
225 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
226 Instruction *visitAllocationInst(AllocationInst &AI);
227 Instruction *visitFreeInst(FreeInst &FI);
228 Instruction *visitLoadInst(LoadInst &LI);
229 Instruction *visitStoreInst(StoreInst &SI);
230 Instruction *visitBranchInst(BranchInst &BI);
231 Instruction *visitSwitchInst(SwitchInst &SI);
232 Instruction *visitInsertElementInst(InsertElementInst &IE);
233 Instruction *visitExtractElementInst(ExtractElementInst &EI);
234 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235 Instruction *visitExtractValueInst(ExtractValueInst &EV);
237 // visitInstruction - Specify what to return for unhandled instructions...
238 Instruction *visitInstruction(Instruction &I) { return 0; }
241 Instruction *visitCallSite(CallSite CS);
242 bool transformConstExprCastCall(CallSite CS);
243 Instruction *transformCallThroughTrampoline(CallSite CS);
244 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245 bool DoXform = true);
246 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
249 // InsertNewInstBefore - insert an instruction New before instruction Old
250 // in the program. Add the new instruction to the worklist.
252 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
253 assert(New && New->getParent() == 0 &&
254 "New instruction already inserted into a basic block!");
255 BasicBlock *BB = Old.getParent();
256 BB->getInstList().insert(&Old, New); // Insert inst
261 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262 /// This also adds the cast to the worklist. Finally, this returns the
264 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
266 if (V->getType() == Ty) return V;
268 if (Constant *CV = dyn_cast<Constant>(V))
269 return ConstantExpr::getCast(opc, CV, Ty);
271 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
276 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
281 // ReplaceInstUsesWith - This method is to be used when an instruction is
282 // found to be dead, replacable with another preexisting expression. Here
283 // we add all uses of I to the worklist, replace all uses of I with the new
284 // value, then return I, so that the inst combiner will know that I was
287 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
288 AddUsersToWorkList(I); // Add all modified instrs to worklist
290 I.replaceAllUsesWith(V);
293 // If we are replacing the instruction with itself, this must be in a
294 // segment of unreachable code, so just clobber the instruction.
295 I.replaceAllUsesWith(UndefValue::get(I.getType()));
300 // UpdateValueUsesWith - This method is to be used when an value is
301 // found to be replacable with another preexisting expression or was
302 // updated. Here we add all uses of I to the worklist, replace all uses of
303 // I with the new value (unless the instruction was just updated), then
304 // return true, so that the inst combiner will know that I was modified.
306 bool UpdateValueUsesWith(Value *Old, Value *New) {
307 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
309 Old->replaceAllUsesWith(New);
310 if (Instruction *I = dyn_cast<Instruction>(Old))
312 if (Instruction *I = dyn_cast<Instruction>(New))
317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
324 RemoveFromWorkList(&I);
326 return 0; // Don't do anything with FI
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344 /// InsertBefore instruction. This is specialized a bit to avoid inserting
345 /// casts that are known to not do anything...
347 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348 Value *V, const Type *DestTy,
349 Instruction *InsertBefore);
351 /// SimplifyCommutative - This performs a few simplifications for
352 /// commutative operators.
353 bool SimplifyCommutative(BinaryOperator &I);
355 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356 /// most-complex to least-complex order.
357 bool SimplifyCompare(CmpInst &I);
359 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360 /// on the demanded bits.
361 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
362 APInt& KnownZero, APInt& KnownOne,
365 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366 uint64_t &UndefElts, unsigned Depth = 0);
368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384 bool isSub, Instruction &I);
385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386 bool isSigned, bool Inside, Instruction &IB);
387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388 Instruction *MatchBSwap(BinaryOperator &I);
389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391 Instruction *SimplifyMemSet(MemSetInst *MI);
394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
396 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
398 int &NumCastsRemoved);
399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
402 // visitExtractValue helpers
403 Value *FindScalarValue(Value *V,
404 const unsigned *idx_begin,
405 const unsigned *idx_end,
406 Instruction &InsertBefore);
407 Value *BuildSubAggregate(Value *From,
408 const unsigned *idx_begin,
409 const unsigned *idx_end,
410 Instruction &InsertBefore);
411 Value *BuildSubAggregate(Value *From,
413 const Type *IndexedType,
414 SmallVector<unsigned, 10> &Idxs,
416 Instruction &InsertBefore);
420 char InstCombiner::ID = 0;
421 static RegisterPass<InstCombiner>
422 X("instcombine", "Combine redundant instructions");
424 // getComplexity: Assign a complexity or rank value to LLVM Values...
425 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
426 static unsigned getComplexity(Value *V) {
427 if (isa<Instruction>(V)) {
428 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
432 if (isa<Argument>(V)) return 3;
433 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
436 // isOnlyUse - Return true if this instruction will be deleted if we stop using
438 static bool isOnlyUse(Value *V) {
439 return V->hasOneUse() || isa<Constant>(V);
442 // getPromotedType - Return the specified type promoted as it would be to pass
443 // though a va_arg area...
444 static const Type *getPromotedType(const Type *Ty) {
445 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
446 if (ITy->getBitWidth() < 32)
447 return Type::Int32Ty;
452 /// getBitCastOperand - If the specified operand is a CastInst or a constant
453 /// expression bitcast, return the operand value, otherwise return null.
454 static Value *getBitCastOperand(Value *V) {
455 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
456 return I->getOperand(0);
457 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
458 if (CE->getOpcode() == Instruction::BitCast)
459 return CE->getOperand(0);
463 /// This function is a wrapper around CastInst::isEliminableCastPair. It
464 /// simply extracts arguments and returns what that function returns.
465 static Instruction::CastOps
466 isEliminableCastPair(
467 const CastInst *CI, ///< The first cast instruction
468 unsigned opcode, ///< The opcode of the second cast instruction
469 const Type *DstTy, ///< The target type for the second cast instruction
470 TargetData *TD ///< The target data for pointer size
473 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
474 const Type *MidTy = CI->getType(); // B from above
476 // Get the opcodes of the two Cast instructions
477 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
478 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
480 return Instruction::CastOps(
481 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
482 DstTy, TD->getIntPtrType()));
485 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
486 /// in any code being generated. It does not require codegen if V is simple
487 /// enough or if the cast can be folded into other casts.
488 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
489 const Type *Ty, TargetData *TD) {
490 if (V->getType() == Ty || isa<Constant>(V)) return false;
492 // If this is another cast that can be eliminated, it isn't codegen either.
493 if (const CastInst *CI = dyn_cast<CastInst>(V))
494 if (isEliminableCastPair(CI, opcode, Ty, TD))
499 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
500 /// InsertBefore instruction. This is specialized a bit to avoid inserting
501 /// casts that are known to not do anything...
503 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
504 Value *V, const Type *DestTy,
505 Instruction *InsertBefore) {
506 if (V->getType() == DestTy) return V;
507 if (Constant *C = dyn_cast<Constant>(V))
508 return ConstantExpr::getCast(opcode, C, DestTy);
510 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
513 // SimplifyCommutative - This performs a few simplifications for commutative
516 // 1. Order operands such that they are listed from right (least complex) to
517 // left (most complex). This puts constants before unary operators before
520 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
521 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
523 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
524 bool Changed = false;
525 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
526 Changed = !I.swapOperands();
528 if (!I.isAssociative()) return Changed;
529 Instruction::BinaryOps Opcode = I.getOpcode();
530 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
531 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
532 if (isa<Constant>(I.getOperand(1))) {
533 Constant *Folded = ConstantExpr::get(I.getOpcode(),
534 cast<Constant>(I.getOperand(1)),
535 cast<Constant>(Op->getOperand(1)));
536 I.setOperand(0, Op->getOperand(0));
537 I.setOperand(1, Folded);
539 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
540 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
541 isOnlyUse(Op) && isOnlyUse(Op1)) {
542 Constant *C1 = cast<Constant>(Op->getOperand(1));
543 Constant *C2 = cast<Constant>(Op1->getOperand(1));
545 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
546 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
547 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
551 I.setOperand(0, New);
552 I.setOperand(1, Folded);
559 /// SimplifyCompare - For a CmpInst this function just orders the operands
560 /// so that theyare listed from right (least complex) to left (most complex).
561 /// This puts constants before unary operators before binary operators.
562 bool InstCombiner::SimplifyCompare(CmpInst &I) {
563 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
566 // Compare instructions are not associative so there's nothing else we can do.
570 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
571 // if the LHS is a constant zero (which is the 'negate' form).
573 static inline Value *dyn_castNegVal(Value *V) {
574 if (BinaryOperator::isNeg(V))
575 return BinaryOperator::getNegArgument(V);
577 // Constants can be considered to be negated values if they can be folded.
578 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
579 return ConstantExpr::getNeg(C);
581 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
582 if (C->getType()->getElementType()->isInteger())
583 return ConstantExpr::getNeg(C);
588 static inline Value *dyn_castNotVal(Value *V) {
589 if (BinaryOperator::isNot(V))
590 return BinaryOperator::getNotArgument(V);
592 // Constants can be considered to be not'ed values...
593 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
594 return ConstantInt::get(~C->getValue());
598 // dyn_castFoldableMul - If this value is a multiply that can be folded into
599 // other computations (because it has a constant operand), return the
600 // non-constant operand of the multiply, and set CST to point to the multiplier.
601 // Otherwise, return null.
603 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
604 if (V->hasOneUse() && V->getType()->isInteger())
605 if (Instruction *I = dyn_cast<Instruction>(V)) {
606 if (I->getOpcode() == Instruction::Mul)
607 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
608 return I->getOperand(0);
609 if (I->getOpcode() == Instruction::Shl)
610 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
611 // The multiplier is really 1 << CST.
612 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
613 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
614 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
615 return I->getOperand(0);
621 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
622 /// expression, return it.
623 static User *dyn_castGetElementPtr(Value *V) {
624 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
625 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
626 if (CE->getOpcode() == Instruction::GetElementPtr)
627 return cast<User>(V);
631 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
632 /// opcode value. Otherwise return UserOp1.
633 static unsigned getOpcode(const Value *V) {
634 if (const Instruction *I = dyn_cast<Instruction>(V))
635 return I->getOpcode();
636 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
637 return CE->getOpcode();
638 // Use UserOp1 to mean there's no opcode.
639 return Instruction::UserOp1;
642 /// AddOne - Add one to a ConstantInt
643 static ConstantInt *AddOne(ConstantInt *C) {
644 APInt Val(C->getValue());
645 return ConstantInt::get(++Val);
647 /// SubOne - Subtract one from a ConstantInt
648 static ConstantInt *SubOne(ConstantInt *C) {
649 APInt Val(C->getValue());
650 return ConstantInt::get(--Val);
652 /// Add - Add two ConstantInts together
653 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
654 return ConstantInt::get(C1->getValue() + C2->getValue());
656 /// And - Bitwise AND two ConstantInts together
657 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
658 return ConstantInt::get(C1->getValue() & C2->getValue());
660 /// Subtract - Subtract one ConstantInt from another
661 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
662 return ConstantInt::get(C1->getValue() - C2->getValue());
664 /// Multiply - Multiply two ConstantInts together
665 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
666 return ConstantInt::get(C1->getValue() * C2->getValue());
668 /// MultiplyOverflows - True if the multiply can not be expressed in an int
670 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
671 uint32_t W = C1->getBitWidth();
672 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
681 APInt MulExt = LHSExt * RHSExt;
684 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
685 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
686 return MulExt.slt(Min) || MulExt.sgt(Max);
688 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
692 /// ShrinkDemandedConstant - Check to see if the specified operand of the
693 /// specified instruction is a constant integer. If so, check to see if there
694 /// are any bits set in the constant that are not demanded. If so, shrink the
695 /// constant and return true.
696 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
698 assert(I && "No instruction?");
699 assert(OpNo < I->getNumOperands() && "Operand index too large");
701 // If the operand is not a constant integer, nothing to do.
702 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
703 if (!OpC) return false;
705 // If there are no bits set that aren't demanded, nothing to do.
706 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
707 if ((~Demanded & OpC->getValue()) == 0)
710 // This instruction is producing bits that are not demanded. Shrink the RHS.
711 Demanded &= OpC->getValue();
712 I->setOperand(OpNo, ConstantInt::get(Demanded));
716 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
717 // set of known zero and one bits, compute the maximum and minimum values that
718 // could have the specified known zero and known one bits, returning them in
720 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
721 const APInt& KnownZero,
722 const APInt& KnownOne,
723 APInt& Min, APInt& Max) {
724 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
725 assert(KnownZero.getBitWidth() == BitWidth &&
726 KnownOne.getBitWidth() == BitWidth &&
727 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
728 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
729 APInt UnknownBits = ~(KnownZero|KnownOne);
731 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
732 // bit if it is unknown.
734 Max = KnownOne|UnknownBits;
736 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
738 Max.clear(BitWidth-1);
742 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
743 // a set of known zero and one bits, compute the maximum and minimum values that
744 // could have the specified known zero and known one bits, returning them in
746 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
747 const APInt &KnownZero,
748 const APInt &KnownOne,
749 APInt &Min, APInt &Max) {
750 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
751 assert(KnownZero.getBitWidth() == BitWidth &&
752 KnownOne.getBitWidth() == BitWidth &&
753 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
754 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
755 APInt UnknownBits = ~(KnownZero|KnownOne);
757 // The minimum value is when the unknown bits are all zeros.
759 // The maximum value is when the unknown bits are all ones.
760 Max = KnownOne|UnknownBits;
763 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
764 /// value based on the demanded bits. When this function is called, it is known
765 /// that only the bits set in DemandedMask of the result of V are ever used
766 /// downstream. Consequently, depending on the mask and V, it may be possible
767 /// to replace V with a constant or one of its operands. In such cases, this
768 /// function does the replacement and returns true. In all other cases, it
769 /// returns false after analyzing the expression and setting KnownOne and known
770 /// to be one in the expression. KnownZero contains all the bits that are known
771 /// to be zero in the expression. These are provided to potentially allow the
772 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
773 /// the expression. KnownOne and KnownZero always follow the invariant that
774 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
775 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
776 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
777 /// and KnownOne must all be the same.
778 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
779 APInt& KnownZero, APInt& KnownOne,
781 assert(V != 0 && "Null pointer of Value???");
782 assert(Depth <= 6 && "Limit Search Depth");
783 uint32_t BitWidth = DemandedMask.getBitWidth();
784 const IntegerType *VTy = cast<IntegerType>(V->getType());
785 assert(VTy->getBitWidth() == BitWidth &&
786 KnownZero.getBitWidth() == BitWidth &&
787 KnownOne.getBitWidth() == BitWidth &&
788 "Value *V, DemandedMask, KnownZero and KnownOne \
789 must have same BitWidth");
790 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
791 // We know all of the bits for a constant!
792 KnownOne = CI->getValue() & DemandedMask;
793 KnownZero = ~KnownOne & DemandedMask;
799 if (!V->hasOneUse()) { // Other users may use these bits.
800 if (Depth != 0) { // Not at the root.
801 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
802 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
805 // If this is the root being simplified, allow it to have multiple uses,
806 // just set the DemandedMask to all bits.
807 DemandedMask = APInt::getAllOnesValue(BitWidth);
808 } else if (DemandedMask == 0) { // Not demanding any bits from V.
809 if (V != UndefValue::get(VTy))
810 return UpdateValueUsesWith(V, UndefValue::get(VTy));
812 } else if (Depth == 6) { // Limit search depth.
816 Instruction *I = dyn_cast<Instruction>(V);
817 if (!I) return false; // Only analyze instructions.
819 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
820 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
821 switch (I->getOpcode()) {
823 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
825 case Instruction::And:
826 // If either the LHS or the RHS are Zero, the result is zero.
827 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
828 RHSKnownZero, RHSKnownOne, Depth+1))
830 assert((RHSKnownZero & RHSKnownOne) == 0 &&
831 "Bits known to be one AND zero?");
833 // If something is known zero on the RHS, the bits aren't demanded on the
835 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
836 LHSKnownZero, LHSKnownOne, Depth+1))
838 assert((LHSKnownZero & LHSKnownOne) == 0 &&
839 "Bits known to be one AND zero?");
841 // If all of the demanded bits are known 1 on one side, return the other.
842 // These bits cannot contribute to the result of the 'and'.
843 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
844 (DemandedMask & ~LHSKnownZero))
845 return UpdateValueUsesWith(I, I->getOperand(0));
846 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
847 (DemandedMask & ~RHSKnownZero))
848 return UpdateValueUsesWith(I, I->getOperand(1));
850 // If all of the demanded bits in the inputs are known zeros, return zero.
851 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
852 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
854 // If the RHS is a constant, see if we can simplify it.
855 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
856 return UpdateValueUsesWith(I, I);
858 // Output known-1 bits are only known if set in both the LHS & RHS.
859 RHSKnownOne &= LHSKnownOne;
860 // Output known-0 are known to be clear if zero in either the LHS | RHS.
861 RHSKnownZero |= LHSKnownZero;
863 case Instruction::Or:
864 // If either the LHS or the RHS are One, the result is One.
865 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
866 RHSKnownZero, RHSKnownOne, Depth+1))
868 assert((RHSKnownZero & RHSKnownOne) == 0 &&
869 "Bits known to be one AND zero?");
870 // If something is known one on the RHS, the bits aren't demanded on the
872 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
873 LHSKnownZero, LHSKnownOne, Depth+1))
875 assert((LHSKnownZero & LHSKnownOne) == 0 &&
876 "Bits known to be one AND zero?");
878 // If all of the demanded bits are known zero on one side, return the other.
879 // These bits cannot contribute to the result of the 'or'.
880 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
881 (DemandedMask & ~LHSKnownOne))
882 return UpdateValueUsesWith(I, I->getOperand(0));
883 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
884 (DemandedMask & ~RHSKnownOne))
885 return UpdateValueUsesWith(I, I->getOperand(1));
887 // If all of the potentially set bits on one side are known to be set on
888 // the other side, just use the 'other' side.
889 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
890 (DemandedMask & (~RHSKnownZero)))
891 return UpdateValueUsesWith(I, I->getOperand(0));
892 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
893 (DemandedMask & (~LHSKnownZero)))
894 return UpdateValueUsesWith(I, I->getOperand(1));
896 // If the RHS is a constant, see if we can simplify it.
897 if (ShrinkDemandedConstant(I, 1, DemandedMask))
898 return UpdateValueUsesWith(I, I);
900 // Output known-0 bits are only known if clear in both the LHS & RHS.
901 RHSKnownZero &= LHSKnownZero;
902 // Output known-1 are known to be set if set in either the LHS | RHS.
903 RHSKnownOne |= LHSKnownOne;
905 case Instruction::Xor: {
906 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
907 RHSKnownZero, RHSKnownOne, Depth+1))
909 assert((RHSKnownZero & RHSKnownOne) == 0 &&
910 "Bits known to be one AND zero?");
911 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
912 LHSKnownZero, LHSKnownOne, Depth+1))
914 assert((LHSKnownZero & LHSKnownOne) == 0 &&
915 "Bits known to be one AND zero?");
917 // If all of the demanded bits are known zero on one side, return the other.
918 // These bits cannot contribute to the result of the 'xor'.
919 if ((DemandedMask & RHSKnownZero) == DemandedMask)
920 return UpdateValueUsesWith(I, I->getOperand(0));
921 if ((DemandedMask & LHSKnownZero) == DemandedMask)
922 return UpdateValueUsesWith(I, I->getOperand(1));
924 // Output known-0 bits are known if clear or set in both the LHS & RHS.
925 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
926 (RHSKnownOne & LHSKnownOne);
927 // Output known-1 are known to be set if set in only one of the LHS, RHS.
928 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
929 (RHSKnownOne & LHSKnownZero);
931 // If all of the demanded bits are known to be zero on one side or the
932 // other, turn this into an *inclusive* or.
933 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
934 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
936 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
938 InsertNewInstBefore(Or, *I);
939 return UpdateValueUsesWith(I, Or);
942 // If all of the demanded bits on one side are known, and all of the set
943 // bits on that side are also known to be set on the other side, turn this
944 // into an AND, as we know the bits will be cleared.
945 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
946 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
948 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
949 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
951 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
952 InsertNewInstBefore(And, *I);
953 return UpdateValueUsesWith(I, And);
957 // If the RHS is a constant, see if we can simplify it.
958 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
959 if (ShrinkDemandedConstant(I, 1, DemandedMask))
960 return UpdateValueUsesWith(I, I);
962 RHSKnownZero = KnownZeroOut;
963 RHSKnownOne = KnownOneOut;
966 case Instruction::Select:
967 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
968 RHSKnownZero, RHSKnownOne, Depth+1))
970 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
971 LHSKnownZero, LHSKnownOne, Depth+1))
973 assert((RHSKnownZero & RHSKnownOne) == 0 &&
974 "Bits known to be one AND zero?");
975 assert((LHSKnownZero & LHSKnownOne) == 0 &&
976 "Bits known to be one AND zero?");
978 // If the operands are constants, see if we can simplify them.
979 if (ShrinkDemandedConstant(I, 1, DemandedMask))
980 return UpdateValueUsesWith(I, I);
981 if (ShrinkDemandedConstant(I, 2, DemandedMask))
982 return UpdateValueUsesWith(I, I);
984 // Only known if known in both the LHS and RHS.
985 RHSKnownOne &= LHSKnownOne;
986 RHSKnownZero &= LHSKnownZero;
988 case Instruction::Trunc: {
990 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
991 DemandedMask.zext(truncBf);
992 RHSKnownZero.zext(truncBf);
993 RHSKnownOne.zext(truncBf);
994 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
995 RHSKnownZero, RHSKnownOne, Depth+1))
997 DemandedMask.trunc(BitWidth);
998 RHSKnownZero.trunc(BitWidth);
999 RHSKnownOne.trunc(BitWidth);
1000 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1001 "Bits known to be one AND zero?");
1004 case Instruction::BitCast:
1005 if (!I->getOperand(0)->getType()->isInteger())
1008 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009 RHSKnownZero, RHSKnownOne, Depth+1))
1011 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1012 "Bits known to be one AND zero?");
1014 case Instruction::ZExt: {
1015 // Compute the bits in the result that are not present in the input.
1016 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1017 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1019 DemandedMask.trunc(SrcBitWidth);
1020 RHSKnownZero.trunc(SrcBitWidth);
1021 RHSKnownOne.trunc(SrcBitWidth);
1022 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1023 RHSKnownZero, RHSKnownOne, Depth+1))
1025 DemandedMask.zext(BitWidth);
1026 RHSKnownZero.zext(BitWidth);
1027 RHSKnownOne.zext(BitWidth);
1028 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1029 "Bits known to be one AND zero?");
1030 // The top bits are known to be zero.
1031 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1034 case Instruction::SExt: {
1035 // Compute the bits in the result that are not present in the input.
1036 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1037 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1039 APInt InputDemandedBits = DemandedMask &
1040 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1042 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1043 // If any of the sign extended bits are demanded, we know that the sign
1045 if ((NewBits & DemandedMask) != 0)
1046 InputDemandedBits.set(SrcBitWidth-1);
1048 InputDemandedBits.trunc(SrcBitWidth);
1049 RHSKnownZero.trunc(SrcBitWidth);
1050 RHSKnownOne.trunc(SrcBitWidth);
1051 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1052 RHSKnownZero, RHSKnownOne, Depth+1))
1054 InputDemandedBits.zext(BitWidth);
1055 RHSKnownZero.zext(BitWidth);
1056 RHSKnownOne.zext(BitWidth);
1057 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1058 "Bits known to be one AND zero?");
1060 // If the sign bit of the input is known set or clear, then we know the
1061 // top bits of the result.
1063 // If the input sign bit is known zero, or if the NewBits are not demanded
1064 // convert this into a zero extension.
1065 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1067 // Convert to ZExt cast
1068 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1069 return UpdateValueUsesWith(I, NewCast);
1070 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1071 RHSKnownOne |= NewBits;
1075 case Instruction::Add: {
1076 // Figure out what the input bits are. If the top bits of the and result
1077 // are not demanded, then the add doesn't demand them from its input
1079 uint32_t NLZ = DemandedMask.countLeadingZeros();
1081 // If there is a constant on the RHS, there are a variety of xformations
1083 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1084 // If null, this should be simplified elsewhere. Some of the xforms here
1085 // won't work if the RHS is zero.
1089 // If the top bit of the output is demanded, demand everything from the
1090 // input. Otherwise, we demand all the input bits except NLZ top bits.
1091 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1093 // Find information about known zero/one bits in the input.
1094 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1095 LHSKnownZero, LHSKnownOne, Depth+1))
1098 // If the RHS of the add has bits set that can't affect the input, reduce
1100 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1101 return UpdateValueUsesWith(I, I);
1103 // Avoid excess work.
1104 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1107 // Turn it into OR if input bits are zero.
1108 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1110 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1112 InsertNewInstBefore(Or, *I);
1113 return UpdateValueUsesWith(I, Or);
1116 // We can say something about the output known-zero and known-one bits,
1117 // depending on potential carries from the input constant and the
1118 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1119 // bits set and the RHS constant is 0x01001, then we know we have a known
1120 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1122 // To compute this, we first compute the potential carry bits. These are
1123 // the bits which may be modified. I'm not aware of a better way to do
1125 const APInt& RHSVal = RHS->getValue();
1126 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1128 // Now that we know which bits have carries, compute the known-1/0 sets.
1130 // Bits are known one if they are known zero in one operand and one in the
1131 // other, and there is no input carry.
1132 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1133 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1135 // Bits are known zero if they are known zero in both operands and there
1136 // is no input carry.
1137 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1139 // If the high-bits of this ADD are not demanded, then it does not demand
1140 // the high bits of its LHS or RHS.
1141 if (DemandedMask[BitWidth-1] == 0) {
1142 // Right fill the mask of bits for this ADD to demand the most
1143 // significant bit and all those below it.
1144 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1145 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1146 LHSKnownZero, LHSKnownOne, Depth+1))
1148 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1149 LHSKnownZero, LHSKnownOne, Depth+1))
1155 case Instruction::Sub:
1156 // If the high-bits of this SUB are not demanded, then it does not demand
1157 // the high bits of its LHS or RHS.
1158 if (DemandedMask[BitWidth-1] == 0) {
1159 // Right fill the mask of bits for this SUB to demand the most
1160 // significant bit and all those below it.
1161 uint32_t NLZ = DemandedMask.countLeadingZeros();
1162 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1163 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1164 LHSKnownZero, LHSKnownOne, Depth+1))
1166 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1167 LHSKnownZero, LHSKnownOne, Depth+1))
1170 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1171 // the known zeros and ones.
1172 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1174 case Instruction::Shl:
1175 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1176 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1177 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1178 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1179 RHSKnownZero, RHSKnownOne, Depth+1))
1181 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1182 "Bits known to be one AND zero?");
1183 RHSKnownZero <<= ShiftAmt;
1184 RHSKnownOne <<= ShiftAmt;
1185 // low bits known zero.
1187 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1190 case Instruction::LShr:
1191 // For a logical shift right
1192 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1193 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1195 // Unsigned shift right.
1196 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1197 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1198 RHSKnownZero, RHSKnownOne, Depth+1))
1200 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1201 "Bits known to be one AND zero?");
1202 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1203 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1205 // Compute the new bits that are at the top now.
1206 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1207 RHSKnownZero |= HighBits; // high bits known zero.
1211 case Instruction::AShr:
1212 // If this is an arithmetic shift right and only the low-bit is set, we can
1213 // always convert this into a logical shr, even if the shift amount is
1214 // variable. The low bit of the shift cannot be an input sign bit unless
1215 // the shift amount is >= the size of the datatype, which is undefined.
1216 if (DemandedMask == 1) {
1217 // Perform the logical shift right.
1218 Value *NewVal = BinaryOperator::CreateLShr(
1219 I->getOperand(0), I->getOperand(1), I->getName());
1220 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1221 return UpdateValueUsesWith(I, NewVal);
1224 // If the sign bit is the only bit demanded by this ashr, then there is no
1225 // need to do it, the shift doesn't change the high bit.
1226 if (DemandedMask.isSignBit())
1227 return UpdateValueUsesWith(I, I->getOperand(0));
1229 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1230 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1232 // Signed shift right.
1233 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1234 // If any of the "high bits" are demanded, we should set the sign bit as
1236 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1237 DemandedMaskIn.set(BitWidth-1);
1238 if (SimplifyDemandedBits(I->getOperand(0),
1240 RHSKnownZero, RHSKnownOne, Depth+1))
1242 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1243 "Bits known to be one AND zero?");
1244 // Compute the new bits that are at the top now.
1245 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1246 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1247 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1249 // Handle the sign bits.
1250 APInt SignBit(APInt::getSignBit(BitWidth));
1251 // Adjust to where it is now in the mask.
1252 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1254 // If the input sign bit is known to be zero, or if none of the top bits
1255 // are demanded, turn this into an unsigned shift right.
1256 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1257 (HighBits & ~DemandedMask) == HighBits) {
1258 // Perform the logical shift right.
1259 Value *NewVal = BinaryOperator::CreateLShr(
1260 I->getOperand(0), SA, I->getName());
1261 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1262 return UpdateValueUsesWith(I, NewVal);
1263 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1264 RHSKnownOne |= HighBits;
1268 case Instruction::SRem:
1269 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1270 APInt RA = Rem->getValue();
1271 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1272 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1273 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1274 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1275 LHSKnownZero, LHSKnownOne, Depth+1))
1278 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1279 LHSKnownZero |= ~LowBits;
1280 else if (LHSKnownOne[BitWidth-1])
1281 LHSKnownOne |= ~LowBits;
1283 KnownZero |= LHSKnownZero & DemandedMask;
1284 KnownOne |= LHSKnownOne & DemandedMask;
1286 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1290 case Instruction::URem: {
1291 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1292 APInt RA = Rem->getValue();
1293 if (RA.isPowerOf2()) {
1294 APInt LowBits = (RA - 1);
1295 APInt Mask2 = LowBits & DemandedMask;
1296 KnownZero |= ~LowBits & DemandedMask;
1297 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1298 KnownZero, KnownOne, Depth+1))
1301 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1306 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1307 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1308 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1309 KnownZero2, KnownOne2, Depth+1))
1312 uint32_t Leaders = KnownZero2.countLeadingOnes();
1313 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1314 KnownZero2, KnownOne2, Depth+1))
1317 Leaders = std::max(Leaders,
1318 KnownZero2.countLeadingOnes());
1319 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1324 // If the client is only demanding bits that we know, return the known
1326 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1327 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1332 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1333 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1334 /// actually used by the caller. This method analyzes which elements of the
1335 /// operand are undef and returns that information in UndefElts.
1337 /// If the information about demanded elements can be used to simplify the
1338 /// operation, the operation is simplified, then the resultant value is
1339 /// returned. This returns null if no change was made.
1340 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1341 uint64_t &UndefElts,
1343 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1344 assert(VWidth <= 64 && "Vector too wide to analyze!");
1345 uint64_t EltMask = ~0ULL >> (64-VWidth);
1346 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1347 "Invalid DemandedElts!");
1349 if (isa<UndefValue>(V)) {
1350 // If the entire vector is undefined, just return this info.
1351 UndefElts = EltMask;
1353 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1354 UndefElts = EltMask;
1355 return UndefValue::get(V->getType());
1359 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1360 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1361 Constant *Undef = UndefValue::get(EltTy);
1363 std::vector<Constant*> Elts;
1364 for (unsigned i = 0; i != VWidth; ++i)
1365 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1366 Elts.push_back(Undef);
1367 UndefElts |= (1ULL << i);
1368 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1369 Elts.push_back(Undef);
1370 UndefElts |= (1ULL << i);
1371 } else { // Otherwise, defined.
1372 Elts.push_back(CP->getOperand(i));
1375 // If we changed the constant, return it.
1376 Constant *NewCP = ConstantVector::get(Elts);
1377 return NewCP != CP ? NewCP : 0;
1378 } else if (isa<ConstantAggregateZero>(V)) {
1379 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1381 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1382 Constant *Zero = Constant::getNullValue(EltTy);
1383 Constant *Undef = UndefValue::get(EltTy);
1384 std::vector<Constant*> Elts;
1385 for (unsigned i = 0; i != VWidth; ++i)
1386 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1387 UndefElts = DemandedElts ^ EltMask;
1388 return ConstantVector::get(Elts);
1391 if (!V->hasOneUse()) { // Other users may use these bits.
1392 if (Depth != 0) { // Not at the root.
1393 // TODO: Just compute the UndefElts information recursively.
1397 } else if (Depth == 10) { // Limit search depth.
1401 Instruction *I = dyn_cast<Instruction>(V);
1402 if (!I) return false; // Only analyze instructions.
1404 bool MadeChange = false;
1405 uint64_t UndefElts2;
1407 switch (I->getOpcode()) {
1410 case Instruction::InsertElement: {
1411 // If this is a variable index, we don't know which element it overwrites.
1412 // demand exactly the same input as we produce.
1413 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1415 // Note that we can't propagate undef elt info, because we don't know
1416 // which elt is getting updated.
1417 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1418 UndefElts2, Depth+1);
1419 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1423 // If this is inserting an element that isn't demanded, remove this
1425 unsigned IdxNo = Idx->getZExtValue();
1426 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1427 return AddSoonDeadInstToWorklist(*I, 0);
1429 // Otherwise, the element inserted overwrites whatever was there, so the
1430 // input demanded set is simpler than the output set.
1431 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1432 DemandedElts & ~(1ULL << IdxNo),
1433 UndefElts, Depth+1);
1434 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1436 // The inserted element is defined.
1437 UndefElts |= 1ULL << IdxNo;
1440 case Instruction::BitCast: {
1441 // Vector->vector casts only.
1442 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1444 unsigned InVWidth = VTy->getNumElements();
1445 uint64_t InputDemandedElts = 0;
1448 if (VWidth == InVWidth) {
1449 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1450 // elements as are demanded of us.
1452 InputDemandedElts = DemandedElts;
1453 } else if (VWidth > InVWidth) {
1457 // If there are more elements in the result than there are in the source,
1458 // then an input element is live if any of the corresponding output
1459 // elements are live.
1460 Ratio = VWidth/InVWidth;
1461 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1462 if (DemandedElts & (1ULL << OutIdx))
1463 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1469 // If there are more elements in the source than there are in the result,
1470 // then an input element is live if the corresponding output element is
1472 Ratio = InVWidth/VWidth;
1473 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1474 if (DemandedElts & (1ULL << InIdx/Ratio))
1475 InputDemandedElts |= 1ULL << InIdx;
1478 // div/rem demand all inputs, because they don't want divide by zero.
1479 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1480 UndefElts2, Depth+1);
1482 I->setOperand(0, TmpV);
1486 UndefElts = UndefElts2;
1487 if (VWidth > InVWidth) {
1488 assert(0 && "Unimp");
1489 // If there are more elements in the result than there are in the source,
1490 // then an output element is undef if the corresponding input element is
1492 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1493 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1494 UndefElts |= 1ULL << OutIdx;
1495 } else if (VWidth < InVWidth) {
1496 assert(0 && "Unimp");
1497 // If there are more elements in the source than there are in the result,
1498 // then a result element is undef if all of the corresponding input
1499 // elements are undef.
1500 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1501 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1502 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1503 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1507 case Instruction::And:
1508 case Instruction::Or:
1509 case Instruction::Xor:
1510 case Instruction::Add:
1511 case Instruction::Sub:
1512 case Instruction::Mul:
1513 // div/rem demand all inputs, because they don't want divide by zero.
1514 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1515 UndefElts, Depth+1);
1516 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1518 UndefElts2, Depth+1);
1519 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1521 // Output elements are undefined if both are undefined. Consider things
1522 // like undef&0. The result is known zero, not undef.
1523 UndefElts &= UndefElts2;
1526 case Instruction::Call: {
1527 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1529 switch (II->getIntrinsicID()) {
1532 // Binary vector operations that work column-wise. A dest element is a
1533 // function of the corresponding input elements from the two inputs.
1534 case Intrinsic::x86_sse_sub_ss:
1535 case Intrinsic::x86_sse_mul_ss:
1536 case Intrinsic::x86_sse_min_ss:
1537 case Intrinsic::x86_sse_max_ss:
1538 case Intrinsic::x86_sse2_sub_sd:
1539 case Intrinsic::x86_sse2_mul_sd:
1540 case Intrinsic::x86_sse2_min_sd:
1541 case Intrinsic::x86_sse2_max_sd:
1542 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1543 UndefElts, Depth+1);
1544 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1545 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1546 UndefElts2, Depth+1);
1547 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1549 // If only the low elt is demanded and this is a scalarizable intrinsic,
1550 // scalarize it now.
1551 if (DemandedElts == 1) {
1552 switch (II->getIntrinsicID()) {
1554 case Intrinsic::x86_sse_sub_ss:
1555 case Intrinsic::x86_sse_mul_ss:
1556 case Intrinsic::x86_sse2_sub_sd:
1557 case Intrinsic::x86_sse2_mul_sd:
1558 // TODO: Lower MIN/MAX/ABS/etc
1559 Value *LHS = II->getOperand(1);
1560 Value *RHS = II->getOperand(2);
1561 // Extract the element as scalars.
1562 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1563 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1565 switch (II->getIntrinsicID()) {
1566 default: assert(0 && "Case stmts out of sync!");
1567 case Intrinsic::x86_sse_sub_ss:
1568 case Intrinsic::x86_sse2_sub_sd:
1569 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1570 II->getName()), *II);
1572 case Intrinsic::x86_sse_mul_ss:
1573 case Intrinsic::x86_sse2_mul_sd:
1574 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1575 II->getName()), *II);
1580 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1582 InsertNewInstBefore(New, *II);
1583 AddSoonDeadInstToWorklist(*II, 0);
1588 // Output elements are undefined if both are undefined. Consider things
1589 // like undef&0. The result is known zero, not undef.
1590 UndefElts &= UndefElts2;
1596 return MadeChange ? I : 0;
1600 /// AssociativeOpt - Perform an optimization on an associative operator. This
1601 /// function is designed to check a chain of associative operators for a
1602 /// potential to apply a certain optimization. Since the optimization may be
1603 /// applicable if the expression was reassociated, this checks the chain, then
1604 /// reassociates the expression as necessary to expose the optimization
1605 /// opportunity. This makes use of a special Functor, which must define
1606 /// 'shouldApply' and 'apply' methods.
1608 template<typename Functor>
1609 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1610 unsigned Opcode = Root.getOpcode();
1611 Value *LHS = Root.getOperand(0);
1613 // Quick check, see if the immediate LHS matches...
1614 if (F.shouldApply(LHS))
1615 return F.apply(Root);
1617 // Otherwise, if the LHS is not of the same opcode as the root, return.
1618 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1619 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1620 // Should we apply this transform to the RHS?
1621 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1623 // If not to the RHS, check to see if we should apply to the LHS...
1624 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1625 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1629 // If the functor wants to apply the optimization to the RHS of LHSI,
1630 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1632 BasicBlock *BB = Root.getParent();
1634 // Now all of the instructions are in the current basic block, go ahead
1635 // and perform the reassociation.
1636 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1638 // First move the selected RHS to the LHS of the root...
1639 Root.setOperand(0, LHSI->getOperand(1));
1641 // Make what used to be the LHS of the root be the user of the root...
1642 Value *ExtraOperand = TmpLHSI->getOperand(1);
1643 if (&Root == TmpLHSI) {
1644 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1647 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1648 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1649 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1650 BasicBlock::iterator ARI = &Root; ++ARI;
1651 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1654 // Now propagate the ExtraOperand down the chain of instructions until we
1656 while (TmpLHSI != LHSI) {
1657 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1658 // Move the instruction to immediately before the chain we are
1659 // constructing to avoid breaking dominance properties.
1660 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1661 BB->getInstList().insert(ARI, NextLHSI);
1664 Value *NextOp = NextLHSI->getOperand(1);
1665 NextLHSI->setOperand(1, ExtraOperand);
1667 ExtraOperand = NextOp;
1670 // Now that the instructions are reassociated, have the functor perform
1671 // the transformation...
1672 return F.apply(Root);
1675 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1682 // AddRHS - Implements: X + X --> X << 1
1685 AddRHS(Value *rhs) : RHS(rhs) {}
1686 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1687 Instruction *apply(BinaryOperator &Add) const {
1688 return BinaryOperator::CreateShl(Add.getOperand(0),
1689 ConstantInt::get(Add.getType(), 1));
1693 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1695 struct AddMaskingAnd {
1697 AddMaskingAnd(Constant *c) : C2(c) {}
1698 bool shouldApply(Value *LHS) const {
1700 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1701 ConstantExpr::getAnd(C1, C2)->isNullValue();
1703 Instruction *apply(BinaryOperator &Add) const {
1704 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1710 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1712 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1713 if (Constant *SOC = dyn_cast<Constant>(SO))
1714 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1716 return IC->InsertNewInstBefore(CastInst::Create(
1717 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1720 // Figure out if the constant is the left or the right argument.
1721 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1722 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1724 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1726 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1727 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1730 Value *Op0 = SO, *Op1 = ConstOperand;
1732 std::swap(Op0, Op1);
1734 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1735 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1736 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1737 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1738 SO->getName()+".cmp");
1740 assert(0 && "Unknown binary instruction type!");
1743 return IC->InsertNewInstBefore(New, I);
1746 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1747 // constant as the other operand, try to fold the binary operator into the
1748 // select arguments. This also works for Cast instructions, which obviously do
1749 // not have a second operand.
1750 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1752 // Don't modify shared select instructions
1753 if (!SI->hasOneUse()) return 0;
1754 Value *TV = SI->getOperand(1);
1755 Value *FV = SI->getOperand(2);
1757 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1758 // Bool selects with constant operands can be folded to logical ops.
1759 if (SI->getType() == Type::Int1Ty) return 0;
1761 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1762 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1764 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1771 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1772 /// node as operand #0, see if we can fold the instruction into the PHI (which
1773 /// is only possible if all operands to the PHI are constants).
1774 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1775 PHINode *PN = cast<PHINode>(I.getOperand(0));
1776 unsigned NumPHIValues = PN->getNumIncomingValues();
1777 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1779 // Check to see if all of the operands of the PHI are constants. If there is
1780 // one non-constant value, remember the BB it is. If there is more than one
1781 // or if *it* is a PHI, bail out.
1782 BasicBlock *NonConstBB = 0;
1783 for (unsigned i = 0; i != NumPHIValues; ++i)
1784 if (!isa<Constant>(PN->getIncomingValue(i))) {
1785 if (NonConstBB) return 0; // More than one non-const value.
1786 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1787 NonConstBB = PN->getIncomingBlock(i);
1789 // If the incoming non-constant value is in I's block, we have an infinite
1791 if (NonConstBB == I.getParent())
1795 // If there is exactly one non-constant value, we can insert a copy of the
1796 // operation in that block. However, if this is a critical edge, we would be
1797 // inserting the computation one some other paths (e.g. inside a loop). Only
1798 // do this if the pred block is unconditionally branching into the phi block.
1800 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1801 if (!BI || !BI->isUnconditional()) return 0;
1804 // Okay, we can do the transformation: create the new PHI node.
1805 PHINode *NewPN = PHINode::Create(I.getType(), "");
1806 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1807 InsertNewInstBefore(NewPN, *PN);
1808 NewPN->takeName(PN);
1810 // Next, add all of the operands to the PHI.
1811 if (I.getNumOperands() == 2) {
1812 Constant *C = cast<Constant>(I.getOperand(1));
1813 for (unsigned i = 0; i != NumPHIValues; ++i) {
1815 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1816 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1817 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1819 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1821 assert(PN->getIncomingBlock(i) == NonConstBB);
1822 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1823 InV = BinaryOperator::Create(BO->getOpcode(),
1824 PN->getIncomingValue(i), C, "phitmp",
1825 NonConstBB->getTerminator());
1826 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1827 InV = CmpInst::Create(CI->getOpcode(),
1829 PN->getIncomingValue(i), C, "phitmp",
1830 NonConstBB->getTerminator());
1832 assert(0 && "Unknown binop!");
1834 AddToWorkList(cast<Instruction>(InV));
1836 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1839 CastInst *CI = cast<CastInst>(&I);
1840 const Type *RetTy = CI->getType();
1841 for (unsigned i = 0; i != NumPHIValues; ++i) {
1843 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1844 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1846 assert(PN->getIncomingBlock(i) == NonConstBB);
1847 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
1848 I.getType(), "phitmp",
1849 NonConstBB->getTerminator());
1850 AddToWorkList(cast<Instruction>(InV));
1852 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1855 return ReplaceInstUsesWith(I, NewPN);
1859 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1860 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1861 /// This basically requires proving that the add in the original type would not
1862 /// overflow to change the sign bit or have a carry out.
1863 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1864 // There are different heuristics we can use for this. Here are some simple
1867 // Add has the property that adding any two 2's complement numbers can only
1868 // have one carry bit which can change a sign. As such, if LHS and RHS each
1869 // have at least two sign bits, we know that the addition of the two values will
1870 // sign extend fine.
1871 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1875 // If one of the operands only has one non-zero bit, and if the other operand
1876 // has a known-zero bit in a more significant place than it (not including the
1877 // sign bit) the ripple may go up to and fill the zero, but won't change the
1878 // sign. For example, (X & ~4) + 1.
1886 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1887 bool Changed = SimplifyCommutative(I);
1888 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1890 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1891 // X + undef -> undef
1892 if (isa<UndefValue>(RHS))
1893 return ReplaceInstUsesWith(I, RHS);
1896 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1897 if (RHSC->isNullValue())
1898 return ReplaceInstUsesWith(I, LHS);
1899 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1900 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1901 (I.getType())->getValueAPF()))
1902 return ReplaceInstUsesWith(I, LHS);
1905 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1906 // X + (signbit) --> X ^ signbit
1907 const APInt& Val = CI->getValue();
1908 uint32_t BitWidth = Val.getBitWidth();
1909 if (Val == APInt::getSignBit(BitWidth))
1910 return BinaryOperator::CreateXor(LHS, RHS);
1912 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1913 // (X & 254)+1 -> (X&254)|1
1914 if (!isa<VectorType>(I.getType())) {
1915 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1916 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1917 KnownZero, KnownOne))
1922 if (isa<PHINode>(LHS))
1923 if (Instruction *NV = FoldOpIntoPhi(I))
1926 ConstantInt *XorRHS = 0;
1928 if (isa<ConstantInt>(RHSC) &&
1929 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1930 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1931 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1933 uint32_t Size = TySizeBits / 2;
1934 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1935 APInt CFF80Val(-C0080Val);
1937 if (TySizeBits > Size) {
1938 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1939 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1940 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1941 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1942 // This is a sign extend if the top bits are known zero.
1943 if (!MaskedValueIsZero(XorLHS,
1944 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1945 Size = 0; // Not a sign ext, but can't be any others either.
1950 C0080Val = APIntOps::lshr(C0080Val, Size);
1951 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1952 } while (Size >= 1);
1954 // FIXME: This shouldn't be necessary. When the backends can handle types
1955 // with funny bit widths then this switch statement should be removed. It
1956 // is just here to get the size of the "middle" type back up to something
1957 // that the back ends can handle.
1958 const Type *MiddleType = 0;
1961 case 32: MiddleType = Type::Int32Ty; break;
1962 case 16: MiddleType = Type::Int16Ty; break;
1963 case 8: MiddleType = Type::Int8Ty; break;
1966 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1967 InsertNewInstBefore(NewTrunc, I);
1968 return new SExtInst(NewTrunc, I.getType(), I.getName());
1973 if (I.getType() == Type::Int1Ty)
1974 return BinaryOperator::CreateXor(LHS, RHS);
1977 if (I.getType()->isInteger()) {
1978 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1980 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1981 if (RHSI->getOpcode() == Instruction::Sub)
1982 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1983 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1985 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1986 if (LHSI->getOpcode() == Instruction::Sub)
1987 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1988 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1993 // -A + -B --> -(A + B)
1994 if (Value *LHSV = dyn_castNegVal(LHS)) {
1995 if (LHS->getType()->isIntOrIntVector()) {
1996 if (Value *RHSV = dyn_castNegVal(RHS)) {
1997 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
1998 InsertNewInstBefore(NewAdd, I);
1999 return BinaryOperator::CreateNeg(NewAdd);
2003 return BinaryOperator::CreateSub(RHS, LHSV);
2007 if (!isa<Constant>(RHS))
2008 if (Value *V = dyn_castNegVal(RHS))
2009 return BinaryOperator::CreateSub(LHS, V);
2013 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2014 if (X == RHS) // X*C + X --> X * (C+1)
2015 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2017 // X*C1 + X*C2 --> X * (C1+C2)
2019 if (X == dyn_castFoldableMul(RHS, C1))
2020 return BinaryOperator::CreateMul(X, Add(C1, C2));
2023 // X + X*C --> X * (C+1)
2024 if (dyn_castFoldableMul(RHS, C2) == LHS)
2025 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2027 // X + ~X --> -1 since ~X = -X-1
2028 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2029 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2032 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2033 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2034 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2037 // A+B --> A|B iff A and B have no bits set in common.
2038 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2039 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2040 APInt LHSKnownOne(IT->getBitWidth(), 0);
2041 APInt LHSKnownZero(IT->getBitWidth(), 0);
2042 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2043 if (LHSKnownZero != 0) {
2044 APInt RHSKnownOne(IT->getBitWidth(), 0);
2045 APInt RHSKnownZero(IT->getBitWidth(), 0);
2046 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2048 // No bits in common -> bitwise or.
2049 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2050 return BinaryOperator::CreateOr(LHS, RHS);
2054 // W*X + Y*Z --> W * (X+Z) iff W == Y
2055 if (I.getType()->isIntOrIntVector()) {
2056 Value *W, *X, *Y, *Z;
2057 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2058 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2062 } else if (Y == X) {
2064 } else if (X == Z) {
2071 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2072 LHS->getName()), I);
2073 return BinaryOperator::CreateMul(W, NewAdd);
2078 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2080 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2081 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2083 // (X & FF00) + xx00 -> (X+xx00) & FF00
2084 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2085 Constant *Anded = And(CRHS, C2);
2086 if (Anded == CRHS) {
2087 // See if all bits from the first bit set in the Add RHS up are included
2088 // in the mask. First, get the rightmost bit.
2089 const APInt& AddRHSV = CRHS->getValue();
2091 // Form a mask of all bits from the lowest bit added through the top.
2092 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2094 // See if the and mask includes all of these bits.
2095 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2097 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2098 // Okay, the xform is safe. Insert the new add pronto.
2099 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2100 LHS->getName()), I);
2101 return BinaryOperator::CreateAnd(NewAdd, C2);
2106 // Try to fold constant add into select arguments.
2107 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2108 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2112 // add (cast *A to intptrtype) B ->
2113 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
2115 CastInst *CI = dyn_cast<CastInst>(LHS);
2118 CI = dyn_cast<CastInst>(RHS);
2121 if (CI && CI->getType()->isSized() &&
2122 (CI->getType()->getPrimitiveSizeInBits() ==
2123 TD->getIntPtrType()->getPrimitiveSizeInBits())
2124 && isa<PointerType>(CI->getOperand(0)->getType())) {
2126 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2127 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2128 PointerType::get(Type::Int8Ty, AS), I);
2129 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2130 return new PtrToIntInst(I2, CI->getType());
2134 // add (select X 0 (sub n A)) A --> select X A n
2136 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2139 SI = dyn_cast<SelectInst>(RHS);
2142 if (SI && SI->hasOneUse()) {
2143 Value *TV = SI->getTrueValue();
2144 Value *FV = SI->getFalseValue();
2147 // Can we fold the add into the argument of the select?
2148 // We check both true and false select arguments for a matching subtract.
2149 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2150 A == Other) // Fold the add into the true select value.
2151 return SelectInst::Create(SI->getCondition(), N, A);
2152 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2153 A == Other) // Fold the add into the false select value.
2154 return SelectInst::Create(SI->getCondition(), A, N);
2158 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2159 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2160 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2161 return ReplaceInstUsesWith(I, LHS);
2163 // Check for (add (sext x), y), see if we can merge this into an
2164 // integer add followed by a sext.
2165 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2166 // (add (sext x), cst) --> (sext (add x, cst'))
2167 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2169 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2170 if (LHSConv->hasOneUse() &&
2171 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2172 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2173 // Insert the new, smaller add.
2174 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2176 InsertNewInstBefore(NewAdd, I);
2177 return new SExtInst(NewAdd, I.getType());
2181 // (add (sext x), (sext y)) --> (sext (add int x, y))
2182 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2183 // Only do this if x/y have the same type, if at last one of them has a
2184 // single use (so we don't increase the number of sexts), and if the
2185 // integer add will not overflow.
2186 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2187 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2188 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2189 RHSConv->getOperand(0))) {
2190 // Insert the new integer add.
2191 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2192 RHSConv->getOperand(0),
2194 InsertNewInstBefore(NewAdd, I);
2195 return new SExtInst(NewAdd, I.getType());
2200 // Check for (add double (sitofp x), y), see if we can merge this into an
2201 // integer add followed by a promotion.
2202 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2203 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2204 // ... if the constant fits in the integer value. This is useful for things
2205 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2206 // requires a constant pool load, and generally allows the add to be better
2208 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2210 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2211 if (LHSConv->hasOneUse() &&
2212 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2213 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2214 // Insert the new integer add.
2215 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2217 InsertNewInstBefore(NewAdd, I);
2218 return new SIToFPInst(NewAdd, I.getType());
2222 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2223 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2224 // Only do this if x/y have the same type, if at last one of them has a
2225 // single use (so we don't increase the number of int->fp conversions),
2226 // and if the integer add will not overflow.
2227 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2228 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2229 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2230 RHSConv->getOperand(0))) {
2231 // Insert the new integer add.
2232 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2233 RHSConv->getOperand(0),
2235 InsertNewInstBefore(NewAdd, I);
2236 return new SIToFPInst(NewAdd, I.getType());
2241 return Changed ? &I : 0;
2244 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2245 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2247 if (Op0 == Op1) // sub X, X -> 0
2248 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2250 // If this is a 'B = x-(-A)', change to B = x+A...
2251 if (Value *V = dyn_castNegVal(Op1))
2252 return BinaryOperator::CreateAdd(Op0, V);
2254 if (isa<UndefValue>(Op0))
2255 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2256 if (isa<UndefValue>(Op1))
2257 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2259 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2260 // Replace (-1 - A) with (~A)...
2261 if (C->isAllOnesValue())
2262 return BinaryOperator::CreateNot(Op1);
2264 // C - ~X == X + (1+C)
2266 if (match(Op1, m_Not(m_Value(X))))
2267 return BinaryOperator::CreateAdd(X, AddOne(C));
2269 // -(X >>u 31) -> (X >>s 31)
2270 // -(X >>s 31) -> (X >>u 31)
2272 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2273 if (SI->getOpcode() == Instruction::LShr) {
2274 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2275 // Check to see if we are shifting out everything but the sign bit.
2276 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2277 SI->getType()->getPrimitiveSizeInBits()-1) {
2278 // Ok, the transformation is safe. Insert AShr.
2279 return BinaryOperator::Create(Instruction::AShr,
2280 SI->getOperand(0), CU, SI->getName());
2284 else if (SI->getOpcode() == Instruction::AShr) {
2285 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2286 // Check to see if we are shifting out everything but the sign bit.
2287 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2288 SI->getType()->getPrimitiveSizeInBits()-1) {
2289 // Ok, the transformation is safe. Insert LShr.
2290 return BinaryOperator::CreateLShr(
2291 SI->getOperand(0), CU, SI->getName());
2298 // Try to fold constant sub into select arguments.
2299 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2300 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2303 if (isa<PHINode>(Op0))
2304 if (Instruction *NV = FoldOpIntoPhi(I))
2308 if (I.getType() == Type::Int1Ty)
2309 return BinaryOperator::CreateXor(Op0, Op1);
2311 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2312 if (Op1I->getOpcode() == Instruction::Add &&
2313 !Op0->getType()->isFPOrFPVector()) {
2314 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2315 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2316 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2317 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2318 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2319 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2320 // C1-(X+C2) --> (C1-C2)-X
2321 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
2322 Op1I->getOperand(0));
2326 if (Op1I->hasOneUse()) {
2327 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2328 // is not used by anyone else...
2330 if (Op1I->getOpcode() == Instruction::Sub &&
2331 !Op1I->getType()->isFPOrFPVector()) {
2332 // Swap the two operands of the subexpr...
2333 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2334 Op1I->setOperand(0, IIOp1);
2335 Op1I->setOperand(1, IIOp0);
2337 // Create the new top level add instruction...
2338 return BinaryOperator::CreateAdd(Op0, Op1);
2341 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2343 if (Op1I->getOpcode() == Instruction::And &&
2344 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2345 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2348 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2349 return BinaryOperator::CreateAnd(Op0, NewNot);
2352 // 0 - (X sdiv C) -> (X sdiv -C)
2353 if (Op1I->getOpcode() == Instruction::SDiv)
2354 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2356 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2357 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2358 ConstantExpr::getNeg(DivRHS));
2360 // X - X*C --> X * (1-C)
2361 ConstantInt *C2 = 0;
2362 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2363 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2364 return BinaryOperator::CreateMul(Op0, CP1);
2367 // X - ((X / Y) * Y) --> X % Y
2368 if (Op1I->getOpcode() == Instruction::Mul)
2369 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2370 if (Op0 == I->getOperand(0) &&
2371 Op1I->getOperand(1) == I->getOperand(1)) {
2372 if (I->getOpcode() == Instruction::SDiv)
2373 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2374 if (I->getOpcode() == Instruction::UDiv)
2375 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2380 if (!Op0->getType()->isFPOrFPVector())
2381 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2382 if (Op0I->getOpcode() == Instruction::Add) {
2383 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2384 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2385 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2386 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2387 } else if (Op0I->getOpcode() == Instruction::Sub) {
2388 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2389 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2394 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2395 if (X == Op1) // X*C - X --> X * (C-1)
2396 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2398 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2399 if (X == dyn_castFoldableMul(Op1, C2))
2400 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2405 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2406 /// comparison only checks the sign bit. If it only checks the sign bit, set
2407 /// TrueIfSigned if the result of the comparison is true when the input value is
2409 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2410 bool &TrueIfSigned) {
2412 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2413 TrueIfSigned = true;
2414 return RHS->isZero();
2415 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2416 TrueIfSigned = true;
2417 return RHS->isAllOnesValue();
2418 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2419 TrueIfSigned = false;
2420 return RHS->isAllOnesValue();
2421 case ICmpInst::ICMP_UGT:
2422 // True if LHS u> RHS and RHS == high-bit-mask - 1
2423 TrueIfSigned = true;
2424 return RHS->getValue() ==
2425 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2426 case ICmpInst::ICMP_UGE:
2427 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2428 TrueIfSigned = true;
2429 return RHS->getValue().isSignBit();
2435 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2436 bool Changed = SimplifyCommutative(I);
2437 Value *Op0 = I.getOperand(0);
2439 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2440 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2442 // Simplify mul instructions with a constant RHS...
2443 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2444 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2446 // ((X << C1)*C2) == (X * (C2 << C1))
2447 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2448 if (SI->getOpcode() == Instruction::Shl)
2449 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2450 return BinaryOperator::CreateMul(SI->getOperand(0),
2451 ConstantExpr::getShl(CI, ShOp));
2454 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2455 if (CI->equalsInt(1)) // X * 1 == X
2456 return ReplaceInstUsesWith(I, Op0);
2457 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2458 return BinaryOperator::CreateNeg(Op0, I.getName());
2460 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2461 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2462 return BinaryOperator::CreateShl(Op0,
2463 ConstantInt::get(Op0->getType(), Val.logBase2()));
2465 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2466 if (Op1F->isNullValue())
2467 return ReplaceInstUsesWith(I, Op1);
2469 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2470 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2471 // We need a better interface for long double here.
2472 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2473 if (Op1F->isExactlyValue(1.0))
2474 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2477 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2478 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2479 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2480 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2481 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2483 InsertNewInstBefore(Add, I);
2484 Value *C1C2 = ConstantExpr::getMul(Op1,
2485 cast<Constant>(Op0I->getOperand(1)));
2486 return BinaryOperator::CreateAdd(Add, C1C2);
2490 // Try to fold constant mul into select arguments.
2491 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2492 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2495 if (isa<PHINode>(Op0))
2496 if (Instruction *NV = FoldOpIntoPhi(I))
2500 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2501 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2502 return BinaryOperator::CreateMul(Op0v, Op1v);
2504 if (I.getType() == Type::Int1Ty)
2505 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2507 // If one of the operands of the multiply is a cast from a boolean value, then
2508 // we know the bool is either zero or one, so this is a 'masking' multiply.
2509 // See if we can simplify things based on how the boolean was originally
2511 CastInst *BoolCast = 0;
2512 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2513 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2516 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2517 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2520 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2521 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2522 const Type *SCOpTy = SCIOp0->getType();
2525 // If the icmp is true iff the sign bit of X is set, then convert this
2526 // multiply into a shift/and combination.
2527 if (isa<ConstantInt>(SCIOp1) &&
2528 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2530 // Shift the X value right to turn it into "all signbits".
2531 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2532 SCOpTy->getPrimitiveSizeInBits()-1);
2534 InsertNewInstBefore(
2535 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2536 BoolCast->getOperand(0)->getName()+
2539 // If the multiply type is not the same as the source type, sign extend
2540 // or truncate to the multiply type.
2541 if (I.getType() != V->getType()) {
2542 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2543 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2544 Instruction::CastOps opcode =
2545 (SrcBits == DstBits ? Instruction::BitCast :
2546 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2547 V = InsertCastBefore(opcode, V, I.getType(), I);
2550 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2551 return BinaryOperator::CreateAnd(V, OtherOp);
2556 return Changed ? &I : 0;
2559 /// This function implements the transforms on div instructions that work
2560 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2561 /// used by the visitors to those instructions.
2562 /// @brief Transforms common to all three div instructions
2563 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2564 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2566 // undef / X -> 0 for integer.
2567 // undef / X -> undef for FP (the undef could be a snan).
2568 if (isa<UndefValue>(Op0)) {
2569 if (Op0->getType()->isFPOrFPVector())
2570 return ReplaceInstUsesWith(I, Op0);
2571 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2574 // X / undef -> undef
2575 if (isa<UndefValue>(Op1))
2576 return ReplaceInstUsesWith(I, Op1);
2578 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2579 // This does not apply for fdiv.
2580 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2581 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2582 // the same basic block, then we replace the select with Y, and the
2583 // condition of the select with false (if the cond value is in the same BB).
2584 // If the select has uses other than the div, this allows them to be
2585 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2586 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2587 if (ST->isNullValue()) {
2588 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2589 if (CondI && CondI->getParent() == I.getParent())
2590 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2591 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2592 I.setOperand(1, SI->getOperand(2));
2594 UpdateValueUsesWith(SI, SI->getOperand(2));
2598 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2599 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2600 if (ST->isNullValue()) {
2601 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2602 if (CondI && CondI->getParent() == I.getParent())
2603 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2604 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2605 I.setOperand(1, SI->getOperand(1));
2607 UpdateValueUsesWith(SI, SI->getOperand(1));
2615 /// This function implements the transforms common to both integer division
2616 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2617 /// division instructions.
2618 /// @brief Common integer divide transforms
2619 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2622 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2624 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2625 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2626 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2627 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2630 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2631 return ReplaceInstUsesWith(I, CI);
2634 if (Instruction *Common = commonDivTransforms(I))
2637 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2639 if (RHS->equalsInt(1))
2640 return ReplaceInstUsesWith(I, Op0);
2642 // (X / C1) / C2 -> X / (C1*C2)
2643 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2644 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2645 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2646 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2647 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2649 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2650 Multiply(RHS, LHSRHS));
2653 if (!RHS->isZero()) { // avoid X udiv 0
2654 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2655 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2657 if (isa<PHINode>(Op0))
2658 if (Instruction *NV = FoldOpIntoPhi(I))
2663 // 0 / X == 0, we don't need to preserve faults!
2664 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2665 if (LHS->equalsInt(0))
2666 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2668 // It can't be division by zero, hence it must be division by one.
2669 if (I.getType() == Type::Int1Ty)
2670 return ReplaceInstUsesWith(I, Op0);
2675 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2676 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2678 // Handle the integer div common cases
2679 if (Instruction *Common = commonIDivTransforms(I))
2682 // X udiv C^2 -> X >> C
2683 // Check to see if this is an unsigned division with an exact power of 2,
2684 // if so, convert to a right shift.
2685 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2686 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2687 return BinaryOperator::CreateLShr(Op0,
2688 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2691 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2692 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2693 if (RHSI->getOpcode() == Instruction::Shl &&
2694 isa<ConstantInt>(RHSI->getOperand(0))) {
2695 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2696 if (C1.isPowerOf2()) {
2697 Value *N = RHSI->getOperand(1);
2698 const Type *NTy = N->getType();
2699 if (uint32_t C2 = C1.logBase2()) {
2700 Constant *C2V = ConstantInt::get(NTy, C2);
2701 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2703 return BinaryOperator::CreateLShr(Op0, N);
2708 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2709 // where C1&C2 are powers of two.
2710 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2711 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2712 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2713 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2714 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2715 // Compute the shift amounts
2716 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2717 // Construct the "on true" case of the select
2718 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2719 Instruction *TSI = BinaryOperator::CreateLShr(
2720 Op0, TC, SI->getName()+".t");
2721 TSI = InsertNewInstBefore(TSI, I);
2723 // Construct the "on false" case of the select
2724 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2725 Instruction *FSI = BinaryOperator::CreateLShr(
2726 Op0, FC, SI->getName()+".f");
2727 FSI = InsertNewInstBefore(FSI, I);
2729 // construct the select instruction and return it.
2730 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2736 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2737 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2739 // Handle the integer div common cases
2740 if (Instruction *Common = commonIDivTransforms(I))
2743 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2745 if (RHS->isAllOnesValue())
2746 return BinaryOperator::CreateNeg(Op0);
2749 if (Value *LHSNeg = dyn_castNegVal(Op0))
2750 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2753 // If the sign bits of both operands are zero (i.e. we can prove they are
2754 // unsigned inputs), turn this into a udiv.
2755 if (I.getType()->isInteger()) {
2756 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2757 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2758 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2759 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2766 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2767 return commonDivTransforms(I);
2770 /// This function implements the transforms on rem instructions that work
2771 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2772 /// is used by the visitors to those instructions.
2773 /// @brief Transforms common to all three rem instructions
2774 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2775 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2777 // 0 % X == 0 for integer, we don't need to preserve faults!
2778 if (Constant *LHS = dyn_cast<Constant>(Op0))
2779 if (LHS->isNullValue())
2780 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2782 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2783 if (I.getType()->isFPOrFPVector())
2784 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
2785 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2787 if (isa<UndefValue>(Op1))
2788 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2790 // Handle cases involving: rem X, (select Cond, Y, Z)
2791 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2792 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2793 // the same basic block, then we replace the select with Y, and the
2794 // condition of the select with false (if the cond value is in the same
2795 // BB). If the select has uses other than the div, this allows them to be
2797 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2798 if (ST->isNullValue()) {
2799 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2800 if (CondI && CondI->getParent() == I.getParent())
2801 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2802 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2803 I.setOperand(1, SI->getOperand(2));
2805 UpdateValueUsesWith(SI, SI->getOperand(2));
2808 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2809 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2810 if (ST->isNullValue()) {
2811 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2812 if (CondI && CondI->getParent() == I.getParent())
2813 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2814 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2815 I.setOperand(1, SI->getOperand(1));
2817 UpdateValueUsesWith(SI, SI->getOperand(1));
2825 /// This function implements the transforms common to both integer remainder
2826 /// instructions (urem and srem). It is called by the visitors to those integer
2827 /// remainder instructions.
2828 /// @brief Common integer remainder transforms
2829 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2830 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2832 if (Instruction *common = commonRemTransforms(I))
2835 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2836 // X % 0 == undef, we don't need to preserve faults!
2837 if (RHS->equalsInt(0))
2838 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2840 if (RHS->equalsInt(1)) // X % 1 == 0
2841 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2843 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2844 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2845 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2847 } else if (isa<PHINode>(Op0I)) {
2848 if (Instruction *NV = FoldOpIntoPhi(I))
2852 // See if we can fold away this rem instruction.
2853 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2854 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2855 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2856 KnownZero, KnownOne))
2864 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2865 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2867 if (Instruction *common = commonIRemTransforms(I))
2870 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2871 // X urem C^2 -> X and C
2872 // Check to see if this is an unsigned remainder with an exact power of 2,
2873 // if so, convert to a bitwise and.
2874 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2875 if (C->getValue().isPowerOf2())
2876 return BinaryOperator::CreateAnd(Op0, SubOne(C));
2879 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2880 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2881 if (RHSI->getOpcode() == Instruction::Shl &&
2882 isa<ConstantInt>(RHSI->getOperand(0))) {
2883 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2884 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2885 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2887 return BinaryOperator::CreateAnd(Op0, Add);
2892 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2893 // where C1&C2 are powers of two.
2894 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2895 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2896 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2897 // STO == 0 and SFO == 0 handled above.
2898 if ((STO->getValue().isPowerOf2()) &&
2899 (SFO->getValue().isPowerOf2())) {
2900 Value *TrueAnd = InsertNewInstBefore(
2901 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2902 Value *FalseAnd = InsertNewInstBefore(
2903 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2904 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2912 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2913 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2915 // Handle the integer rem common cases
2916 if (Instruction *common = commonIRemTransforms(I))
2919 if (Value *RHSNeg = dyn_castNegVal(Op1))
2920 if (!isa<ConstantInt>(RHSNeg) ||
2921 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2923 AddUsesToWorkList(I);
2924 I.setOperand(1, RHSNeg);
2928 // If the sign bits of both operands are zero (i.e. we can prove they are
2929 // unsigned inputs), turn this into a urem.
2930 if (I.getType()->isInteger()) {
2931 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2932 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2933 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2934 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2941 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2942 return commonRemTransforms(I);
2945 // isMaxValueMinusOne - return true if this is Max-1
2946 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2947 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2949 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2950 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2953 // isMinValuePlusOne - return true if this is Min+1
2954 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2956 return C->getValue() == 1; // unsigned
2958 // Calculate 1111111111000000000000
2959 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2960 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2963 // isOneBitSet - Return true if there is exactly one bit set in the specified
2965 static bool isOneBitSet(const ConstantInt *CI) {
2966 return CI->getValue().isPowerOf2();
2969 // isHighOnes - Return true if the constant is of the form 1+0+.
2970 // This is the same as lowones(~X).
2971 static bool isHighOnes(const ConstantInt *CI) {
2972 return (~CI->getValue() + 1).isPowerOf2();
2975 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2976 /// are carefully arranged to allow folding of expressions such as:
2978 /// (A < B) | (A > B) --> (A != B)
2980 /// Note that this is only valid if the first and second predicates have the
2981 /// same sign. Is illegal to do: (A u< B) | (A s> B)
2983 /// Three bits are used to represent the condition, as follows:
2988 /// <=> Value Definition
2989 /// 000 0 Always false
2996 /// 111 7 Always true
2998 static unsigned getICmpCode(const ICmpInst *ICI) {
2999 switch (ICI->getPredicate()) {
3001 case ICmpInst::ICMP_UGT: return 1; // 001
3002 case ICmpInst::ICMP_SGT: return 1; // 001
3003 case ICmpInst::ICMP_EQ: return 2; // 010
3004 case ICmpInst::ICMP_UGE: return 3; // 011
3005 case ICmpInst::ICMP_SGE: return 3; // 011
3006 case ICmpInst::ICMP_ULT: return 4; // 100
3007 case ICmpInst::ICMP_SLT: return 4; // 100
3008 case ICmpInst::ICMP_NE: return 5; // 101
3009 case ICmpInst::ICMP_ULE: return 6; // 110
3010 case ICmpInst::ICMP_SLE: return 6; // 110
3013 assert(0 && "Invalid ICmp predicate!");
3018 /// getICmpValue - This is the complement of getICmpCode, which turns an
3019 /// opcode and two operands into either a constant true or false, or a brand
3020 /// new ICmp instruction. The sign is passed in to determine which kind
3021 /// of predicate to use in new icmp instructions.
3022 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3024 default: assert(0 && "Illegal ICmp code!");
3025 case 0: return ConstantInt::getFalse();
3028 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3030 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3031 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3034 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3036 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3039 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3041 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3042 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3045 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3047 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3048 case 7: return ConstantInt::getTrue();
3052 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3053 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3054 (ICmpInst::isSignedPredicate(p1) &&
3055 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3056 (ICmpInst::isSignedPredicate(p2) &&
3057 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3061 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3062 struct FoldICmpLogical {
3065 ICmpInst::Predicate pred;
3066 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3067 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3068 pred(ICI->getPredicate()) {}
3069 bool shouldApply(Value *V) const {
3070 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3071 if (PredicatesFoldable(pred, ICI->getPredicate()))
3072 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3073 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3076 Instruction *apply(Instruction &Log) const {
3077 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3078 if (ICI->getOperand(0) != LHS) {
3079 assert(ICI->getOperand(1) == LHS);
3080 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3083 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3084 unsigned LHSCode = getICmpCode(ICI);
3085 unsigned RHSCode = getICmpCode(RHSICI);
3087 switch (Log.getOpcode()) {
3088 case Instruction::And: Code = LHSCode & RHSCode; break;
3089 case Instruction::Or: Code = LHSCode | RHSCode; break;
3090 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3091 default: assert(0 && "Illegal logical opcode!"); return 0;
3094 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3095 ICmpInst::isSignedPredicate(ICI->getPredicate());
3097 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3098 if (Instruction *I = dyn_cast<Instruction>(RV))
3100 // Otherwise, it's a constant boolean value...
3101 return IC.ReplaceInstUsesWith(Log, RV);
3104 } // end anonymous namespace
3106 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3107 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3108 // guaranteed to be a binary operator.
3109 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3111 ConstantInt *AndRHS,
3112 BinaryOperator &TheAnd) {
3113 Value *X = Op->getOperand(0);
3114 Constant *Together = 0;
3116 Together = And(AndRHS, OpRHS);
3118 switch (Op->getOpcode()) {
3119 case Instruction::Xor:
3120 if (Op->hasOneUse()) {
3121 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3122 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3123 InsertNewInstBefore(And, TheAnd);
3125 return BinaryOperator::CreateXor(And, Together);
3128 case Instruction::Or:
3129 if (Together == AndRHS) // (X | C) & C --> C
3130 return ReplaceInstUsesWith(TheAnd, AndRHS);
3132 if (Op->hasOneUse() && Together != OpRHS) {
3133 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3134 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3135 InsertNewInstBefore(Or, TheAnd);
3137 return BinaryOperator::CreateAnd(Or, AndRHS);
3140 case Instruction::Add:
3141 if (Op->hasOneUse()) {
3142 // Adding a one to a single bit bit-field should be turned into an XOR
3143 // of the bit. First thing to check is to see if this AND is with a
3144 // single bit constant.
3145 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3147 // If there is only one bit set...
3148 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3149 // Ok, at this point, we know that we are masking the result of the
3150 // ADD down to exactly one bit. If the constant we are adding has
3151 // no bits set below this bit, then we can eliminate the ADD.
3152 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3154 // Check to see if any bits below the one bit set in AndRHSV are set.
3155 if ((AddRHS & (AndRHSV-1)) == 0) {
3156 // If not, the only thing that can effect the output of the AND is
3157 // the bit specified by AndRHSV. If that bit is set, the effect of
3158 // the XOR is to toggle the bit. If it is clear, then the ADD has
3160 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3161 TheAnd.setOperand(0, X);
3164 // Pull the XOR out of the AND.
3165 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3166 InsertNewInstBefore(NewAnd, TheAnd);
3167 NewAnd->takeName(Op);
3168 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3175 case Instruction::Shl: {
3176 // We know that the AND will not produce any of the bits shifted in, so if
3177 // the anded constant includes them, clear them now!
3179 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3180 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3181 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3182 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3184 if (CI->getValue() == ShlMask) {
3185 // Masking out bits that the shift already masks
3186 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3187 } else if (CI != AndRHS) { // Reducing bits set in and.
3188 TheAnd.setOperand(1, CI);
3193 case Instruction::LShr:
3195 // We know that the AND will not produce any of the bits shifted in, so if
3196 // the anded constant includes them, clear them now! This only applies to
3197 // unsigned shifts, because a signed shr may bring in set bits!
3199 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3200 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3201 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3202 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3204 if (CI->getValue() == ShrMask) {
3205 // Masking out bits that the shift already masks.
3206 return ReplaceInstUsesWith(TheAnd, Op);
3207 } else if (CI != AndRHS) {
3208 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3213 case Instruction::AShr:
3215 // See if this is shifting in some sign extension, then masking it out
3217 if (Op->hasOneUse()) {
3218 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3219 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3220 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3221 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3222 if (C == AndRHS) { // Masking out bits shifted in.
3223 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3224 // Make the argument unsigned.
3225 Value *ShVal = Op->getOperand(0);
3226 ShVal = InsertNewInstBefore(
3227 BinaryOperator::CreateLShr(ShVal, OpRHS,
3228 Op->getName()), TheAnd);
3229 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3238 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3239 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3240 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3241 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3242 /// insert new instructions.
3243 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3244 bool isSigned, bool Inside,
3246 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3247 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3248 "Lo is not <= Hi in range emission code!");
3251 if (Lo == Hi) // Trivially false.
3252 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3254 // V >= Min && V < Hi --> V < Hi
3255 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3256 ICmpInst::Predicate pred = (isSigned ?
3257 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3258 return new ICmpInst(pred, V, Hi);
3261 // Emit V-Lo <u Hi-Lo
3262 Constant *NegLo = ConstantExpr::getNeg(Lo);
3263 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3264 InsertNewInstBefore(Add, IB);
3265 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3266 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3269 if (Lo == Hi) // Trivially true.
3270 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3272 // V < Min || V >= Hi -> V > Hi-1
3273 Hi = SubOne(cast<ConstantInt>(Hi));
3274 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3275 ICmpInst::Predicate pred = (isSigned ?
3276 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3277 return new ICmpInst(pred, V, Hi);
3280 // Emit V-Lo >u Hi-1-Lo
3281 // Note that Hi has already had one subtracted from it, above.
3282 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3283 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3284 InsertNewInstBefore(Add, IB);
3285 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3286 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3289 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3290 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3291 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3292 // not, since all 1s are not contiguous.
3293 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3294 const APInt& V = Val->getValue();
3295 uint32_t BitWidth = Val->getType()->getBitWidth();
3296 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3298 // look for the first zero bit after the run of ones
3299 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3300 // look for the first non-zero bit
3301 ME = V.getActiveBits();
3305 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3306 /// where isSub determines whether the operator is a sub. If we can fold one of
3307 /// the following xforms:
3309 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3310 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3311 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3313 /// return (A +/- B).
3315 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3316 ConstantInt *Mask, bool isSub,
3318 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3319 if (!LHSI || LHSI->getNumOperands() != 2 ||
3320 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3322 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3324 switch (LHSI->getOpcode()) {
3326 case Instruction::And:
3327 if (And(N, Mask) == Mask) {
3328 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3329 if ((Mask->getValue().countLeadingZeros() +
3330 Mask->getValue().countPopulation()) ==
3331 Mask->getValue().getBitWidth())
3334 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3335 // part, we don't need any explicit masks to take them out of A. If that
3336 // is all N is, ignore it.
3337 uint32_t MB = 0, ME = 0;
3338 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3339 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3340 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3341 if (MaskedValueIsZero(RHS, Mask))
3346 case Instruction::Or:
3347 case Instruction::Xor:
3348 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3349 if ((Mask->getValue().countLeadingZeros() +
3350 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3351 && And(N, Mask)->isZero())
3358 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3360 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3361 return InsertNewInstBefore(New, I);
3364 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3365 bool Changed = SimplifyCommutative(I);
3366 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3368 if (isa<UndefValue>(Op1)) // X & undef -> 0
3369 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3373 return ReplaceInstUsesWith(I, Op1);
3375 // See if we can simplify any instructions used by the instruction whose sole
3376 // purpose is to compute bits we don't care about.
3377 if (!isa<VectorType>(I.getType())) {
3378 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3379 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3380 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3381 KnownZero, KnownOne))
3384 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3385 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3386 return ReplaceInstUsesWith(I, I.getOperand(0));
3387 } else if (isa<ConstantAggregateZero>(Op1)) {
3388 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3392 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3393 const APInt& AndRHSMask = AndRHS->getValue();
3394 APInt NotAndRHS(~AndRHSMask);
3396 // Optimize a variety of ((val OP C1) & C2) combinations...
3397 if (isa<BinaryOperator>(Op0)) {
3398 Instruction *Op0I = cast<Instruction>(Op0);
3399 Value *Op0LHS = Op0I->getOperand(0);
3400 Value *Op0RHS = Op0I->getOperand(1);
3401 switch (Op0I->getOpcode()) {
3402 case Instruction::Xor:
3403 case Instruction::Or:
3404 // If the mask is only needed on one incoming arm, push it up.
3405 if (Op0I->hasOneUse()) {
3406 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3407 // Not masking anything out for the LHS, move to RHS.
3408 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3409 Op0RHS->getName()+".masked");
3410 InsertNewInstBefore(NewRHS, I);
3411 return BinaryOperator::Create(
3412 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3414 if (!isa<Constant>(Op0RHS) &&
3415 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3416 // Not masking anything out for the RHS, move to LHS.
3417 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3418 Op0LHS->getName()+".masked");
3419 InsertNewInstBefore(NewLHS, I);
3420 return BinaryOperator::Create(
3421 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3426 case Instruction::Add:
3427 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3428 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3429 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3430 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3431 return BinaryOperator::CreateAnd(V, AndRHS);
3432 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3433 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
3436 case Instruction::Sub:
3437 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3438 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3439 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3440 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3441 return BinaryOperator::CreateAnd(V, AndRHS);
3445 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3446 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3448 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3449 // If this is an integer truncation or change from signed-to-unsigned, and
3450 // if the source is an and/or with immediate, transform it. This
3451 // frequently occurs for bitfield accesses.
3452 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3453 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3454 CastOp->getNumOperands() == 2)
3455 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3456 if (CastOp->getOpcode() == Instruction::And) {
3457 // Change: and (cast (and X, C1) to T), C2
3458 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3459 // This will fold the two constants together, which may allow
3460 // other simplifications.
3461 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3462 CastOp->getOperand(0), I.getType(),
3463 CastOp->getName()+".shrunk");
3464 NewCast = InsertNewInstBefore(NewCast, I);
3465 // trunc_or_bitcast(C1)&C2
3466 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3467 C3 = ConstantExpr::getAnd(C3, AndRHS);
3468 return BinaryOperator::CreateAnd(NewCast, C3);
3469 } else if (CastOp->getOpcode() == Instruction::Or) {
3470 // Change: and (cast (or X, C1) to T), C2
3471 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3472 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3473 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3474 return ReplaceInstUsesWith(I, AndRHS);
3480 // Try to fold constant and into select arguments.
3481 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3482 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3484 if (isa<PHINode>(Op0))
3485 if (Instruction *NV = FoldOpIntoPhi(I))
3489 Value *Op0NotVal = dyn_castNotVal(Op0);
3490 Value *Op1NotVal = dyn_castNotVal(Op1);
3492 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3493 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3495 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3496 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3497 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3498 I.getName()+".demorgan");
3499 InsertNewInstBefore(Or, I);
3500 return BinaryOperator::CreateNot(Or);
3504 Value *A = 0, *B = 0, *C = 0, *D = 0;
3505 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3506 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3507 return ReplaceInstUsesWith(I, Op1);
3509 // (A|B) & ~(A&B) -> A^B
3510 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3511 if ((A == C && B == D) || (A == D && B == C))
3512 return BinaryOperator::CreateXor(A, B);
3516 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3517 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3518 return ReplaceInstUsesWith(I, Op0);
3520 // ~(A&B) & (A|B) -> A^B
3521 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3522 if ((A == C && B == D) || (A == D && B == C))
3523 return BinaryOperator::CreateXor(A, B);
3527 if (Op0->hasOneUse() &&
3528 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3529 if (A == Op1) { // (A^B)&A -> A&(A^B)
3530 I.swapOperands(); // Simplify below
3531 std::swap(Op0, Op1);
3532 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3533 cast<BinaryOperator>(Op0)->swapOperands();
3534 I.swapOperands(); // Simplify below
3535 std::swap(Op0, Op1);
3538 if (Op1->hasOneUse() &&
3539 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3540 if (B == Op0) { // B&(A^B) -> B&(B^A)
3541 cast<BinaryOperator>(Op1)->swapOperands();
3544 if (A == Op0) { // A&(A^B) -> A & ~B
3545 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3546 InsertNewInstBefore(NotB, I);
3547 return BinaryOperator::CreateAnd(A, NotB);
3552 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3553 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3554 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3557 Value *LHSVal, *RHSVal;
3558 ConstantInt *LHSCst, *RHSCst;
3559 ICmpInst::Predicate LHSCC, RHSCC;
3560 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3561 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3562 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3563 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3564 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3565 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3566 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3567 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3569 // Don't try to fold ICMP_SLT + ICMP_ULT.
3570 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3571 ICmpInst::isSignedPredicate(LHSCC) ==
3572 ICmpInst::isSignedPredicate(RHSCC))) {
3573 // Ensure that the larger constant is on the RHS.
3574 ICmpInst::Predicate GT;
3575 if (ICmpInst::isSignedPredicate(LHSCC) ||
3576 (ICmpInst::isEquality(LHSCC) &&
3577 ICmpInst::isSignedPredicate(RHSCC)))
3578 GT = ICmpInst::ICMP_SGT;
3580 GT = ICmpInst::ICMP_UGT;
3582 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3583 ICmpInst *LHS = cast<ICmpInst>(Op0);
3584 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3585 std::swap(LHS, RHS);
3586 std::swap(LHSCst, RHSCst);
3587 std::swap(LHSCC, RHSCC);
3590 // At this point, we know we have have two icmp instructions
3591 // comparing a value against two constants and and'ing the result
3592 // together. Because of the above check, we know that we only have
3593 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3594 // (from the FoldICmpLogical check above), that the two constants
3595 // are not equal and that the larger constant is on the RHS
3596 assert(LHSCst != RHSCst && "Compares not folded above?");
3599 default: assert(0 && "Unknown integer condition code!");
3600 case ICmpInst::ICMP_EQ:
3602 default: assert(0 && "Unknown integer condition code!");
3603 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3604 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3605 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3606 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3607 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3608 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3609 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3610 return ReplaceInstUsesWith(I, LHS);
3612 case ICmpInst::ICMP_NE:
3614 default: assert(0 && "Unknown integer condition code!");
3615 case ICmpInst::ICMP_ULT:
3616 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3617 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3618 break; // (X != 13 & X u< 15) -> no change
3619 case ICmpInst::ICMP_SLT:
3620 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3621 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3622 break; // (X != 13 & X s< 15) -> no change
3623 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3624 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3625 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3626 return ReplaceInstUsesWith(I, RHS);
3627 case ICmpInst::ICMP_NE:
3628 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3629 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3630 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3631 LHSVal->getName()+".off");
3632 InsertNewInstBefore(Add, I);
3633 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3634 ConstantInt::get(Add->getType(), 1));
3636 break; // (X != 13 & X != 15) -> no change
3639 case ICmpInst::ICMP_ULT:
3641 default: assert(0 && "Unknown integer condition code!");
3642 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3643 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3644 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3645 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3647 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3648 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3649 return ReplaceInstUsesWith(I, LHS);
3650 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3654 case ICmpInst::ICMP_SLT:
3656 default: assert(0 && "Unknown integer condition code!");
3657 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3658 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3659 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3660 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3662 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3663 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3664 return ReplaceInstUsesWith(I, LHS);
3665 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3669 case ICmpInst::ICMP_UGT:
3671 default: assert(0 && "Unknown integer condition code!");
3672 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3673 return ReplaceInstUsesWith(I, LHS);
3674 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3675 return ReplaceInstUsesWith(I, RHS);
3676 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3678 case ICmpInst::ICMP_NE:
3679 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3680 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3681 break; // (X u> 13 & X != 15) -> no change
3682 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3683 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3685 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3689 case ICmpInst::ICMP_SGT:
3691 default: assert(0 && "Unknown integer condition code!");
3692 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3693 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3694 return ReplaceInstUsesWith(I, RHS);
3695 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3697 case ICmpInst::ICMP_NE:
3698 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3699 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3700 break; // (X s> 13 & X != 15) -> no change
3701 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3702 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3704 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3712 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3713 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3714 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3715 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3716 const Type *SrcTy = Op0C->getOperand(0)->getType();
3717 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3718 // Only do this if the casts both really cause code to be generated.
3719 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3721 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3723 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3724 Op1C->getOperand(0),
3726 InsertNewInstBefore(NewOp, I);
3727 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3731 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3732 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3733 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3734 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3735 SI0->getOperand(1) == SI1->getOperand(1) &&
3736 (SI0->hasOneUse() || SI1->hasOneUse())) {
3737 Instruction *NewOp =
3738 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3740 SI0->getName()), I);
3741 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
3742 SI1->getOperand(1));
3746 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3747 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3748 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3749 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3750 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3751 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3752 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3753 // If either of the constants are nans, then the whole thing returns
3755 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3756 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3757 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3758 RHS->getOperand(0));
3763 return Changed ? &I : 0;
3766 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3767 /// in the result. If it does, and if the specified byte hasn't been filled in
3768 /// yet, fill it in and return false.
3769 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3770 Instruction *I = dyn_cast<Instruction>(V);
3771 if (I == 0) return true;
3773 // If this is an or instruction, it is an inner node of the bswap.
3774 if (I->getOpcode() == Instruction::Or)
3775 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3776 CollectBSwapParts(I->getOperand(1), ByteValues);
3778 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3779 // If this is a shift by a constant int, and it is "24", then its operand
3780 // defines a byte. We only handle unsigned types here.
3781 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3782 // Not shifting the entire input by N-1 bytes?
3783 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3784 8*(ByteValues.size()-1))
3788 if (I->getOpcode() == Instruction::Shl) {
3789 // X << 24 defines the top byte with the lowest of the input bytes.
3790 DestNo = ByteValues.size()-1;
3792 // X >>u 24 defines the low byte with the highest of the input bytes.
3796 // If the destination byte value is already defined, the values are or'd
3797 // together, which isn't a bswap (unless it's an or of the same bits).
3798 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3800 ByteValues[DestNo] = I->getOperand(0);
3804 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3806 Value *Shift = 0, *ShiftLHS = 0;
3807 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3808 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3809 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3811 Instruction *SI = cast<Instruction>(Shift);
3813 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3814 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3815 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3818 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3820 if (AndAmt->getValue().getActiveBits() > 64)
3822 uint64_t AndAmtVal = AndAmt->getZExtValue();
3823 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3824 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3826 // Unknown mask for bswap.
3827 if (DestByte == ByteValues.size()) return true;
3829 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3831 if (SI->getOpcode() == Instruction::Shl)
3832 SrcByte = DestByte - ShiftBytes;
3834 SrcByte = DestByte + ShiftBytes;
3836 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3837 if (SrcByte != ByteValues.size()-DestByte-1)
3840 // If the destination byte value is already defined, the values are or'd
3841 // together, which isn't a bswap (unless it's an or of the same bits).
3842 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3844 ByteValues[DestByte] = SI->getOperand(0);
3848 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3849 /// If so, insert the new bswap intrinsic and return it.
3850 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3851 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3852 if (!ITy || ITy->getBitWidth() % 16)
3853 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3855 /// ByteValues - For each byte of the result, we keep track of which value
3856 /// defines each byte.
3857 SmallVector<Value*, 8> ByteValues;
3858 ByteValues.resize(ITy->getBitWidth()/8);
3860 // Try to find all the pieces corresponding to the bswap.
3861 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3862 CollectBSwapParts(I.getOperand(1), ByteValues))
3865 // Check to see if all of the bytes come from the same value.
3866 Value *V = ByteValues[0];
3867 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3869 // Check to make sure that all of the bytes come from the same value.
3870 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3871 if (ByteValues[i] != V)
3873 const Type *Tys[] = { ITy };
3874 Module *M = I.getParent()->getParent()->getParent();
3875 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3876 return CallInst::Create(F, V);
3880 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3881 bool Changed = SimplifyCommutative(I);
3882 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3884 if (isa<UndefValue>(Op1)) // X | undef -> -1
3885 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3889 return ReplaceInstUsesWith(I, Op0);
3891 // See if we can simplify any instructions used by the instruction whose sole
3892 // purpose is to compute bits we don't care about.
3893 if (!isa<VectorType>(I.getType())) {
3894 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3895 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3896 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3897 KnownZero, KnownOne))
3899 } else if (isa<ConstantAggregateZero>(Op1)) {
3900 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3901 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3902 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3903 return ReplaceInstUsesWith(I, I.getOperand(1));
3909 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3910 ConstantInt *C1 = 0; Value *X = 0;
3911 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3912 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3913 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3914 InsertNewInstBefore(Or, I);
3916 return BinaryOperator::CreateAnd(Or,
3917 ConstantInt::get(RHS->getValue() | C1->getValue()));
3920 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3921 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3922 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3923 InsertNewInstBefore(Or, I);
3925 return BinaryOperator::CreateXor(Or,
3926 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3929 // Try to fold constant and into select arguments.
3930 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3931 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3933 if (isa<PHINode>(Op0))
3934 if (Instruction *NV = FoldOpIntoPhi(I))
3938 Value *A = 0, *B = 0;
3939 ConstantInt *C1 = 0, *C2 = 0;
3941 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3942 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3943 return ReplaceInstUsesWith(I, Op1);
3944 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3945 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3946 return ReplaceInstUsesWith(I, Op0);
3948 // (A | B) | C and A | (B | C) -> bswap if possible.
3949 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3950 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3951 match(Op1, m_Or(m_Value(), m_Value())) ||
3952 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3953 match(Op1, m_Shift(m_Value(), m_Value())))) {
3954 if (Instruction *BSwap = MatchBSwap(I))
3958 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3959 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3960 MaskedValueIsZero(Op1, C1->getValue())) {
3961 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
3962 InsertNewInstBefore(NOr, I);
3964 return BinaryOperator::CreateXor(NOr, C1);
3967 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3968 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3969 MaskedValueIsZero(Op0, C1->getValue())) {
3970 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
3971 InsertNewInstBefore(NOr, I);
3973 return BinaryOperator::CreateXor(NOr, C1);
3977 Value *C = 0, *D = 0;
3978 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3979 match(Op1, m_And(m_Value(B), m_Value(D)))) {
3980 Value *V1 = 0, *V2 = 0, *V3 = 0;
3981 C1 = dyn_cast<ConstantInt>(C);
3982 C2 = dyn_cast<ConstantInt>(D);
3983 if (C1 && C2) { // (A & C1)|(B & C2)
3984 // If we have: ((V + N) & C1) | (V & C2)
3985 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3986 // replace with V+N.
3987 if (C1->getValue() == ~C2->getValue()) {
3988 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3989 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3990 // Add commutes, try both ways.
3991 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3992 return ReplaceInstUsesWith(I, A);
3993 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3994 return ReplaceInstUsesWith(I, A);
3996 // Or commutes, try both ways.
3997 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3998 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3999 // Add commutes, try both ways.
4000 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4001 return ReplaceInstUsesWith(I, B);
4002 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4003 return ReplaceInstUsesWith(I, B);
4006 V1 = 0; V2 = 0; V3 = 0;
4009 // Check to see if we have any common things being and'ed. If so, find the
4010 // terms for V1 & (V2|V3).
4011 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4012 if (A == B) // (A & C)|(A & D) == A & (C|D)
4013 V1 = A, V2 = C, V3 = D;
4014 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4015 V1 = A, V2 = B, V3 = C;
4016 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4017 V1 = C, V2 = A, V3 = D;
4018 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4019 V1 = C, V2 = A, V3 = B;
4023 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4024 return BinaryOperator::CreateAnd(V1, Or);
4029 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4030 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4031 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4032 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4033 SI0->getOperand(1) == SI1->getOperand(1) &&
4034 (SI0->hasOneUse() || SI1->hasOneUse())) {
4035 Instruction *NewOp =
4036 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4038 SI0->getName()), I);
4039 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4040 SI1->getOperand(1));
4044 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4045 if (A == Op1) // ~A | A == -1
4046 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4050 // Note, A is still live here!
4051 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4053 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4055 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4056 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4057 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4058 I.getName()+".demorgan"), I);
4059 return BinaryOperator::CreateNot(And);
4063 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4064 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4065 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4068 Value *LHSVal, *RHSVal;
4069 ConstantInt *LHSCst, *RHSCst;
4070 ICmpInst::Predicate LHSCC, RHSCC;
4071 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4072 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4073 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4074 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4075 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4076 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4077 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4078 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4079 // We can't fold (ugt x, C) | (sgt x, C2).
4080 PredicatesFoldable(LHSCC, RHSCC)) {
4081 // Ensure that the larger constant is on the RHS.
4082 ICmpInst *LHS = cast<ICmpInst>(Op0);
4084 if (ICmpInst::isSignedPredicate(LHSCC))
4085 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4087 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4090 std::swap(LHS, RHS);
4091 std::swap(LHSCst, RHSCst);
4092 std::swap(LHSCC, RHSCC);
4095 // At this point, we know we have have two icmp instructions
4096 // comparing a value against two constants and or'ing the result
4097 // together. Because of the above check, we know that we only have
4098 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4099 // FoldICmpLogical check above), that the two constants are not
4101 assert(LHSCst != RHSCst && "Compares not folded above?");
4104 default: assert(0 && "Unknown integer condition code!");
4105 case ICmpInst::ICMP_EQ:
4107 default: assert(0 && "Unknown integer condition code!");
4108 case ICmpInst::ICMP_EQ:
4109 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4110 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4111 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4112 LHSVal->getName()+".off");
4113 InsertNewInstBefore(Add, I);
4114 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4115 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4117 break; // (X == 13 | X == 15) -> no change
4118 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4119 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4121 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4122 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4123 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4124 return ReplaceInstUsesWith(I, RHS);
4127 case ICmpInst::ICMP_NE:
4129 default: assert(0 && "Unknown integer condition code!");
4130 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4131 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4132 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4133 return ReplaceInstUsesWith(I, LHS);
4134 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4135 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4136 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4137 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4140 case ICmpInst::ICMP_ULT:
4142 default: assert(0 && "Unknown integer condition code!");
4143 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4145 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4146 // If RHSCst is [us]MAXINT, it is always false. Not handling
4147 // this can cause overflow.
4148 if (RHSCst->isMaxValue(false))
4149 return ReplaceInstUsesWith(I, LHS);
4150 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4152 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4154 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4155 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4156 return ReplaceInstUsesWith(I, RHS);
4157 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4161 case ICmpInst::ICMP_SLT:
4163 default: assert(0 && "Unknown integer condition code!");
4164 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4166 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4167 // If RHSCst is [us]MAXINT, it is always false. Not handling
4168 // this can cause overflow.
4169 if (RHSCst->isMaxValue(true))
4170 return ReplaceInstUsesWith(I, LHS);
4171 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4173 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4175 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4176 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4177 return ReplaceInstUsesWith(I, RHS);
4178 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4182 case ICmpInst::ICMP_UGT:
4184 default: assert(0 && "Unknown integer condition code!");
4185 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4186 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4187 return ReplaceInstUsesWith(I, LHS);
4188 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4190 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4191 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4192 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4193 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4197 case ICmpInst::ICMP_SGT:
4199 default: assert(0 && "Unknown integer condition code!");
4200 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4201 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4202 return ReplaceInstUsesWith(I, LHS);
4203 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4205 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4206 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4207 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4208 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4216 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4217 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4218 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4219 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4220 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4221 !isa<ICmpInst>(Op1C->getOperand(0))) {
4222 const Type *SrcTy = Op0C->getOperand(0)->getType();
4223 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4224 // Only do this if the casts both really cause code to be
4226 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4228 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4230 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4231 Op1C->getOperand(0),
4233 InsertNewInstBefore(NewOp, I);
4234 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4241 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4242 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4243 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4244 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4245 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4246 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4247 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4248 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4249 // If either of the constants are nans, then the whole thing returns
4251 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4252 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4254 // Otherwise, no need to compare the two constants, compare the
4256 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4257 RHS->getOperand(0));
4262 return Changed ? &I : 0;
4267 // XorSelf - Implements: X ^ X --> 0
4270 XorSelf(Value *rhs) : RHS(rhs) {}
4271 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4272 Instruction *apply(BinaryOperator &Xor) const {
4279 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4280 bool Changed = SimplifyCommutative(I);
4281 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4283 if (isa<UndefValue>(Op1)) {
4284 if (isa<UndefValue>(Op0))
4285 // Handle undef ^ undef -> 0 special case. This is a common
4287 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4288 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4291 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4292 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4293 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4297 // See if we can simplify any instructions used by the instruction whose sole
4298 // purpose is to compute bits we don't care about.
4299 if (!isa<VectorType>(I.getType())) {
4300 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4301 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4302 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4303 KnownZero, KnownOne))
4305 } else if (isa<ConstantAggregateZero>(Op1)) {
4306 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4309 // Is this a ~ operation?
4310 if (Value *NotOp = dyn_castNotVal(&I)) {
4311 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4312 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4313 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4314 if (Op0I->getOpcode() == Instruction::And ||
4315 Op0I->getOpcode() == Instruction::Or) {
4316 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4317 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4319 BinaryOperator::CreateNot(Op0I->getOperand(1),
4320 Op0I->getOperand(1)->getName()+".not");
4321 InsertNewInstBefore(NotY, I);
4322 if (Op0I->getOpcode() == Instruction::And)
4323 return BinaryOperator::CreateOr(Op0NotVal, NotY);
4325 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4332 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4333 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4334 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4335 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4336 return new ICmpInst(ICI->getInversePredicate(),
4337 ICI->getOperand(0), ICI->getOperand(1));
4339 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4340 return new FCmpInst(FCI->getInversePredicate(),
4341 FCI->getOperand(0), FCI->getOperand(1));
4344 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4345 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4346 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4347 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4348 Instruction::CastOps Opcode = Op0C->getOpcode();
4349 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4350 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4351 Op0C->getDestTy())) {
4352 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4353 CI->getOpcode(), CI->getInversePredicate(),
4354 CI->getOperand(0), CI->getOperand(1)), I);
4355 NewCI->takeName(CI);
4356 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4363 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4364 // ~(c-X) == X-c-1 == X+(-c-1)
4365 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4366 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4367 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4368 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4369 ConstantInt::get(I.getType(), 1));
4370 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4373 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4374 if (Op0I->getOpcode() == Instruction::Add) {
4375 // ~(X-c) --> (-c-1)-X
4376 if (RHS->isAllOnesValue()) {
4377 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4378 return BinaryOperator::CreateSub(
4379 ConstantExpr::getSub(NegOp0CI,
4380 ConstantInt::get(I.getType(), 1)),
4381 Op0I->getOperand(0));
4382 } else if (RHS->getValue().isSignBit()) {
4383 // (X + C) ^ signbit -> (X + C + signbit)
4384 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4385 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4388 } else if (Op0I->getOpcode() == Instruction::Or) {
4389 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4390 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4391 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4392 // Anything in both C1 and C2 is known to be zero, remove it from
4394 Constant *CommonBits = And(Op0CI, RHS);
4395 NewRHS = ConstantExpr::getAnd(NewRHS,
4396 ConstantExpr::getNot(CommonBits));
4397 AddToWorkList(Op0I);
4398 I.setOperand(0, Op0I->getOperand(0));
4399 I.setOperand(1, NewRHS);
4406 // Try to fold constant and into select arguments.
4407 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4408 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4410 if (isa<PHINode>(Op0))
4411 if (Instruction *NV = FoldOpIntoPhi(I))
4415 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4417 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4419 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4421 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4424 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4427 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4428 if (A == Op0) { // B^(B|A) == (A|B)^B
4429 Op1I->swapOperands();
4431 std::swap(Op0, Op1);
4432 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4433 I.swapOperands(); // Simplified below.
4434 std::swap(Op0, Op1);
4436 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4437 if (Op0 == A) // A^(A^B) == B
4438 return ReplaceInstUsesWith(I, B);
4439 else if (Op0 == B) // A^(B^A) == B
4440 return ReplaceInstUsesWith(I, A);
4441 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4442 if (A == Op0) { // A^(A&B) -> A^(B&A)
4443 Op1I->swapOperands();
4446 if (B == Op0) { // A^(B&A) -> (B&A)^A
4447 I.swapOperands(); // Simplified below.
4448 std::swap(Op0, Op1);
4453 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4456 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4457 if (A == Op1) // (B|A)^B == (A|B)^B
4459 if (B == Op1) { // (A|B)^B == A & ~B
4461 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4462 return BinaryOperator::CreateAnd(A, NotB);
4464 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4465 if (Op1 == A) // (A^B)^A == B
4466 return ReplaceInstUsesWith(I, B);
4467 else if (Op1 == B) // (B^A)^A == B
4468 return ReplaceInstUsesWith(I, A);
4469 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4470 if (A == Op1) // (A&B)^A -> (B&A)^A
4472 if (B == Op1 && // (B&A)^A == ~B & A
4473 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4475 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4476 return BinaryOperator::CreateAnd(N, Op1);
4481 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4482 if (Op0I && Op1I && Op0I->isShift() &&
4483 Op0I->getOpcode() == Op1I->getOpcode() &&
4484 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4485 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4486 Instruction *NewOp =
4487 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4488 Op1I->getOperand(0),
4489 Op0I->getName()), I);
4490 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
4491 Op1I->getOperand(1));
4495 Value *A, *B, *C, *D;
4496 // (A & B)^(A | B) -> A ^ B
4497 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4498 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4499 if ((A == C && B == D) || (A == D && B == C))
4500 return BinaryOperator::CreateXor(A, B);
4502 // (A | B)^(A & B) -> A ^ B
4503 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4504 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4505 if ((A == C && B == D) || (A == D && B == C))
4506 return BinaryOperator::CreateXor(A, B);
4510 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4511 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4512 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4513 // (X & Y)^(X & Y) -> (Y^Z) & X
4514 Value *X = 0, *Y = 0, *Z = 0;
4516 X = A, Y = B, Z = D;
4518 X = A, Y = B, Z = C;
4520 X = B, Y = A, Z = D;
4522 X = B, Y = A, Z = C;
4525 Instruction *NewOp =
4526 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4527 return BinaryOperator::CreateAnd(NewOp, X);
4532 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4533 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4534 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4537 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4538 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4539 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4540 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4541 const Type *SrcTy = Op0C->getOperand(0)->getType();
4542 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4543 // Only do this if the casts both really cause code to be generated.
4544 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4546 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4548 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4549 Op1C->getOperand(0),
4551 InsertNewInstBefore(NewOp, I);
4552 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4557 return Changed ? &I : 0;
4560 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4561 /// overflowed for this type.
4562 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4563 ConstantInt *In2, bool IsSigned = false) {
4564 Result = cast<ConstantInt>(Add(In1, In2));
4567 if (In2->getValue().isNegative())
4568 return Result->getValue().sgt(In1->getValue());
4570 return Result->getValue().slt(In1->getValue());
4572 return Result->getValue().ult(In1->getValue());
4575 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4576 /// code necessary to compute the offset from the base pointer (without adding
4577 /// in the base pointer). Return the result as a signed integer of intptr size.
4578 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4579 TargetData &TD = IC.getTargetData();
4580 gep_type_iterator GTI = gep_type_begin(GEP);
4581 const Type *IntPtrTy = TD.getIntPtrType();
4582 Value *Result = Constant::getNullValue(IntPtrTy);
4584 // Build a mask for high order bits.
4585 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4586 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4588 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4591 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4592 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4593 if (OpC->isZero()) continue;
4595 // Handle a struct index, which adds its field offset to the pointer.
4596 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4597 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4599 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4600 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4602 Result = IC.InsertNewInstBefore(
4603 BinaryOperator::CreateAdd(Result,
4604 ConstantInt::get(IntPtrTy, Size),
4605 GEP->getName()+".offs"), I);
4609 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4610 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4611 Scale = ConstantExpr::getMul(OC, Scale);
4612 if (Constant *RC = dyn_cast<Constant>(Result))
4613 Result = ConstantExpr::getAdd(RC, Scale);
4615 // Emit an add instruction.
4616 Result = IC.InsertNewInstBefore(
4617 BinaryOperator::CreateAdd(Result, Scale,
4618 GEP->getName()+".offs"), I);
4622 // Convert to correct type.
4623 if (Op->getType() != IntPtrTy) {
4624 if (Constant *OpC = dyn_cast<Constant>(Op))
4625 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4627 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4628 Op->getName()+".c"), I);
4631 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4632 if (Constant *OpC = dyn_cast<Constant>(Op))
4633 Op = ConstantExpr::getMul(OpC, Scale);
4634 else // We'll let instcombine(mul) convert this to a shl if possible.
4635 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4636 GEP->getName()+".idx"), I);
4639 // Emit an add instruction.
4640 if (isa<Constant>(Op) && isa<Constant>(Result))
4641 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4642 cast<Constant>(Result));
4644 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4645 GEP->getName()+".offs"), I);
4651 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4652 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4653 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4654 /// complex, and scales are involved. The above expression would also be legal
4655 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4656 /// later form is less amenable to optimization though, and we are allowed to
4657 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4659 /// If we can't emit an optimized form for this expression, this returns null.
4661 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4663 TargetData &TD = IC.getTargetData();
4664 gep_type_iterator GTI = gep_type_begin(GEP);
4666 // Check to see if this gep only has a single variable index. If so, and if
4667 // any constant indices are a multiple of its scale, then we can compute this
4668 // in terms of the scale of the variable index. For example, if the GEP
4669 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4670 // because the expression will cross zero at the same point.
4671 unsigned i, e = GEP->getNumOperands();
4673 for (i = 1; i != e; ++i, ++GTI) {
4674 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4675 // Compute the aggregate offset of constant indices.
4676 if (CI->isZero()) continue;
4678 // Handle a struct index, which adds its field offset to the pointer.
4679 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4680 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4682 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4683 Offset += Size*CI->getSExtValue();
4686 // Found our variable index.
4691 // If there are no variable indices, we must have a constant offset, just
4692 // evaluate it the general way.
4693 if (i == e) return 0;
4695 Value *VariableIdx = GEP->getOperand(i);
4696 // Determine the scale factor of the variable element. For example, this is
4697 // 4 if the variable index is into an array of i32.
4698 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4700 // Verify that there are no other variable indices. If so, emit the hard way.
4701 for (++i, ++GTI; i != e; ++i, ++GTI) {
4702 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4705 // Compute the aggregate offset of constant indices.
4706 if (CI->isZero()) continue;
4708 // Handle a struct index, which adds its field offset to the pointer.
4709 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4710 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4712 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4713 Offset += Size*CI->getSExtValue();
4717 // Okay, we know we have a single variable index, which must be a
4718 // pointer/array/vector index. If there is no offset, life is simple, return
4720 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4722 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4723 // we don't need to bother extending: the extension won't affect where the
4724 // computation crosses zero.
4725 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4726 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4727 VariableIdx->getNameStart(), &I);
4731 // Otherwise, there is an index. The computation we will do will be modulo
4732 // the pointer size, so get it.
4733 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4735 Offset &= PtrSizeMask;
4736 VariableScale &= PtrSizeMask;
4738 // To do this transformation, any constant index must be a multiple of the
4739 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4740 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4741 // multiple of the variable scale.
4742 int64_t NewOffs = Offset / (int64_t)VariableScale;
4743 if (Offset != NewOffs*(int64_t)VariableScale)
4746 // Okay, we can do this evaluation. Start by converting the index to intptr.
4747 const Type *IntPtrTy = TD.getIntPtrType();
4748 if (VariableIdx->getType() != IntPtrTy)
4749 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4751 VariableIdx->getNameStart(), &I);
4752 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4753 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4757 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4758 /// else. At this point we know that the GEP is on the LHS of the comparison.
4759 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4760 ICmpInst::Predicate Cond,
4762 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4764 // Look through bitcasts.
4765 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4766 RHS = BCI->getOperand(0);
4768 Value *PtrBase = GEPLHS->getOperand(0);
4769 if (PtrBase == RHS) {
4770 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4771 // This transformation (ignoring the base and scales) is valid because we
4772 // know pointers can't overflow. See if we can output an optimized form.
4773 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4775 // If not, synthesize the offset the hard way.
4777 Offset = EmitGEPOffset(GEPLHS, I, *this);
4778 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4779 Constant::getNullValue(Offset->getType()));
4780 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4781 // If the base pointers are different, but the indices are the same, just
4782 // compare the base pointer.
4783 if (PtrBase != GEPRHS->getOperand(0)) {
4784 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4785 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4786 GEPRHS->getOperand(0)->getType();
4788 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4789 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4790 IndicesTheSame = false;
4794 // If all indices are the same, just compare the base pointers.
4796 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4797 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4799 // Otherwise, the base pointers are different and the indices are
4800 // different, bail out.
4804 // If one of the GEPs has all zero indices, recurse.
4805 bool AllZeros = true;
4806 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4807 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4808 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4813 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4814 ICmpInst::getSwappedPredicate(Cond), I);
4816 // If the other GEP has all zero indices, recurse.
4818 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4819 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4820 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4825 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4827 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4828 // If the GEPs only differ by one index, compare it.
4829 unsigned NumDifferences = 0; // Keep track of # differences.
4830 unsigned DiffOperand = 0; // The operand that differs.
4831 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4832 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4833 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4834 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4835 // Irreconcilable differences.
4839 if (NumDifferences++) break;
4844 if (NumDifferences == 0) // SAME GEP?
4845 return ReplaceInstUsesWith(I, // No comparison is needed here.
4846 ConstantInt::get(Type::Int1Ty,
4847 ICmpInst::isTrueWhenEqual(Cond)));
4849 else if (NumDifferences == 1) {
4850 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4851 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4852 // Make sure we do a signed comparison here.
4853 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4857 // Only lower this if the icmp is the only user of the GEP or if we expect
4858 // the result to fold to a constant!
4859 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4860 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4861 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4862 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4863 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4864 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4870 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4872 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4875 if (!isa<ConstantFP>(RHSC)) return 0;
4876 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4878 // Get the width of the mantissa. We don't want to hack on conversions that
4879 // might lose information from the integer, e.g. "i64 -> float"
4880 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4881 if (MantissaWidth == -1) return 0; // Unknown.
4883 // Check to see that the input is converted from an integer type that is small
4884 // enough that preserves all bits. TODO: check here for "known" sign bits.
4885 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4886 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4888 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4889 if (isa<UIToFPInst>(LHSI))
4892 // If the conversion would lose info, don't hack on this.
4893 if ((int)InputSize > MantissaWidth)
4896 // Otherwise, we can potentially simplify the comparison. We know that it
4897 // will always come through as an integer value and we know the constant is
4898 // not a NAN (it would have been previously simplified).
4899 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4901 ICmpInst::Predicate Pred;
4902 switch (I.getPredicate()) {
4903 default: assert(0 && "Unexpected predicate!");
4904 case FCmpInst::FCMP_UEQ:
4905 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4906 case FCmpInst::FCMP_UGT:
4907 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4908 case FCmpInst::FCMP_UGE:
4909 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4910 case FCmpInst::FCMP_ULT:
4911 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4912 case FCmpInst::FCMP_ULE:
4913 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4914 case FCmpInst::FCMP_UNE:
4915 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4916 case FCmpInst::FCMP_ORD:
4917 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4918 case FCmpInst::FCMP_UNO:
4919 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4922 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4924 // Now we know that the APFloat is a normal number, zero or inf.
4926 // See if the FP constant is too large for the integer. For example,
4927 // comparing an i8 to 300.0.
4928 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4930 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4931 // and large values.
4932 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4933 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4934 APFloat::rmNearestTiesToEven);
4935 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4936 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4937 Pred == ICmpInst::ICMP_SLE)
4938 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4939 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4942 // See if the RHS value is < SignedMin.
4943 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4944 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4945 APFloat::rmNearestTiesToEven);
4946 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4947 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4948 Pred == ICmpInst::ICMP_SGE)
4949 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4950 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4953 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4954 // it may still be fractional. See if it is fractional by casting the FP
4955 // value to the integer value and back, checking for equality. Don't do this
4956 // for zero, because -0.0 is not fractional.
4957 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4958 if (!RHS.isZero() &&
4959 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4960 // If we had a comparison against a fractional value, we have to adjust
4961 // the compare predicate and sometimes the value. RHSC is rounded towards
4962 // zero at this point.
4964 default: assert(0 && "Unexpected integer comparison!");
4965 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
4966 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4967 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
4968 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4969 case ICmpInst::ICMP_SLE:
4970 // (float)int <= 4.4 --> int <= 4
4971 // (float)int <= -4.4 --> int < -4
4972 if (RHS.isNegative())
4973 Pred = ICmpInst::ICMP_SLT;
4975 case ICmpInst::ICMP_SLT:
4976 // (float)int < -4.4 --> int < -4
4977 // (float)int < 4.4 --> int <= 4
4978 if (!RHS.isNegative())
4979 Pred = ICmpInst::ICMP_SLE;
4981 case ICmpInst::ICMP_SGT:
4982 // (float)int > 4.4 --> int > 4
4983 // (float)int > -4.4 --> int >= -4
4984 if (RHS.isNegative())
4985 Pred = ICmpInst::ICMP_SGE;
4987 case ICmpInst::ICMP_SGE:
4988 // (float)int >= -4.4 --> int >= -4
4989 // (float)int >= 4.4 --> int > 4
4990 if (!RHS.isNegative())
4991 Pred = ICmpInst::ICMP_SGT;
4996 // Lower this FP comparison into an appropriate integer version of the
4998 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5001 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5002 bool Changed = SimplifyCompare(I);
5003 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5005 // Fold trivial predicates.
5006 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5007 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5008 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5009 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5011 // Simplify 'fcmp pred X, X'
5013 switch (I.getPredicate()) {
5014 default: assert(0 && "Unknown predicate!");
5015 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5016 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5017 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5018 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5019 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5020 case FCmpInst::FCMP_OLT: // True if ordered and less than
5021 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5022 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5024 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5025 case FCmpInst::FCMP_ULT: // True if unordered or less than
5026 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5027 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5028 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5029 I.setPredicate(FCmpInst::FCMP_UNO);
5030 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5033 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5034 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5035 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5036 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5037 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5038 I.setPredicate(FCmpInst::FCMP_ORD);
5039 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5044 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5045 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5047 // Handle fcmp with constant RHS
5048 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5049 // If the constant is a nan, see if we can fold the comparison based on it.
5050 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5051 if (CFP->getValueAPF().isNaN()) {
5052 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5053 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5054 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5055 "Comparison must be either ordered or unordered!");
5056 // True if unordered.
5057 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5061 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5062 switch (LHSI->getOpcode()) {
5063 case Instruction::PHI:
5064 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5065 // block. If in the same block, we're encouraging jump threading. If
5066 // not, we are just pessimizing the code by making an i1 phi.
5067 if (LHSI->getParent() == I.getParent())
5068 if (Instruction *NV = FoldOpIntoPhi(I))
5071 case Instruction::SIToFP:
5072 case Instruction::UIToFP:
5073 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5076 case Instruction::Select:
5077 // If either operand of the select is a constant, we can fold the
5078 // comparison into the select arms, which will cause one to be
5079 // constant folded and the select turned into a bitwise or.
5080 Value *Op1 = 0, *Op2 = 0;
5081 if (LHSI->hasOneUse()) {
5082 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5083 // Fold the known value into the constant operand.
5084 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5085 // Insert a new FCmp of the other select operand.
5086 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5087 LHSI->getOperand(2), RHSC,
5089 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5090 // Fold the known value into the constant operand.
5091 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5092 // Insert a new FCmp of the other select operand.
5093 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5094 LHSI->getOperand(1), RHSC,
5100 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5105 return Changed ? &I : 0;
5108 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5109 bool Changed = SimplifyCompare(I);
5110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5111 const Type *Ty = Op0->getType();
5115 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5116 I.isTrueWhenEqual()));
5118 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5119 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5121 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5122 // addresses never equal each other! We already know that Op0 != Op1.
5123 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5124 isa<ConstantPointerNull>(Op0)) &&
5125 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5126 isa<ConstantPointerNull>(Op1)))
5127 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5128 !I.isTrueWhenEqual()));
5130 // icmp's with boolean values can always be turned into bitwise operations
5131 if (Ty == Type::Int1Ty) {
5132 switch (I.getPredicate()) {
5133 default: assert(0 && "Invalid icmp instruction!");
5134 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
5135 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5136 InsertNewInstBefore(Xor, I);
5137 return BinaryOperator::CreateNot(Xor);
5139 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
5140 return BinaryOperator::CreateXor(Op0, Op1);
5142 case ICmpInst::ICMP_UGT:
5143 case ICmpInst::ICMP_SGT:
5144 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5146 case ICmpInst::ICMP_ULT:
5147 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
5148 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5149 InsertNewInstBefore(Not, I);
5150 return BinaryOperator::CreateAnd(Not, Op1);
5152 case ICmpInst::ICMP_UGE:
5153 case ICmpInst::ICMP_SGE:
5154 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5156 case ICmpInst::ICMP_ULE:
5157 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
5158 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5159 InsertNewInstBefore(Not, I);
5160 return BinaryOperator::CreateOr(Not, Op1);
5165 // See if we are doing a comparison between a constant and an instruction that
5166 // can be folded into the comparison.
5167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5170 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5171 if (I.isEquality() && CI->isNullValue() &&
5172 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5173 // (icmp cond A B) if cond is equality
5174 return new ICmpInst(I.getPredicate(), A, B);
5177 switch (I.getPredicate()) {
5179 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5180 if (CI->isMinValue(false))
5181 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5182 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5183 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5184 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5185 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5186 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5187 if (CI->isMinValue(true))
5188 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5189 ConstantInt::getAllOnesValue(Op0->getType()));
5193 case ICmpInst::ICMP_SLT:
5194 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5195 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5196 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5197 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5198 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5199 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5202 case ICmpInst::ICMP_UGT:
5203 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5204 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5205 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5206 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5207 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5208 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5210 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5211 if (CI->isMaxValue(true))
5212 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5213 ConstantInt::getNullValue(Op0->getType()));
5216 case ICmpInst::ICMP_SGT:
5217 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5218 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5219 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5220 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5221 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5222 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5225 case ICmpInst::ICMP_ULE:
5226 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5227 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5228 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5229 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5230 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5231 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5234 case ICmpInst::ICMP_SLE:
5235 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5236 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5237 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5238 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5239 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5240 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5243 case ICmpInst::ICMP_UGE:
5244 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5245 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5246 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5247 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5248 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5249 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5252 case ICmpInst::ICMP_SGE:
5253 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5254 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5255 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5256 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5257 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5258 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5262 // If we still have a icmp le or icmp ge instruction, turn it into the
5263 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5264 // already been handled above, this requires little checking.
5266 switch (I.getPredicate()) {
5268 case ICmpInst::ICMP_ULE:
5269 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5270 case ICmpInst::ICMP_SLE:
5271 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5272 case ICmpInst::ICMP_UGE:
5273 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5274 case ICmpInst::ICMP_SGE:
5275 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5278 // See if we can fold the comparison based on bits known to be zero or one
5279 // in the input. If this comparison is a normal comparison, it demands all
5280 // bits, if it is a sign bit comparison, it only demands the sign bit.
5283 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5285 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5286 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5287 if (SimplifyDemandedBits(Op0,
5288 isSignBit ? APInt::getSignBit(BitWidth)
5289 : APInt::getAllOnesValue(BitWidth),
5290 KnownZero, KnownOne, 0))
5293 // Given the known and unknown bits, compute a range that the LHS could be
5295 if ((KnownOne | KnownZero) != 0) {
5296 // Compute the Min, Max and RHS values based on the known bits. For the
5297 // EQ and NE we use unsigned values.
5298 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5299 const APInt& RHSVal = CI->getValue();
5300 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5301 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5304 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5307 switch (I.getPredicate()) { // LE/GE have been folded already.
5308 default: assert(0 && "Unknown icmp opcode!");
5309 case ICmpInst::ICMP_EQ:
5310 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5311 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5313 case ICmpInst::ICMP_NE:
5314 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5315 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5317 case ICmpInst::ICMP_ULT:
5318 if (Max.ult(RHSVal))
5319 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5320 if (Min.uge(RHSVal))
5321 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5323 case ICmpInst::ICMP_UGT:
5324 if (Min.ugt(RHSVal))
5325 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5326 if (Max.ule(RHSVal))
5327 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5329 case ICmpInst::ICMP_SLT:
5330 if (Max.slt(RHSVal))
5331 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5332 if (Min.sgt(RHSVal))
5333 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5335 case ICmpInst::ICMP_SGT:
5336 if (Min.sgt(RHSVal))
5337 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5338 if (Max.sle(RHSVal))
5339 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5344 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5345 // instruction, see if that instruction also has constants so that the
5346 // instruction can be folded into the icmp
5347 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5348 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5352 // Handle icmp with constant (but not simple integer constant) RHS
5353 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5354 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5355 switch (LHSI->getOpcode()) {
5356 case Instruction::GetElementPtr:
5357 if (RHSC->isNullValue()) {
5358 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5359 bool isAllZeros = true;
5360 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5361 if (!isa<Constant>(LHSI->getOperand(i)) ||
5362 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5367 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5368 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5372 case Instruction::PHI:
5373 // Only fold icmp into the PHI if the phi and fcmp are in the same
5374 // block. If in the same block, we're encouraging jump threading. If
5375 // not, we are just pessimizing the code by making an i1 phi.
5376 if (LHSI->getParent() == I.getParent())
5377 if (Instruction *NV = FoldOpIntoPhi(I))
5380 case Instruction::Select: {
5381 // If either operand of the select is a constant, we can fold the
5382 // comparison into the select arms, which will cause one to be
5383 // constant folded and the select turned into a bitwise or.
5384 Value *Op1 = 0, *Op2 = 0;
5385 if (LHSI->hasOneUse()) {
5386 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5387 // Fold the known value into the constant operand.
5388 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5389 // Insert a new ICmp of the other select operand.
5390 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5391 LHSI->getOperand(2), RHSC,
5393 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5394 // Fold the known value into the constant operand.
5395 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5396 // Insert a new ICmp of the other select operand.
5397 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5398 LHSI->getOperand(1), RHSC,
5404 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5407 case Instruction::Malloc:
5408 // If we have (malloc != null), and if the malloc has a single use, we
5409 // can assume it is successful and remove the malloc.
5410 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5411 AddToWorkList(LHSI);
5412 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5413 !I.isTrueWhenEqual()));
5419 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5420 if (User *GEP = dyn_castGetElementPtr(Op0))
5421 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5423 if (User *GEP = dyn_castGetElementPtr(Op1))
5424 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5425 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5428 // Test to see if the operands of the icmp are casted versions of other
5429 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5431 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5432 if (isa<PointerType>(Op0->getType()) &&
5433 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5434 // We keep moving the cast from the left operand over to the right
5435 // operand, where it can often be eliminated completely.
5436 Op0 = CI->getOperand(0);
5438 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5439 // so eliminate it as well.
5440 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5441 Op1 = CI2->getOperand(0);
5443 // If Op1 is a constant, we can fold the cast into the constant.
5444 if (Op0->getType() != Op1->getType()) {
5445 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5446 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5448 // Otherwise, cast the RHS right before the icmp
5449 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5452 return new ICmpInst(I.getPredicate(), Op0, Op1);
5456 if (isa<CastInst>(Op0)) {
5457 // Handle the special case of: icmp (cast bool to X), <cst>
5458 // This comes up when you have code like
5461 // For generality, we handle any zero-extension of any operand comparison
5462 // with a constant or another cast from the same type.
5463 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5464 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5468 // ~x < ~y --> y < x
5470 if (match(Op0, m_Not(m_Value(A))) &&
5471 match(Op1, m_Not(m_Value(B))))
5472 return new ICmpInst(I.getPredicate(), B, A);
5475 if (I.isEquality()) {
5476 Value *A, *B, *C, *D;
5478 // -x == -y --> x == y
5479 if (match(Op0, m_Neg(m_Value(A))) &&
5480 match(Op1, m_Neg(m_Value(B))))
5481 return new ICmpInst(I.getPredicate(), A, B);
5483 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5484 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5485 Value *OtherVal = A == Op1 ? B : A;
5486 return new ICmpInst(I.getPredicate(), OtherVal,
5487 Constant::getNullValue(A->getType()));
5490 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5491 // A^c1 == C^c2 --> A == C^(c1^c2)
5492 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5493 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5494 if (Op1->hasOneUse()) {
5495 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5496 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5497 return new ICmpInst(I.getPredicate(), A,
5498 InsertNewInstBefore(Xor, I));
5501 // A^B == A^D -> B == D
5502 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5503 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5504 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5505 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5509 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5510 (A == Op0 || B == Op0)) {
5511 // A == (A^B) -> B == 0
5512 Value *OtherVal = A == Op0 ? B : A;
5513 return new ICmpInst(I.getPredicate(), OtherVal,
5514 Constant::getNullValue(A->getType()));
5516 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5517 // (A-B) == A -> B == 0
5518 return new ICmpInst(I.getPredicate(), B,
5519 Constant::getNullValue(B->getType()));
5521 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5522 // A == (A-B) -> B == 0
5523 return new ICmpInst(I.getPredicate(), B,
5524 Constant::getNullValue(B->getType()));
5527 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5528 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5529 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5530 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5531 Value *X = 0, *Y = 0, *Z = 0;
5534 X = B; Y = D; Z = A;
5535 } else if (A == D) {
5536 X = B; Y = C; Z = A;
5537 } else if (B == C) {
5538 X = A; Y = D; Z = B;
5539 } else if (B == D) {
5540 X = A; Y = C; Z = B;
5543 if (X) { // Build (X^Y) & Z
5544 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5545 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5546 I.setOperand(0, Op1);
5547 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5552 return Changed ? &I : 0;
5556 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5557 /// and CmpRHS are both known to be integer constants.
5558 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5559 ConstantInt *DivRHS) {
5560 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5561 const APInt &CmpRHSV = CmpRHS->getValue();
5563 // FIXME: If the operand types don't match the type of the divide
5564 // then don't attempt this transform. The code below doesn't have the
5565 // logic to deal with a signed divide and an unsigned compare (and
5566 // vice versa). This is because (x /s C1) <s C2 produces different
5567 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5568 // (x /u C1) <u C2. Simply casting the operands and result won't
5569 // work. :( The if statement below tests that condition and bails
5571 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5572 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5574 if (DivRHS->isZero())
5575 return 0; // The ProdOV computation fails on divide by zero.
5577 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5578 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5579 // C2 (CI). By solving for X we can turn this into a range check
5580 // instead of computing a divide.
5581 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5583 // Determine if the product overflows by seeing if the product is
5584 // not equal to the divide. Make sure we do the same kind of divide
5585 // as in the LHS instruction that we're folding.
5586 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5587 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5589 // Get the ICmp opcode
5590 ICmpInst::Predicate Pred = ICI.getPredicate();
5592 // Figure out the interval that is being checked. For example, a comparison
5593 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5594 // Compute this interval based on the constants involved and the signedness of
5595 // the compare/divide. This computes a half-open interval, keeping track of
5596 // whether either value in the interval overflows. After analysis each
5597 // overflow variable is set to 0 if it's corresponding bound variable is valid
5598 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5599 int LoOverflow = 0, HiOverflow = 0;
5600 ConstantInt *LoBound = 0, *HiBound = 0;
5603 if (!DivIsSigned) { // udiv
5604 // e.g. X/5 op 3 --> [15, 20)
5606 HiOverflow = LoOverflow = ProdOV;
5608 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5609 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5610 if (CmpRHSV == 0) { // (X / pos) op 0
5611 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5612 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5614 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
5615 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5616 HiOverflow = LoOverflow = ProdOV;
5618 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5619 } else { // (X / pos) op neg
5620 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5621 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5622 LoOverflow = AddWithOverflow(LoBound, Prod,
5623 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5624 HiBound = AddOne(Prod);
5625 HiOverflow = ProdOV ? -1 : 0;
5627 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5628 if (CmpRHSV == 0) { // (X / neg) op 0
5629 // e.g. X/-5 op 0 --> [-4, 5)
5630 LoBound = AddOne(DivRHS);
5631 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5632 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5633 HiOverflow = 1; // [INTMIN+1, overflow)
5634 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5636 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
5637 // e.g. X/-5 op 3 --> [-19, -14)
5638 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5640 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5641 HiBound = AddOne(Prod);
5642 } else { // (X / neg) op neg
5643 // e.g. X/-5 op -3 --> [15, 20)
5645 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5646 HiBound = Subtract(Prod, DivRHS);
5649 // Dividing by a negative swaps the condition. LT <-> GT
5650 Pred = ICmpInst::getSwappedPredicate(Pred);
5653 Value *X = DivI->getOperand(0);
5655 default: assert(0 && "Unhandled icmp opcode!");
5656 case ICmpInst::ICMP_EQ:
5657 if (LoOverflow && HiOverflow)
5658 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5659 else if (HiOverflow)
5660 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5661 ICmpInst::ICMP_UGE, X, LoBound);
5662 else if (LoOverflow)
5663 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5664 ICmpInst::ICMP_ULT, X, HiBound);
5666 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5667 case ICmpInst::ICMP_NE:
5668 if (LoOverflow && HiOverflow)
5669 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5670 else if (HiOverflow)
5671 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5672 ICmpInst::ICMP_ULT, X, LoBound);
5673 else if (LoOverflow)
5674 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5675 ICmpInst::ICMP_UGE, X, HiBound);
5677 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5678 case ICmpInst::ICMP_ULT:
5679 case ICmpInst::ICMP_SLT:
5680 if (LoOverflow == +1) // Low bound is greater than input range.
5681 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5682 if (LoOverflow == -1) // Low bound is less than input range.
5683 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5684 return new ICmpInst(Pred, X, LoBound);
5685 case ICmpInst::ICMP_UGT:
5686 case ICmpInst::ICMP_SGT:
5687 if (HiOverflow == +1) // High bound greater than input range.
5688 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5689 else if (HiOverflow == -1) // High bound less than input range.
5690 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5691 if (Pred == ICmpInst::ICMP_UGT)
5692 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5694 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5699 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5701 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5704 const APInt &RHSV = RHS->getValue();
5706 switch (LHSI->getOpcode()) {
5707 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5708 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5709 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5711 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5712 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5713 Value *CompareVal = LHSI->getOperand(0);
5715 // If the sign bit of the XorCST is not set, there is no change to
5716 // the operation, just stop using the Xor.
5717 if (!XorCST->getValue().isNegative()) {
5718 ICI.setOperand(0, CompareVal);
5719 AddToWorkList(LHSI);
5723 // Was the old condition true if the operand is positive?
5724 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5726 // If so, the new one isn't.
5727 isTrueIfPositive ^= true;
5729 if (isTrueIfPositive)
5730 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5732 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5736 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5737 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5738 LHSI->getOperand(0)->hasOneUse()) {
5739 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5741 // If the LHS is an AND of a truncating cast, we can widen the
5742 // and/compare to be the input width without changing the value
5743 // produced, eliminating a cast.
5744 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5745 // We can do this transformation if either the AND constant does not
5746 // have its sign bit set or if it is an equality comparison.
5747 // Extending a relational comparison when we're checking the sign
5748 // bit would not work.
5749 if (Cast->hasOneUse() &&
5750 (ICI.isEquality() ||
5751 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5753 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5754 APInt NewCST = AndCST->getValue();
5755 NewCST.zext(BitWidth);
5757 NewCI.zext(BitWidth);
5758 Instruction *NewAnd =
5759 BinaryOperator::CreateAnd(Cast->getOperand(0),
5760 ConstantInt::get(NewCST),LHSI->getName());
5761 InsertNewInstBefore(NewAnd, ICI);
5762 return new ICmpInst(ICI.getPredicate(), NewAnd,
5763 ConstantInt::get(NewCI));
5767 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5768 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5769 // happens a LOT in code produced by the C front-end, for bitfield
5771 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5772 if (Shift && !Shift->isShift())
5776 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5777 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5778 const Type *AndTy = AndCST->getType(); // Type of the and.
5780 // We can fold this as long as we can't shift unknown bits
5781 // into the mask. This can only happen with signed shift
5782 // rights, as they sign-extend.
5784 bool CanFold = Shift->isLogicalShift();
5786 // To test for the bad case of the signed shr, see if any
5787 // of the bits shifted in could be tested after the mask.
5788 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5789 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5791 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5792 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5793 AndCST->getValue()) == 0)
5799 if (Shift->getOpcode() == Instruction::Shl)
5800 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5802 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5804 // Check to see if we are shifting out any of the bits being
5806 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5807 // If we shifted bits out, the fold is not going to work out.
5808 // As a special case, check to see if this means that the
5809 // result is always true or false now.
5810 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5811 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5812 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5813 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5815 ICI.setOperand(1, NewCst);
5816 Constant *NewAndCST;
5817 if (Shift->getOpcode() == Instruction::Shl)
5818 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5820 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5821 LHSI->setOperand(1, NewAndCST);
5822 LHSI->setOperand(0, Shift->getOperand(0));
5823 AddToWorkList(Shift); // Shift is dead.
5824 AddUsesToWorkList(ICI);
5830 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5831 // preferable because it allows the C<<Y expression to be hoisted out
5832 // of a loop if Y is invariant and X is not.
5833 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5834 ICI.isEquality() && !Shift->isArithmeticShift() &&
5835 isa<Instruction>(Shift->getOperand(0))) {
5838 if (Shift->getOpcode() == Instruction::LShr) {
5839 NS = BinaryOperator::CreateShl(AndCST,
5840 Shift->getOperand(1), "tmp");
5842 // Insert a logical shift.
5843 NS = BinaryOperator::CreateLShr(AndCST,
5844 Shift->getOperand(1), "tmp");
5846 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5848 // Compute X & (C << Y).
5849 Instruction *NewAnd =
5850 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5851 InsertNewInstBefore(NewAnd, ICI);
5853 ICI.setOperand(0, NewAnd);
5859 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5860 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5863 uint32_t TypeBits = RHSV.getBitWidth();
5865 // Check that the shift amount is in range. If not, don't perform
5866 // undefined shifts. When the shift is visited it will be
5868 if (ShAmt->uge(TypeBits))
5871 if (ICI.isEquality()) {
5872 // If we are comparing against bits always shifted out, the
5873 // comparison cannot succeed.
5875 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5876 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5877 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5878 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5879 return ReplaceInstUsesWith(ICI, Cst);
5882 if (LHSI->hasOneUse()) {
5883 // Otherwise strength reduce the shift into an and.
5884 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5886 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5889 BinaryOperator::CreateAnd(LHSI->getOperand(0),
5890 Mask, LHSI->getName()+".mask");
5891 Value *And = InsertNewInstBefore(AndI, ICI);
5892 return new ICmpInst(ICI.getPredicate(), And,
5893 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5897 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5898 bool TrueIfSigned = false;
5899 if (LHSI->hasOneUse() &&
5900 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5901 // (X << 31) <s 0 --> (X&1) != 0
5902 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5903 (TypeBits-ShAmt->getZExtValue()-1));
5905 BinaryOperator::CreateAnd(LHSI->getOperand(0),
5906 Mask, LHSI->getName()+".mask");
5907 Value *And = InsertNewInstBefore(AndI, ICI);
5909 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5910 And, Constant::getNullValue(And->getType()));
5915 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5916 case Instruction::AShr: {
5917 // Only handle equality comparisons of shift-by-constant.
5918 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5919 if (!ShAmt || !ICI.isEquality()) break;
5921 // Check that the shift amount is in range. If not, don't perform
5922 // undefined shifts. When the shift is visited it will be
5924 uint32_t TypeBits = RHSV.getBitWidth();
5925 if (ShAmt->uge(TypeBits))
5928 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5930 // If we are comparing against bits always shifted out, the
5931 // comparison cannot succeed.
5932 APInt Comp = RHSV << ShAmtVal;
5933 if (LHSI->getOpcode() == Instruction::LShr)
5934 Comp = Comp.lshr(ShAmtVal);
5936 Comp = Comp.ashr(ShAmtVal);
5938 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5939 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5940 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5941 return ReplaceInstUsesWith(ICI, Cst);
5944 // Otherwise, check to see if the bits shifted out are known to be zero.
5945 // If so, we can compare against the unshifted value:
5946 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
5947 if (LHSI->hasOneUse() &&
5948 MaskedValueIsZero(LHSI->getOperand(0),
5949 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5950 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5951 ConstantExpr::getShl(RHS, ShAmt));
5954 if (LHSI->hasOneUse()) {
5955 // Otherwise strength reduce the shift into an and.
5956 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5957 Constant *Mask = ConstantInt::get(Val);
5960 BinaryOperator::CreateAnd(LHSI->getOperand(0),
5961 Mask, LHSI->getName()+".mask");
5962 Value *And = InsertNewInstBefore(AndI, ICI);
5963 return new ICmpInst(ICI.getPredicate(), And,
5964 ConstantExpr::getShl(RHS, ShAmt));
5969 case Instruction::SDiv:
5970 case Instruction::UDiv:
5971 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5972 // Fold this div into the comparison, producing a range check.
5973 // Determine, based on the divide type, what the range is being
5974 // checked. If there is an overflow on the low or high side, remember
5975 // it, otherwise compute the range [low, hi) bounding the new value.
5976 // See: InsertRangeTest above for the kinds of replacements possible.
5977 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5978 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5983 case Instruction::Add:
5984 // Fold: icmp pred (add, X, C1), C2
5986 if (!ICI.isEquality()) {
5987 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5989 const APInt &LHSV = LHSC->getValue();
5991 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5994 if (ICI.isSignedPredicate()) {
5995 if (CR.getLower().isSignBit()) {
5996 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5997 ConstantInt::get(CR.getUpper()));
5998 } else if (CR.getUpper().isSignBit()) {
5999 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6000 ConstantInt::get(CR.getLower()));
6003 if (CR.getLower().isMinValue()) {
6004 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6005 ConstantInt::get(CR.getUpper()));
6006 } else if (CR.getUpper().isMinValue()) {
6007 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6008 ConstantInt::get(CR.getLower()));
6015 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6016 if (ICI.isEquality()) {
6017 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6019 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6020 // the second operand is a constant, simplify a bit.
6021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6022 switch (BO->getOpcode()) {
6023 case Instruction::SRem:
6024 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6025 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6026 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6027 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6028 Instruction *NewRem =
6029 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6031 InsertNewInstBefore(NewRem, ICI);
6032 return new ICmpInst(ICI.getPredicate(), NewRem,
6033 Constant::getNullValue(BO->getType()));
6037 case Instruction::Add:
6038 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6039 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6040 if (BO->hasOneUse())
6041 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6042 Subtract(RHS, BOp1C));
6043 } else if (RHSV == 0) {
6044 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6045 // efficiently invertible, or if the add has just this one use.
6046 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6048 if (Value *NegVal = dyn_castNegVal(BOp1))
6049 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6050 else if (Value *NegVal = dyn_castNegVal(BOp0))
6051 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6052 else if (BO->hasOneUse()) {
6053 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6054 InsertNewInstBefore(Neg, ICI);
6056 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6060 case Instruction::Xor:
6061 // For the xor case, we can xor two constants together, eliminating
6062 // the explicit xor.
6063 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6064 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6065 ConstantExpr::getXor(RHS, BOC));
6068 case Instruction::Sub:
6069 // Replace (([sub|xor] A, B) != 0) with (A != B)
6071 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6075 case Instruction::Or:
6076 // If bits are being or'd in that are not present in the constant we
6077 // are comparing against, then the comparison could never succeed!
6078 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6079 Constant *NotCI = ConstantExpr::getNot(RHS);
6080 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6081 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6086 case Instruction::And:
6087 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6088 // If bits are being compared against that are and'd out, then the
6089 // comparison can never succeed!
6090 if ((RHSV & ~BOC->getValue()) != 0)
6091 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6094 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6095 if (RHS == BOC && RHSV.isPowerOf2())
6096 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6097 ICmpInst::ICMP_NE, LHSI,
6098 Constant::getNullValue(RHS->getType()));
6100 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6101 if (BOC->getValue().isSignBit()) {
6102 Value *X = BO->getOperand(0);
6103 Constant *Zero = Constant::getNullValue(X->getType());
6104 ICmpInst::Predicate pred = isICMP_NE ?
6105 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6106 return new ICmpInst(pred, X, Zero);
6109 // ((X & ~7) == 0) --> X < 8
6110 if (RHSV == 0 && isHighOnes(BOC)) {
6111 Value *X = BO->getOperand(0);
6112 Constant *NegX = ConstantExpr::getNeg(BOC);
6113 ICmpInst::Predicate pred = isICMP_NE ?
6114 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6115 return new ICmpInst(pred, X, NegX);
6120 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6121 // Handle icmp {eq|ne} <intrinsic>, intcst.
6122 if (II->getIntrinsicID() == Intrinsic::bswap) {
6124 ICI.setOperand(0, II->getOperand(1));
6125 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6129 } else { // Not a ICMP_EQ/ICMP_NE
6130 // If the LHS is a cast from an integral value of the same size,
6131 // then since we know the RHS is a constant, try to simlify.
6132 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6133 Value *CastOp = Cast->getOperand(0);
6134 const Type *SrcTy = CastOp->getType();
6135 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6136 if (SrcTy->isInteger() &&
6137 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6138 // If this is an unsigned comparison, try to make the comparison use
6139 // smaller constant values.
6140 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6141 // X u< 128 => X s> -1
6142 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6143 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6144 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6145 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6146 // X u> 127 => X s< 0
6147 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6148 Constant::getNullValue(SrcTy));
6156 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6157 /// We only handle extending casts so far.
6159 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6160 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6161 Value *LHSCIOp = LHSCI->getOperand(0);
6162 const Type *SrcTy = LHSCIOp->getType();
6163 const Type *DestTy = LHSCI->getType();
6166 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6167 // integer type is the same size as the pointer type.
6168 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6169 getTargetData().getPointerSizeInBits() ==
6170 cast<IntegerType>(DestTy)->getBitWidth()) {
6172 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6173 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6174 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6175 RHSOp = RHSC->getOperand(0);
6176 // If the pointer types don't match, insert a bitcast.
6177 if (LHSCIOp->getType() != RHSOp->getType())
6178 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6182 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6185 // The code below only handles extension cast instructions, so far.
6187 if (LHSCI->getOpcode() != Instruction::ZExt &&
6188 LHSCI->getOpcode() != Instruction::SExt)
6191 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6192 bool isSignedCmp = ICI.isSignedPredicate();
6194 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6195 // Not an extension from the same type?
6196 RHSCIOp = CI->getOperand(0);
6197 if (RHSCIOp->getType() != LHSCIOp->getType())
6200 // If the signedness of the two casts doesn't agree (i.e. one is a sext
6201 // and the other is a zext), then we can't handle this.
6202 if (CI->getOpcode() != LHSCI->getOpcode())
6205 // Deal with equality cases early.
6206 if (ICI.isEquality())
6207 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6209 // A signed comparison of sign extended values simplifies into a
6210 // signed comparison.
6211 if (isSignedCmp && isSignedExt)
6212 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6214 // The other three cases all fold into an unsigned comparison.
6215 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6218 // If we aren't dealing with a constant on the RHS, exit early
6219 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6223 // Compute the constant that would happen if we truncated to SrcTy then
6224 // reextended to DestTy.
6225 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6226 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6228 // If the re-extended constant didn't change...
6230 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6231 // For example, we might have:
6232 // %A = sext short %X to uint
6233 // %B = icmp ugt uint %A, 1330
6234 // It is incorrect to transform this into
6235 // %B = icmp ugt short %X, 1330
6236 // because %A may have negative value.
6238 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6239 // OR operation is EQ/NE.
6240 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6241 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6246 // The re-extended constant changed so the constant cannot be represented
6247 // in the shorter type. Consequently, we cannot emit a simple comparison.
6249 // First, handle some easy cases. We know the result cannot be equal at this
6250 // point so handle the ICI.isEquality() cases
6251 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6252 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6253 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6254 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6256 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6257 // should have been folded away previously and not enter in here.
6260 // We're performing a signed comparison.
6261 if (cast<ConstantInt>(CI)->getValue().isNegative())
6262 Result = ConstantInt::getFalse(); // X < (small) --> false
6264 Result = ConstantInt::getTrue(); // X < (large) --> true
6266 // We're performing an unsigned comparison.
6268 // We're performing an unsigned comp with a sign extended value.
6269 // This is true if the input is >= 0. [aka >s -1]
6270 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6271 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6272 NegOne, ICI.getName()), ICI);
6274 // Unsigned extend & unsigned compare -> always true.
6275 Result = ConstantInt::getTrue();
6279 // Finally, return the value computed.
6280 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6281 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6282 return ReplaceInstUsesWith(ICI, Result);
6284 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6285 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6286 "ICmp should be folded!");
6287 if (Constant *CI = dyn_cast<Constant>(Result))
6288 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6290 return BinaryOperator::CreateNot(Result);
6294 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6295 return commonShiftTransforms(I);
6298 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6299 return commonShiftTransforms(I);
6302 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6303 if (Instruction *R = commonShiftTransforms(I))
6306 Value *Op0 = I.getOperand(0);
6308 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6309 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6310 if (CSI->isAllOnesValue())
6311 return ReplaceInstUsesWith(I, CSI);
6313 // See if we can turn a signed shr into an unsigned shr.
6314 if (MaskedValueIsZero(Op0,
6315 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6316 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6321 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6322 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6323 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6325 // shl X, 0 == X and shr X, 0 == X
6326 // shl 0, X == 0 and shr 0, X == 0
6327 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6328 Op0 == Constant::getNullValue(Op0->getType()))
6329 return ReplaceInstUsesWith(I, Op0);
6331 if (isa<UndefValue>(Op0)) {
6332 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6333 return ReplaceInstUsesWith(I, Op0);
6334 else // undef << X -> 0, undef >>u X -> 0
6335 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6337 if (isa<UndefValue>(Op1)) {
6338 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6339 return ReplaceInstUsesWith(I, Op0);
6340 else // X << undef, X >>u undef -> 0
6341 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6344 // Try to fold constant and into select arguments.
6345 if (isa<Constant>(Op0))
6346 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6347 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6350 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6351 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6356 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6357 BinaryOperator &I) {
6358 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6360 // See if we can simplify any instructions used by the instruction whose sole
6361 // purpose is to compute bits we don't care about.
6362 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6363 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6364 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6365 KnownZero, KnownOne))
6368 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6369 // of a signed value.
6371 if (Op1->uge(TypeBits)) {
6372 if (I.getOpcode() != Instruction::AShr)
6373 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6375 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6380 // ((X*C1) << C2) == (X * (C1 << C2))
6381 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6382 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6383 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6384 return BinaryOperator::CreateMul(BO->getOperand(0),
6385 ConstantExpr::getShl(BOOp, Op1));
6387 // Try to fold constant and into select arguments.
6388 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6389 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6391 if (isa<PHINode>(Op0))
6392 if (Instruction *NV = FoldOpIntoPhi(I))
6395 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6396 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6397 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6398 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6399 // place. Don't try to do this transformation in this case. Also, we
6400 // require that the input operand is a shift-by-constant so that we have
6401 // confidence that the shifts will get folded together. We could do this
6402 // xform in more cases, but it is unlikely to be profitable.
6403 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6404 isa<ConstantInt>(TrOp->getOperand(1))) {
6405 // Okay, we'll do this xform. Make the shift of shift.
6406 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6407 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6409 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6411 // For logical shifts, the truncation has the effect of making the high
6412 // part of the register be zeros. Emulate this by inserting an AND to
6413 // clear the top bits as needed. This 'and' will usually be zapped by
6414 // other xforms later if dead.
6415 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6416 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6417 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6419 // The mask we constructed says what the trunc would do if occurring
6420 // between the shifts. We want to know the effect *after* the second
6421 // shift. We know that it is a logical shift by a constant, so adjust the
6422 // mask as appropriate.
6423 if (I.getOpcode() == Instruction::Shl)
6424 MaskV <<= Op1->getZExtValue();
6426 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6427 MaskV = MaskV.lshr(Op1->getZExtValue());
6430 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6432 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6434 // Return the value truncated to the interesting size.
6435 return new TruncInst(And, I.getType());
6439 if (Op0->hasOneUse()) {
6440 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6441 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6444 switch (Op0BO->getOpcode()) {
6446 case Instruction::Add:
6447 case Instruction::And:
6448 case Instruction::Or:
6449 case Instruction::Xor: {
6450 // These operators commute.
6451 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6452 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6453 match(Op0BO->getOperand(1),
6454 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6455 Instruction *YS = BinaryOperator::CreateShl(
6456 Op0BO->getOperand(0), Op1,
6458 InsertNewInstBefore(YS, I); // (Y << C)
6460 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6461 Op0BO->getOperand(1)->getName());
6462 InsertNewInstBefore(X, I); // (X + (Y << C))
6463 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6464 return BinaryOperator::CreateAnd(X, ConstantInt::get(
6465 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6468 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6469 Value *Op0BOOp1 = Op0BO->getOperand(1);
6470 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6472 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6473 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6475 Instruction *YS = BinaryOperator::CreateShl(
6476 Op0BO->getOperand(0), Op1,
6478 InsertNewInstBefore(YS, I); // (Y << C)
6480 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6481 V1->getName()+".mask");
6482 InsertNewInstBefore(XM, I); // X & (CC << C)
6484 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6489 case Instruction::Sub: {
6490 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6491 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6492 match(Op0BO->getOperand(0),
6493 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6494 Instruction *YS = BinaryOperator::CreateShl(
6495 Op0BO->getOperand(1), Op1,
6497 InsertNewInstBefore(YS, I); // (Y << C)
6499 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6500 Op0BO->getOperand(0)->getName());
6501 InsertNewInstBefore(X, I); // (X + (Y << C))
6502 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6503 return BinaryOperator::CreateAnd(X, ConstantInt::get(
6504 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6507 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6508 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6509 match(Op0BO->getOperand(0),
6510 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6511 m_ConstantInt(CC))) && V2 == Op1 &&
6512 cast<BinaryOperator>(Op0BO->getOperand(0))
6513 ->getOperand(0)->hasOneUse()) {
6514 Instruction *YS = BinaryOperator::CreateShl(
6515 Op0BO->getOperand(1), Op1,
6517 InsertNewInstBefore(YS, I); // (Y << C)
6519 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6520 V1->getName()+".mask");
6521 InsertNewInstBefore(XM, I); // X & (CC << C)
6523 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6531 // If the operand is an bitwise operator with a constant RHS, and the
6532 // shift is the only use, we can pull it out of the shift.
6533 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6534 bool isValid = true; // Valid only for And, Or, Xor
6535 bool highBitSet = false; // Transform if high bit of constant set?
6537 switch (Op0BO->getOpcode()) {
6538 default: isValid = false; break; // Do not perform transform!
6539 case Instruction::Add:
6540 isValid = isLeftShift;
6542 case Instruction::Or:
6543 case Instruction::Xor:
6546 case Instruction::And:
6551 // If this is a signed shift right, and the high bit is modified
6552 // by the logical operation, do not perform the transformation.
6553 // The highBitSet boolean indicates the value of the high bit of
6554 // the constant which would cause it to be modified for this
6557 if (isValid && I.getOpcode() == Instruction::AShr)
6558 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6561 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6563 Instruction *NewShift =
6564 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6565 InsertNewInstBefore(NewShift, I);
6566 NewShift->takeName(Op0BO);
6568 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6575 // Find out if this is a shift of a shift by a constant.
6576 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6577 if (ShiftOp && !ShiftOp->isShift())
6580 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6581 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6582 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6583 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6584 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6585 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6586 Value *X = ShiftOp->getOperand(0);
6588 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6589 if (AmtSum > TypeBits)
6592 const IntegerType *Ty = cast<IntegerType>(I.getType());
6594 // Check for (X << c1) << c2 and (X >> c1) >> c2
6595 if (I.getOpcode() == ShiftOp->getOpcode()) {
6596 return BinaryOperator::Create(I.getOpcode(), X,
6597 ConstantInt::get(Ty, AmtSum));
6598 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6599 I.getOpcode() == Instruction::AShr) {
6600 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6601 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6602 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6603 I.getOpcode() == Instruction::LShr) {
6604 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6605 Instruction *Shift =
6606 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6607 InsertNewInstBefore(Shift, I);
6609 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6610 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6613 // Okay, if we get here, one shift must be left, and the other shift must be
6614 // right. See if the amounts are equal.
6615 if (ShiftAmt1 == ShiftAmt2) {
6616 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6617 if (I.getOpcode() == Instruction::Shl) {
6618 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6619 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6621 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6622 if (I.getOpcode() == Instruction::LShr) {
6623 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6624 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6626 // We can simplify ((X << C) >>s C) into a trunc + sext.
6627 // NOTE: we could do this for any C, but that would make 'unusual' integer
6628 // types. For now, just stick to ones well-supported by the code
6630 const Type *SExtType = 0;
6631 switch (Ty->getBitWidth() - ShiftAmt1) {
6638 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6643 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6644 InsertNewInstBefore(NewTrunc, I);
6645 return new SExtInst(NewTrunc, Ty);
6647 // Otherwise, we can't handle it yet.
6648 } else if (ShiftAmt1 < ShiftAmt2) {
6649 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6651 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6652 if (I.getOpcode() == Instruction::Shl) {
6653 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6654 ShiftOp->getOpcode() == Instruction::AShr);
6655 Instruction *Shift =
6656 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6657 InsertNewInstBefore(Shift, I);
6659 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6660 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6663 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6664 if (I.getOpcode() == Instruction::LShr) {
6665 assert(ShiftOp->getOpcode() == Instruction::Shl);
6666 Instruction *Shift =
6667 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6668 InsertNewInstBefore(Shift, I);
6670 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6671 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6674 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6676 assert(ShiftAmt2 < ShiftAmt1);
6677 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6679 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6680 if (I.getOpcode() == Instruction::Shl) {
6681 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6682 ShiftOp->getOpcode() == Instruction::AShr);
6683 Instruction *Shift =
6684 BinaryOperator::Create(ShiftOp->getOpcode(), X,
6685 ConstantInt::get(Ty, ShiftDiff));
6686 InsertNewInstBefore(Shift, I);
6688 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6689 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6692 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6693 if (I.getOpcode() == Instruction::LShr) {
6694 assert(ShiftOp->getOpcode() == Instruction::Shl);
6695 Instruction *Shift =
6696 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6697 InsertNewInstBefore(Shift, I);
6699 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6700 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6703 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6710 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6711 /// expression. If so, decompose it, returning some value X, such that Val is
6714 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6716 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6717 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6718 Offset = CI->getZExtValue();
6720 return ConstantInt::get(Type::Int32Ty, 0);
6721 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6722 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6723 if (I->getOpcode() == Instruction::Shl) {
6724 // This is a value scaled by '1 << the shift amt'.
6725 Scale = 1U << RHS->getZExtValue();
6727 return I->getOperand(0);
6728 } else if (I->getOpcode() == Instruction::Mul) {
6729 // This value is scaled by 'RHS'.
6730 Scale = RHS->getZExtValue();
6732 return I->getOperand(0);
6733 } else if (I->getOpcode() == Instruction::Add) {
6734 // We have X+C. Check to see if we really have (X*C2)+C1,
6735 // where C1 is divisible by C2.
6738 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6739 Offset += RHS->getZExtValue();
6746 // Otherwise, we can't look past this.
6753 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6754 /// try to eliminate the cast by moving the type information into the alloc.
6755 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6756 AllocationInst &AI) {
6757 const PointerType *PTy = cast<PointerType>(CI.getType());
6759 // Remove any uses of AI that are dead.
6760 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6762 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6763 Instruction *User = cast<Instruction>(*UI++);
6764 if (isInstructionTriviallyDead(User)) {
6765 while (UI != E && *UI == User)
6766 ++UI; // If this instruction uses AI more than once, don't break UI.
6769 DOUT << "IC: DCE: " << *User;
6770 EraseInstFromFunction(*User);
6774 // Get the type really allocated and the type casted to.
6775 const Type *AllocElTy = AI.getAllocatedType();
6776 const Type *CastElTy = PTy->getElementType();
6777 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6779 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6780 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6781 if (CastElTyAlign < AllocElTyAlign) return 0;
6783 // If the allocation has multiple uses, only promote it if we are strictly
6784 // increasing the alignment of the resultant allocation. If we keep it the
6785 // same, we open the door to infinite loops of various kinds.
6786 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6788 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6789 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6790 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6792 // See if we can satisfy the modulus by pulling a scale out of the array
6794 unsigned ArraySizeScale;
6796 Value *NumElements = // See if the array size is a decomposable linear expr.
6797 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6799 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6801 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6802 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6804 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6809 // If the allocation size is constant, form a constant mul expression
6810 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6811 if (isa<ConstantInt>(NumElements))
6812 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6813 // otherwise multiply the amount and the number of elements
6814 else if (Scale != 1) {
6815 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6816 Amt = InsertNewInstBefore(Tmp, AI);
6820 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6821 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6822 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6823 Amt = InsertNewInstBefore(Tmp, AI);
6826 AllocationInst *New;
6827 if (isa<MallocInst>(AI))
6828 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6830 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6831 InsertNewInstBefore(New, AI);
6834 // If the allocation has multiple uses, insert a cast and change all things
6835 // that used it to use the new cast. This will also hack on CI, but it will
6837 if (!AI.hasOneUse()) {
6838 AddUsesToWorkList(AI);
6839 // New is the allocation instruction, pointer typed. AI is the original
6840 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6841 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6842 InsertNewInstBefore(NewCast, AI);
6843 AI.replaceAllUsesWith(NewCast);
6845 return ReplaceInstUsesWith(CI, New);
6848 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6849 /// and return it as type Ty without inserting any new casts and without
6850 /// changing the computed value. This is used by code that tries to decide
6851 /// whether promoting or shrinking integer operations to wider or smaller types
6852 /// will allow us to eliminate a truncate or extend.
6854 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6855 /// extension operation if Ty is larger.
6856 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6858 int &NumCastsRemoved) {
6859 // We can always evaluate constants in another type.
6860 if (isa<ConstantInt>(V))
6863 Instruction *I = dyn_cast<Instruction>(V);
6864 if (!I) return false;
6866 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6868 // If this is an extension or truncate, we can often eliminate it.
6869 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6870 // If this is a cast from the destination type, we can trivially eliminate
6871 // it, and this will remove a cast overall.
6872 if (I->getOperand(0)->getType() == Ty) {
6873 // If the first operand is itself a cast, and is eliminable, do not count
6874 // this as an eliminable cast. We would prefer to eliminate those two
6876 if (!isa<CastInst>(I->getOperand(0)))
6882 // We can't extend or shrink something that has multiple uses: doing so would
6883 // require duplicating the instruction in general, which isn't profitable.
6884 if (!I->hasOneUse()) return false;
6886 switch (I->getOpcode()) {
6887 case Instruction::Add:
6888 case Instruction::Sub:
6889 case Instruction::And:
6890 case Instruction::Or:
6891 case Instruction::Xor:
6892 // These operators can all arbitrarily be extended or truncated.
6893 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6895 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6898 case Instruction::Mul:
6899 // A multiply can be truncated by truncating its operands.
6900 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6901 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6903 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6906 case Instruction::Shl:
6907 // If we are truncating the result of this SHL, and if it's a shift of a
6908 // constant amount, we can always perform a SHL in a smaller type.
6909 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6910 uint32_t BitWidth = Ty->getBitWidth();
6911 if (BitWidth < OrigTy->getBitWidth() &&
6912 CI->getLimitedValue(BitWidth) < BitWidth)
6913 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6917 case Instruction::LShr:
6918 // If this is a truncate of a logical shr, we can truncate it to a smaller
6919 // lshr iff we know that the bits we would otherwise be shifting in are
6921 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6922 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6923 uint32_t BitWidth = Ty->getBitWidth();
6924 if (BitWidth < OrigBitWidth &&
6925 MaskedValueIsZero(I->getOperand(0),
6926 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6927 CI->getLimitedValue(BitWidth) < BitWidth) {
6928 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6933 case Instruction::ZExt:
6934 case Instruction::SExt:
6935 case Instruction::Trunc:
6936 // If this is the same kind of case as our original (e.g. zext+zext), we
6937 // can safely replace it. Note that replacing it does not reduce the number
6938 // of casts in the input.
6939 if (I->getOpcode() == CastOpc)
6944 // TODO: Can handle more cases here.
6951 /// EvaluateInDifferentType - Given an expression that
6952 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6953 /// evaluate the expression.
6954 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6956 if (Constant *C = dyn_cast<Constant>(V))
6957 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6959 // Otherwise, it must be an instruction.
6960 Instruction *I = cast<Instruction>(V);
6961 Instruction *Res = 0;
6962 switch (I->getOpcode()) {
6963 case Instruction::Add:
6964 case Instruction::Sub:
6965 case Instruction::Mul:
6966 case Instruction::And:
6967 case Instruction::Or:
6968 case Instruction::Xor:
6969 case Instruction::AShr:
6970 case Instruction::LShr:
6971 case Instruction::Shl: {
6972 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6973 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6974 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
6975 LHS, RHS, I->getName());
6978 case Instruction::Trunc:
6979 case Instruction::ZExt:
6980 case Instruction::SExt:
6981 // If the source type of the cast is the type we're trying for then we can
6982 // just return the source. There's no need to insert it because it is not
6984 if (I->getOperand(0)->getType() == Ty)
6985 return I->getOperand(0);
6987 // Otherwise, must be the same type of case, so just reinsert a new one.
6988 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6992 // TODO: Can handle more cases here.
6993 assert(0 && "Unreachable!");
6997 return InsertNewInstBefore(Res, *I);
7000 /// @brief Implement the transforms common to all CastInst visitors.
7001 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7002 Value *Src = CI.getOperand(0);
7004 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7005 // eliminate it now.
7006 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7007 if (Instruction::CastOps opc =
7008 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7009 // The first cast (CSrc) is eliminable so we need to fix up or replace
7010 // the second cast (CI). CSrc will then have a good chance of being dead.
7011 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7015 // If we are casting a select then fold the cast into the select
7016 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7017 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7020 // If we are casting a PHI then fold the cast into the PHI
7021 if (isa<PHINode>(Src))
7022 if (Instruction *NV = FoldOpIntoPhi(CI))
7028 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7029 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7030 Value *Src = CI.getOperand(0);
7032 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7033 // If casting the result of a getelementptr instruction with no offset, turn
7034 // this into a cast of the original pointer!
7035 if (GEP->hasAllZeroIndices()) {
7036 // Changing the cast operand is usually not a good idea but it is safe
7037 // here because the pointer operand is being replaced with another
7038 // pointer operand so the opcode doesn't need to change.
7040 CI.setOperand(0, GEP->getOperand(0));
7044 // If the GEP has a single use, and the base pointer is a bitcast, and the
7045 // GEP computes a constant offset, see if we can convert these three
7046 // instructions into fewer. This typically happens with unions and other
7047 // non-type-safe code.
7048 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7049 if (GEP->hasAllConstantIndices()) {
7050 // We are guaranteed to get a constant from EmitGEPOffset.
7051 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7052 int64_t Offset = OffsetV->getSExtValue();
7054 // Get the base pointer input of the bitcast, and the type it points to.
7055 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7056 const Type *GEPIdxTy =
7057 cast<PointerType>(OrigBase->getType())->getElementType();
7058 if (GEPIdxTy->isSized()) {
7059 SmallVector<Value*, 8> NewIndices;
7061 // Start with the index over the outer type. Note that the type size
7062 // might be zero (even if the offset isn't zero) if the indexed type
7063 // is something like [0 x {int, int}]
7064 const Type *IntPtrTy = TD->getIntPtrType();
7065 int64_t FirstIdx = 0;
7066 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7067 FirstIdx = Offset/TySize;
7070 // Handle silly modulus not returning values values [0..TySize).
7074 assert(Offset >= 0);
7076 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7079 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7081 // Index into the types. If we fail, set OrigBase to null.
7083 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7084 const StructLayout *SL = TD->getStructLayout(STy);
7085 if (Offset < (int64_t)SL->getSizeInBytes()) {
7086 unsigned Elt = SL->getElementContainingOffset(Offset);
7087 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7089 Offset -= SL->getElementOffset(Elt);
7090 GEPIdxTy = STy->getElementType(Elt);
7092 // Otherwise, we can't index into this, bail out.
7096 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7097 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7098 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7099 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7102 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7104 GEPIdxTy = STy->getElementType();
7106 // Otherwise, we can't index into this, bail out.
7112 // If we were able to index down into an element, create the GEP
7113 // and bitcast the result. This eliminates one bitcast, potentially
7115 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7117 NewIndices.end(), "");
7118 InsertNewInstBefore(NGEP, CI);
7119 NGEP->takeName(GEP);
7121 if (isa<BitCastInst>(CI))
7122 return new BitCastInst(NGEP, CI.getType());
7123 assert(isa<PtrToIntInst>(CI));
7124 return new PtrToIntInst(NGEP, CI.getType());
7131 return commonCastTransforms(CI);
7136 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7137 /// integer types. This function implements the common transforms for all those
7139 /// @brief Implement the transforms common to CastInst with integer operands
7140 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7141 if (Instruction *Result = commonCastTransforms(CI))
7144 Value *Src = CI.getOperand(0);
7145 const Type *SrcTy = Src->getType();
7146 const Type *DestTy = CI.getType();
7147 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7148 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7150 // See if we can simplify any instructions used by the LHS whose sole
7151 // purpose is to compute bits we don't care about.
7152 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7153 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7154 KnownZero, KnownOne))
7157 // If the source isn't an instruction or has more than one use then we
7158 // can't do anything more.
7159 Instruction *SrcI = dyn_cast<Instruction>(Src);
7160 if (!SrcI || !Src->hasOneUse())
7163 // Attempt to propagate the cast into the instruction for int->int casts.
7164 int NumCastsRemoved = 0;
7165 if (!isa<BitCastInst>(CI) &&
7166 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7167 CI.getOpcode(), NumCastsRemoved)) {
7168 // If this cast is a truncate, evaluting in a different type always
7169 // eliminates the cast, so it is always a win. If this is a zero-extension,
7170 // we need to do an AND to maintain the clear top-part of the computation,
7171 // so we require that the input have eliminated at least one cast. If this
7172 // is a sign extension, we insert two new casts (to do the extension) so we
7173 // require that two casts have been eliminated.
7175 switch (CI.getOpcode()) {
7177 // All the others use floating point so we shouldn't actually
7178 // get here because of the check above.
7179 assert(0 && "Unknown cast type");
7180 case Instruction::Trunc:
7183 case Instruction::ZExt:
7184 DoXForm = NumCastsRemoved >= 1;
7186 case Instruction::SExt:
7187 DoXForm = NumCastsRemoved >= 2;
7192 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7193 CI.getOpcode() == Instruction::SExt);
7194 assert(Res->getType() == DestTy);
7195 switch (CI.getOpcode()) {
7196 default: assert(0 && "Unknown cast type!");
7197 case Instruction::Trunc:
7198 case Instruction::BitCast:
7199 // Just replace this cast with the result.
7200 return ReplaceInstUsesWith(CI, Res);
7201 case Instruction::ZExt: {
7202 // We need to emit an AND to clear the high bits.
7203 assert(SrcBitSize < DestBitSize && "Not a zext?");
7204 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7206 return BinaryOperator::CreateAnd(Res, C);
7208 case Instruction::SExt:
7209 // We need to emit a cast to truncate, then a cast to sext.
7210 return CastInst::Create(Instruction::SExt,
7211 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7217 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7218 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7220 switch (SrcI->getOpcode()) {
7221 case Instruction::Add:
7222 case Instruction::Mul:
7223 case Instruction::And:
7224 case Instruction::Or:
7225 case Instruction::Xor:
7226 // If we are discarding information, rewrite.
7227 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7228 // Don't insert two casts if they cannot be eliminated. We allow
7229 // two casts to be inserted if the sizes are the same. This could
7230 // only be converting signedness, which is a noop.
7231 if (DestBitSize == SrcBitSize ||
7232 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7233 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7234 Instruction::CastOps opcode = CI.getOpcode();
7235 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7236 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7237 return BinaryOperator::Create(
7238 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7242 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7243 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7244 SrcI->getOpcode() == Instruction::Xor &&
7245 Op1 == ConstantInt::getTrue() &&
7246 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7247 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7248 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7251 case Instruction::SDiv:
7252 case Instruction::UDiv:
7253 case Instruction::SRem:
7254 case Instruction::URem:
7255 // If we are just changing the sign, rewrite.
7256 if (DestBitSize == SrcBitSize) {
7257 // Don't insert two casts if they cannot be eliminated. We allow
7258 // two casts to be inserted if the sizes are the same. This could
7259 // only be converting signedness, which is a noop.
7260 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7261 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7262 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7264 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7266 return BinaryOperator::Create(
7267 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7272 case Instruction::Shl:
7273 // Allow changing the sign of the source operand. Do not allow
7274 // changing the size of the shift, UNLESS the shift amount is a
7275 // constant. We must not change variable sized shifts to a smaller
7276 // size, because it is undefined to shift more bits out than exist
7278 if (DestBitSize == SrcBitSize ||
7279 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7280 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7281 Instruction::BitCast : Instruction::Trunc);
7282 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7283 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7284 return BinaryOperator::CreateShl(Op0c, Op1c);
7287 case Instruction::AShr:
7288 // If this is a signed shr, and if all bits shifted in are about to be
7289 // truncated off, turn it into an unsigned shr to allow greater
7291 if (DestBitSize < SrcBitSize &&
7292 isa<ConstantInt>(Op1)) {
7293 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7294 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7295 // Insert the new logical shift right.
7296 return BinaryOperator::CreateLShr(Op0, Op1);
7304 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7305 if (Instruction *Result = commonIntCastTransforms(CI))
7308 Value *Src = CI.getOperand(0);
7309 const Type *Ty = CI.getType();
7310 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7311 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7313 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7314 switch (SrcI->getOpcode()) {
7316 case Instruction::LShr:
7317 // We can shrink lshr to something smaller if we know the bits shifted in
7318 // are already zeros.
7319 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7320 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7322 // Get a mask for the bits shifting in.
7323 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7324 Value* SrcIOp0 = SrcI->getOperand(0);
7325 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7326 if (ShAmt >= DestBitWidth) // All zeros.
7327 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7329 // Okay, we can shrink this. Truncate the input, then return a new
7331 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7332 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7334 return BinaryOperator::CreateLShr(V1, V2);
7336 } else { // This is a variable shr.
7338 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7339 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7340 // loop-invariant and CSE'd.
7341 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7342 Value *One = ConstantInt::get(SrcI->getType(), 1);
7344 Value *V = InsertNewInstBefore(
7345 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7347 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7348 SrcI->getOperand(0),
7350 Value *Zero = Constant::getNullValue(V->getType());
7351 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7361 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7362 /// in order to eliminate the icmp.
7363 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7365 // If we are just checking for a icmp eq of a single bit and zext'ing it
7366 // to an integer, then shift the bit to the appropriate place and then
7367 // cast to integer to avoid the comparison.
7368 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7369 const APInt &Op1CV = Op1C->getValue();
7371 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7372 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7373 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7374 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7375 if (!DoXform) return ICI;
7377 Value *In = ICI->getOperand(0);
7378 Value *Sh = ConstantInt::get(In->getType(),
7379 In->getType()->getPrimitiveSizeInBits()-1);
7380 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7381 In->getName()+".lobit"),
7383 if (In->getType() != CI.getType())
7384 In = CastInst::CreateIntegerCast(In, CI.getType(),
7385 false/*ZExt*/, "tmp", &CI);
7387 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7388 Constant *One = ConstantInt::get(In->getType(), 1);
7389 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7390 In->getName()+".not"),
7394 return ReplaceInstUsesWith(CI, In);
7399 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7400 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7401 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7402 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7403 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7404 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7405 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7406 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7407 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7408 // This only works for EQ and NE
7409 ICI->isEquality()) {
7410 // If Op1C some other power of two, convert:
7411 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7412 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7413 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7414 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7416 APInt KnownZeroMask(~KnownZero);
7417 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7418 if (!DoXform) return ICI;
7420 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7421 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7422 // (X&4) == 2 --> false
7423 // (X&4) != 2 --> true
7424 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7425 Res = ConstantExpr::getZExt(Res, CI.getType());
7426 return ReplaceInstUsesWith(CI, Res);
7429 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7430 Value *In = ICI->getOperand(0);
7432 // Perform a logical shr by shiftamt.
7433 // Insert the shift to put the result in the low bit.
7434 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7435 ConstantInt::get(In->getType(), ShiftAmt),
7436 In->getName()+".lobit"), CI);
7439 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7440 Constant *One = ConstantInt::get(In->getType(), 1);
7441 In = BinaryOperator::CreateXor(In, One, "tmp");
7442 InsertNewInstBefore(cast<Instruction>(In), CI);
7445 if (CI.getType() == In->getType())
7446 return ReplaceInstUsesWith(CI, In);
7448 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7456 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7457 // If one of the common conversion will work ..
7458 if (Instruction *Result = commonIntCastTransforms(CI))
7461 Value *Src = CI.getOperand(0);
7463 // If this is a cast of a cast
7464 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7465 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7466 // types and if the sizes are just right we can convert this into a logical
7467 // 'and' which will be much cheaper than the pair of casts.
7468 if (isa<TruncInst>(CSrc)) {
7469 // Get the sizes of the types involved
7470 Value *A = CSrc->getOperand(0);
7471 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7472 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7473 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7474 // If we're actually extending zero bits and the trunc is a no-op
7475 if (MidSize < DstSize && SrcSize == DstSize) {
7476 // Replace both of the casts with an And of the type mask.
7477 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7478 Constant *AndConst = ConstantInt::get(AndValue);
7480 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7481 // Unfortunately, if the type changed, we need to cast it back.
7482 if (And->getType() != CI.getType()) {
7483 And->setName(CSrc->getName()+".mask");
7484 InsertNewInstBefore(And, CI);
7485 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7492 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7493 return transformZExtICmp(ICI, CI);
7495 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7496 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7497 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7498 // of the (zext icmp) will be transformed.
7499 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7500 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7501 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7502 (transformZExtICmp(LHS, CI, false) ||
7503 transformZExtICmp(RHS, CI, false))) {
7504 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7505 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7506 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7513 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7514 if (Instruction *I = commonIntCastTransforms(CI))
7517 Value *Src = CI.getOperand(0);
7519 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7520 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7521 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7522 // If we are just checking for a icmp eq of a single bit and zext'ing it
7523 // to an integer, then shift the bit to the appropriate place and then
7524 // cast to integer to avoid the comparison.
7525 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7526 const APInt &Op1CV = Op1C->getValue();
7528 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7529 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7530 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7531 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7532 Value *In = ICI->getOperand(0);
7533 Value *Sh = ConstantInt::get(In->getType(),
7534 In->getType()->getPrimitiveSizeInBits()-1);
7535 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7536 In->getName()+".lobit"),
7538 if (In->getType() != CI.getType())
7539 In = CastInst::CreateIntegerCast(In, CI.getType(),
7540 true/*SExt*/, "tmp", &CI);
7542 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7543 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7544 In->getName()+".not"), CI);
7546 return ReplaceInstUsesWith(CI, In);
7551 // See if the value being truncated is already sign extended. If so, just
7552 // eliminate the trunc/sext pair.
7553 if (getOpcode(Src) == Instruction::Trunc) {
7554 Value *Op = cast<User>(Src)->getOperand(0);
7555 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7556 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7557 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7558 unsigned NumSignBits = ComputeNumSignBits(Op);
7560 if (OpBits == DestBits) {
7561 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7562 // bits, it is already ready.
7563 if (NumSignBits > DestBits-MidBits)
7564 return ReplaceInstUsesWith(CI, Op);
7565 } else if (OpBits < DestBits) {
7566 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7567 // bits, just sext from i32.
7568 if (NumSignBits > OpBits-MidBits)
7569 return new SExtInst(Op, CI.getType(), "tmp");
7571 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7572 // bits, just truncate to i32.
7573 if (NumSignBits > OpBits-MidBits)
7574 return new TruncInst(Op, CI.getType(), "tmp");
7581 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7582 /// in the specified FP type without changing its value.
7583 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7584 APFloat F = CFP->getValueAPF();
7585 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7586 return ConstantFP::get(F);
7590 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7591 /// through it until we get the source value.
7592 static Value *LookThroughFPExtensions(Value *V) {
7593 if (Instruction *I = dyn_cast<Instruction>(V))
7594 if (I->getOpcode() == Instruction::FPExt)
7595 return LookThroughFPExtensions(I->getOperand(0));
7597 // If this value is a constant, return the constant in the smallest FP type
7598 // that can accurately represent it. This allows us to turn
7599 // (float)((double)X+2.0) into x+2.0f.
7600 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7601 if (CFP->getType() == Type::PPC_FP128Ty)
7602 return V; // No constant folding of this.
7603 // See if the value can be truncated to float and then reextended.
7604 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7606 if (CFP->getType() == Type::DoubleTy)
7607 return V; // Won't shrink.
7608 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7610 // Don't try to shrink to various long double types.
7616 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7617 if (Instruction *I = commonCastTransforms(CI))
7620 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7621 // smaller than the destination type, we can eliminate the truncate by doing
7622 // the add as the smaller type. This applies to add/sub/mul/div as well as
7623 // many builtins (sqrt, etc).
7624 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7625 if (OpI && OpI->hasOneUse()) {
7626 switch (OpI->getOpcode()) {
7628 case Instruction::Add:
7629 case Instruction::Sub:
7630 case Instruction::Mul:
7631 case Instruction::FDiv:
7632 case Instruction::FRem:
7633 const Type *SrcTy = OpI->getType();
7634 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7635 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7636 if (LHSTrunc->getType() != SrcTy &&
7637 RHSTrunc->getType() != SrcTy) {
7638 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7639 // If the source types were both smaller than the destination type of
7640 // the cast, do this xform.
7641 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7642 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7643 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7645 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7647 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7656 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7657 return commonCastTransforms(CI);
7660 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7661 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7662 // mantissa to accurately represent all values of X. For example, do not
7663 // do this with i64->float->i64.
7664 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7665 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7666 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7667 SrcI->getType()->getFPMantissaWidth())
7668 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7670 return commonCastTransforms(FI);
7673 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7674 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7675 // mantissa to accurately represent all values of X. For example, do not
7676 // do this with i64->float->i64.
7677 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7678 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7679 (int)FI.getType()->getPrimitiveSizeInBits() <=
7680 SrcI->getType()->getFPMantissaWidth())
7681 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7683 return commonCastTransforms(FI);
7686 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7687 return commonCastTransforms(CI);
7690 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7691 return commonCastTransforms(CI);
7694 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7695 return commonPointerCastTransforms(CI);
7698 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7699 if (Instruction *I = commonCastTransforms(CI))
7702 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7703 if (!DestPointee->isSized()) return 0;
7705 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7708 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7709 m_ConstantInt(Cst)))) {
7710 // If the source and destination operands have the same type, see if this
7711 // is a single-index GEP.
7712 if (X->getType() == CI.getType()) {
7713 // Get the size of the pointee type.
7714 uint64_t Size = TD->getABITypeSize(DestPointee);
7716 // Convert the constant to intptr type.
7717 APInt Offset = Cst->getValue();
7718 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7720 // If Offset is evenly divisible by Size, we can do this xform.
7721 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7722 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7723 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7726 // TODO: Could handle other cases, e.g. where add is indexing into field of
7728 } else if (CI.getOperand(0)->hasOneUse() &&
7729 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7730 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7731 // "inttoptr+GEP" instead of "add+intptr".
7733 // Get the size of the pointee type.
7734 uint64_t Size = TD->getABITypeSize(DestPointee);
7736 // Convert the constant to intptr type.
7737 APInt Offset = Cst->getValue();
7738 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7740 // If Offset is evenly divisible by Size, we can do this xform.
7741 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7742 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7744 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7746 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7752 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7753 // If the operands are integer typed then apply the integer transforms,
7754 // otherwise just apply the common ones.
7755 Value *Src = CI.getOperand(0);
7756 const Type *SrcTy = Src->getType();
7757 const Type *DestTy = CI.getType();
7759 if (SrcTy->isInteger() && DestTy->isInteger()) {
7760 if (Instruction *Result = commonIntCastTransforms(CI))
7762 } else if (isa<PointerType>(SrcTy)) {
7763 if (Instruction *I = commonPointerCastTransforms(CI))
7766 if (Instruction *Result = commonCastTransforms(CI))
7771 // Get rid of casts from one type to the same type. These are useless and can
7772 // be replaced by the operand.
7773 if (DestTy == Src->getType())
7774 return ReplaceInstUsesWith(CI, Src);
7776 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7777 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7778 const Type *DstElTy = DstPTy->getElementType();
7779 const Type *SrcElTy = SrcPTy->getElementType();
7781 // If the address spaces don't match, don't eliminate the bitcast, which is
7782 // required for changing types.
7783 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7786 // If we are casting a malloc or alloca to a pointer to a type of the same
7787 // size, rewrite the allocation instruction to allocate the "right" type.
7788 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7789 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7792 // If the source and destination are pointers, and this cast is equivalent
7793 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7794 // This can enhance SROA and other transforms that want type-safe pointers.
7795 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7796 unsigned NumZeros = 0;
7797 while (SrcElTy != DstElTy &&
7798 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7799 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7800 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7804 // If we found a path from the src to dest, create the getelementptr now.
7805 if (SrcElTy == DstElTy) {
7806 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7807 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7808 ((Instruction*) NULL));
7812 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7813 if (SVI->hasOneUse()) {
7814 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7815 // a bitconvert to a vector with the same # elts.
7816 if (isa<VectorType>(DestTy) &&
7817 cast<VectorType>(DestTy)->getNumElements() ==
7818 SVI->getType()->getNumElements()) {
7820 // If either of the operands is a cast from CI.getType(), then
7821 // evaluating the shuffle in the casted destination's type will allow
7822 // us to eliminate at least one cast.
7823 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7824 Tmp->getOperand(0)->getType() == DestTy) ||
7825 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7826 Tmp->getOperand(0)->getType() == DestTy)) {
7827 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7828 SVI->getOperand(0), DestTy, &CI);
7829 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7830 SVI->getOperand(1), DestTy, &CI);
7831 // Return a new shuffle vector. Use the same element ID's, as we
7832 // know the vector types match #elts.
7833 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7841 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7843 /// %D = select %cond, %C, %A
7845 /// %C = select %cond, %B, 0
7848 /// Assuming that the specified instruction is an operand to the select, return
7849 /// a bitmask indicating which operands of this instruction are foldable if they
7850 /// equal the other incoming value of the select.
7852 static unsigned GetSelectFoldableOperands(Instruction *I) {
7853 switch (I->getOpcode()) {
7854 case Instruction::Add:
7855 case Instruction::Mul:
7856 case Instruction::And:
7857 case Instruction::Or:
7858 case Instruction::Xor:
7859 return 3; // Can fold through either operand.
7860 case Instruction::Sub: // Can only fold on the amount subtracted.
7861 case Instruction::Shl: // Can only fold on the shift amount.
7862 case Instruction::LShr:
7863 case Instruction::AShr:
7866 return 0; // Cannot fold
7870 /// GetSelectFoldableConstant - For the same transformation as the previous
7871 /// function, return the identity constant that goes into the select.
7872 static Constant *GetSelectFoldableConstant(Instruction *I) {
7873 switch (I->getOpcode()) {
7874 default: assert(0 && "This cannot happen!"); abort();
7875 case Instruction::Add:
7876 case Instruction::Sub:
7877 case Instruction::Or:
7878 case Instruction::Xor:
7879 case Instruction::Shl:
7880 case Instruction::LShr:
7881 case Instruction::AShr:
7882 return Constant::getNullValue(I->getType());
7883 case Instruction::And:
7884 return Constant::getAllOnesValue(I->getType());
7885 case Instruction::Mul:
7886 return ConstantInt::get(I->getType(), 1);
7890 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7891 /// have the same opcode and only one use each. Try to simplify this.
7892 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7894 if (TI->getNumOperands() == 1) {
7895 // If this is a non-volatile load or a cast from the same type,
7898 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7901 return 0; // unknown unary op.
7904 // Fold this by inserting a select from the input values.
7905 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7906 FI->getOperand(0), SI.getName()+".v");
7907 InsertNewInstBefore(NewSI, SI);
7908 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
7912 // Only handle binary operators here.
7913 if (!isa<BinaryOperator>(TI))
7916 // Figure out if the operations have any operands in common.
7917 Value *MatchOp, *OtherOpT, *OtherOpF;
7919 if (TI->getOperand(0) == FI->getOperand(0)) {
7920 MatchOp = TI->getOperand(0);
7921 OtherOpT = TI->getOperand(1);
7922 OtherOpF = FI->getOperand(1);
7923 MatchIsOpZero = true;
7924 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7925 MatchOp = TI->getOperand(1);
7926 OtherOpT = TI->getOperand(0);
7927 OtherOpF = FI->getOperand(0);
7928 MatchIsOpZero = false;
7929 } else if (!TI->isCommutative()) {
7931 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7932 MatchOp = TI->getOperand(0);
7933 OtherOpT = TI->getOperand(1);
7934 OtherOpF = FI->getOperand(0);
7935 MatchIsOpZero = true;
7936 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7937 MatchOp = TI->getOperand(1);
7938 OtherOpT = TI->getOperand(0);
7939 OtherOpF = FI->getOperand(1);
7940 MatchIsOpZero = true;
7945 // If we reach here, they do have operations in common.
7946 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7947 OtherOpF, SI.getName()+".v");
7948 InsertNewInstBefore(NewSI, SI);
7950 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7952 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
7954 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
7956 assert(0 && "Shouldn't get here");
7960 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7961 Value *CondVal = SI.getCondition();
7962 Value *TrueVal = SI.getTrueValue();
7963 Value *FalseVal = SI.getFalseValue();
7965 // select true, X, Y -> X
7966 // select false, X, Y -> Y
7967 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7968 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7970 // select C, X, X -> X
7971 if (TrueVal == FalseVal)
7972 return ReplaceInstUsesWith(SI, TrueVal);
7974 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7975 return ReplaceInstUsesWith(SI, FalseVal);
7976 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7977 return ReplaceInstUsesWith(SI, TrueVal);
7978 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7979 if (isa<Constant>(TrueVal))
7980 return ReplaceInstUsesWith(SI, TrueVal);
7982 return ReplaceInstUsesWith(SI, FalseVal);
7985 if (SI.getType() == Type::Int1Ty) {
7986 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7987 if (C->getZExtValue()) {
7988 // Change: A = select B, true, C --> A = or B, C
7989 return BinaryOperator::CreateOr(CondVal, FalseVal);
7991 // Change: A = select B, false, C --> A = and !B, C
7993 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
7994 "not."+CondVal->getName()), SI);
7995 return BinaryOperator::CreateAnd(NotCond, FalseVal);
7997 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7998 if (C->getZExtValue() == false) {
7999 // Change: A = select B, C, false --> A = and B, C
8000 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8002 // Change: A = select B, C, true --> A = or !B, C
8004 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8005 "not."+CondVal->getName()), SI);
8006 return BinaryOperator::CreateOr(NotCond, TrueVal);
8010 // select a, b, a -> a&b
8011 // select a, a, b -> a|b
8012 if (CondVal == TrueVal)
8013 return BinaryOperator::CreateOr(CondVal, FalseVal);
8014 else if (CondVal == FalseVal)
8015 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8018 // Selecting between two integer constants?
8019 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8020 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8021 // select C, 1, 0 -> zext C to int
8022 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8023 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8024 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8025 // select C, 0, 1 -> zext !C to int
8027 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8028 "not."+CondVal->getName()), SI);
8029 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8032 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8034 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8036 // (x <s 0) ? -1 : 0 -> ashr x, 31
8037 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8038 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8039 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8040 // The comparison constant and the result are not neccessarily the
8041 // same width. Make an all-ones value by inserting a AShr.
8042 Value *X = IC->getOperand(0);
8043 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8044 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8045 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8047 InsertNewInstBefore(SRA, SI);
8049 // Finally, convert to the type of the select RHS. We figure out
8050 // if this requires a SExt, Trunc or BitCast based on the sizes.
8051 Instruction::CastOps opc = Instruction::BitCast;
8052 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8053 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8054 if (SRASize < SISize)
8055 opc = Instruction::SExt;
8056 else if (SRASize > SISize)
8057 opc = Instruction::Trunc;
8058 return CastInst::Create(opc, SRA, SI.getType());
8063 // If one of the constants is zero (we know they can't both be) and we
8064 // have an icmp instruction with zero, and we have an 'and' with the
8065 // non-constant value, eliminate this whole mess. This corresponds to
8066 // cases like this: ((X & 27) ? 27 : 0)
8067 if (TrueValC->isZero() || FalseValC->isZero())
8068 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8069 cast<Constant>(IC->getOperand(1))->isNullValue())
8070 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8071 if (ICA->getOpcode() == Instruction::And &&
8072 isa<ConstantInt>(ICA->getOperand(1)) &&
8073 (ICA->getOperand(1) == TrueValC ||
8074 ICA->getOperand(1) == FalseValC) &&
8075 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8076 // Okay, now we know that everything is set up, we just don't
8077 // know whether we have a icmp_ne or icmp_eq and whether the
8078 // true or false val is the zero.
8079 bool ShouldNotVal = !TrueValC->isZero();
8080 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8083 V = InsertNewInstBefore(BinaryOperator::Create(
8084 Instruction::Xor, V, ICA->getOperand(1)), SI);
8085 return ReplaceInstUsesWith(SI, V);
8090 // See if we are selecting two values based on a comparison of the two values.
8091 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8092 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8093 // Transform (X == Y) ? X : Y -> Y
8094 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8095 // This is not safe in general for floating point:
8096 // consider X== -0, Y== +0.
8097 // It becomes safe if either operand is a nonzero constant.
8098 ConstantFP *CFPt, *CFPf;
8099 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8100 !CFPt->getValueAPF().isZero()) ||
8101 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8102 !CFPf->getValueAPF().isZero()))
8103 return ReplaceInstUsesWith(SI, FalseVal);
8105 // Transform (X != Y) ? X : Y -> X
8106 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8107 return ReplaceInstUsesWith(SI, TrueVal);
8108 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8110 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8111 // Transform (X == Y) ? Y : X -> X
8112 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8113 // This is not safe in general for floating point:
8114 // consider X== -0, Y== +0.
8115 // It becomes safe if either operand is a nonzero constant.
8116 ConstantFP *CFPt, *CFPf;
8117 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8118 !CFPt->getValueAPF().isZero()) ||
8119 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8120 !CFPf->getValueAPF().isZero()))
8121 return ReplaceInstUsesWith(SI, FalseVal);
8123 // Transform (X != Y) ? Y : X -> Y
8124 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8125 return ReplaceInstUsesWith(SI, TrueVal);
8126 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8130 // See if we are selecting two values based on a comparison of the two values.
8131 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8132 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8133 // Transform (X == Y) ? X : Y -> Y
8134 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8135 return ReplaceInstUsesWith(SI, FalseVal);
8136 // Transform (X != Y) ? X : Y -> X
8137 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8138 return ReplaceInstUsesWith(SI, TrueVal);
8139 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8141 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8142 // Transform (X == Y) ? Y : X -> X
8143 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8144 return ReplaceInstUsesWith(SI, FalseVal);
8145 // Transform (X != Y) ? Y : X -> Y
8146 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8147 return ReplaceInstUsesWith(SI, TrueVal);
8148 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8152 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8153 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8154 if (TI->hasOneUse() && FI->hasOneUse()) {
8155 Instruction *AddOp = 0, *SubOp = 0;
8157 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8158 if (TI->getOpcode() == FI->getOpcode())
8159 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8162 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8163 // even legal for FP.
8164 if (TI->getOpcode() == Instruction::Sub &&
8165 FI->getOpcode() == Instruction::Add) {
8166 AddOp = FI; SubOp = TI;
8167 } else if (FI->getOpcode() == Instruction::Sub &&
8168 TI->getOpcode() == Instruction::Add) {
8169 AddOp = TI; SubOp = FI;
8173 Value *OtherAddOp = 0;
8174 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8175 OtherAddOp = AddOp->getOperand(1);
8176 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8177 OtherAddOp = AddOp->getOperand(0);
8181 // So at this point we know we have (Y -> OtherAddOp):
8182 // select C, (add X, Y), (sub X, Z)
8183 Value *NegVal; // Compute -Z
8184 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8185 NegVal = ConstantExpr::getNeg(C);
8187 NegVal = InsertNewInstBefore(
8188 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8191 Value *NewTrueOp = OtherAddOp;
8192 Value *NewFalseOp = NegVal;
8194 std::swap(NewTrueOp, NewFalseOp);
8195 Instruction *NewSel =
8196 SelectInst::Create(CondVal, NewTrueOp,
8197 NewFalseOp, SI.getName() + ".p");
8199 NewSel = InsertNewInstBefore(NewSel, SI);
8200 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8205 // See if we can fold the select into one of our operands.
8206 if (SI.getType()->isInteger()) {
8207 // See the comment above GetSelectFoldableOperands for a description of the
8208 // transformation we are doing here.
8209 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8210 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8211 !isa<Constant>(FalseVal))
8212 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8213 unsigned OpToFold = 0;
8214 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8216 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8221 Constant *C = GetSelectFoldableConstant(TVI);
8222 Instruction *NewSel =
8223 SelectInst::Create(SI.getCondition(),
8224 TVI->getOperand(2-OpToFold), C);
8225 InsertNewInstBefore(NewSel, SI);
8226 NewSel->takeName(TVI);
8227 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8228 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8230 assert(0 && "Unknown instruction!!");
8235 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8236 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8237 !isa<Constant>(TrueVal))
8238 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8239 unsigned OpToFold = 0;
8240 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8242 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8247 Constant *C = GetSelectFoldableConstant(FVI);
8248 Instruction *NewSel =
8249 SelectInst::Create(SI.getCondition(), C,
8250 FVI->getOperand(2-OpToFold));
8251 InsertNewInstBefore(NewSel, SI);
8252 NewSel->takeName(FVI);
8253 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8254 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8256 assert(0 && "Unknown instruction!!");
8261 if (BinaryOperator::isNot(CondVal)) {
8262 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8263 SI.setOperand(1, FalseVal);
8264 SI.setOperand(2, TrueVal);
8271 /// EnforceKnownAlignment - If the specified pointer points to an object that
8272 /// we control, modify the object's alignment to PrefAlign. This isn't
8273 /// often possible though. If alignment is important, a more reliable approach
8274 /// is to simply align all global variables and allocation instructions to
8275 /// their preferred alignment from the beginning.
8277 static unsigned EnforceKnownAlignment(Value *V,
8278 unsigned Align, unsigned PrefAlign) {
8280 User *U = dyn_cast<User>(V);
8281 if (!U) return Align;
8283 switch (getOpcode(U)) {
8285 case Instruction::BitCast:
8286 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8287 case Instruction::GetElementPtr: {
8288 // If all indexes are zero, it is just the alignment of the base pointer.
8289 bool AllZeroOperands = true;
8290 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8291 if (!isa<Constant>(*i) ||
8292 !cast<Constant>(*i)->isNullValue()) {
8293 AllZeroOperands = false;
8297 if (AllZeroOperands) {
8298 // Treat this like a bitcast.
8299 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8305 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8306 // If there is a large requested alignment and we can, bump up the alignment
8308 if (!GV->isDeclaration()) {
8309 GV->setAlignment(PrefAlign);
8312 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8313 // If there is a requested alignment and if this is an alloca, round up. We
8314 // don't do this for malloc, because some systems can't respect the request.
8315 if (isa<AllocaInst>(AI)) {
8316 AI->setAlignment(PrefAlign);
8324 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8325 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8326 /// and it is more than the alignment of the ultimate object, see if we can
8327 /// increase the alignment of the ultimate object, making this check succeed.
8328 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8329 unsigned PrefAlign) {
8330 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8331 sizeof(PrefAlign) * CHAR_BIT;
8332 APInt Mask = APInt::getAllOnesValue(BitWidth);
8333 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8334 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8335 unsigned TrailZ = KnownZero.countTrailingOnes();
8336 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8338 if (PrefAlign > Align)
8339 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8341 // We don't need to make any adjustment.
8345 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8346 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8347 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8348 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8349 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8351 if (CopyAlign < MinAlign) {
8352 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8356 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8358 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8359 if (MemOpLength == 0) return 0;
8361 // Source and destination pointer types are always "i8*" for intrinsic. See
8362 // if the size is something we can handle with a single primitive load/store.
8363 // A single load+store correctly handles overlapping memory in the memmove
8365 unsigned Size = MemOpLength->getZExtValue();
8366 if (Size == 0) return MI; // Delete this mem transfer.
8368 if (Size > 8 || (Size&(Size-1)))
8369 return 0; // If not 1/2/4/8 bytes, exit.
8371 // Use an integer load+store unless we can find something better.
8372 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8374 // Memcpy forces the use of i8* for the source and destination. That means
8375 // that if you're using memcpy to move one double around, you'll get a cast
8376 // from double* to i8*. We'd much rather use a double load+store rather than
8377 // an i64 load+store, here because this improves the odds that the source or
8378 // dest address will be promotable. See if we can find a better type than the
8379 // integer datatype.
8380 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8381 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8382 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8383 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8384 // down through these levels if so.
8385 while (!SrcETy->isSingleValueType()) {
8386 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8387 if (STy->getNumElements() == 1)
8388 SrcETy = STy->getElementType(0);
8391 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8392 if (ATy->getNumElements() == 1)
8393 SrcETy = ATy->getElementType();
8400 if (SrcETy->isSingleValueType())
8401 NewPtrTy = PointerType::getUnqual(SrcETy);
8406 // If the memcpy/memmove provides better alignment info than we can
8408 SrcAlign = std::max(SrcAlign, CopyAlign);
8409 DstAlign = std::max(DstAlign, CopyAlign);
8411 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8412 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8413 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8414 InsertNewInstBefore(L, *MI);
8415 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8417 // Set the size of the copy to 0, it will be deleted on the next iteration.
8418 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8422 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8423 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8424 if (MI->getAlignment()->getZExtValue() < Alignment) {
8425 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8429 // Extract the length and alignment and fill if they are constant.
8430 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8431 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8432 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8434 uint64_t Len = LenC->getZExtValue();
8435 Alignment = MI->getAlignment()->getZExtValue();
8437 // If the length is zero, this is a no-op
8438 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8440 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8441 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8442 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8444 Value *Dest = MI->getDest();
8445 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8447 // Alignment 0 is identity for alignment 1 for memset, but not store.
8448 if (Alignment == 0) Alignment = 1;
8450 // Extract the fill value and store.
8451 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8452 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8455 // Set the size of the copy to 0, it will be deleted on the next iteration.
8456 MI->setLength(Constant::getNullValue(LenC->getType()));
8464 /// visitCallInst - CallInst simplification. This mostly only handles folding
8465 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8466 /// the heavy lifting.
8468 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8469 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8470 if (!II) return visitCallSite(&CI);
8472 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8474 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8475 bool Changed = false;
8477 // memmove/cpy/set of zero bytes is a noop.
8478 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8479 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8481 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8482 if (CI->getZExtValue() == 1) {
8483 // Replace the instruction with just byte operations. We would
8484 // transform other cases to loads/stores, but we don't know if
8485 // alignment is sufficient.
8489 // If we have a memmove and the source operation is a constant global,
8490 // then the source and dest pointers can't alias, so we can change this
8491 // into a call to memcpy.
8492 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8493 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8494 if (GVSrc->isConstant()) {
8495 Module *M = CI.getParent()->getParent()->getParent();
8496 Intrinsic::ID MemCpyID;
8497 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8498 MemCpyID = Intrinsic::memcpy_i32;
8500 MemCpyID = Intrinsic::memcpy_i64;
8501 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8505 // memmove(x,x,size) -> noop.
8506 if (MMI->getSource() == MMI->getDest())
8507 return EraseInstFromFunction(CI);
8510 // If we can determine a pointer alignment that is bigger than currently
8511 // set, update the alignment.
8512 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8513 if (Instruction *I = SimplifyMemTransfer(MI))
8515 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8516 if (Instruction *I = SimplifyMemSet(MSI))
8520 if (Changed) return II;
8522 switch (II->getIntrinsicID()) {
8524 case Intrinsic::ppc_altivec_lvx:
8525 case Intrinsic::ppc_altivec_lvxl:
8526 case Intrinsic::x86_sse_loadu_ps:
8527 case Intrinsic::x86_sse2_loadu_pd:
8528 case Intrinsic::x86_sse2_loadu_dq:
8529 // Turn PPC lvx -> load if the pointer is known aligned.
8530 // Turn X86 loadups -> load if the pointer is known aligned.
8531 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8532 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8533 PointerType::getUnqual(II->getType()),
8535 return new LoadInst(Ptr);
8538 case Intrinsic::ppc_altivec_stvx:
8539 case Intrinsic::ppc_altivec_stvxl:
8540 // Turn stvx -> store if the pointer is known aligned.
8541 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8542 const Type *OpPtrTy =
8543 PointerType::getUnqual(II->getOperand(1)->getType());
8544 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8545 return new StoreInst(II->getOperand(1), Ptr);
8548 case Intrinsic::x86_sse_storeu_ps:
8549 case Intrinsic::x86_sse2_storeu_pd:
8550 case Intrinsic::x86_sse2_storeu_dq:
8551 case Intrinsic::x86_sse2_storel_dq:
8552 // Turn X86 storeu -> store if the pointer is known aligned.
8553 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8554 const Type *OpPtrTy =
8555 PointerType::getUnqual(II->getOperand(2)->getType());
8556 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8557 return new StoreInst(II->getOperand(2), Ptr);
8561 case Intrinsic::x86_sse_cvttss2si: {
8562 // These intrinsics only demands the 0th element of its input vector. If
8563 // we can simplify the input based on that, do so now.
8565 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8567 II->setOperand(1, V);
8573 case Intrinsic::ppc_altivec_vperm:
8574 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8575 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8576 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8578 // Check that all of the elements are integer constants or undefs.
8579 bool AllEltsOk = true;
8580 for (unsigned i = 0; i != 16; ++i) {
8581 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8582 !isa<UndefValue>(Mask->getOperand(i))) {
8589 // Cast the input vectors to byte vectors.
8590 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8591 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8592 Value *Result = UndefValue::get(Op0->getType());
8594 // Only extract each element once.
8595 Value *ExtractedElts[32];
8596 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8598 for (unsigned i = 0; i != 16; ++i) {
8599 if (isa<UndefValue>(Mask->getOperand(i)))
8601 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8602 Idx &= 31; // Match the hardware behavior.
8604 if (ExtractedElts[Idx] == 0) {
8606 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8607 InsertNewInstBefore(Elt, CI);
8608 ExtractedElts[Idx] = Elt;
8611 // Insert this value into the result vector.
8612 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8614 InsertNewInstBefore(cast<Instruction>(Result), CI);
8616 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8621 case Intrinsic::stackrestore: {
8622 // If the save is right next to the restore, remove the restore. This can
8623 // happen when variable allocas are DCE'd.
8624 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8625 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8626 BasicBlock::iterator BI = SS;
8628 return EraseInstFromFunction(CI);
8632 // Scan down this block to see if there is another stack restore in the
8633 // same block without an intervening call/alloca.
8634 BasicBlock::iterator BI = II;
8635 TerminatorInst *TI = II->getParent()->getTerminator();
8636 bool CannotRemove = false;
8637 for (++BI; &*BI != TI; ++BI) {
8638 if (isa<AllocaInst>(BI)) {
8639 CannotRemove = true;
8642 if (isa<CallInst>(BI)) {
8643 if (!isa<IntrinsicInst>(BI)) {
8644 CannotRemove = true;
8647 // If there is a stackrestore below this one, remove this one.
8648 return EraseInstFromFunction(CI);
8652 // If the stack restore is in a return/unwind block and if there are no
8653 // allocas or calls between the restore and the return, nuke the restore.
8654 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8655 return EraseInstFromFunction(CI);
8661 return visitCallSite(II);
8664 // InvokeInst simplification
8666 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8667 return visitCallSite(&II);
8670 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
8671 /// passed through the varargs area, we can eliminate the use of the cast.
8672 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8673 const CastInst * const CI,
8674 const TargetData * const TD,
8676 if (!CI->isLosslessCast())
8679 // The size of ByVal arguments is derived from the type, so we
8680 // can't change to a type with a different size. If the size were
8681 // passed explicitly we could avoid this check.
8682 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8686 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8687 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8688 if (!SrcTy->isSized() || !DstTy->isSized())
8690 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8695 // visitCallSite - Improvements for call and invoke instructions.
8697 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8698 bool Changed = false;
8700 // If the callee is a constexpr cast of a function, attempt to move the cast
8701 // to the arguments of the call/invoke.
8702 if (transformConstExprCastCall(CS)) return 0;
8704 Value *Callee = CS.getCalledValue();
8706 if (Function *CalleeF = dyn_cast<Function>(Callee))
8707 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8708 Instruction *OldCall = CS.getInstruction();
8709 // If the call and callee calling conventions don't match, this call must
8710 // be unreachable, as the call is undefined.
8711 new StoreInst(ConstantInt::getTrue(),
8712 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8714 if (!OldCall->use_empty())
8715 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8716 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8717 return EraseInstFromFunction(*OldCall);
8721 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8722 // This instruction is not reachable, just remove it. We insert a store to
8723 // undef so that we know that this code is not reachable, despite the fact
8724 // that we can't modify the CFG here.
8725 new StoreInst(ConstantInt::getTrue(),
8726 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8727 CS.getInstruction());
8729 if (!CS.getInstruction()->use_empty())
8730 CS.getInstruction()->
8731 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8733 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8734 // Don't break the CFG, insert a dummy cond branch.
8735 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8736 ConstantInt::getTrue(), II);
8738 return EraseInstFromFunction(*CS.getInstruction());
8741 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8742 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8743 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8744 return transformCallThroughTrampoline(CS);
8746 const PointerType *PTy = cast<PointerType>(Callee->getType());
8747 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8748 if (FTy->isVarArg()) {
8749 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8750 // See if we can optimize any arguments passed through the varargs area of
8752 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8753 E = CS.arg_end(); I != E; ++I, ++ix) {
8754 CastInst *CI = dyn_cast<CastInst>(*I);
8755 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8756 *I = CI->getOperand(0);
8762 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8763 // Inline asm calls cannot throw - mark them 'nounwind'.
8764 CS.setDoesNotThrow();
8768 return Changed ? CS.getInstruction() : 0;
8771 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8772 // attempt to move the cast to the arguments of the call/invoke.
8774 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8775 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8776 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8777 if (CE->getOpcode() != Instruction::BitCast ||
8778 !isa<Function>(CE->getOperand(0)))
8780 Function *Callee = cast<Function>(CE->getOperand(0));
8781 Instruction *Caller = CS.getInstruction();
8782 const PAListPtr &CallerPAL = CS.getParamAttrs();
8784 // Okay, this is a cast from a function to a different type. Unless doing so
8785 // would cause a type conversion of one of our arguments, change this call to
8786 // be a direct call with arguments casted to the appropriate types.
8788 const FunctionType *FT = Callee->getFunctionType();
8789 const Type *OldRetTy = Caller->getType();
8790 const Type *NewRetTy = FT->getReturnType();
8792 if (isa<StructType>(NewRetTy))
8793 return false; // TODO: Handle multiple return values.
8795 // Check to see if we are changing the return type...
8796 if (OldRetTy != NewRetTy) {
8797 if (Callee->isDeclaration() &&
8798 // Conversion is ok if changing from one pointer type to another or from
8799 // a pointer to an integer of the same size.
8800 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8801 isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))
8802 return false; // Cannot transform this return value.
8804 if (!Caller->use_empty() &&
8805 // void -> non-void is handled specially
8806 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8807 return false; // Cannot transform this return value.
8809 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8810 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8811 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8812 return false; // Attribute not compatible with transformed value.
8815 // If the callsite is an invoke instruction, and the return value is used by
8816 // a PHI node in a successor, we cannot change the return type of the call
8817 // because there is no place to put the cast instruction (without breaking
8818 // the critical edge). Bail out in this case.
8819 if (!Caller->use_empty())
8820 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8821 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8823 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8824 if (PN->getParent() == II->getNormalDest() ||
8825 PN->getParent() == II->getUnwindDest())
8829 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8830 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8832 CallSite::arg_iterator AI = CS.arg_begin();
8833 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8834 const Type *ParamTy = FT->getParamType(i);
8835 const Type *ActTy = (*AI)->getType();
8837 if (!CastInst::isCastable(ActTy, ParamTy))
8838 return false; // Cannot transform this parameter value.
8840 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8841 return false; // Attribute not compatible with transformed value.
8843 // Converting from one pointer type to another or between a pointer and an
8844 // integer of the same size is safe even if we do not have a body.
8845 bool isConvertible = ActTy == ParamTy ||
8846 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8847 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8848 if (Callee->isDeclaration() && !isConvertible) return false;
8851 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8852 Callee->isDeclaration())
8853 return false; // Do not delete arguments unless we have a function body.
8855 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8856 !CallerPAL.isEmpty())
8857 // In this case we have more arguments than the new function type, but we
8858 // won't be dropping them. Check that these extra arguments have attributes
8859 // that are compatible with being a vararg call argument.
8860 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8861 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8863 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8864 if (PAttrs & ParamAttr::VarArgsIncompatible)
8868 // Okay, we decided that this is a safe thing to do: go ahead and start
8869 // inserting cast instructions as necessary...
8870 std::vector<Value*> Args;
8871 Args.reserve(NumActualArgs);
8872 SmallVector<ParamAttrsWithIndex, 8> attrVec;
8873 attrVec.reserve(NumCommonArgs);
8875 // Get any return attributes.
8876 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8878 // If the return value is not being used, the type may not be compatible
8879 // with the existing attributes. Wipe out any problematic attributes.
8880 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
8882 // Add the new return attributes.
8884 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8886 AI = CS.arg_begin();
8887 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8888 const Type *ParamTy = FT->getParamType(i);
8889 if ((*AI)->getType() == ParamTy) {
8890 Args.push_back(*AI);
8892 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8893 false, ParamTy, false);
8894 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
8895 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8898 // Add any parameter attributes.
8899 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8900 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8903 // If the function takes more arguments than the call was taking, add them
8905 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8906 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8908 // If we are removing arguments to the function, emit an obnoxious warning...
8909 if (FT->getNumParams() < NumActualArgs) {
8910 if (!FT->isVarArg()) {
8911 cerr << "WARNING: While resolving call to function '"
8912 << Callee->getName() << "' arguments were dropped!\n";
8914 // Add all of the arguments in their promoted form to the arg list...
8915 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8916 const Type *PTy = getPromotedType((*AI)->getType());
8917 if (PTy != (*AI)->getType()) {
8918 // Must promote to pass through va_arg area!
8919 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8921 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
8922 InsertNewInstBefore(Cast, *Caller);
8923 Args.push_back(Cast);
8925 Args.push_back(*AI);
8928 // Add any parameter attributes.
8929 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8930 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8935 if (NewRetTy == Type::VoidTy)
8936 Caller->setName(""); // Void type should not have a name.
8938 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
8941 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8942 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
8943 Args.begin(), Args.end(),
8944 Caller->getName(), Caller);
8945 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8946 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
8948 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8949 Caller->getName(), Caller);
8950 CallInst *CI = cast<CallInst>(Caller);
8951 if (CI->isTailCall())
8952 cast<CallInst>(NC)->setTailCall();
8953 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8954 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
8957 // Insert a cast of the return type as necessary.
8959 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
8960 if (NV->getType() != Type::VoidTy) {
8961 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
8963 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
8965 // If this is an invoke instruction, we should insert it after the first
8966 // non-phi, instruction in the normal successor block.
8967 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8968 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
8969 InsertNewInstBefore(NC, *I);
8971 // Otherwise, it's a call, just insert cast right after the call instr
8972 InsertNewInstBefore(NC, *Caller);
8974 AddUsersToWorkList(*Caller);
8976 NV = UndefValue::get(Caller->getType());
8980 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8981 Caller->replaceAllUsesWith(NV);
8982 Caller->eraseFromParent();
8983 RemoveFromWorkList(Caller);
8987 // transformCallThroughTrampoline - Turn a call to a function created by the
8988 // init_trampoline intrinsic into a direct call to the underlying function.
8990 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8991 Value *Callee = CS.getCalledValue();
8992 const PointerType *PTy = cast<PointerType>(Callee->getType());
8993 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8994 const PAListPtr &Attrs = CS.getParamAttrs();
8996 // If the call already has the 'nest' attribute somewhere then give up -
8997 // otherwise 'nest' would occur twice after splicing in the chain.
8998 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9001 IntrinsicInst *Tramp =
9002 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9004 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9005 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9006 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9008 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9009 if (!NestAttrs.isEmpty()) {
9010 unsigned NestIdx = 1;
9011 const Type *NestTy = 0;
9012 ParameterAttributes NestAttr = ParamAttr::None;
9014 // Look for a parameter marked with the 'nest' attribute.
9015 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9016 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9017 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9018 // Record the parameter type and any other attributes.
9020 NestAttr = NestAttrs.getParamAttrs(NestIdx);
9025 Instruction *Caller = CS.getInstruction();
9026 std::vector<Value*> NewArgs;
9027 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9029 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9030 NewAttrs.reserve(Attrs.getNumSlots() + 1);
9032 // Insert the nest argument into the call argument list, which may
9033 // mean appending it. Likewise for attributes.
9035 // Add any function result attributes.
9036 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9037 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9041 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9043 if (Idx == NestIdx) {
9044 // Add the chain argument and attributes.
9045 Value *NestVal = Tramp->getOperand(3);
9046 if (NestVal->getType() != NestTy)
9047 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9048 NewArgs.push_back(NestVal);
9049 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9055 // Add the original argument and attributes.
9056 NewArgs.push_back(*I);
9057 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9059 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9065 // The trampoline may have been bitcast to a bogus type (FTy).
9066 // Handle this by synthesizing a new function type, equal to FTy
9067 // with the chain parameter inserted.
9069 std::vector<const Type*> NewTypes;
9070 NewTypes.reserve(FTy->getNumParams()+1);
9072 // Insert the chain's type into the list of parameter types, which may
9073 // mean appending it.
9076 FunctionType::param_iterator I = FTy->param_begin(),
9077 E = FTy->param_end();
9081 // Add the chain's type.
9082 NewTypes.push_back(NestTy);
9087 // Add the original type.
9088 NewTypes.push_back(*I);
9094 // Replace the trampoline call with a direct call. Let the generic
9095 // code sort out any function type mismatches.
9096 FunctionType *NewFTy =
9097 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9098 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9099 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9100 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9102 Instruction *NewCaller;
9103 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9104 NewCaller = InvokeInst::Create(NewCallee,
9105 II->getNormalDest(), II->getUnwindDest(),
9106 NewArgs.begin(), NewArgs.end(),
9107 Caller->getName(), Caller);
9108 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9109 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9111 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9112 Caller->getName(), Caller);
9113 if (cast<CallInst>(Caller)->isTailCall())
9114 cast<CallInst>(NewCaller)->setTailCall();
9115 cast<CallInst>(NewCaller)->
9116 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9117 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9119 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9120 Caller->replaceAllUsesWith(NewCaller);
9121 Caller->eraseFromParent();
9122 RemoveFromWorkList(Caller);
9127 // Replace the trampoline call with a direct call. Since there is no 'nest'
9128 // parameter, there is no need to adjust the argument list. Let the generic
9129 // code sort out any function type mismatches.
9130 Constant *NewCallee =
9131 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9132 CS.setCalledFunction(NewCallee);
9133 return CS.getInstruction();
9136 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9137 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9138 /// and a single binop.
9139 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9140 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9141 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9142 isa<CmpInst>(FirstInst));
9143 unsigned Opc = FirstInst->getOpcode();
9144 Value *LHSVal = FirstInst->getOperand(0);
9145 Value *RHSVal = FirstInst->getOperand(1);
9147 const Type *LHSType = LHSVal->getType();
9148 const Type *RHSType = RHSVal->getType();
9150 // Scan to see if all operands are the same opcode, all have one use, and all
9151 // kill their operands (i.e. the operands have one use).
9152 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9153 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9154 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9155 // Verify type of the LHS matches so we don't fold cmp's of different
9156 // types or GEP's with different index types.
9157 I->getOperand(0)->getType() != LHSType ||
9158 I->getOperand(1)->getType() != RHSType)
9161 // If they are CmpInst instructions, check their predicates
9162 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9163 if (cast<CmpInst>(I)->getPredicate() !=
9164 cast<CmpInst>(FirstInst)->getPredicate())
9167 // Keep track of which operand needs a phi node.
9168 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9169 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9172 // Otherwise, this is safe to transform, determine if it is profitable.
9174 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9175 // Indexes are often folded into load/store instructions, so we don't want to
9176 // hide them behind a phi.
9177 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9180 Value *InLHS = FirstInst->getOperand(0);
9181 Value *InRHS = FirstInst->getOperand(1);
9182 PHINode *NewLHS = 0, *NewRHS = 0;
9184 NewLHS = PHINode::Create(LHSType,
9185 FirstInst->getOperand(0)->getName() + ".pn");
9186 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9187 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9188 InsertNewInstBefore(NewLHS, PN);
9193 NewRHS = PHINode::Create(RHSType,
9194 FirstInst->getOperand(1)->getName() + ".pn");
9195 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9196 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9197 InsertNewInstBefore(NewRHS, PN);
9201 // Add all operands to the new PHIs.
9202 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9204 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9205 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9208 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9209 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9213 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9214 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9215 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9216 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9219 assert(isa<GetElementPtrInst>(FirstInst));
9220 return GetElementPtrInst::Create(LHSVal, RHSVal);
9224 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9225 /// of the block that defines it. This means that it must be obvious the value
9226 /// of the load is not changed from the point of the load to the end of the
9229 /// Finally, it is safe, but not profitable, to sink a load targetting a
9230 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
9232 static bool isSafeToSinkLoad(LoadInst *L) {
9233 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9235 for (++BBI; BBI != E; ++BBI)
9236 if (BBI->mayWriteToMemory())
9239 // Check for non-address taken alloca. If not address-taken already, it isn't
9240 // profitable to do this xform.
9241 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9242 bool isAddressTaken = false;
9243 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9245 if (isa<LoadInst>(UI)) continue;
9246 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9247 // If storing TO the alloca, then the address isn't taken.
9248 if (SI->getOperand(1) == AI) continue;
9250 isAddressTaken = true;
9254 if (!isAddressTaken)
9262 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9263 // operator and they all are only used by the PHI, PHI together their
9264 // inputs, and do the operation once, to the result of the PHI.
9265 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9266 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9268 // Scan the instruction, looking for input operations that can be folded away.
9269 // If all input operands to the phi are the same instruction (e.g. a cast from
9270 // the same type or "+42") we can pull the operation through the PHI, reducing
9271 // code size and simplifying code.
9272 Constant *ConstantOp = 0;
9273 const Type *CastSrcTy = 0;
9274 bool isVolatile = false;
9275 if (isa<CastInst>(FirstInst)) {
9276 CastSrcTy = FirstInst->getOperand(0)->getType();
9277 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9278 // Can fold binop, compare or shift here if the RHS is a constant,
9279 // otherwise call FoldPHIArgBinOpIntoPHI.
9280 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9281 if (ConstantOp == 0)
9282 return FoldPHIArgBinOpIntoPHI(PN);
9283 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9284 isVolatile = LI->isVolatile();
9285 // We can't sink the load if the loaded value could be modified between the
9286 // load and the PHI.
9287 if (LI->getParent() != PN.getIncomingBlock(0) ||
9288 !isSafeToSinkLoad(LI))
9290 } else if (isa<GetElementPtrInst>(FirstInst)) {
9291 if (FirstInst->getNumOperands() == 2)
9292 return FoldPHIArgBinOpIntoPHI(PN);
9293 // Can't handle general GEPs yet.
9296 return 0; // Cannot fold this operation.
9299 // Check to see if all arguments are the same operation.
9300 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9301 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9302 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9303 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9306 if (I->getOperand(0)->getType() != CastSrcTy)
9307 return 0; // Cast operation must match.
9308 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9309 // We can't sink the load if the loaded value could be modified between
9310 // the load and the PHI.
9311 if (LI->isVolatile() != isVolatile ||
9312 LI->getParent() != PN.getIncomingBlock(i) ||
9313 !isSafeToSinkLoad(LI))
9316 // If the PHI is volatile and its block has multiple successors, sinking
9317 // it would remove a load of the volatile value from the path through the
9320 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9324 } else if (I->getOperand(1) != ConstantOp) {
9329 // Okay, they are all the same operation. Create a new PHI node of the
9330 // correct type, and PHI together all of the LHS's of the instructions.
9331 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9332 PN.getName()+".in");
9333 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9335 Value *InVal = FirstInst->getOperand(0);
9336 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9338 // Add all operands to the new PHI.
9339 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9340 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9341 if (NewInVal != InVal)
9343 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9348 // The new PHI unions all of the same values together. This is really
9349 // common, so we handle it intelligently here for compile-time speed.
9353 InsertNewInstBefore(NewPN, PN);
9357 // Insert and return the new operation.
9358 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9359 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9360 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9361 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9362 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9363 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
9364 PhiVal, ConstantOp);
9365 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9367 // If this was a volatile load that we are merging, make sure to loop through
9368 // and mark all the input loads as non-volatile. If we don't do this, we will
9369 // insert a new volatile load and the old ones will not be deletable.
9371 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9372 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9374 return new LoadInst(PhiVal, "", isVolatile);
9377 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9379 static bool DeadPHICycle(PHINode *PN,
9380 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9381 if (PN->use_empty()) return true;
9382 if (!PN->hasOneUse()) return false;
9384 // Remember this node, and if we find the cycle, return.
9385 if (!PotentiallyDeadPHIs.insert(PN))
9388 // Don't scan crazily complex things.
9389 if (PotentiallyDeadPHIs.size() == 16)
9392 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9393 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9398 /// PHIsEqualValue - Return true if this phi node is always equal to
9399 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9400 /// z = some value; x = phi (y, z); y = phi (x, z)
9401 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9402 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9403 // See if we already saw this PHI node.
9404 if (!ValueEqualPHIs.insert(PN))
9407 // Don't scan crazily complex things.
9408 if (ValueEqualPHIs.size() == 16)
9411 // Scan the operands to see if they are either phi nodes or are equal to
9413 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9414 Value *Op = PN->getIncomingValue(i);
9415 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9416 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9418 } else if (Op != NonPhiInVal)
9426 // PHINode simplification
9428 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9429 // If LCSSA is around, don't mess with Phi nodes
9430 if (MustPreserveLCSSA) return 0;
9432 if (Value *V = PN.hasConstantValue())
9433 return ReplaceInstUsesWith(PN, V);
9435 // If all PHI operands are the same operation, pull them through the PHI,
9436 // reducing code size.
9437 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9438 PN.getIncomingValue(0)->hasOneUse())
9439 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9442 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9443 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9444 // PHI)... break the cycle.
9445 if (PN.hasOneUse()) {
9446 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9447 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9448 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9449 PotentiallyDeadPHIs.insert(&PN);
9450 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9451 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9454 // If this phi has a single use, and if that use just computes a value for
9455 // the next iteration of a loop, delete the phi. This occurs with unused
9456 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9457 // common case here is good because the only other things that catch this
9458 // are induction variable analysis (sometimes) and ADCE, which is only run
9460 if (PHIUser->hasOneUse() &&
9461 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9462 PHIUser->use_back() == &PN) {
9463 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9467 // We sometimes end up with phi cycles that non-obviously end up being the
9468 // same value, for example:
9469 // z = some value; x = phi (y, z); y = phi (x, z)
9470 // where the phi nodes don't necessarily need to be in the same block. Do a
9471 // quick check to see if the PHI node only contains a single non-phi value, if
9472 // so, scan to see if the phi cycle is actually equal to that value.
9474 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9475 // Scan for the first non-phi operand.
9476 while (InValNo != NumOperandVals &&
9477 isa<PHINode>(PN.getIncomingValue(InValNo)))
9480 if (InValNo != NumOperandVals) {
9481 Value *NonPhiInVal = PN.getOperand(InValNo);
9483 // Scan the rest of the operands to see if there are any conflicts, if so
9484 // there is no need to recursively scan other phis.
9485 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9486 Value *OpVal = PN.getIncomingValue(InValNo);
9487 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9491 // If we scanned over all operands, then we have one unique value plus
9492 // phi values. Scan PHI nodes to see if they all merge in each other or
9494 if (InValNo == NumOperandVals) {
9495 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9496 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9497 return ReplaceInstUsesWith(PN, NonPhiInVal);
9504 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9505 Instruction *InsertPoint,
9507 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9508 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9509 // We must cast correctly to the pointer type. Ensure that we
9510 // sign extend the integer value if it is smaller as this is
9511 // used for address computation.
9512 Instruction::CastOps opcode =
9513 (VTySize < PtrSize ? Instruction::SExt :
9514 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9515 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9519 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9520 Value *PtrOp = GEP.getOperand(0);
9521 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9522 // If so, eliminate the noop.
9523 if (GEP.getNumOperands() == 1)
9524 return ReplaceInstUsesWith(GEP, PtrOp);
9526 if (isa<UndefValue>(GEP.getOperand(0)))
9527 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9529 bool HasZeroPointerIndex = false;
9530 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9531 HasZeroPointerIndex = C->isNullValue();
9533 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9534 return ReplaceInstUsesWith(GEP, PtrOp);
9536 // Eliminate unneeded casts for indices.
9537 bool MadeChange = false;
9539 gep_type_iterator GTI = gep_type_begin(GEP);
9540 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9541 i != e; ++i, ++GTI) {
9542 if (isa<SequentialType>(*GTI)) {
9543 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9544 if (CI->getOpcode() == Instruction::ZExt ||
9545 CI->getOpcode() == Instruction::SExt) {
9546 const Type *SrcTy = CI->getOperand(0)->getType();
9547 // We can eliminate a cast from i32 to i64 iff the target
9548 // is a 32-bit pointer target.
9549 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9551 *i = CI->getOperand(0);
9555 // If we are using a wider index than needed for this platform, shrink it
9556 // to what we need. If the incoming value needs a cast instruction,
9557 // insert it. This explicit cast can make subsequent optimizations more
9560 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9561 if (Constant *C = dyn_cast<Constant>(Op)) {
9562 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9565 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9573 if (MadeChange) return &GEP;
9575 // If this GEP instruction doesn't move the pointer, and if the input operand
9576 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9577 // real input to the dest type.
9578 if (GEP.hasAllZeroIndices()) {
9579 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9580 // If the bitcast is of an allocation, and the allocation will be
9581 // converted to match the type of the cast, don't touch this.
9582 if (isa<AllocationInst>(BCI->getOperand(0))) {
9583 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9584 if (Instruction *I = visitBitCast(*BCI)) {
9587 BCI->getParent()->getInstList().insert(BCI, I);
9588 ReplaceInstUsesWith(*BCI, I);
9593 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9597 // Combine Indices - If the source pointer to this getelementptr instruction
9598 // is a getelementptr instruction, combine the indices of the two
9599 // getelementptr instructions into a single instruction.
9601 SmallVector<Value*, 8> SrcGEPOperands;
9602 if (User *Src = dyn_castGetElementPtr(PtrOp))
9603 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9605 if (!SrcGEPOperands.empty()) {
9606 // Note that if our source is a gep chain itself that we wait for that
9607 // chain to be resolved before we perform this transformation. This
9608 // avoids us creating a TON of code in some cases.
9610 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9611 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9612 return 0; // Wait until our source is folded to completion.
9614 SmallVector<Value*, 8> Indices;
9616 // Find out whether the last index in the source GEP is a sequential idx.
9617 bool EndsWithSequential = false;
9618 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9619 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9620 EndsWithSequential = !isa<StructType>(*I);
9622 // Can we combine the two pointer arithmetics offsets?
9623 if (EndsWithSequential) {
9624 // Replace: gep (gep %P, long B), long A, ...
9625 // With: T = long A+B; gep %P, T, ...
9627 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9628 if (SO1 == Constant::getNullValue(SO1->getType())) {
9630 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9633 // If they aren't the same type, convert both to an integer of the
9634 // target's pointer size.
9635 if (SO1->getType() != GO1->getType()) {
9636 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9637 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9638 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9639 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9641 unsigned PS = TD->getPointerSizeInBits();
9642 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9643 // Convert GO1 to SO1's type.
9644 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9646 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9647 // Convert SO1 to GO1's type.
9648 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9650 const Type *PT = TD->getIntPtrType();
9651 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9652 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9656 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9657 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9659 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9660 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9664 // Recycle the GEP we already have if possible.
9665 if (SrcGEPOperands.size() == 2) {
9666 GEP.setOperand(0, SrcGEPOperands[0]);
9667 GEP.setOperand(1, Sum);
9670 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9671 SrcGEPOperands.end()-1);
9672 Indices.push_back(Sum);
9673 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9675 } else if (isa<Constant>(*GEP.idx_begin()) &&
9676 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9677 SrcGEPOperands.size() != 1) {
9678 // Otherwise we can do the fold if the first index of the GEP is a zero
9679 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9680 SrcGEPOperands.end());
9681 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9684 if (!Indices.empty())
9685 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9686 Indices.end(), GEP.getName());
9688 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9689 // GEP of global variable. If all of the indices for this GEP are
9690 // constants, we can promote this to a constexpr instead of an instruction.
9692 // Scan for nonconstants...
9693 SmallVector<Constant*, 8> Indices;
9694 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9695 for (; I != E && isa<Constant>(*I); ++I)
9696 Indices.push_back(cast<Constant>(*I));
9698 if (I == E) { // If they are all constants...
9699 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9700 &Indices[0],Indices.size());
9702 // Replace all uses of the GEP with the new constexpr...
9703 return ReplaceInstUsesWith(GEP, CE);
9705 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9706 if (!isa<PointerType>(X->getType())) {
9707 // Not interesting. Source pointer must be a cast from pointer.
9708 } else if (HasZeroPointerIndex) {
9709 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9710 // into : GEP [10 x i8]* X, i32 0, ...
9712 // This occurs when the program declares an array extern like "int X[];"
9714 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9715 const PointerType *XTy = cast<PointerType>(X->getType());
9716 if (const ArrayType *XATy =
9717 dyn_cast<ArrayType>(XTy->getElementType()))
9718 if (const ArrayType *CATy =
9719 dyn_cast<ArrayType>(CPTy->getElementType()))
9720 if (CATy->getElementType() == XATy->getElementType()) {
9721 // At this point, we know that the cast source type is a pointer
9722 // to an array of the same type as the destination pointer
9723 // array. Because the array type is never stepped over (there
9724 // is a leading zero) we can fold the cast into this GEP.
9725 GEP.setOperand(0, X);
9728 } else if (GEP.getNumOperands() == 2) {
9729 // Transform things like:
9730 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9731 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9732 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9733 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9734 if (isa<ArrayType>(SrcElTy) &&
9735 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9736 TD->getABITypeSize(ResElTy)) {
9738 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9739 Idx[1] = GEP.getOperand(1);
9740 Value *V = InsertNewInstBefore(
9741 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9742 // V and GEP are both pointer types --> BitCast
9743 return new BitCastInst(V, GEP.getType());
9746 // Transform things like:
9747 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9748 // (where tmp = 8*tmp2) into:
9749 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9751 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9752 uint64_t ArrayEltSize =
9753 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9755 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9756 // allow either a mul, shift, or constant here.
9758 ConstantInt *Scale = 0;
9759 if (ArrayEltSize == 1) {
9760 NewIdx = GEP.getOperand(1);
9761 Scale = ConstantInt::get(NewIdx->getType(), 1);
9762 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9763 NewIdx = ConstantInt::get(CI->getType(), 1);
9765 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9766 if (Inst->getOpcode() == Instruction::Shl &&
9767 isa<ConstantInt>(Inst->getOperand(1))) {
9768 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9769 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9770 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9771 NewIdx = Inst->getOperand(0);
9772 } else if (Inst->getOpcode() == Instruction::Mul &&
9773 isa<ConstantInt>(Inst->getOperand(1))) {
9774 Scale = cast<ConstantInt>(Inst->getOperand(1));
9775 NewIdx = Inst->getOperand(0);
9779 // If the index will be to exactly the right offset with the scale taken
9780 // out, perform the transformation. Note, we don't know whether Scale is
9781 // signed or not. We'll use unsigned version of division/modulo
9782 // operation after making sure Scale doesn't have the sign bit set.
9783 if (Scale && Scale->getSExtValue() >= 0LL &&
9784 Scale->getZExtValue() % ArrayEltSize == 0) {
9785 Scale = ConstantInt::get(Scale->getType(),
9786 Scale->getZExtValue() / ArrayEltSize);
9787 if (Scale->getZExtValue() != 1) {
9788 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9790 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9791 NewIdx = InsertNewInstBefore(Sc, GEP);
9794 // Insert the new GEP instruction.
9796 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9798 Instruction *NewGEP =
9799 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9800 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9801 // The NewGEP must be pointer typed, so must the old one -> BitCast
9802 return new BitCastInst(NewGEP, GEP.getType());
9811 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9812 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9813 if (AI.isArrayAllocation()) { // Check C != 1
9814 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9816 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9817 AllocationInst *New = 0;
9819 // Create and insert the replacement instruction...
9820 if (isa<MallocInst>(AI))
9821 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9823 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9824 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9827 InsertNewInstBefore(New, AI);
9829 // Scan to the end of the allocation instructions, to skip over a block of
9830 // allocas if possible...
9832 BasicBlock::iterator It = New;
9833 while (isa<AllocationInst>(*It)) ++It;
9835 // Now that I is pointing to the first non-allocation-inst in the block,
9836 // insert our getelementptr instruction...
9838 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9842 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9843 New->getName()+".sub", It);
9845 // Now make everything use the getelementptr instead of the original
9847 return ReplaceInstUsesWith(AI, V);
9848 } else if (isa<UndefValue>(AI.getArraySize())) {
9849 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9853 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9854 // Note that we only do this for alloca's, because malloc should allocate and
9855 // return a unique pointer, even for a zero byte allocation.
9856 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9857 TD->getABITypeSize(AI.getAllocatedType()) == 0)
9858 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9863 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9864 Value *Op = FI.getOperand(0);
9866 // free undef -> unreachable.
9867 if (isa<UndefValue>(Op)) {
9868 // Insert a new store to null because we cannot modify the CFG here.
9869 new StoreInst(ConstantInt::getTrue(),
9870 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9871 return EraseInstFromFunction(FI);
9874 // If we have 'free null' delete the instruction. This can happen in stl code
9875 // when lots of inlining happens.
9876 if (isa<ConstantPointerNull>(Op))
9877 return EraseInstFromFunction(FI);
9879 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9880 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9881 FI.setOperand(0, CI->getOperand(0));
9885 // Change free (gep X, 0,0,0,0) into free(X)
9886 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9887 if (GEPI->hasAllZeroIndices()) {
9888 AddToWorkList(GEPI);
9889 FI.setOperand(0, GEPI->getOperand(0));
9894 // Change free(malloc) into nothing, if the malloc has a single use.
9895 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9896 if (MI->hasOneUse()) {
9897 EraseInstFromFunction(FI);
9898 return EraseInstFromFunction(*MI);
9905 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9906 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9907 const TargetData *TD) {
9908 User *CI = cast<User>(LI.getOperand(0));
9909 Value *CastOp = CI->getOperand(0);
9911 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9912 // Instead of loading constant c string, use corresponding integer value
9913 // directly if string length is small enough.
9914 const std::string &Str = CE->getOperand(0)->getStringValue();
9916 unsigned len = Str.length();
9917 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9918 unsigned numBits = Ty->getPrimitiveSizeInBits();
9919 // Replace LI with immediate integer store.
9920 if ((numBits >> 3) == len + 1) {
9921 APInt StrVal(numBits, 0);
9922 APInt SingleChar(numBits, 0);
9923 if (TD->isLittleEndian()) {
9924 for (signed i = len-1; i >= 0; i--) {
9925 SingleChar = (uint64_t) Str[i];
9926 StrVal = (StrVal << 8) | SingleChar;
9929 for (unsigned i = 0; i < len; i++) {
9930 SingleChar = (uint64_t) Str[i];
9931 StrVal = (StrVal << 8) | SingleChar;
9933 // Append NULL at the end.
9935 StrVal = (StrVal << 8) | SingleChar;
9937 Value *NL = ConstantInt::get(StrVal);
9938 return IC.ReplaceInstUsesWith(LI, NL);
9943 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9944 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9945 const Type *SrcPTy = SrcTy->getElementType();
9947 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
9948 isa<VectorType>(DestPTy)) {
9949 // If the source is an array, the code below will not succeed. Check to
9950 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9952 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9953 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9954 if (ASrcTy->getNumElements() != 0) {
9956 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9957 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9958 SrcTy = cast<PointerType>(CastOp->getType());
9959 SrcPTy = SrcTy->getElementType();
9962 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
9963 isa<VectorType>(SrcPTy)) &&
9964 // Do not allow turning this into a load of an integer, which is then
9965 // casted to a pointer, this pessimizes pointer analysis a lot.
9966 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9967 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9968 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9970 // Okay, we are casting from one integer or pointer type to another of
9971 // the same size. Instead of casting the pointer before the load, cast
9972 // the result of the loaded value.
9973 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9975 LI.isVolatile()),LI);
9976 // Now cast the result of the load.
9977 return new BitCastInst(NewLoad, LI.getType());
9984 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9985 /// from this value cannot trap. If it is not obviously safe to load from the
9986 /// specified pointer, we do a quick local scan of the basic block containing
9987 /// ScanFrom, to determine if the address is already accessed.
9988 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9989 // If it is an alloca it is always safe to load from.
9990 if (isa<AllocaInst>(V)) return true;
9992 // If it is a global variable it is mostly safe to load from.
9993 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9994 // Don't try to evaluate aliases. External weak GV can be null.
9995 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9997 // Otherwise, be a little bit agressive by scanning the local block where we
9998 // want to check to see if the pointer is already being loaded or stored
9999 // from/to. If so, the previous load or store would have already trapped,
10000 // so there is no harm doing an extra load (also, CSE will later eliminate
10001 // the load entirely).
10002 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10007 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10008 if (LI->getOperand(0) == V) return true;
10009 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10010 if (SI->getOperand(1) == V) return true;
10016 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10017 /// until we find the underlying object a pointer is referring to or something
10018 /// we don't understand. Note that the returned pointer may be offset from the
10019 /// input, because we ignore GEP indices.
10020 static Value *GetUnderlyingObject(Value *Ptr) {
10022 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10023 if (CE->getOpcode() == Instruction::BitCast ||
10024 CE->getOpcode() == Instruction::GetElementPtr)
10025 Ptr = CE->getOperand(0);
10028 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10029 Ptr = BCI->getOperand(0);
10030 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10031 Ptr = GEP->getOperand(0);
10038 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10039 Value *Op = LI.getOperand(0);
10041 // Attempt to improve the alignment.
10042 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10044 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10045 LI.getAlignment()))
10046 LI.setAlignment(KnownAlign);
10048 // load (cast X) --> cast (load X) iff safe
10049 if (isa<CastInst>(Op))
10050 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10053 // None of the following transforms are legal for volatile loads.
10054 if (LI.isVolatile()) return 0;
10056 if (&LI.getParent()->front() != &LI) {
10057 BasicBlock::iterator BBI = &LI; --BBI;
10058 // If the instruction immediately before this is a store to the same
10059 // address, do a simple form of store->load forwarding.
10060 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10061 if (SI->getOperand(1) == LI.getOperand(0))
10062 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10063 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10064 if (LIB->getOperand(0) == LI.getOperand(0))
10065 return ReplaceInstUsesWith(LI, LIB);
10068 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10069 const Value *GEPI0 = GEPI->getOperand(0);
10070 // TODO: Consider a target hook for valid address spaces for this xform.
10071 if (isa<ConstantPointerNull>(GEPI0) &&
10072 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10073 // Insert a new store to null instruction before the load to indicate
10074 // that this code is not reachable. We do this instead of inserting
10075 // an unreachable instruction directly because we cannot modify the
10077 new StoreInst(UndefValue::get(LI.getType()),
10078 Constant::getNullValue(Op->getType()), &LI);
10079 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10083 if (Constant *C = dyn_cast<Constant>(Op)) {
10084 // load null/undef -> undef
10085 // TODO: Consider a target hook for valid address spaces for this xform.
10086 if (isa<UndefValue>(C) || (C->isNullValue() &&
10087 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10088 // Insert a new store to null instruction before the load to indicate that
10089 // this code is not reachable. We do this instead of inserting an
10090 // unreachable instruction directly because we cannot modify the CFG.
10091 new StoreInst(UndefValue::get(LI.getType()),
10092 Constant::getNullValue(Op->getType()), &LI);
10093 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10096 // Instcombine load (constant global) into the value loaded.
10097 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10098 if (GV->isConstant() && !GV->isDeclaration())
10099 return ReplaceInstUsesWith(LI, GV->getInitializer());
10101 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10102 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10103 if (CE->getOpcode() == Instruction::GetElementPtr) {
10104 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10105 if (GV->isConstant() && !GV->isDeclaration())
10107 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10108 return ReplaceInstUsesWith(LI, V);
10109 if (CE->getOperand(0)->isNullValue()) {
10110 // Insert a new store to null instruction before the load to indicate
10111 // that this code is not reachable. We do this instead of inserting
10112 // an unreachable instruction directly because we cannot modify the
10114 new StoreInst(UndefValue::get(LI.getType()),
10115 Constant::getNullValue(Op->getType()), &LI);
10116 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10119 } else if (CE->isCast()) {
10120 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10126 // If this load comes from anywhere in a constant global, and if the global
10127 // is all undef or zero, we know what it loads.
10128 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10129 if (GV->isConstant() && GV->hasInitializer()) {
10130 if (GV->getInitializer()->isNullValue())
10131 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10132 else if (isa<UndefValue>(GV->getInitializer()))
10133 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10137 if (Op->hasOneUse()) {
10138 // Change select and PHI nodes to select values instead of addresses: this
10139 // helps alias analysis out a lot, allows many others simplifications, and
10140 // exposes redundancy in the code.
10142 // Note that we cannot do the transformation unless we know that the
10143 // introduced loads cannot trap! Something like this is valid as long as
10144 // the condition is always false: load (select bool %C, int* null, int* %G),
10145 // but it would not be valid if we transformed it to load from null
10146 // unconditionally.
10148 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10149 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10150 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10151 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10152 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10153 SI->getOperand(1)->getName()+".val"), LI);
10154 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10155 SI->getOperand(2)->getName()+".val"), LI);
10156 return SelectInst::Create(SI->getCondition(), V1, V2);
10159 // load (select (cond, null, P)) -> load P
10160 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10161 if (C->isNullValue()) {
10162 LI.setOperand(0, SI->getOperand(2));
10166 // load (select (cond, P, null)) -> load P
10167 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10168 if (C->isNullValue()) {
10169 LI.setOperand(0, SI->getOperand(1));
10177 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10179 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10180 User *CI = cast<User>(SI.getOperand(1));
10181 Value *CastOp = CI->getOperand(0);
10183 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10184 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10185 const Type *SrcPTy = SrcTy->getElementType();
10187 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10188 // If the source is an array, the code below will not succeed. Check to
10189 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10191 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10192 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10193 if (ASrcTy->getNumElements() != 0) {
10195 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10196 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10197 SrcTy = cast<PointerType>(CastOp->getType());
10198 SrcPTy = SrcTy->getElementType();
10201 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10202 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10203 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10205 // Okay, we are casting from one integer or pointer type to another of
10206 // the same size. Instead of casting the pointer before
10207 // the store, cast the value to be stored.
10209 Value *SIOp0 = SI.getOperand(0);
10210 Instruction::CastOps opcode = Instruction::BitCast;
10211 const Type* CastSrcTy = SIOp0->getType();
10212 const Type* CastDstTy = SrcPTy;
10213 if (isa<PointerType>(CastDstTy)) {
10214 if (CastSrcTy->isInteger())
10215 opcode = Instruction::IntToPtr;
10216 } else if (isa<IntegerType>(CastDstTy)) {
10217 if (isa<PointerType>(SIOp0->getType()))
10218 opcode = Instruction::PtrToInt;
10220 if (Constant *C = dyn_cast<Constant>(SIOp0))
10221 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10223 NewCast = IC.InsertNewInstBefore(
10224 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10226 return new StoreInst(NewCast, CastOp);
10233 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10234 Value *Val = SI.getOperand(0);
10235 Value *Ptr = SI.getOperand(1);
10237 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10238 EraseInstFromFunction(SI);
10243 // If the RHS is an alloca with a single use, zapify the store, making the
10245 if (Ptr->hasOneUse() && !SI.isVolatile()) {
10246 if (isa<AllocaInst>(Ptr)) {
10247 EraseInstFromFunction(SI);
10252 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10253 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10254 GEP->getOperand(0)->hasOneUse()) {
10255 EraseInstFromFunction(SI);
10261 // Attempt to improve the alignment.
10262 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10264 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10265 SI.getAlignment()))
10266 SI.setAlignment(KnownAlign);
10268 // Do really simple DSE, to catch cases where there are several consequtive
10269 // stores to the same location, separated by a few arithmetic operations. This
10270 // situation often occurs with bitfield accesses.
10271 BasicBlock::iterator BBI = &SI;
10272 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10276 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10277 // Prev store isn't volatile, and stores to the same location?
10278 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10281 EraseInstFromFunction(*PrevSI);
10287 // If this is a load, we have to stop. However, if the loaded value is from
10288 // the pointer we're loading and is producing the pointer we're storing,
10289 // then *this* store is dead (X = load P; store X -> P).
10290 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10291 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10292 EraseInstFromFunction(SI);
10296 // Otherwise, this is a load from some other location. Stores before it
10297 // may not be dead.
10301 // Don't skip over loads or things that can modify memory.
10302 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10307 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10309 // store X, null -> turns into 'unreachable' in SimplifyCFG
10310 if (isa<ConstantPointerNull>(Ptr)) {
10311 if (!isa<UndefValue>(Val)) {
10312 SI.setOperand(0, UndefValue::get(Val->getType()));
10313 if (Instruction *U = dyn_cast<Instruction>(Val))
10314 AddToWorkList(U); // Dropped a use.
10317 return 0; // Do not modify these!
10320 // store undef, Ptr -> noop
10321 if (isa<UndefValue>(Val)) {
10322 EraseInstFromFunction(SI);
10327 // If the pointer destination is a cast, see if we can fold the cast into the
10329 if (isa<CastInst>(Ptr))
10330 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10332 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10334 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10338 // If this store is the last instruction in the basic block, and if the block
10339 // ends with an unconditional branch, try to move it to the successor block.
10341 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10342 if (BI->isUnconditional())
10343 if (SimplifyStoreAtEndOfBlock(SI))
10344 return 0; // xform done!
10349 /// SimplifyStoreAtEndOfBlock - Turn things like:
10350 /// if () { *P = v1; } else { *P = v2 }
10351 /// into a phi node with a store in the successor.
10353 /// Simplify things like:
10354 /// *P = v1; if () { *P = v2; }
10355 /// into a phi node with a store in the successor.
10357 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10358 BasicBlock *StoreBB = SI.getParent();
10360 // Check to see if the successor block has exactly two incoming edges. If
10361 // so, see if the other predecessor contains a store to the same location.
10362 // if so, insert a PHI node (if needed) and move the stores down.
10363 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10365 // Determine whether Dest has exactly two predecessors and, if so, compute
10366 // the other predecessor.
10367 pred_iterator PI = pred_begin(DestBB);
10368 BasicBlock *OtherBB = 0;
10369 if (*PI != StoreBB)
10372 if (PI == pred_end(DestBB))
10375 if (*PI != StoreBB) {
10380 if (++PI != pred_end(DestBB))
10383 // Bail out if all the relevant blocks aren't distinct (this can happen,
10384 // for example, if SI is in an infinite loop)
10385 if (StoreBB == DestBB || OtherBB == DestBB)
10388 // Verify that the other block ends in a branch and is not otherwise empty.
10389 BasicBlock::iterator BBI = OtherBB->getTerminator();
10390 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10391 if (!OtherBr || BBI == OtherBB->begin())
10394 // If the other block ends in an unconditional branch, check for the 'if then
10395 // else' case. there is an instruction before the branch.
10396 StoreInst *OtherStore = 0;
10397 if (OtherBr->isUnconditional()) {
10398 // If this isn't a store, or isn't a store to the same location, bail out.
10400 OtherStore = dyn_cast<StoreInst>(BBI);
10401 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10404 // Otherwise, the other block ended with a conditional branch. If one of the
10405 // destinations is StoreBB, then we have the if/then case.
10406 if (OtherBr->getSuccessor(0) != StoreBB &&
10407 OtherBr->getSuccessor(1) != StoreBB)
10410 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10411 // if/then triangle. See if there is a store to the same ptr as SI that
10412 // lives in OtherBB.
10414 // Check to see if we find the matching store.
10415 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10416 if (OtherStore->getOperand(1) != SI.getOperand(1))
10420 // If we find something that may be using or overwriting the stored
10421 // value, or if we run out of instructions, we can't do the xform.
10422 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10423 BBI == OtherBB->begin())
10427 // In order to eliminate the store in OtherBr, we have to
10428 // make sure nothing reads or overwrites the stored value in
10430 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10431 // FIXME: This should really be AA driven.
10432 if (I->mayReadFromMemory() || I->mayWriteToMemory())
10437 // Insert a PHI node now if we need it.
10438 Value *MergedVal = OtherStore->getOperand(0);
10439 if (MergedVal != SI.getOperand(0)) {
10440 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10441 PN->reserveOperandSpace(2);
10442 PN->addIncoming(SI.getOperand(0), SI.getParent());
10443 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10444 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10447 // Advance to a place where it is safe to insert the new store and
10449 BBI = DestBB->getFirstNonPHI();
10450 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10451 OtherStore->isVolatile()), *BBI);
10453 // Nuke the old stores.
10454 EraseInstFromFunction(SI);
10455 EraseInstFromFunction(*OtherStore);
10461 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10462 // Change br (not X), label True, label False to: br X, label False, True
10464 BasicBlock *TrueDest;
10465 BasicBlock *FalseDest;
10466 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10467 !isa<Constant>(X)) {
10468 // Swap Destinations and condition...
10469 BI.setCondition(X);
10470 BI.setSuccessor(0, FalseDest);
10471 BI.setSuccessor(1, TrueDest);
10475 // Cannonicalize fcmp_one -> fcmp_oeq
10476 FCmpInst::Predicate FPred; Value *Y;
10477 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10478 TrueDest, FalseDest)))
10479 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10480 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10481 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10482 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10483 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10484 NewSCC->takeName(I);
10485 // Swap Destinations and condition...
10486 BI.setCondition(NewSCC);
10487 BI.setSuccessor(0, FalseDest);
10488 BI.setSuccessor(1, TrueDest);
10489 RemoveFromWorkList(I);
10490 I->eraseFromParent();
10491 AddToWorkList(NewSCC);
10495 // Cannonicalize icmp_ne -> icmp_eq
10496 ICmpInst::Predicate IPred;
10497 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10498 TrueDest, FalseDest)))
10499 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10500 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10501 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10502 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10503 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10504 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10505 NewSCC->takeName(I);
10506 // Swap Destinations and condition...
10507 BI.setCondition(NewSCC);
10508 BI.setSuccessor(0, FalseDest);
10509 BI.setSuccessor(1, TrueDest);
10510 RemoveFromWorkList(I);
10511 I->eraseFromParent();;
10512 AddToWorkList(NewSCC);
10519 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10520 Value *Cond = SI.getCondition();
10521 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10522 if (I->getOpcode() == Instruction::Add)
10523 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10524 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10525 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10526 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10528 SI.setOperand(0, I->getOperand(0));
10536 // This is the recursive version of BuildSubAggregate. It takes a few different
10537 // arguments. Idxs is the index within the nested struct From that we are
10538 // looking at now (which is of type IndexedType). IdxSkip is the number of
10539 // indices from Idxs that should be left out when inserting into the resulting
10540 // struct. To is the result struct built so far, new insertvalue instructions
10542 Value *InstCombiner::BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
10543 SmallVector<unsigned, 10> &Idxs,
10545 Instruction &InsertBefore) {
10546 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
10548 // General case, the type indexed by Idxs is a struct
10549 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
10550 // Process each struct element recursively
10552 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip, InsertBefore);
10557 // Base case, the type indexed by SourceIdxs is not a struct
10558 // Load the value from the nested struct into the sub struct (and skip
10559 // IdxSkip indices when indexing the sub struct).
10560 Instruction *V = llvm::ExtractValueInst::Create(From, Idxs.begin(), Idxs.end(), "tmp");
10561 InsertNewInstBefore(V, InsertBefore);
10562 Instruction *Ins = llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip, Idxs.end(), "tmp");
10563 InsertNewInstBefore(Ins, InsertBefore);
10568 // This helper takes a nested struct and extracts a part of it (which is again a
10569 // struct) into a new value. For example, given the struct:
10570 // { a, { b, { c, d }, e } }
10571 // and the indices "1, 1" this returns
10574 // It does this by inserting an extractvalue and insertvalue for each element in
10575 // the resulting struct, as opposed to just inserting a single struct. This
10576 // allows for later folding of these individual extractvalue instructions with
10577 // insertvalue instructions that fill the nested struct.
10579 // Any inserted instructions are inserted before InsertBefore
10580 Value *InstCombiner::BuildSubAggregate(Value *From, const unsigned *idx_begin, const unsigned *idx_end, Instruction &InsertBefore) {
10581 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(), idx_begin, idx_end);
10582 Value *To = UndefValue::get(IndexedType);
10583 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
10584 unsigned IdxSkip = Idxs.size();
10586 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
10589 /// FindScalarValue - Given an aggregrate and an sequence of indices, see if the
10590 /// scalar value indexed is already around as a register, for example if it were
10591 /// inserted directly into the aggregrate.
10592 Value *InstCombiner::FindScalarValue(Value *V, const unsigned *idx_begin,
10593 const unsigned *idx_end, Instruction &InsertBefore) {
10594 // Nothing to index? Just return V then (this is useful at the end of our
10596 if (idx_begin == idx_end)
10598 // We have indices, so V should have an indexable type
10599 assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
10600 && "Not looking at a struct or array?");
10601 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
10602 && "Invalid indices for type?");
10603 const CompositeType *PTy = cast<CompositeType>(V->getType());
10605 if (isa<UndefValue>(V))
10606 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
10609 else if (isa<ConstantAggregateZero>(V))
10610 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
10613 else if (Constant *C = dyn_cast<Constant>(V)) {
10614 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
10615 // Recursively process this constant
10616 return FindScalarValue(C->getOperand(*idx_begin), ++idx_begin, idx_end, InsertBefore);
10617 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
10618 // Loop the indices for the insertvalue instruction in parallel with the
10619 // requested indices
10620 const unsigned *req_idx = idx_begin;
10621 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); i != e; ++i, ++req_idx) {
10622 if (req_idx == idx_end)
10623 // The requested index is a part of a nested aggregate. Handle this
10625 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
10627 // This insert value inserts something else than what we are looking for.
10628 // See if the (aggregrate) value inserted into has the value we are
10629 // looking for, then.
10630 if (*req_idx != *i)
10631 return FindScalarValue(I->getAggregateOperand(), idx_begin, idx_end, InsertBefore);
10633 // If we end up here, the indices of the insertvalue match with those
10634 // requested (though possibly only partially). Now we recursively look at
10635 // the inserted value, passing any remaining indices.
10636 return FindScalarValue(I->getInsertedValueOperand(), req_idx, idx_end, InsertBefore);
10637 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
10638 // If we're extracting a value from an aggregrate that was extracted from
10639 // something else, we can extract from that something else directly instead.
10640 // However, we will need to chain I's indices with the requested indices.
10642 // Calculate the number of indices required
10643 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
10644 // Allocate some space to put the new indices in
10645 unsigned *new_begin = new unsigned[size];
10646 // Auto cleanup this array
10647 std::auto_ptr<unsigned> newptr(new_begin);
10648 // Start inserting at the beginning
10649 unsigned *new_end = new_begin;
10650 // Add indices from the extract value instruction
10651 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); i != e; ++i, ++new_end)
10654 // Add requested indices
10655 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i, ++new_end)
10658 assert((unsigned)(new_end - new_begin) == size && "Number of indices added not correct?");
10660 return FindScalarValue(I->getAggregateOperand(), new_begin, new_end, InsertBefore);
10662 // Otherwise, we don't know (such as, extracting from a function return value
10663 // or load instruction)
10667 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10668 // See if we are trying to extract a known value. If so, use that instead.
10669 if (Value *Elt = FindScalarValue(EV.getOperand(0), EV.idx_begin(), EV.idx_end(), EV))
10670 return ReplaceInstUsesWith(EV, Elt);
10676 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10677 /// is to leave as a vector operation.
10678 static bool CheapToScalarize(Value *V, bool isConstant) {
10679 if (isa<ConstantAggregateZero>(V))
10681 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10682 if (isConstant) return true;
10683 // If all elts are the same, we can extract.
10684 Constant *Op0 = C->getOperand(0);
10685 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10686 if (C->getOperand(i) != Op0)
10690 Instruction *I = dyn_cast<Instruction>(V);
10691 if (!I) return false;
10693 // Insert element gets simplified to the inserted element or is deleted if
10694 // this is constant idx extract element and its a constant idx insertelt.
10695 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10696 isa<ConstantInt>(I->getOperand(2)))
10698 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10700 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10701 if (BO->hasOneUse() &&
10702 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10703 CheapToScalarize(BO->getOperand(1), isConstant)))
10705 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10706 if (CI->hasOneUse() &&
10707 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10708 CheapToScalarize(CI->getOperand(1), isConstant)))
10714 /// Read and decode a shufflevector mask.
10716 /// It turns undef elements into values that are larger than the number of
10717 /// elements in the input.
10718 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10719 unsigned NElts = SVI->getType()->getNumElements();
10720 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10721 return std::vector<unsigned>(NElts, 0);
10722 if (isa<UndefValue>(SVI->getOperand(2)))
10723 return std::vector<unsigned>(NElts, 2*NElts);
10725 std::vector<unsigned> Result;
10726 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10727 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10728 if (isa<UndefValue>(*i))
10729 Result.push_back(NElts*2); // undef -> 8
10731 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10735 /// FindScalarElement - Given a vector and an element number, see if the scalar
10736 /// value is already around as a register, for example if it were inserted then
10737 /// extracted from the vector.
10738 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10739 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10740 const VectorType *PTy = cast<VectorType>(V->getType());
10741 unsigned Width = PTy->getNumElements();
10742 if (EltNo >= Width) // Out of range access.
10743 return UndefValue::get(PTy->getElementType());
10745 if (isa<UndefValue>(V))
10746 return UndefValue::get(PTy->getElementType());
10747 else if (isa<ConstantAggregateZero>(V))
10748 return Constant::getNullValue(PTy->getElementType());
10749 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10750 return CP->getOperand(EltNo);
10751 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10752 // If this is an insert to a variable element, we don't know what it is.
10753 if (!isa<ConstantInt>(III->getOperand(2)))
10755 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10757 // If this is an insert to the element we are looking for, return the
10759 if (EltNo == IIElt)
10760 return III->getOperand(1);
10762 // Otherwise, the insertelement doesn't modify the value, recurse on its
10764 return FindScalarElement(III->getOperand(0), EltNo);
10765 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10766 unsigned InEl = getShuffleMask(SVI)[EltNo];
10768 return FindScalarElement(SVI->getOperand(0), InEl);
10769 else if (InEl < Width*2)
10770 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10772 return UndefValue::get(PTy->getElementType());
10775 // Otherwise, we don't know.
10779 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10780 // If vector val is undef, replace extract with scalar undef.
10781 if (isa<UndefValue>(EI.getOperand(0)))
10782 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10784 // If vector val is constant 0, replace extract with scalar 0.
10785 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10786 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10788 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10789 // If vector val is constant with all elements the same, replace EI with
10790 // that element. When the elements are not identical, we cannot replace yet
10791 // (we do that below, but only when the index is constant).
10792 Constant *op0 = C->getOperand(0);
10793 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10794 if (C->getOperand(i) != op0) {
10799 return ReplaceInstUsesWith(EI, op0);
10802 // If extracting a specified index from the vector, see if we can recursively
10803 // find a previously computed scalar that was inserted into the vector.
10804 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10805 unsigned IndexVal = IdxC->getZExtValue();
10806 unsigned VectorWidth =
10807 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10809 // If this is extracting an invalid index, turn this into undef, to avoid
10810 // crashing the code below.
10811 if (IndexVal >= VectorWidth)
10812 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10814 // This instruction only demands the single element from the input vector.
10815 // If the input vector has a single use, simplify it based on this use
10817 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10818 uint64_t UndefElts;
10819 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10822 EI.setOperand(0, V);
10827 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10828 return ReplaceInstUsesWith(EI, Elt);
10830 // If the this extractelement is directly using a bitcast from a vector of
10831 // the same number of elements, see if we can find the source element from
10832 // it. In this case, we will end up needing to bitcast the scalars.
10833 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10834 if (const VectorType *VT =
10835 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10836 if (VT->getNumElements() == VectorWidth)
10837 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10838 return new BitCastInst(Elt, EI.getType());
10842 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10843 if (I->hasOneUse()) {
10844 // Push extractelement into predecessor operation if legal and
10845 // profitable to do so
10846 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10847 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10848 if (CheapToScalarize(BO, isConstantElt)) {
10849 ExtractElementInst *newEI0 =
10850 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10851 EI.getName()+".lhs");
10852 ExtractElementInst *newEI1 =
10853 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10854 EI.getName()+".rhs");
10855 InsertNewInstBefore(newEI0, EI);
10856 InsertNewInstBefore(newEI1, EI);
10857 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10859 } else if (isa<LoadInst>(I)) {
10861 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10862 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10863 PointerType::get(EI.getType(), AS),EI);
10864 GetElementPtrInst *GEP =
10865 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10866 InsertNewInstBefore(GEP, EI);
10867 return new LoadInst(GEP);
10870 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10871 // Extracting the inserted element?
10872 if (IE->getOperand(2) == EI.getOperand(1))
10873 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10874 // If the inserted and extracted elements are constants, they must not
10875 // be the same value, extract from the pre-inserted value instead.
10876 if (isa<Constant>(IE->getOperand(2)) &&
10877 isa<Constant>(EI.getOperand(1))) {
10878 AddUsesToWorkList(EI);
10879 EI.setOperand(0, IE->getOperand(0));
10882 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10883 // If this is extracting an element from a shufflevector, figure out where
10884 // it came from and extract from the appropriate input element instead.
10885 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10886 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10888 if (SrcIdx < SVI->getType()->getNumElements())
10889 Src = SVI->getOperand(0);
10890 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10891 SrcIdx -= SVI->getType()->getNumElements();
10892 Src = SVI->getOperand(1);
10894 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10896 return new ExtractElementInst(Src, SrcIdx);
10903 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10904 /// elements from either LHS or RHS, return the shuffle mask and true.
10905 /// Otherwise, return false.
10906 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10907 std::vector<Constant*> &Mask) {
10908 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10909 "Invalid CollectSingleShuffleElements");
10910 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10912 if (isa<UndefValue>(V)) {
10913 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10915 } else if (V == LHS) {
10916 for (unsigned i = 0; i != NumElts; ++i)
10917 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10919 } else if (V == RHS) {
10920 for (unsigned i = 0; i != NumElts; ++i)
10921 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10923 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10924 // If this is an insert of an extract from some other vector, include it.
10925 Value *VecOp = IEI->getOperand(0);
10926 Value *ScalarOp = IEI->getOperand(1);
10927 Value *IdxOp = IEI->getOperand(2);
10929 if (!isa<ConstantInt>(IdxOp))
10931 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10933 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10934 // Okay, we can handle this if the vector we are insertinting into is
10935 // transitively ok.
10936 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10937 // If so, update the mask to reflect the inserted undef.
10938 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10941 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10942 if (isa<ConstantInt>(EI->getOperand(1)) &&
10943 EI->getOperand(0)->getType() == V->getType()) {
10944 unsigned ExtractedIdx =
10945 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10947 // This must be extracting from either LHS or RHS.
10948 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10949 // Okay, we can handle this if the vector we are insertinting into is
10950 // transitively ok.
10951 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10952 // If so, update the mask to reflect the inserted value.
10953 if (EI->getOperand(0) == LHS) {
10954 Mask[InsertedIdx & (NumElts-1)] =
10955 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10957 assert(EI->getOperand(0) == RHS);
10958 Mask[InsertedIdx & (NumElts-1)] =
10959 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10968 // TODO: Handle shufflevector here!
10973 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10974 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10975 /// that computes V and the LHS value of the shuffle.
10976 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10978 assert(isa<VectorType>(V->getType()) &&
10979 (RHS == 0 || V->getType() == RHS->getType()) &&
10980 "Invalid shuffle!");
10981 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10983 if (isa<UndefValue>(V)) {
10984 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10986 } else if (isa<ConstantAggregateZero>(V)) {
10987 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10989 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10990 // If this is an insert of an extract from some other vector, include it.
10991 Value *VecOp = IEI->getOperand(0);
10992 Value *ScalarOp = IEI->getOperand(1);
10993 Value *IdxOp = IEI->getOperand(2);
10995 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10996 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10997 EI->getOperand(0)->getType() == V->getType()) {
10998 unsigned ExtractedIdx =
10999 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11000 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11002 // Either the extracted from or inserted into vector must be RHSVec,
11003 // otherwise we'd end up with a shuffle of three inputs.
11004 if (EI->getOperand(0) == RHS || RHS == 0) {
11005 RHS = EI->getOperand(0);
11006 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11007 Mask[InsertedIdx & (NumElts-1)] =
11008 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11012 if (VecOp == RHS) {
11013 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11014 // Everything but the extracted element is replaced with the RHS.
11015 for (unsigned i = 0; i != NumElts; ++i) {
11016 if (i != InsertedIdx)
11017 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11022 // If this insertelement is a chain that comes from exactly these two
11023 // vectors, return the vector and the effective shuffle.
11024 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11025 return EI->getOperand(0);
11030 // TODO: Handle shufflevector here!
11032 // Otherwise, can't do anything fancy. Return an identity vector.
11033 for (unsigned i = 0; i != NumElts; ++i)
11034 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11038 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11039 Value *VecOp = IE.getOperand(0);
11040 Value *ScalarOp = IE.getOperand(1);
11041 Value *IdxOp = IE.getOperand(2);
11043 // Inserting an undef or into an undefined place, remove this.
11044 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11045 ReplaceInstUsesWith(IE, VecOp);
11047 // If the inserted element was extracted from some other vector, and if the
11048 // indexes are constant, try to turn this into a shufflevector operation.
11049 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11050 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11051 EI->getOperand(0)->getType() == IE.getType()) {
11052 unsigned NumVectorElts = IE.getType()->getNumElements();
11053 unsigned ExtractedIdx =
11054 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11055 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11057 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11058 return ReplaceInstUsesWith(IE, VecOp);
11060 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11061 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11063 // If we are extracting a value from a vector, then inserting it right
11064 // back into the same place, just use the input vector.
11065 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11066 return ReplaceInstUsesWith(IE, VecOp);
11068 // We could theoretically do this for ANY input. However, doing so could
11069 // turn chains of insertelement instructions into a chain of shufflevector
11070 // instructions, and right now we do not merge shufflevectors. As such,
11071 // only do this in a situation where it is clear that there is benefit.
11072 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11073 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11074 // the values of VecOp, except then one read from EIOp0.
11075 // Build a new shuffle mask.
11076 std::vector<Constant*> Mask;
11077 if (isa<UndefValue>(VecOp))
11078 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11080 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11081 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11084 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11085 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11086 ConstantVector::get(Mask));
11089 // If this insertelement isn't used by some other insertelement, turn it
11090 // (and any insertelements it points to), into one big shuffle.
11091 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11092 std::vector<Constant*> Mask;
11094 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11095 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11096 // We now have a shuffle of LHS, RHS, Mask.
11097 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11106 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11107 Value *LHS = SVI.getOperand(0);
11108 Value *RHS = SVI.getOperand(1);
11109 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11111 bool MadeChange = false;
11113 // Undefined shuffle mask -> undefined value.
11114 if (isa<UndefValue>(SVI.getOperand(2)))
11115 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11117 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11118 // the undef, change them to undefs.
11119 if (isa<UndefValue>(SVI.getOperand(1))) {
11120 // Scan to see if there are any references to the RHS. If so, replace them
11121 // with undef element refs and set MadeChange to true.
11122 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11123 if (Mask[i] >= e && Mask[i] != 2*e) {
11130 // Remap any references to RHS to use LHS.
11131 std::vector<Constant*> Elts;
11132 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11133 if (Mask[i] == 2*e)
11134 Elts.push_back(UndefValue::get(Type::Int32Ty));
11136 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11138 SVI.setOperand(2, ConstantVector::get(Elts));
11142 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11143 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11144 if (LHS == RHS || isa<UndefValue>(LHS)) {
11145 if (isa<UndefValue>(LHS) && LHS == RHS) {
11146 // shuffle(undef,undef,mask) -> undef.
11147 return ReplaceInstUsesWith(SVI, LHS);
11150 // Remap any references to RHS to use LHS.
11151 std::vector<Constant*> Elts;
11152 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11153 if (Mask[i] >= 2*e)
11154 Elts.push_back(UndefValue::get(Type::Int32Ty));
11156 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11157 (Mask[i] < e && isa<UndefValue>(LHS)))
11158 Mask[i] = 2*e; // Turn into undef.
11160 Mask[i] &= (e-1); // Force to LHS.
11161 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11164 SVI.setOperand(0, SVI.getOperand(1));
11165 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11166 SVI.setOperand(2, ConstantVector::get(Elts));
11167 LHS = SVI.getOperand(0);
11168 RHS = SVI.getOperand(1);
11172 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11173 bool isLHSID = true, isRHSID = true;
11175 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11176 if (Mask[i] >= e*2) continue; // Ignore undef values.
11177 // Is this an identity shuffle of the LHS value?
11178 isLHSID &= (Mask[i] == i);
11180 // Is this an identity shuffle of the RHS value?
11181 isRHSID &= (Mask[i]-e == i);
11184 // Eliminate identity shuffles.
11185 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11186 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11188 // If the LHS is a shufflevector itself, see if we can combine it with this
11189 // one without producing an unusual shuffle. Here we are really conservative:
11190 // we are absolutely afraid of producing a shuffle mask not in the input
11191 // program, because the code gen may not be smart enough to turn a merged
11192 // shuffle into two specific shuffles: it may produce worse code. As such,
11193 // we only merge two shuffles if the result is one of the two input shuffle
11194 // masks. In this case, merging the shuffles just removes one instruction,
11195 // which we know is safe. This is good for things like turning:
11196 // (splat(splat)) -> splat.
11197 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11198 if (isa<UndefValue>(RHS)) {
11199 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11201 std::vector<unsigned> NewMask;
11202 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11203 if (Mask[i] >= 2*e)
11204 NewMask.push_back(2*e);
11206 NewMask.push_back(LHSMask[Mask[i]]);
11208 // If the result mask is equal to the src shuffle or this shuffle mask, do
11209 // the replacement.
11210 if (NewMask == LHSMask || NewMask == Mask) {
11211 std::vector<Constant*> Elts;
11212 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11213 if (NewMask[i] >= e*2) {
11214 Elts.push_back(UndefValue::get(Type::Int32Ty));
11216 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11219 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11220 LHSSVI->getOperand(1),
11221 ConstantVector::get(Elts));
11226 return MadeChange ? &SVI : 0;
11232 /// TryToSinkInstruction - Try to move the specified instruction from its
11233 /// current block into the beginning of DestBlock, which can only happen if it's
11234 /// safe to move the instruction past all of the instructions between it and the
11235 /// end of its block.
11236 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11237 assert(I->hasOneUse() && "Invariants didn't hold!");
11239 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11240 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11243 // Do not sink alloca instructions out of the entry block.
11244 if (isa<AllocaInst>(I) && I->getParent() ==
11245 &DestBlock->getParent()->getEntryBlock())
11248 // We can only sink load instructions if there is nothing between the load and
11249 // the end of block that could change the value.
11250 if (I->mayReadFromMemory()) {
11251 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11253 if (Scan->mayWriteToMemory())
11257 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11259 I->moveBefore(InsertPos);
11265 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11266 /// all reachable code to the worklist.
11268 /// This has a couple of tricks to make the code faster and more powerful. In
11269 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11270 /// them to the worklist (this significantly speeds up instcombine on code where
11271 /// many instructions are dead or constant). Additionally, if we find a branch
11272 /// whose condition is a known constant, we only visit the reachable successors.
11274 static void AddReachableCodeToWorklist(BasicBlock *BB,
11275 SmallPtrSet<BasicBlock*, 64> &Visited,
11277 const TargetData *TD) {
11278 std::vector<BasicBlock*> Worklist;
11279 Worklist.push_back(BB);
11281 while (!Worklist.empty()) {
11282 BB = Worklist.back();
11283 Worklist.pop_back();
11285 // We have now visited this block! If we've already been here, ignore it.
11286 if (!Visited.insert(BB)) continue;
11288 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11289 Instruction *Inst = BBI++;
11291 // DCE instruction if trivially dead.
11292 if (isInstructionTriviallyDead(Inst)) {
11294 DOUT << "IC: DCE: " << *Inst;
11295 Inst->eraseFromParent();
11299 // ConstantProp instruction if trivially constant.
11300 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11301 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11302 Inst->replaceAllUsesWith(C);
11304 Inst->eraseFromParent();
11308 IC.AddToWorkList(Inst);
11311 // Recursively visit successors. If this is a branch or switch on a
11312 // constant, only visit the reachable successor.
11313 TerminatorInst *TI = BB->getTerminator();
11314 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11315 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11316 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11317 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11318 Worklist.push_back(ReachableBB);
11321 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11322 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11323 // See if this is an explicit destination.
11324 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11325 if (SI->getCaseValue(i) == Cond) {
11326 BasicBlock *ReachableBB = SI->getSuccessor(i);
11327 Worklist.push_back(ReachableBB);
11331 // Otherwise it is the default destination.
11332 Worklist.push_back(SI->getSuccessor(0));
11337 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11338 Worklist.push_back(TI->getSuccessor(i));
11342 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11343 bool Changed = false;
11344 TD = &getAnalysis<TargetData>();
11346 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11347 << F.getNameStr() << "\n");
11350 // Do a depth-first traversal of the function, populate the worklist with
11351 // the reachable instructions. Ignore blocks that are not reachable. Keep
11352 // track of which blocks we visit.
11353 SmallPtrSet<BasicBlock*, 64> Visited;
11354 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11356 // Do a quick scan over the function. If we find any blocks that are
11357 // unreachable, remove any instructions inside of them. This prevents
11358 // the instcombine code from having to deal with some bad special cases.
11359 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11360 if (!Visited.count(BB)) {
11361 Instruction *Term = BB->getTerminator();
11362 while (Term != BB->begin()) { // Remove instrs bottom-up
11363 BasicBlock::iterator I = Term; --I;
11365 DOUT << "IC: DCE: " << *I;
11368 if (!I->use_empty())
11369 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11370 I->eraseFromParent();
11375 while (!Worklist.empty()) {
11376 Instruction *I = RemoveOneFromWorkList();
11377 if (I == 0) continue; // skip null values.
11379 // Check to see if we can DCE the instruction.
11380 if (isInstructionTriviallyDead(I)) {
11381 // Add operands to the worklist.
11382 if (I->getNumOperands() < 4)
11383 AddUsesToWorkList(*I);
11386 DOUT << "IC: DCE: " << *I;
11388 I->eraseFromParent();
11389 RemoveFromWorkList(I);
11393 // Instruction isn't dead, see if we can constant propagate it.
11394 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11395 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11397 // Add operands to the worklist.
11398 AddUsesToWorkList(*I);
11399 ReplaceInstUsesWith(*I, C);
11402 I->eraseFromParent();
11403 RemoveFromWorkList(I);
11407 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11408 // See if we can constant fold its operands.
11409 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11411 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11417 // See if we can trivially sink this instruction to a successor basic block.
11418 // FIXME: Remove GetResultInst test when first class support for aggregates
11420 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11421 BasicBlock *BB = I->getParent();
11422 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11423 if (UserParent != BB) {
11424 bool UserIsSuccessor = false;
11425 // See if the user is one of our successors.
11426 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11427 if (*SI == UserParent) {
11428 UserIsSuccessor = true;
11432 // If the user is one of our immediate successors, and if that successor
11433 // only has us as a predecessors (we'd have to split the critical edge
11434 // otherwise), we can keep going.
11435 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11436 next(pred_begin(UserParent)) == pred_end(UserParent))
11437 // Okay, the CFG is simple enough, try to sink this instruction.
11438 Changed |= TryToSinkInstruction(I, UserParent);
11442 // Now that we have an instruction, try combining it to simplify it...
11446 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11447 if (Instruction *Result = visit(*I)) {
11449 // Should we replace the old instruction with a new one?
11451 DOUT << "IC: Old = " << *I
11452 << " New = " << *Result;
11454 // Everything uses the new instruction now.
11455 I->replaceAllUsesWith(Result);
11457 // Push the new instruction and any users onto the worklist.
11458 AddToWorkList(Result);
11459 AddUsersToWorkList(*Result);
11461 // Move the name to the new instruction first.
11462 Result->takeName(I);
11464 // Insert the new instruction into the basic block...
11465 BasicBlock *InstParent = I->getParent();
11466 BasicBlock::iterator InsertPos = I;
11468 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11469 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11472 InstParent->getInstList().insert(InsertPos, Result);
11474 // Make sure that we reprocess all operands now that we reduced their
11476 AddUsesToWorkList(*I);
11478 // Instructions can end up on the worklist more than once. Make sure
11479 // we do not process an instruction that has been deleted.
11480 RemoveFromWorkList(I);
11482 // Erase the old instruction.
11483 InstParent->getInstList().erase(I);
11486 DOUT << "IC: Mod = " << OrigI
11487 << " New = " << *I;
11490 // If the instruction was modified, it's possible that it is now dead.
11491 // if so, remove it.
11492 if (isInstructionTriviallyDead(I)) {
11493 // Make sure we process all operands now that we are reducing their
11495 AddUsesToWorkList(*I);
11497 // Instructions may end up in the worklist more than once. Erase all
11498 // occurrences of this instruction.
11499 RemoveFromWorkList(I);
11500 I->eraseFromParent();
11503 AddUsersToWorkList(*I);
11510 assert(WorklistMap.empty() && "Worklist empty, but map not?");
11512 // Do an explicit clear, this shrinks the map if needed.
11513 WorklistMap.clear();
11518 bool InstCombiner::runOnFunction(Function &F) {
11519 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11521 bool EverMadeChange = false;
11523 // Iterate while there is work to do.
11524 unsigned Iteration = 0;
11525 while (DoOneIteration(F, Iteration++))
11526 EverMadeChange = true;
11527 return EverMadeChange;
11530 FunctionPass *llvm::createInstructionCombiningPass() {
11531 return new InstCombiner();