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 SmallVector<Instruction*, 256> 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())).second)
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 bool SimplifyDivRemOfSelect(BinaryOperator &I);
176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
183 Instruction *visitAnd(BinaryOperator &I);
184 Instruction *visitOr (BinaryOperator &I);
185 Instruction *visitXor(BinaryOperator &I);
186 Instruction *visitShl(BinaryOperator &I);
187 Instruction *visitAShr(BinaryOperator &I);
188 Instruction *visitLShr(BinaryOperator &I);
189 Instruction *commonShiftTransforms(BinaryOperator &I);
190 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
192 Instruction *visitFCmpInst(FCmpInst &I);
193 Instruction *visitICmpInst(ICmpInst &I);
194 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
195 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
198 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
199 ConstantInt *DivRHS);
201 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
202 ICmpInst::Predicate Cond, Instruction &I);
203 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
205 Instruction *commonCastTransforms(CastInst &CI);
206 Instruction *commonIntCastTransforms(CastInst &CI);
207 Instruction *commonPointerCastTransforms(CastInst &CI);
208 Instruction *visitTrunc(TruncInst &CI);
209 Instruction *visitZExt(ZExtInst &CI);
210 Instruction *visitSExt(SExtInst &CI);
211 Instruction *visitFPTrunc(FPTruncInst &CI);
212 Instruction *visitFPExt(CastInst &CI);
213 Instruction *visitFPToUI(FPToUIInst &FI);
214 Instruction *visitFPToSI(FPToSIInst &FI);
215 Instruction *visitUIToFP(CastInst &CI);
216 Instruction *visitSIToFP(CastInst &CI);
217 Instruction *visitPtrToInt(CastInst &CI);
218 Instruction *visitIntToPtr(IntToPtrInst &CI);
219 Instruction *visitBitCast(BitCastInst &CI);
220 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
222 Instruction *visitSelectInst(SelectInst &CI);
223 Instruction *visitCallInst(CallInst &CI);
224 Instruction *visitInvokeInst(InvokeInst &II);
225 Instruction *visitPHINode(PHINode &PN);
226 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
227 Instruction *visitAllocationInst(AllocationInst &AI);
228 Instruction *visitFreeInst(FreeInst &FI);
229 Instruction *visitLoadInst(LoadInst &LI);
230 Instruction *visitStoreInst(StoreInst &SI);
231 Instruction *visitBranchInst(BranchInst &BI);
232 Instruction *visitSwitchInst(SwitchInst &SI);
233 Instruction *visitInsertElementInst(InsertElementInst &IE);
234 Instruction *visitExtractElementInst(ExtractElementInst &EI);
235 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
236 Instruction *visitExtractValueInst(ExtractValueInst &EV);
238 // visitInstruction - Specify what to return for unhandled instructions...
239 Instruction *visitInstruction(Instruction &I) { return 0; }
242 Instruction *visitCallSite(CallSite CS);
243 bool transformConstExprCastCall(CallSite CS);
244 Instruction *transformCallThroughTrampoline(CallSite CS);
245 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
246 bool DoXform = true);
247 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
250 // InsertNewInstBefore - insert an instruction New before instruction Old
251 // in the program. Add the new instruction to the worklist.
253 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
254 assert(New && New->getParent() == 0 &&
255 "New instruction already inserted into a basic block!");
256 BasicBlock *BB = Old.getParent();
257 BB->getInstList().insert(&Old, New); // Insert inst
262 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
263 /// This also adds the cast to the worklist. Finally, this returns the
265 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
267 if (V->getType() == Ty) return V;
269 if (Constant *CV = dyn_cast<Constant>(V))
270 return ConstantExpr::getCast(opc, CV, Ty);
272 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
277 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
278 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
282 // ReplaceInstUsesWith - This method is to be used when an instruction is
283 // found to be dead, replacable with another preexisting expression. Here
284 // we add all uses of I to the worklist, replace all uses of I with the new
285 // value, then return I, so that the inst combiner will know that I was
288 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
289 AddUsersToWorkList(I); // Add all modified instrs to worklist
291 I.replaceAllUsesWith(V);
294 // If we are replacing the instruction with itself, this must be in a
295 // segment of unreachable code, so just clobber the instruction.
296 I.replaceAllUsesWith(UndefValue::get(I.getType()));
301 // UpdateValueUsesWith - This method is to be used when an value is
302 // found to be replacable with another preexisting expression or was
303 // updated. Here we add all uses of I to the worklist, replace all uses of
304 // I with the new value (unless the instruction was just updated), then
305 // return true, so that the inst combiner will know that I was modified.
307 bool UpdateValueUsesWith(Value *Old, Value *New) {
308 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
310 Old->replaceAllUsesWith(New);
311 if (Instruction *I = dyn_cast<Instruction>(Old))
313 if (Instruction *I = dyn_cast<Instruction>(New))
318 // EraseInstFromFunction - When dealing with an instruction that has side
319 // effects or produces a void value, we can't rely on DCE to delete the
320 // instruction. Instead, visit methods should return the value returned by
322 Instruction *EraseInstFromFunction(Instruction &I) {
323 assert(I.use_empty() && "Cannot erase instruction that is used!");
324 AddUsesToWorkList(I);
325 RemoveFromWorkList(&I);
327 return 0; // Don't do anything with FI
330 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
331 APInt &KnownOne, unsigned Depth = 0) const {
332 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 bool MaskedValueIsZero(Value *V, const APInt &Mask,
336 unsigned Depth = 0) const {
337 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
339 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
340 return llvm::ComputeNumSignBits(Op, TD, Depth);
344 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
345 /// InsertBefore instruction. This is specialized a bit to avoid inserting
346 /// casts that are known to not do anything...
348 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
349 Value *V, const Type *DestTy,
350 Instruction *InsertBefore);
352 /// SimplifyCommutative - This performs a few simplifications for
353 /// commutative operators.
354 bool SimplifyCommutative(BinaryOperator &I);
356 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
357 /// most-complex to least-complex order.
358 bool SimplifyCompare(CmpInst &I);
360 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
361 /// on the demanded bits.
362 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
363 APInt& KnownZero, APInt& KnownOne,
366 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
367 uint64_t &UndefElts, unsigned Depth = 0);
369 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370 // PHI node as operand #0, see if we can fold the instruction into the PHI
371 // (which is only possible if all operands to the PHI are constants).
372 Instruction *FoldOpIntoPhi(Instruction &I);
374 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375 // operator and they all are only used by the PHI, PHI together their
376 // inputs, and do the operation once, to the result of the PHI.
377 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
378 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385 bool isSub, Instruction &I);
386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387 bool isSigned, bool Inside, Instruction &IB);
388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389 Instruction *MatchBSwap(BinaryOperator &I);
390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
392 Instruction *SimplifyMemSet(MemSetInst *MI);
395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
397 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
399 int &NumCastsRemoved);
400 unsigned GetOrEnforceKnownAlignment(Value *V,
401 unsigned PrefAlign = 0);
406 char InstCombiner::ID = 0;
407 static RegisterPass<InstCombiner>
408 X("instcombine", "Combine redundant instructions");
410 // getComplexity: Assign a complexity or rank value to LLVM Values...
411 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
412 static unsigned getComplexity(Value *V) {
413 if (isa<Instruction>(V)) {
414 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
418 if (isa<Argument>(V)) return 3;
419 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
422 // isOnlyUse - Return true if this instruction will be deleted if we stop using
424 static bool isOnlyUse(Value *V) {
425 return V->hasOneUse() || isa<Constant>(V);
428 // getPromotedType - Return the specified type promoted as it would be to pass
429 // though a va_arg area...
430 static const Type *getPromotedType(const Type *Ty) {
431 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
432 if (ITy->getBitWidth() < 32)
433 return Type::Int32Ty;
438 /// getBitCastOperand - If the specified operand is a CastInst or a constant
439 /// expression bitcast, return the operand value, otherwise return null.
440 static Value *getBitCastOperand(Value *V) {
441 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
442 return I->getOperand(0);
443 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
444 if (CE->getOpcode() == Instruction::BitCast)
445 return CE->getOperand(0);
449 /// This function is a wrapper around CastInst::isEliminableCastPair. It
450 /// simply extracts arguments and returns what that function returns.
451 static Instruction::CastOps
452 isEliminableCastPair(
453 const CastInst *CI, ///< The first cast instruction
454 unsigned opcode, ///< The opcode of the second cast instruction
455 const Type *DstTy, ///< The target type for the second cast instruction
456 TargetData *TD ///< The target data for pointer size
459 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
460 const Type *MidTy = CI->getType(); // B from above
462 // Get the opcodes of the two Cast instructions
463 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
464 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
466 return Instruction::CastOps(
467 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
468 DstTy, TD->getIntPtrType()));
471 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
472 /// in any code being generated. It does not require codegen if V is simple
473 /// enough or if the cast can be folded into other casts.
474 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
475 const Type *Ty, TargetData *TD) {
476 if (V->getType() == Ty || isa<Constant>(V)) return false;
478 // If this is another cast that can be eliminated, it isn't codegen either.
479 if (const CastInst *CI = dyn_cast<CastInst>(V))
480 if (isEliminableCastPair(CI, opcode, Ty, TD))
485 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
486 /// InsertBefore instruction. This is specialized a bit to avoid inserting
487 /// casts that are known to not do anything...
489 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
490 Value *V, const Type *DestTy,
491 Instruction *InsertBefore) {
492 if (V->getType() == DestTy) return V;
493 if (Constant *C = dyn_cast<Constant>(V))
494 return ConstantExpr::getCast(opcode, C, DestTy);
496 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
499 // SimplifyCommutative - This performs a few simplifications for commutative
502 // 1. Order operands such that they are listed from right (least complex) to
503 // left (most complex). This puts constants before unary operators before
506 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
507 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
509 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
510 bool Changed = false;
511 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
512 Changed = !I.swapOperands();
514 if (!I.isAssociative()) return Changed;
515 Instruction::BinaryOps Opcode = I.getOpcode();
516 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
517 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
518 if (isa<Constant>(I.getOperand(1))) {
519 Constant *Folded = ConstantExpr::get(I.getOpcode(),
520 cast<Constant>(I.getOperand(1)),
521 cast<Constant>(Op->getOperand(1)));
522 I.setOperand(0, Op->getOperand(0));
523 I.setOperand(1, Folded);
525 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
526 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
527 isOnlyUse(Op) && isOnlyUse(Op1)) {
528 Constant *C1 = cast<Constant>(Op->getOperand(1));
529 Constant *C2 = cast<Constant>(Op1->getOperand(1));
531 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
532 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
533 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
537 I.setOperand(0, New);
538 I.setOperand(1, Folded);
545 /// SimplifyCompare - For a CmpInst this function just orders the operands
546 /// so that theyare listed from right (least complex) to left (most complex).
547 /// This puts constants before unary operators before binary operators.
548 bool InstCombiner::SimplifyCompare(CmpInst &I) {
549 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
552 // Compare instructions are not associative so there's nothing else we can do.
556 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557 // if the LHS is a constant zero (which is the 'negate' form).
559 static inline Value *dyn_castNegVal(Value *V) {
560 if (BinaryOperator::isNeg(V))
561 return BinaryOperator::getNegArgument(V);
563 // Constants can be considered to be negated values if they can be folded.
564 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
565 return ConstantExpr::getNeg(C);
567 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568 if (C->getType()->getElementType()->isInteger())
569 return ConstantExpr::getNeg(C);
574 static inline Value *dyn_castNotVal(Value *V) {
575 if (BinaryOperator::isNot(V))
576 return BinaryOperator::getNotArgument(V);
578 // Constants can be considered to be not'ed values...
579 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
580 return ConstantInt::get(~C->getValue());
584 // dyn_castFoldableMul - If this value is a multiply that can be folded into
585 // other computations (because it has a constant operand), return the
586 // non-constant operand of the multiply, and set CST to point to the multiplier.
587 // Otherwise, return null.
589 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
590 if (V->hasOneUse() && V->getType()->isInteger())
591 if (Instruction *I = dyn_cast<Instruction>(V)) {
592 if (I->getOpcode() == Instruction::Mul)
593 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
594 return I->getOperand(0);
595 if (I->getOpcode() == Instruction::Shl)
596 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
597 // The multiplier is really 1 << CST.
598 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
599 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
600 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
601 return I->getOperand(0);
607 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
608 /// expression, return it.
609 static User *dyn_castGetElementPtr(Value *V) {
610 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
611 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
612 if (CE->getOpcode() == Instruction::GetElementPtr)
613 return cast<User>(V);
617 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
618 /// opcode value. Otherwise return UserOp1.
619 static unsigned getOpcode(const Value *V) {
620 if (const Instruction *I = dyn_cast<Instruction>(V))
621 return I->getOpcode();
622 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
623 return CE->getOpcode();
624 // Use UserOp1 to mean there's no opcode.
625 return Instruction::UserOp1;
628 /// AddOne - Add one to a ConstantInt
629 static ConstantInt *AddOne(ConstantInt *C) {
630 APInt Val(C->getValue());
631 return ConstantInt::get(++Val);
633 /// SubOne - Subtract one from a ConstantInt
634 static ConstantInt *SubOne(ConstantInt *C) {
635 APInt Val(C->getValue());
636 return ConstantInt::get(--Val);
638 /// Add - Add two ConstantInts together
639 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
640 return ConstantInt::get(C1->getValue() + C2->getValue());
642 /// And - Bitwise AND two ConstantInts together
643 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() & C2->getValue());
646 /// Subtract - Subtract one ConstantInt from another
647 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
648 return ConstantInt::get(C1->getValue() - C2->getValue());
650 /// Multiply - Multiply two ConstantInts together
651 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
652 return ConstantInt::get(C1->getValue() * C2->getValue());
654 /// MultiplyOverflows - True if the multiply can not be expressed in an int
656 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
657 uint32_t W = C1->getBitWidth();
658 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
667 APInt MulExt = LHSExt * RHSExt;
670 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
671 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
672 return MulExt.slt(Min) || MulExt.sgt(Max);
674 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
678 /// ShrinkDemandedConstant - Check to see if the specified operand of the
679 /// specified instruction is a constant integer. If so, check to see if there
680 /// are any bits set in the constant that are not demanded. If so, shrink the
681 /// constant and return true.
682 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
684 assert(I && "No instruction?");
685 assert(OpNo < I->getNumOperands() && "Operand index too large");
687 // If the operand is not a constant integer, nothing to do.
688 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
689 if (!OpC) return false;
691 // If there are no bits set that aren't demanded, nothing to do.
692 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
693 if ((~Demanded & OpC->getValue()) == 0)
696 // This instruction is producing bits that are not demanded. Shrink the RHS.
697 Demanded &= OpC->getValue();
698 I->setOperand(OpNo, ConstantInt::get(Demanded));
702 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
703 // set of known zero and one bits, compute the maximum and minimum values that
704 // could have the specified known zero and known one bits, returning them in
706 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
707 const APInt& KnownZero,
708 const APInt& KnownOne,
709 APInt& Min, APInt& Max) {
710 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
711 assert(KnownZero.getBitWidth() == BitWidth &&
712 KnownOne.getBitWidth() == BitWidth &&
713 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
714 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
715 APInt UnknownBits = ~(KnownZero|KnownOne);
717 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
718 // bit if it is unknown.
720 Max = KnownOne|UnknownBits;
722 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
724 Max.clear(BitWidth-1);
728 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
729 // a set of known zero and one bits, compute the maximum and minimum values that
730 // could have the specified known zero and known one bits, returning them in
732 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
733 const APInt &KnownZero,
734 const APInt &KnownOne,
735 APInt &Min, APInt &Max) {
736 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
737 assert(KnownZero.getBitWidth() == BitWidth &&
738 KnownOne.getBitWidth() == BitWidth &&
739 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
740 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
741 APInt UnknownBits = ~(KnownZero|KnownOne);
743 // The minimum value is when the unknown bits are all zeros.
745 // The maximum value is when the unknown bits are all ones.
746 Max = KnownOne|UnknownBits;
749 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
750 /// value based on the demanded bits. When this function is called, it is known
751 /// that only the bits set in DemandedMask of the result of V are ever used
752 /// downstream. Consequently, depending on the mask and V, it may be possible
753 /// to replace V with a constant or one of its operands. In such cases, this
754 /// function does the replacement and returns true. In all other cases, it
755 /// returns false after analyzing the expression and setting KnownOne and known
756 /// to be one in the expression. KnownZero contains all the bits that are known
757 /// to be zero in the expression. These are provided to potentially allow the
758 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
759 /// the expression. KnownOne and KnownZero always follow the invariant that
760 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
761 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
762 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
763 /// and KnownOne must all be the same.
764 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
765 APInt& KnownZero, APInt& KnownOne,
767 assert(V != 0 && "Null pointer of Value???");
768 assert(Depth <= 6 && "Limit Search Depth");
769 uint32_t BitWidth = DemandedMask.getBitWidth();
770 const IntegerType *VTy = cast<IntegerType>(V->getType());
771 assert(VTy->getBitWidth() == BitWidth &&
772 KnownZero.getBitWidth() == BitWidth &&
773 KnownOne.getBitWidth() == BitWidth &&
774 "Value *V, DemandedMask, KnownZero and KnownOne \
775 must have same BitWidth");
776 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
777 // We know all of the bits for a constant!
778 KnownOne = CI->getValue() & DemandedMask;
779 KnownZero = ~KnownOne & DemandedMask;
785 if (!V->hasOneUse()) { // Other users may use these bits.
786 if (Depth != 0) { // Not at the root.
787 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
788 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
791 // If this is the root being simplified, allow it to have multiple uses,
792 // just set the DemandedMask to all bits.
793 DemandedMask = APInt::getAllOnesValue(BitWidth);
794 } else if (DemandedMask == 0) { // Not demanding any bits from V.
795 if (V != UndefValue::get(VTy))
796 return UpdateValueUsesWith(V, UndefValue::get(VTy));
798 } else if (Depth == 6) { // Limit search depth.
802 Instruction *I = dyn_cast<Instruction>(V);
803 if (!I) return false; // Only analyze instructions.
805 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
806 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
807 switch (I->getOpcode()) {
809 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
811 case Instruction::And:
812 // If either the LHS or the RHS are Zero, the result is zero.
813 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
814 RHSKnownZero, RHSKnownOne, Depth+1))
816 assert((RHSKnownZero & RHSKnownOne) == 0 &&
817 "Bits known to be one AND zero?");
819 // If something is known zero on the RHS, the bits aren't demanded on the
821 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
822 LHSKnownZero, LHSKnownOne, Depth+1))
824 assert((LHSKnownZero & LHSKnownOne) == 0 &&
825 "Bits known to be one AND zero?");
827 // If all of the demanded bits are known 1 on one side, return the other.
828 // These bits cannot contribute to the result of the 'and'.
829 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
830 (DemandedMask & ~LHSKnownZero))
831 return UpdateValueUsesWith(I, I->getOperand(0));
832 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
833 (DemandedMask & ~RHSKnownZero))
834 return UpdateValueUsesWith(I, I->getOperand(1));
836 // If all of the demanded bits in the inputs are known zeros, return zero.
837 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
838 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
840 // If the RHS is a constant, see if we can simplify it.
841 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
842 return UpdateValueUsesWith(I, I);
844 // Output known-1 bits are only known if set in both the LHS & RHS.
845 RHSKnownOne &= LHSKnownOne;
846 // Output known-0 are known to be clear if zero in either the LHS | RHS.
847 RHSKnownZero |= LHSKnownZero;
849 case Instruction::Or:
850 // If either the LHS or the RHS are One, the result is One.
851 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
852 RHSKnownZero, RHSKnownOne, Depth+1))
854 assert((RHSKnownZero & RHSKnownOne) == 0 &&
855 "Bits known to be one AND zero?");
856 // If something is known one on the RHS, the bits aren't demanded on the
858 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
859 LHSKnownZero, LHSKnownOne, Depth+1))
861 assert((LHSKnownZero & LHSKnownOne) == 0 &&
862 "Bits known to be one AND zero?");
864 // If all of the demanded bits are known zero on one side, return the other.
865 // These bits cannot contribute to the result of the 'or'.
866 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
867 (DemandedMask & ~LHSKnownOne))
868 return UpdateValueUsesWith(I, I->getOperand(0));
869 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
870 (DemandedMask & ~RHSKnownOne))
871 return UpdateValueUsesWith(I, I->getOperand(1));
873 // If all of the potentially set bits on one side are known to be set on
874 // the other side, just use the 'other' side.
875 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
876 (DemandedMask & (~RHSKnownZero)))
877 return UpdateValueUsesWith(I, I->getOperand(0));
878 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
879 (DemandedMask & (~LHSKnownZero)))
880 return UpdateValueUsesWith(I, I->getOperand(1));
882 // If the RHS is a constant, see if we can simplify it.
883 if (ShrinkDemandedConstant(I, 1, DemandedMask))
884 return UpdateValueUsesWith(I, I);
886 // Output known-0 bits are only known if clear in both the LHS & RHS.
887 RHSKnownZero &= LHSKnownZero;
888 // Output known-1 are known to be set if set in either the LHS | RHS.
889 RHSKnownOne |= LHSKnownOne;
891 case Instruction::Xor: {
892 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
893 RHSKnownZero, RHSKnownOne, Depth+1))
895 assert((RHSKnownZero & RHSKnownOne) == 0 &&
896 "Bits known to be one AND zero?");
897 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
898 LHSKnownZero, LHSKnownOne, Depth+1))
900 assert((LHSKnownZero & LHSKnownOne) == 0 &&
901 "Bits known to be one AND zero?");
903 // If all of the demanded bits are known zero on one side, return the other.
904 // These bits cannot contribute to the result of the 'xor'.
905 if ((DemandedMask & RHSKnownZero) == DemandedMask)
906 return UpdateValueUsesWith(I, I->getOperand(0));
907 if ((DemandedMask & LHSKnownZero) == DemandedMask)
908 return UpdateValueUsesWith(I, I->getOperand(1));
910 // Output known-0 bits are known if clear or set in both the LHS & RHS.
911 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
912 (RHSKnownOne & LHSKnownOne);
913 // Output known-1 are known to be set if set in only one of the LHS, RHS.
914 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
915 (RHSKnownOne & LHSKnownZero);
917 // If all of the demanded bits are known to be zero on one side or the
918 // other, turn this into an *inclusive* or.
919 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
920 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
922 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
924 InsertNewInstBefore(Or, *I);
925 return UpdateValueUsesWith(I, Or);
928 // If all of the demanded bits on one side are known, and all of the set
929 // bits on that side are also known to be set on the other side, turn this
930 // into an AND, as we know the bits will be cleared.
931 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
932 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
934 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
935 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
937 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
938 InsertNewInstBefore(And, *I);
939 return UpdateValueUsesWith(I, And);
943 // If the RHS is a constant, see if we can simplify it.
944 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
945 if (ShrinkDemandedConstant(I, 1, DemandedMask))
946 return UpdateValueUsesWith(I, I);
948 RHSKnownZero = KnownZeroOut;
949 RHSKnownOne = KnownOneOut;
952 case Instruction::Select:
953 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
954 RHSKnownZero, RHSKnownOne, Depth+1))
956 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
957 LHSKnownZero, LHSKnownOne, Depth+1))
959 assert((RHSKnownZero & RHSKnownOne) == 0 &&
960 "Bits known to be one AND zero?");
961 assert((LHSKnownZero & LHSKnownOne) == 0 &&
962 "Bits known to be one AND zero?");
964 // If the operands are constants, see if we can simplify them.
965 if (ShrinkDemandedConstant(I, 1, DemandedMask))
966 return UpdateValueUsesWith(I, I);
967 if (ShrinkDemandedConstant(I, 2, DemandedMask))
968 return UpdateValueUsesWith(I, I);
970 // Only known if known in both the LHS and RHS.
971 RHSKnownOne &= LHSKnownOne;
972 RHSKnownZero &= LHSKnownZero;
974 case Instruction::Trunc: {
976 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
977 DemandedMask.zext(truncBf);
978 RHSKnownZero.zext(truncBf);
979 RHSKnownOne.zext(truncBf);
980 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
981 RHSKnownZero, RHSKnownOne, Depth+1))
983 DemandedMask.trunc(BitWidth);
984 RHSKnownZero.trunc(BitWidth);
985 RHSKnownOne.trunc(BitWidth);
986 assert((RHSKnownZero & RHSKnownOne) == 0 &&
987 "Bits known to be one AND zero?");
990 case Instruction::BitCast:
991 if (!I->getOperand(0)->getType()->isInteger())
994 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
995 RHSKnownZero, RHSKnownOne, Depth+1))
997 assert((RHSKnownZero & RHSKnownOne) == 0 &&
998 "Bits known to be one AND zero?");
1000 case Instruction::ZExt: {
1001 // Compute the bits in the result that are not present in the input.
1002 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1003 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1005 DemandedMask.trunc(SrcBitWidth);
1006 RHSKnownZero.trunc(SrcBitWidth);
1007 RHSKnownOne.trunc(SrcBitWidth);
1008 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009 RHSKnownZero, RHSKnownOne, Depth+1))
1011 DemandedMask.zext(BitWidth);
1012 RHSKnownZero.zext(BitWidth);
1013 RHSKnownOne.zext(BitWidth);
1014 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1015 "Bits known to be one AND zero?");
1016 // The top bits are known to be zero.
1017 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1020 case Instruction::SExt: {
1021 // Compute the bits in the result that are not present in the input.
1022 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1023 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1025 APInt InputDemandedBits = DemandedMask &
1026 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1028 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1029 // If any of the sign extended bits are demanded, we know that the sign
1031 if ((NewBits & DemandedMask) != 0)
1032 InputDemandedBits.set(SrcBitWidth-1);
1034 InputDemandedBits.trunc(SrcBitWidth);
1035 RHSKnownZero.trunc(SrcBitWidth);
1036 RHSKnownOne.trunc(SrcBitWidth);
1037 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1038 RHSKnownZero, RHSKnownOne, Depth+1))
1040 InputDemandedBits.zext(BitWidth);
1041 RHSKnownZero.zext(BitWidth);
1042 RHSKnownOne.zext(BitWidth);
1043 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1044 "Bits known to be one AND zero?");
1046 // If the sign bit of the input is known set or clear, then we know the
1047 // top bits of the result.
1049 // If the input sign bit is known zero, or if the NewBits are not demanded
1050 // convert this into a zero extension.
1051 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1053 // Convert to ZExt cast
1054 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1055 return UpdateValueUsesWith(I, NewCast);
1056 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1057 RHSKnownOne |= NewBits;
1061 case Instruction::Add: {
1062 // Figure out what the input bits are. If the top bits of the and result
1063 // are not demanded, then the add doesn't demand them from its input
1065 uint32_t NLZ = DemandedMask.countLeadingZeros();
1067 // If there is a constant on the RHS, there are a variety of xformations
1069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070 // If null, this should be simplified elsewhere. Some of the xforms here
1071 // won't work if the RHS is zero.
1075 // If the top bit of the output is demanded, demand everything from the
1076 // input. Otherwise, we demand all the input bits except NLZ top bits.
1077 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1079 // Find information about known zero/one bits in the input.
1080 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1081 LHSKnownZero, LHSKnownOne, Depth+1))
1084 // If the RHS of the add has bits set that can't affect the input, reduce
1086 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1087 return UpdateValueUsesWith(I, I);
1089 // Avoid excess work.
1090 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1093 // Turn it into OR if input bits are zero.
1094 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1096 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1098 InsertNewInstBefore(Or, *I);
1099 return UpdateValueUsesWith(I, Or);
1102 // We can say something about the output known-zero and known-one bits,
1103 // depending on potential carries from the input constant and the
1104 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1105 // bits set and the RHS constant is 0x01001, then we know we have a known
1106 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1108 // To compute this, we first compute the potential carry bits. These are
1109 // the bits which may be modified. I'm not aware of a better way to do
1111 const APInt& RHSVal = RHS->getValue();
1112 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1114 // Now that we know which bits have carries, compute the known-1/0 sets.
1116 // Bits are known one if they are known zero in one operand and one in the
1117 // other, and there is no input carry.
1118 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1119 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1121 // Bits are known zero if they are known zero in both operands and there
1122 // is no input carry.
1123 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1125 // If the high-bits of this ADD are not demanded, then it does not demand
1126 // the high bits of its LHS or RHS.
1127 if (DemandedMask[BitWidth-1] == 0) {
1128 // Right fill the mask of bits for this ADD to demand the most
1129 // significant bit and all those below it.
1130 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1131 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1132 LHSKnownZero, LHSKnownOne, Depth+1))
1134 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1135 LHSKnownZero, LHSKnownOne, Depth+1))
1141 case Instruction::Sub:
1142 // If the high-bits of this SUB are not demanded, then it does not demand
1143 // the high bits of its LHS or RHS.
1144 if (DemandedMask[BitWidth-1] == 0) {
1145 // Right fill the mask of bits for this SUB to demand the most
1146 // significant bit and all those below it.
1147 uint32_t NLZ = DemandedMask.countLeadingZeros();
1148 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1149 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1150 LHSKnownZero, LHSKnownOne, Depth+1))
1152 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1153 LHSKnownZero, LHSKnownOne, Depth+1))
1156 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1157 // the known zeros and ones.
1158 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1160 case Instruction::Shl:
1161 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1162 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1163 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1164 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1165 RHSKnownZero, RHSKnownOne, Depth+1))
1167 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1168 "Bits known to be one AND zero?");
1169 RHSKnownZero <<= ShiftAmt;
1170 RHSKnownOne <<= ShiftAmt;
1171 // low bits known zero.
1173 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1176 case Instruction::LShr:
1177 // For a logical shift right
1178 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1179 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1181 // Unsigned shift right.
1182 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1183 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1184 RHSKnownZero, RHSKnownOne, Depth+1))
1186 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1187 "Bits known to be one AND zero?");
1188 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1189 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1191 // Compute the new bits that are at the top now.
1192 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1193 RHSKnownZero |= HighBits; // high bits known zero.
1197 case Instruction::AShr:
1198 // If this is an arithmetic shift right and only the low-bit is set, we can
1199 // always convert this into a logical shr, even if the shift amount is
1200 // variable. The low bit of the shift cannot be an input sign bit unless
1201 // the shift amount is >= the size of the datatype, which is undefined.
1202 if (DemandedMask == 1) {
1203 // Perform the logical shift right.
1204 Value *NewVal = BinaryOperator::CreateLShr(
1205 I->getOperand(0), I->getOperand(1), I->getName());
1206 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1207 return UpdateValueUsesWith(I, NewVal);
1210 // If the sign bit is the only bit demanded by this ashr, then there is no
1211 // need to do it, the shift doesn't change the high bit.
1212 if (DemandedMask.isSignBit())
1213 return UpdateValueUsesWith(I, I->getOperand(0));
1215 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1216 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1218 // Signed shift right.
1219 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1220 // If any of the "high bits" are demanded, we should set the sign bit as
1222 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1223 DemandedMaskIn.set(BitWidth-1);
1224 if (SimplifyDemandedBits(I->getOperand(0),
1226 RHSKnownZero, RHSKnownOne, Depth+1))
1228 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1229 "Bits known to be one AND zero?");
1230 // Compute the new bits that are at the top now.
1231 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1232 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1233 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1235 // Handle the sign bits.
1236 APInt SignBit(APInt::getSignBit(BitWidth));
1237 // Adjust to where it is now in the mask.
1238 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1240 // If the input sign bit is known to be zero, or if none of the top bits
1241 // are demanded, turn this into an unsigned shift right.
1242 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1243 (HighBits & ~DemandedMask) == HighBits) {
1244 // Perform the logical shift right.
1245 Value *NewVal = BinaryOperator::CreateLShr(
1246 I->getOperand(0), SA, I->getName());
1247 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1248 return UpdateValueUsesWith(I, NewVal);
1249 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1250 RHSKnownOne |= HighBits;
1254 case Instruction::SRem:
1255 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1256 APInt RA = Rem->getValue();
1257 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1258 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1259 return UpdateValueUsesWith(I, I->getOperand(0));
1261 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1262 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1263 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1264 LHSKnownZero, LHSKnownOne, Depth+1))
1267 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1268 LHSKnownZero |= ~LowBits;
1270 KnownZero |= LHSKnownZero & DemandedMask;
1272 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1276 case Instruction::URem: {
1277 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1278 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1279 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1280 KnownZero2, KnownOne2, Depth+1))
1283 uint32_t Leaders = KnownZero2.countLeadingOnes();
1284 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1285 KnownZero2, KnownOne2, Depth+1))
1288 Leaders = std::max(Leaders,
1289 KnownZero2.countLeadingOnes());
1290 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1293 case Instruction::Call:
1294 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1295 switch (II->getIntrinsicID()) {
1297 case Intrinsic::bswap: {
1298 // If the only bits demanded come from one byte of the bswap result,
1299 // just shift the input byte into position to eliminate the bswap.
1300 unsigned NLZ = DemandedMask.countLeadingZeros();
1301 unsigned NTZ = DemandedMask.countTrailingZeros();
1303 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1304 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1305 // have 14 leading zeros, round to 8.
1308 // If we need exactly one byte, we can do this transformation.
1309 if (BitWidth-NLZ-NTZ == 8) {
1310 unsigned ResultBit = NTZ;
1311 unsigned InputBit = BitWidth-NTZ-8;
1313 // Replace this with either a left or right shift to get the byte into
1315 Instruction *NewVal;
1316 if (InputBit > ResultBit)
1317 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1318 ConstantInt::get(I->getType(), InputBit-ResultBit));
1320 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1321 ConstantInt::get(I->getType(), ResultBit-InputBit));
1322 NewVal->takeName(I);
1323 InsertNewInstBefore(NewVal, *I);
1324 return UpdateValueUsesWith(I, NewVal);
1327 // TODO: Could compute known zero/one bits based on the input.
1332 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1336 // If the client is only demanding bits that we know, return the known
1338 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1339 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1344 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1345 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1346 /// actually used by the caller. This method analyzes which elements of the
1347 /// operand are undef and returns that information in UndefElts.
1349 /// If the information about demanded elements can be used to simplify the
1350 /// operation, the operation is simplified, then the resultant value is
1351 /// returned. This returns null if no change was made.
1352 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1353 uint64_t &UndefElts,
1355 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1356 assert(VWidth <= 64 && "Vector too wide to analyze!");
1357 uint64_t EltMask = ~0ULL >> (64-VWidth);
1358 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1359 "Invalid DemandedElts!");
1361 if (isa<UndefValue>(V)) {
1362 // If the entire vector is undefined, just return this info.
1363 UndefElts = EltMask;
1365 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1366 UndefElts = EltMask;
1367 return UndefValue::get(V->getType());
1371 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1372 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1373 Constant *Undef = UndefValue::get(EltTy);
1375 std::vector<Constant*> Elts;
1376 for (unsigned i = 0; i != VWidth; ++i)
1377 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1378 Elts.push_back(Undef);
1379 UndefElts |= (1ULL << i);
1380 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1381 Elts.push_back(Undef);
1382 UndefElts |= (1ULL << i);
1383 } else { // Otherwise, defined.
1384 Elts.push_back(CP->getOperand(i));
1387 // If we changed the constant, return it.
1388 Constant *NewCP = ConstantVector::get(Elts);
1389 return NewCP != CP ? NewCP : 0;
1390 } else if (isa<ConstantAggregateZero>(V)) {
1391 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1393 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1394 Constant *Zero = Constant::getNullValue(EltTy);
1395 Constant *Undef = UndefValue::get(EltTy);
1396 std::vector<Constant*> Elts;
1397 for (unsigned i = 0; i != VWidth; ++i)
1398 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1399 UndefElts = DemandedElts ^ EltMask;
1400 return ConstantVector::get(Elts);
1403 if (!V->hasOneUse()) { // Other users may use these bits.
1404 if (Depth != 0) { // Not at the root.
1405 // TODO: Just compute the UndefElts information recursively.
1409 } else if (Depth == 10) { // Limit search depth.
1413 Instruction *I = dyn_cast<Instruction>(V);
1414 if (!I) return false; // Only analyze instructions.
1416 bool MadeChange = false;
1417 uint64_t UndefElts2;
1419 switch (I->getOpcode()) {
1422 case Instruction::InsertElement: {
1423 // If this is a variable index, we don't know which element it overwrites.
1424 // demand exactly the same input as we produce.
1425 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1427 // Note that we can't propagate undef elt info, because we don't know
1428 // which elt is getting updated.
1429 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1430 UndefElts2, Depth+1);
1431 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1435 // If this is inserting an element that isn't demanded, remove this
1437 unsigned IdxNo = Idx->getZExtValue();
1438 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1439 return AddSoonDeadInstToWorklist(*I, 0);
1441 // Otherwise, the element inserted overwrites whatever was there, so the
1442 // input demanded set is simpler than the output set.
1443 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1444 DemandedElts & ~(1ULL << IdxNo),
1445 UndefElts, Depth+1);
1446 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1448 // The inserted element is defined.
1449 UndefElts |= 1ULL << IdxNo;
1452 case Instruction::BitCast: {
1453 // Vector->vector casts only.
1454 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1456 unsigned InVWidth = VTy->getNumElements();
1457 uint64_t InputDemandedElts = 0;
1460 if (VWidth == InVWidth) {
1461 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1462 // elements as are demanded of us.
1464 InputDemandedElts = DemandedElts;
1465 } else if (VWidth > InVWidth) {
1469 // If there are more elements in the result than there are in the source,
1470 // then an input element is live if any of the corresponding output
1471 // elements are live.
1472 Ratio = VWidth/InVWidth;
1473 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1474 if (DemandedElts & (1ULL << OutIdx))
1475 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1481 // If there are more elements in the source than there are in the result,
1482 // then an input element is live if the corresponding output element is
1484 Ratio = InVWidth/VWidth;
1485 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1486 if (DemandedElts & (1ULL << InIdx/Ratio))
1487 InputDemandedElts |= 1ULL << InIdx;
1490 // div/rem demand all inputs, because they don't want divide by zero.
1491 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1492 UndefElts2, Depth+1);
1494 I->setOperand(0, TmpV);
1498 UndefElts = UndefElts2;
1499 if (VWidth > InVWidth) {
1500 assert(0 && "Unimp");
1501 // If there are more elements in the result than there are in the source,
1502 // then an output element is undef if the corresponding input element is
1504 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1505 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1506 UndefElts |= 1ULL << OutIdx;
1507 } else if (VWidth < InVWidth) {
1508 assert(0 && "Unimp");
1509 // If there are more elements in the source than there are in the result,
1510 // then a result element is undef if all of the corresponding input
1511 // elements are undef.
1512 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1513 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1514 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1515 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1519 case Instruction::And:
1520 case Instruction::Or:
1521 case Instruction::Xor:
1522 case Instruction::Add:
1523 case Instruction::Sub:
1524 case Instruction::Mul:
1525 // div/rem demand all inputs, because they don't want divide by zero.
1526 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527 UndefElts, Depth+1);
1528 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1529 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1530 UndefElts2, Depth+1);
1531 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1533 // Output elements are undefined if both are undefined. Consider things
1534 // like undef&0. The result is known zero, not undef.
1535 UndefElts &= UndefElts2;
1538 case Instruction::Call: {
1539 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1541 switch (II->getIntrinsicID()) {
1544 // Binary vector operations that work column-wise. A dest element is a
1545 // function of the corresponding input elements from the two inputs.
1546 case Intrinsic::x86_sse_sub_ss:
1547 case Intrinsic::x86_sse_mul_ss:
1548 case Intrinsic::x86_sse_min_ss:
1549 case Intrinsic::x86_sse_max_ss:
1550 case Intrinsic::x86_sse2_sub_sd:
1551 case Intrinsic::x86_sse2_mul_sd:
1552 case Intrinsic::x86_sse2_min_sd:
1553 case Intrinsic::x86_sse2_max_sd:
1554 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1555 UndefElts, Depth+1);
1556 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1557 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1558 UndefElts2, Depth+1);
1559 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1561 // If only the low elt is demanded and this is a scalarizable intrinsic,
1562 // scalarize it now.
1563 if (DemandedElts == 1) {
1564 switch (II->getIntrinsicID()) {
1566 case Intrinsic::x86_sse_sub_ss:
1567 case Intrinsic::x86_sse_mul_ss:
1568 case Intrinsic::x86_sse2_sub_sd:
1569 case Intrinsic::x86_sse2_mul_sd:
1570 // TODO: Lower MIN/MAX/ABS/etc
1571 Value *LHS = II->getOperand(1);
1572 Value *RHS = II->getOperand(2);
1573 // Extract the element as scalars.
1574 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1575 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1577 switch (II->getIntrinsicID()) {
1578 default: assert(0 && "Case stmts out of sync!");
1579 case Intrinsic::x86_sse_sub_ss:
1580 case Intrinsic::x86_sse2_sub_sd:
1581 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1582 II->getName()), *II);
1584 case Intrinsic::x86_sse_mul_ss:
1585 case Intrinsic::x86_sse2_mul_sd:
1586 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1587 II->getName()), *II);
1592 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1594 InsertNewInstBefore(New, *II);
1595 AddSoonDeadInstToWorklist(*II, 0);
1600 // Output elements are undefined if both are undefined. Consider things
1601 // like undef&0. The result is known zero, not undef.
1602 UndefElts &= UndefElts2;
1608 return MadeChange ? I : 0;
1612 /// AssociativeOpt - Perform an optimization on an associative operator. This
1613 /// function is designed to check a chain of associative operators for a
1614 /// potential to apply a certain optimization. Since the optimization may be
1615 /// applicable if the expression was reassociated, this checks the chain, then
1616 /// reassociates the expression as necessary to expose the optimization
1617 /// opportunity. This makes use of a special Functor, which must define
1618 /// 'shouldApply' and 'apply' methods.
1620 template<typename Functor>
1621 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1622 unsigned Opcode = Root.getOpcode();
1623 Value *LHS = Root.getOperand(0);
1625 // Quick check, see if the immediate LHS matches...
1626 if (F.shouldApply(LHS))
1627 return F.apply(Root);
1629 // Otherwise, if the LHS is not of the same opcode as the root, return.
1630 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1631 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1632 // Should we apply this transform to the RHS?
1633 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1635 // If not to the RHS, check to see if we should apply to the LHS...
1636 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1637 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1641 // If the functor wants to apply the optimization to the RHS of LHSI,
1642 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1644 // Now all of the instructions are in the current basic block, go ahead
1645 // and perform the reassociation.
1646 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1648 // First move the selected RHS to the LHS of the root...
1649 Root.setOperand(0, LHSI->getOperand(1));
1651 // Make what used to be the LHS of the root be the user of the root...
1652 Value *ExtraOperand = TmpLHSI->getOperand(1);
1653 if (&Root == TmpLHSI) {
1654 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1657 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1658 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1659 BasicBlock::iterator ARI = &Root; ++ARI;
1660 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1663 // Now propagate the ExtraOperand down the chain of instructions until we
1665 while (TmpLHSI != LHSI) {
1666 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1667 // Move the instruction to immediately before the chain we are
1668 // constructing to avoid breaking dominance properties.
1669 NextLHSI->moveBefore(ARI);
1672 Value *NextOp = NextLHSI->getOperand(1);
1673 NextLHSI->setOperand(1, ExtraOperand);
1675 ExtraOperand = NextOp;
1678 // Now that the instructions are reassociated, have the functor perform
1679 // the transformation...
1680 return F.apply(Root);
1683 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1690 // AddRHS - Implements: X + X --> X << 1
1693 AddRHS(Value *rhs) : RHS(rhs) {}
1694 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1695 Instruction *apply(BinaryOperator &Add) const {
1696 return BinaryOperator::CreateShl(Add.getOperand(0),
1697 ConstantInt::get(Add.getType(), 1));
1701 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1703 struct AddMaskingAnd {
1705 AddMaskingAnd(Constant *c) : C2(c) {}
1706 bool shouldApply(Value *LHS) const {
1708 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1709 ConstantExpr::getAnd(C1, C2)->isNullValue();
1711 Instruction *apply(BinaryOperator &Add) const {
1712 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1718 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1720 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1721 if (Constant *SOC = dyn_cast<Constant>(SO))
1722 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1724 return IC->InsertNewInstBefore(CastInst::Create(
1725 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1728 // Figure out if the constant is the left or the right argument.
1729 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1730 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1732 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1734 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1735 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1738 Value *Op0 = SO, *Op1 = ConstOperand;
1740 std::swap(Op0, Op1);
1742 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1743 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1744 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1745 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1746 SO->getName()+".cmp");
1748 assert(0 && "Unknown binary instruction type!");
1751 return IC->InsertNewInstBefore(New, I);
1754 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1755 // constant as the other operand, try to fold the binary operator into the
1756 // select arguments. This also works for Cast instructions, which obviously do
1757 // not have a second operand.
1758 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1760 // Don't modify shared select instructions
1761 if (!SI->hasOneUse()) return 0;
1762 Value *TV = SI->getOperand(1);
1763 Value *FV = SI->getOperand(2);
1765 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1766 // Bool selects with constant operands can be folded to logical ops.
1767 if (SI->getType() == Type::Int1Ty) return 0;
1769 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1770 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1772 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1779 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1780 /// node as operand #0, see if we can fold the instruction into the PHI (which
1781 /// is only possible if all operands to the PHI are constants).
1782 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1783 PHINode *PN = cast<PHINode>(I.getOperand(0));
1784 unsigned NumPHIValues = PN->getNumIncomingValues();
1785 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1787 // Check to see if all of the operands of the PHI are constants. If there is
1788 // one non-constant value, remember the BB it is. If there is more than one
1789 // or if *it* is a PHI, bail out.
1790 BasicBlock *NonConstBB = 0;
1791 for (unsigned i = 0; i != NumPHIValues; ++i)
1792 if (!isa<Constant>(PN->getIncomingValue(i))) {
1793 if (NonConstBB) return 0; // More than one non-const value.
1794 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1795 NonConstBB = PN->getIncomingBlock(i);
1797 // If the incoming non-constant value is in I's block, we have an infinite
1799 if (NonConstBB == I.getParent())
1803 // If there is exactly one non-constant value, we can insert a copy of the
1804 // operation in that block. However, if this is a critical edge, we would be
1805 // inserting the computation one some other paths (e.g. inside a loop). Only
1806 // do this if the pred block is unconditionally branching into the phi block.
1808 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1809 if (!BI || !BI->isUnconditional()) return 0;
1812 // Okay, we can do the transformation: create the new PHI node.
1813 PHINode *NewPN = PHINode::Create(I.getType(), "");
1814 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1815 InsertNewInstBefore(NewPN, *PN);
1816 NewPN->takeName(PN);
1818 // Next, add all of the operands to the PHI.
1819 if (I.getNumOperands() == 2) {
1820 Constant *C = cast<Constant>(I.getOperand(1));
1821 for (unsigned i = 0; i != NumPHIValues; ++i) {
1823 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1824 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1825 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1827 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1829 assert(PN->getIncomingBlock(i) == NonConstBB);
1830 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1831 InV = BinaryOperator::Create(BO->getOpcode(),
1832 PN->getIncomingValue(i), C, "phitmp",
1833 NonConstBB->getTerminator());
1834 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1835 InV = CmpInst::Create(CI->getOpcode(),
1837 PN->getIncomingValue(i), C, "phitmp",
1838 NonConstBB->getTerminator());
1840 assert(0 && "Unknown binop!");
1842 AddToWorkList(cast<Instruction>(InV));
1844 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1847 CastInst *CI = cast<CastInst>(&I);
1848 const Type *RetTy = CI->getType();
1849 for (unsigned i = 0; i != NumPHIValues; ++i) {
1851 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1852 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1854 assert(PN->getIncomingBlock(i) == NonConstBB);
1855 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
1856 I.getType(), "phitmp",
1857 NonConstBB->getTerminator());
1858 AddToWorkList(cast<Instruction>(InV));
1860 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1863 return ReplaceInstUsesWith(I, NewPN);
1867 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1868 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1869 /// This basically requires proving that the add in the original type would not
1870 /// overflow to change the sign bit or have a carry out.
1871 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1872 // There are different heuristics we can use for this. Here are some simple
1875 // Add has the property that adding any two 2's complement numbers can only
1876 // have one carry bit which can change a sign. As such, if LHS and RHS each
1877 // have at least two sign bits, we know that the addition of the two values will
1878 // sign extend fine.
1879 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1883 // If one of the operands only has one non-zero bit, and if the other operand
1884 // has a known-zero bit in a more significant place than it (not including the
1885 // sign bit) the ripple may go up to and fill the zero, but won't change the
1886 // sign. For example, (X & ~4) + 1.
1894 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1895 bool Changed = SimplifyCommutative(I);
1896 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1898 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1899 // X + undef -> undef
1900 if (isa<UndefValue>(RHS))
1901 return ReplaceInstUsesWith(I, RHS);
1904 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1905 if (RHSC->isNullValue())
1906 return ReplaceInstUsesWith(I, LHS);
1907 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1908 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1909 (I.getType())->getValueAPF()))
1910 return ReplaceInstUsesWith(I, LHS);
1913 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1914 // X + (signbit) --> X ^ signbit
1915 const APInt& Val = CI->getValue();
1916 uint32_t BitWidth = Val.getBitWidth();
1917 if (Val == APInt::getSignBit(BitWidth))
1918 return BinaryOperator::CreateXor(LHS, RHS);
1920 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1921 // (X & 254)+1 -> (X&254)|1
1922 if (!isa<VectorType>(I.getType())) {
1923 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1924 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1925 KnownZero, KnownOne))
1930 if (isa<PHINode>(LHS))
1931 if (Instruction *NV = FoldOpIntoPhi(I))
1934 ConstantInt *XorRHS = 0;
1936 if (isa<ConstantInt>(RHSC) &&
1937 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1938 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1939 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1941 uint32_t Size = TySizeBits / 2;
1942 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1943 APInt CFF80Val(-C0080Val);
1945 if (TySizeBits > Size) {
1946 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1947 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1948 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1949 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1950 // This is a sign extend if the top bits are known zero.
1951 if (!MaskedValueIsZero(XorLHS,
1952 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1953 Size = 0; // Not a sign ext, but can't be any others either.
1958 C0080Val = APIntOps::lshr(C0080Val, Size);
1959 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1960 } while (Size >= 1);
1962 // FIXME: This shouldn't be necessary. When the backends can handle types
1963 // with funny bit widths then this switch statement should be removed. It
1964 // is just here to get the size of the "middle" type back up to something
1965 // that the back ends can handle.
1966 const Type *MiddleType = 0;
1969 case 32: MiddleType = Type::Int32Ty; break;
1970 case 16: MiddleType = Type::Int16Ty; break;
1971 case 8: MiddleType = Type::Int8Ty; break;
1974 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1975 InsertNewInstBefore(NewTrunc, I);
1976 return new SExtInst(NewTrunc, I.getType(), I.getName());
1981 if (I.getType() == Type::Int1Ty)
1982 return BinaryOperator::CreateXor(LHS, RHS);
1985 if (I.getType()->isInteger()) {
1986 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1988 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1989 if (RHSI->getOpcode() == Instruction::Sub)
1990 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1991 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1993 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1994 if (LHSI->getOpcode() == Instruction::Sub)
1995 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1996 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2001 // -A + -B --> -(A + B)
2002 if (Value *LHSV = dyn_castNegVal(LHS)) {
2003 if (LHS->getType()->isIntOrIntVector()) {
2004 if (Value *RHSV = dyn_castNegVal(RHS)) {
2005 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2006 InsertNewInstBefore(NewAdd, I);
2007 return BinaryOperator::CreateNeg(NewAdd);
2011 return BinaryOperator::CreateSub(RHS, LHSV);
2015 if (!isa<Constant>(RHS))
2016 if (Value *V = dyn_castNegVal(RHS))
2017 return BinaryOperator::CreateSub(LHS, V);
2021 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2022 if (X == RHS) // X*C + X --> X * (C+1)
2023 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2025 // X*C1 + X*C2 --> X * (C1+C2)
2027 if (X == dyn_castFoldableMul(RHS, C1))
2028 return BinaryOperator::CreateMul(X, Add(C1, C2));
2031 // X + X*C --> X * (C+1)
2032 if (dyn_castFoldableMul(RHS, C2) == LHS)
2033 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2035 // X + ~X --> -1 since ~X = -X-1
2036 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2037 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2040 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2041 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2042 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2045 // A+B --> A|B iff A and B have no bits set in common.
2046 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2047 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2048 APInt LHSKnownOne(IT->getBitWidth(), 0);
2049 APInt LHSKnownZero(IT->getBitWidth(), 0);
2050 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2051 if (LHSKnownZero != 0) {
2052 APInt RHSKnownOne(IT->getBitWidth(), 0);
2053 APInt RHSKnownZero(IT->getBitWidth(), 0);
2054 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2056 // No bits in common -> bitwise or.
2057 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2058 return BinaryOperator::CreateOr(LHS, RHS);
2062 // W*X + Y*Z --> W * (X+Z) iff W == Y
2063 if (I.getType()->isIntOrIntVector()) {
2064 Value *W, *X, *Y, *Z;
2065 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2066 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2070 } else if (Y == X) {
2072 } else if (X == Z) {
2079 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2080 LHS->getName()), I);
2081 return BinaryOperator::CreateMul(W, NewAdd);
2086 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2088 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2089 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2091 // (X & FF00) + xx00 -> (X+xx00) & FF00
2092 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2093 Constant *Anded = And(CRHS, C2);
2094 if (Anded == CRHS) {
2095 // See if all bits from the first bit set in the Add RHS up are included
2096 // in the mask. First, get the rightmost bit.
2097 const APInt& AddRHSV = CRHS->getValue();
2099 // Form a mask of all bits from the lowest bit added through the top.
2100 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2102 // See if the and mask includes all of these bits.
2103 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2105 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2106 // Okay, the xform is safe. Insert the new add pronto.
2107 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2108 LHS->getName()), I);
2109 return BinaryOperator::CreateAnd(NewAdd, C2);
2114 // Try to fold constant add into select arguments.
2115 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2116 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2120 // add (cast *A to intptrtype) B ->
2121 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
2123 CastInst *CI = dyn_cast<CastInst>(LHS);
2126 CI = dyn_cast<CastInst>(RHS);
2129 if (CI && CI->getType()->isSized() &&
2130 (CI->getType()->getPrimitiveSizeInBits() ==
2131 TD->getIntPtrType()->getPrimitiveSizeInBits())
2132 && isa<PointerType>(CI->getOperand(0)->getType())) {
2134 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2135 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2136 PointerType::get(Type::Int8Ty, AS), I);
2137 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2138 return new PtrToIntInst(I2, CI->getType());
2142 // add (select X 0 (sub n A)) A --> select X A n
2144 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2147 SI = dyn_cast<SelectInst>(RHS);
2150 if (SI && SI->hasOneUse()) {
2151 Value *TV = SI->getTrueValue();
2152 Value *FV = SI->getFalseValue();
2155 // Can we fold the add into the argument of the select?
2156 // We check both true and false select arguments for a matching subtract.
2157 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2158 A == Other) // Fold the add into the true select value.
2159 return SelectInst::Create(SI->getCondition(), N, A);
2160 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2161 A == Other) // Fold the add into the false select value.
2162 return SelectInst::Create(SI->getCondition(), A, N);
2166 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2167 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2168 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2169 return ReplaceInstUsesWith(I, LHS);
2171 // Check for (add (sext x), y), see if we can merge this into an
2172 // integer add followed by a sext.
2173 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2174 // (add (sext x), cst) --> (sext (add x, cst'))
2175 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2177 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2178 if (LHSConv->hasOneUse() &&
2179 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2180 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2181 // Insert the new, smaller add.
2182 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2184 InsertNewInstBefore(NewAdd, I);
2185 return new SExtInst(NewAdd, I.getType());
2189 // (add (sext x), (sext y)) --> (sext (add int x, y))
2190 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2191 // Only do this if x/y have the same type, if at last one of them has a
2192 // single use (so we don't increase the number of sexts), and if the
2193 // integer add will not overflow.
2194 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2195 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2196 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2197 RHSConv->getOperand(0))) {
2198 // Insert the new integer add.
2199 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2200 RHSConv->getOperand(0),
2202 InsertNewInstBefore(NewAdd, I);
2203 return new SExtInst(NewAdd, I.getType());
2208 // Check for (add double (sitofp x), y), see if we can merge this into an
2209 // integer add followed by a promotion.
2210 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2211 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2212 // ... if the constant fits in the integer value. This is useful for things
2213 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2214 // requires a constant pool load, and generally allows the add to be better
2216 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2218 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2219 if (LHSConv->hasOneUse() &&
2220 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2221 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2222 // Insert the new integer add.
2223 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2225 InsertNewInstBefore(NewAdd, I);
2226 return new SIToFPInst(NewAdd, I.getType());
2230 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2231 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2232 // Only do this if x/y have the same type, if at last one of them has a
2233 // single use (so we don't increase the number of int->fp conversions),
2234 // and if the integer add will not overflow.
2235 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2236 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2237 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2238 RHSConv->getOperand(0))) {
2239 // Insert the new integer add.
2240 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2241 RHSConv->getOperand(0),
2243 InsertNewInstBefore(NewAdd, I);
2244 return new SIToFPInst(NewAdd, I.getType());
2249 return Changed ? &I : 0;
2252 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2255 if (Op0 == Op1 && // sub X, X -> 0
2256 !I.getType()->isFPOrFPVector())
2257 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2259 // If this is a 'B = x-(-A)', change to B = x+A...
2260 if (Value *V = dyn_castNegVal(Op1))
2261 return BinaryOperator::CreateAdd(Op0, V);
2263 if (isa<UndefValue>(Op0))
2264 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2265 if (isa<UndefValue>(Op1))
2266 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2268 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2269 // Replace (-1 - A) with (~A)...
2270 if (C->isAllOnesValue())
2271 return BinaryOperator::CreateNot(Op1);
2273 // C - ~X == X + (1+C)
2275 if (match(Op1, m_Not(m_Value(X))))
2276 return BinaryOperator::CreateAdd(X, AddOne(C));
2278 // -(X >>u 31) -> (X >>s 31)
2279 // -(X >>s 31) -> (X >>u 31)
2281 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2282 if (SI->getOpcode() == Instruction::LShr) {
2283 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2284 // Check to see if we are shifting out everything but the sign bit.
2285 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2286 SI->getType()->getPrimitiveSizeInBits()-1) {
2287 // Ok, the transformation is safe. Insert AShr.
2288 return BinaryOperator::Create(Instruction::AShr,
2289 SI->getOperand(0), CU, SI->getName());
2293 else if (SI->getOpcode() == Instruction::AShr) {
2294 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2295 // Check to see if we are shifting out everything but the sign bit.
2296 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2297 SI->getType()->getPrimitiveSizeInBits()-1) {
2298 // Ok, the transformation is safe. Insert LShr.
2299 return BinaryOperator::CreateLShr(
2300 SI->getOperand(0), CU, SI->getName());
2307 // Try to fold constant sub into select arguments.
2308 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2309 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2312 if (isa<PHINode>(Op0))
2313 if (Instruction *NV = FoldOpIntoPhi(I))
2317 if (I.getType() == Type::Int1Ty)
2318 return BinaryOperator::CreateXor(Op0, Op1);
2320 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2321 if (Op1I->getOpcode() == Instruction::Add &&
2322 !Op0->getType()->isFPOrFPVector()) {
2323 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2324 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2325 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2326 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2327 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2328 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2329 // C1-(X+C2) --> (C1-C2)-X
2330 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
2331 Op1I->getOperand(0));
2335 if (Op1I->hasOneUse()) {
2336 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2337 // is not used by anyone else...
2339 if (Op1I->getOpcode() == Instruction::Sub &&
2340 !Op1I->getType()->isFPOrFPVector()) {
2341 // Swap the two operands of the subexpr...
2342 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2343 Op1I->setOperand(0, IIOp1);
2344 Op1I->setOperand(1, IIOp0);
2346 // Create the new top level add instruction...
2347 return BinaryOperator::CreateAdd(Op0, Op1);
2350 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2352 if (Op1I->getOpcode() == Instruction::And &&
2353 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2354 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2357 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2358 return BinaryOperator::CreateAnd(Op0, NewNot);
2361 // 0 - (X sdiv C) -> (X sdiv -C)
2362 if (Op1I->getOpcode() == Instruction::SDiv)
2363 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2365 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2366 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2367 ConstantExpr::getNeg(DivRHS));
2369 // X - X*C --> X * (1-C)
2370 ConstantInt *C2 = 0;
2371 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2372 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2373 return BinaryOperator::CreateMul(Op0, CP1);
2376 // X - ((X / Y) * Y) --> X % Y
2377 if (Op1I->getOpcode() == Instruction::Mul)
2378 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2379 if (Op0 == I->getOperand(0) &&
2380 Op1I->getOperand(1) == I->getOperand(1)) {
2381 if (I->getOpcode() == Instruction::SDiv)
2382 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2383 if (I->getOpcode() == Instruction::UDiv)
2384 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2389 if (!Op0->getType()->isFPOrFPVector())
2390 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2391 if (Op0I->getOpcode() == Instruction::Add) {
2392 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2393 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2394 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2395 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2396 } else if (Op0I->getOpcode() == Instruction::Sub) {
2397 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2398 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2403 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2404 if (X == Op1) // X*C - X --> X * (C-1)
2405 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2407 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2408 if (X == dyn_castFoldableMul(Op1, C2))
2409 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2414 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2415 /// comparison only checks the sign bit. If it only checks the sign bit, set
2416 /// TrueIfSigned if the result of the comparison is true when the input value is
2418 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2419 bool &TrueIfSigned) {
2421 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2422 TrueIfSigned = true;
2423 return RHS->isZero();
2424 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2425 TrueIfSigned = true;
2426 return RHS->isAllOnesValue();
2427 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2428 TrueIfSigned = false;
2429 return RHS->isAllOnesValue();
2430 case ICmpInst::ICMP_UGT:
2431 // True if LHS u> RHS and RHS == high-bit-mask - 1
2432 TrueIfSigned = true;
2433 return RHS->getValue() ==
2434 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2435 case ICmpInst::ICMP_UGE:
2436 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2437 TrueIfSigned = true;
2438 return RHS->getValue().isSignBit();
2444 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2445 bool Changed = SimplifyCommutative(I);
2446 Value *Op0 = I.getOperand(0);
2448 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2449 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2451 // Simplify mul instructions with a constant RHS...
2452 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2453 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2455 // ((X << C1)*C2) == (X * (C2 << C1))
2456 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2457 if (SI->getOpcode() == Instruction::Shl)
2458 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2459 return BinaryOperator::CreateMul(SI->getOperand(0),
2460 ConstantExpr::getShl(CI, ShOp));
2463 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2464 if (CI->equalsInt(1)) // X * 1 == X
2465 return ReplaceInstUsesWith(I, Op0);
2466 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2467 return BinaryOperator::CreateNeg(Op0, I.getName());
2469 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2470 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2471 return BinaryOperator::CreateShl(Op0,
2472 ConstantInt::get(Op0->getType(), Val.logBase2()));
2474 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2475 if (Op1F->isNullValue())
2476 return ReplaceInstUsesWith(I, Op1);
2478 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2479 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2480 if (Op1F->isExactlyValue(1.0))
2481 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2482 } else if (isa<VectorType>(Op1->getType())) {
2483 if (isa<ConstantAggregateZero>(Op1))
2484 return ReplaceInstUsesWith(I, Op1);
2486 // As above, vector X*splat(1.0) -> X in all defined cases.
2487 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1))
2488 if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
2489 if (F->isExactlyValue(1.0))
2490 return ReplaceInstUsesWith(I, Op0);
2493 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2494 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2495 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2496 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2497 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2499 InsertNewInstBefore(Add, I);
2500 Value *C1C2 = ConstantExpr::getMul(Op1,
2501 cast<Constant>(Op0I->getOperand(1)));
2502 return BinaryOperator::CreateAdd(Add, C1C2);
2506 // Try to fold constant mul into select arguments.
2507 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2508 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2511 if (isa<PHINode>(Op0))
2512 if (Instruction *NV = FoldOpIntoPhi(I))
2516 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2517 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2518 return BinaryOperator::CreateMul(Op0v, Op1v);
2520 if (I.getType() == Type::Int1Ty)
2521 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2523 // If one of the operands of the multiply is a cast from a boolean value, then
2524 // we know the bool is either zero or one, so this is a 'masking' multiply.
2525 // See if we can simplify things based on how the boolean was originally
2527 CastInst *BoolCast = 0;
2528 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2529 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2532 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2533 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2536 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2537 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2538 const Type *SCOpTy = SCIOp0->getType();
2541 // If the icmp is true iff the sign bit of X is set, then convert this
2542 // multiply into a shift/and combination.
2543 if (isa<ConstantInt>(SCIOp1) &&
2544 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2546 // Shift the X value right to turn it into "all signbits".
2547 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2548 SCOpTy->getPrimitiveSizeInBits()-1);
2550 InsertNewInstBefore(
2551 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2552 BoolCast->getOperand(0)->getName()+
2555 // If the multiply type is not the same as the source type, sign extend
2556 // or truncate to the multiply type.
2557 if (I.getType() != V->getType()) {
2558 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2559 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2560 Instruction::CastOps opcode =
2561 (SrcBits == DstBits ? Instruction::BitCast :
2562 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2563 V = InsertCastBefore(opcode, V, I.getType(), I);
2566 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2567 return BinaryOperator::CreateAnd(V, OtherOp);
2572 return Changed ? &I : 0;
2575 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2577 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2578 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2580 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2581 int NonNullOperand = -1;
2582 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2583 if (ST->isNullValue())
2585 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2586 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2587 if (ST->isNullValue())
2590 if (NonNullOperand == -1)
2593 Value *SelectCond = SI->getOperand(0);
2595 // Change the div/rem to use 'Y' instead of the select.
2596 I.setOperand(1, SI->getOperand(NonNullOperand));
2598 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2599 // problem. However, the select, or the condition of the select may have
2600 // multiple uses. Based on our knowledge that the operand must be non-zero,
2601 // propagate the known value for the select into other uses of it, and
2602 // propagate a known value of the condition into its other users.
2604 // If the select and condition only have a single use, don't bother with this,
2606 if (SI->use_empty() && SelectCond->hasOneUse())
2609 // Scan the current block backward, looking for other uses of SI.
2610 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2612 while (BBI != BBFront) {
2614 // If we found a call to a function, we can't assume it will return, so
2615 // information from below it cannot be propagated above it.
2616 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2619 // Replace uses of the select or its condition with the known values.
2620 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2623 *I = SI->getOperand(NonNullOperand);
2625 } else if (*I == SelectCond) {
2626 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2627 ConstantInt::getFalse();
2632 // If we past the instruction, quit looking for it.
2635 if (&*BBI == SelectCond)
2638 // If we ran out of things to eliminate, break out of the loop.
2639 if (SelectCond == 0 && SI == 0)
2647 /// This function implements the transforms on div instructions that work
2648 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2649 /// used by the visitors to those instructions.
2650 /// @brief Transforms common to all three div instructions
2651 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2652 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2654 // undef / X -> 0 for integer.
2655 // undef / X -> undef for FP (the undef could be a snan).
2656 if (isa<UndefValue>(Op0)) {
2657 if (Op0->getType()->isFPOrFPVector())
2658 return ReplaceInstUsesWith(I, Op0);
2659 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2662 // X / undef -> undef
2663 if (isa<UndefValue>(Op1))
2664 return ReplaceInstUsesWith(I, Op1);
2669 /// This function implements the transforms common to both integer division
2670 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2671 /// division instructions.
2672 /// @brief Common integer divide transforms
2673 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2674 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2676 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2678 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2679 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2680 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2681 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2684 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2685 return ReplaceInstUsesWith(I, CI);
2688 if (Instruction *Common = commonDivTransforms(I))
2691 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2692 // This does not apply for fdiv.
2693 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2696 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2698 if (RHS->equalsInt(1))
2699 return ReplaceInstUsesWith(I, Op0);
2701 // (X / C1) / C2 -> X / (C1*C2)
2702 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2703 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2704 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2705 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2706 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2708 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2709 Multiply(RHS, LHSRHS));
2712 if (!RHS->isZero()) { // avoid X udiv 0
2713 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2714 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2716 if (isa<PHINode>(Op0))
2717 if (Instruction *NV = FoldOpIntoPhi(I))
2722 // 0 / X == 0, we don't need to preserve faults!
2723 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2724 if (LHS->equalsInt(0))
2725 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2727 // It can't be division by zero, hence it must be division by one.
2728 if (I.getType() == Type::Int1Ty)
2729 return ReplaceInstUsesWith(I, Op0);
2734 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2735 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2737 // Handle the integer div common cases
2738 if (Instruction *Common = commonIDivTransforms(I))
2741 // X udiv C^2 -> X >> C
2742 // Check to see if this is an unsigned division with an exact power of 2,
2743 // if so, convert to a right shift.
2744 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2745 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2746 return BinaryOperator::CreateLShr(Op0,
2747 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2750 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2751 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2752 if (RHSI->getOpcode() == Instruction::Shl &&
2753 isa<ConstantInt>(RHSI->getOperand(0))) {
2754 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2755 if (C1.isPowerOf2()) {
2756 Value *N = RHSI->getOperand(1);
2757 const Type *NTy = N->getType();
2758 if (uint32_t C2 = C1.logBase2()) {
2759 Constant *C2V = ConstantInt::get(NTy, C2);
2760 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2762 return BinaryOperator::CreateLShr(Op0, N);
2767 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2768 // where C1&C2 are powers of two.
2769 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2770 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2771 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2772 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2773 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2774 // Compute the shift amounts
2775 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2776 // Construct the "on true" case of the select
2777 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2778 Instruction *TSI = BinaryOperator::CreateLShr(
2779 Op0, TC, SI->getName()+".t");
2780 TSI = InsertNewInstBefore(TSI, I);
2782 // Construct the "on false" case of the select
2783 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2784 Instruction *FSI = BinaryOperator::CreateLShr(
2785 Op0, FC, SI->getName()+".f");
2786 FSI = InsertNewInstBefore(FSI, I);
2788 // construct the select instruction and return it.
2789 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2795 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2796 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2798 // Handle the integer div common cases
2799 if (Instruction *Common = commonIDivTransforms(I))
2802 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2804 if (RHS->isAllOnesValue())
2805 return BinaryOperator::CreateNeg(Op0);
2808 if (Value *LHSNeg = dyn_castNegVal(Op0))
2809 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2812 // If the sign bits of both operands are zero (i.e. we can prove they are
2813 // unsigned inputs), turn this into a udiv.
2814 if (I.getType()->isInteger()) {
2815 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2816 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2817 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2818 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2825 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2826 return commonDivTransforms(I);
2829 /// This function implements the transforms on rem instructions that work
2830 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2831 /// is used by the visitors to those instructions.
2832 /// @brief Transforms common to all three rem instructions
2833 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2834 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2836 // 0 % X == 0 for integer, we don't need to preserve faults!
2837 if (Constant *LHS = dyn_cast<Constant>(Op0))
2838 if (LHS->isNullValue())
2839 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2841 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2842 if (I.getType()->isFPOrFPVector())
2843 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
2844 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2846 if (isa<UndefValue>(Op1))
2847 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2849 // Handle cases involving: rem X, (select Cond, Y, Z)
2850 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2856 /// This function implements the transforms common to both integer remainder
2857 /// instructions (urem and srem). It is called by the visitors to those integer
2858 /// remainder instructions.
2859 /// @brief Common integer remainder transforms
2860 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2861 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2863 if (Instruction *common = commonRemTransforms(I))
2866 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2867 // X % 0 == undef, we don't need to preserve faults!
2868 if (RHS->equalsInt(0))
2869 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2871 if (RHS->equalsInt(1)) // X % 1 == 0
2872 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2874 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2875 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2876 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2878 } else if (isa<PHINode>(Op0I)) {
2879 if (Instruction *NV = FoldOpIntoPhi(I))
2883 // See if we can fold away this rem instruction.
2884 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2885 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2886 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2887 KnownZero, KnownOne))
2895 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2896 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2898 if (Instruction *common = commonIRemTransforms(I))
2901 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2902 // X urem C^2 -> X and C
2903 // Check to see if this is an unsigned remainder with an exact power of 2,
2904 // if so, convert to a bitwise and.
2905 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2906 if (C->getValue().isPowerOf2())
2907 return BinaryOperator::CreateAnd(Op0, SubOne(C));
2910 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2911 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2912 if (RHSI->getOpcode() == Instruction::Shl &&
2913 isa<ConstantInt>(RHSI->getOperand(0))) {
2914 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2915 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2916 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2918 return BinaryOperator::CreateAnd(Op0, Add);
2923 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2924 // where C1&C2 are powers of two.
2925 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2926 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2927 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2928 // STO == 0 and SFO == 0 handled above.
2929 if ((STO->getValue().isPowerOf2()) &&
2930 (SFO->getValue().isPowerOf2())) {
2931 Value *TrueAnd = InsertNewInstBefore(
2932 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2933 Value *FalseAnd = InsertNewInstBefore(
2934 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2935 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2943 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2944 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2946 // Handle the integer rem common cases
2947 if (Instruction *common = commonIRemTransforms(I))
2950 if (Value *RHSNeg = dyn_castNegVal(Op1))
2951 if (!isa<ConstantInt>(RHSNeg) ||
2952 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2954 AddUsesToWorkList(I);
2955 I.setOperand(1, RHSNeg);
2959 // If the sign bits of both operands are zero (i.e. we can prove they are
2960 // unsigned inputs), turn this into a urem.
2961 if (I.getType()->isInteger()) {
2962 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2963 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2964 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2965 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2972 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2973 return commonRemTransforms(I);
2976 // isOneBitSet - Return true if there is exactly one bit set in the specified
2978 static bool isOneBitSet(const ConstantInt *CI) {
2979 return CI->getValue().isPowerOf2();
2982 // isHighOnes - Return true if the constant is of the form 1+0+.
2983 // This is the same as lowones(~X).
2984 static bool isHighOnes(const ConstantInt *CI) {
2985 return (~CI->getValue() + 1).isPowerOf2();
2988 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2989 /// are carefully arranged to allow folding of expressions such as:
2991 /// (A < B) | (A > B) --> (A != B)
2993 /// Note that this is only valid if the first and second predicates have the
2994 /// same sign. Is illegal to do: (A u< B) | (A s> B)
2996 /// Three bits are used to represent the condition, as follows:
3001 /// <=> Value Definition
3002 /// 000 0 Always false
3009 /// 111 7 Always true
3011 static unsigned getICmpCode(const ICmpInst *ICI) {
3012 switch (ICI->getPredicate()) {
3014 case ICmpInst::ICMP_UGT: return 1; // 001
3015 case ICmpInst::ICMP_SGT: return 1; // 001
3016 case ICmpInst::ICMP_EQ: return 2; // 010
3017 case ICmpInst::ICMP_UGE: return 3; // 011
3018 case ICmpInst::ICMP_SGE: return 3; // 011
3019 case ICmpInst::ICMP_ULT: return 4; // 100
3020 case ICmpInst::ICMP_SLT: return 4; // 100
3021 case ICmpInst::ICMP_NE: return 5; // 101
3022 case ICmpInst::ICMP_ULE: return 6; // 110
3023 case ICmpInst::ICMP_SLE: return 6; // 110
3026 assert(0 && "Invalid ICmp predicate!");
3031 /// getICmpValue - This is the complement of getICmpCode, which turns an
3032 /// opcode and two operands into either a constant true or false, or a brand
3033 /// new ICmp instruction. The sign is passed in to determine which kind
3034 /// of predicate to use in new icmp instructions.
3035 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3037 default: assert(0 && "Illegal ICmp code!");
3038 case 0: return ConstantInt::getFalse();
3041 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3043 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3044 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3047 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3049 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3052 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3054 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3055 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3058 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3060 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3061 case 7: return ConstantInt::getTrue();
3065 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3066 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3067 (ICmpInst::isSignedPredicate(p1) &&
3068 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3069 (ICmpInst::isSignedPredicate(p2) &&
3070 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3074 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3075 struct FoldICmpLogical {
3078 ICmpInst::Predicate pred;
3079 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3080 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3081 pred(ICI->getPredicate()) {}
3082 bool shouldApply(Value *V) const {
3083 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3084 if (PredicatesFoldable(pred, ICI->getPredicate()))
3085 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3086 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3089 Instruction *apply(Instruction &Log) const {
3090 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3091 if (ICI->getOperand(0) != LHS) {
3092 assert(ICI->getOperand(1) == LHS);
3093 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3096 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3097 unsigned LHSCode = getICmpCode(ICI);
3098 unsigned RHSCode = getICmpCode(RHSICI);
3100 switch (Log.getOpcode()) {
3101 case Instruction::And: Code = LHSCode & RHSCode; break;
3102 case Instruction::Or: Code = LHSCode | RHSCode; break;
3103 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3104 default: assert(0 && "Illegal logical opcode!"); return 0;
3107 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3108 ICmpInst::isSignedPredicate(ICI->getPredicate());
3110 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3111 if (Instruction *I = dyn_cast<Instruction>(RV))
3113 // Otherwise, it's a constant boolean value...
3114 return IC.ReplaceInstUsesWith(Log, RV);
3117 } // end anonymous namespace
3119 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3120 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3121 // guaranteed to be a binary operator.
3122 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3124 ConstantInt *AndRHS,
3125 BinaryOperator &TheAnd) {
3126 Value *X = Op->getOperand(0);
3127 Constant *Together = 0;
3129 Together = And(AndRHS, OpRHS);
3131 switch (Op->getOpcode()) {
3132 case Instruction::Xor:
3133 if (Op->hasOneUse()) {
3134 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3135 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3136 InsertNewInstBefore(And, TheAnd);
3138 return BinaryOperator::CreateXor(And, Together);
3141 case Instruction::Or:
3142 if (Together == AndRHS) // (X | C) & C --> C
3143 return ReplaceInstUsesWith(TheAnd, AndRHS);
3145 if (Op->hasOneUse() && Together != OpRHS) {
3146 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3147 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3148 InsertNewInstBefore(Or, TheAnd);
3150 return BinaryOperator::CreateAnd(Or, AndRHS);
3153 case Instruction::Add:
3154 if (Op->hasOneUse()) {
3155 // Adding a one to a single bit bit-field should be turned into an XOR
3156 // of the bit. First thing to check is to see if this AND is with a
3157 // single bit constant.
3158 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3160 // If there is only one bit set...
3161 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3162 // Ok, at this point, we know that we are masking the result of the
3163 // ADD down to exactly one bit. If the constant we are adding has
3164 // no bits set below this bit, then we can eliminate the ADD.
3165 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3167 // Check to see if any bits below the one bit set in AndRHSV are set.
3168 if ((AddRHS & (AndRHSV-1)) == 0) {
3169 // If not, the only thing that can effect the output of the AND is
3170 // the bit specified by AndRHSV. If that bit is set, the effect of
3171 // the XOR is to toggle the bit. If it is clear, then the ADD has
3173 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3174 TheAnd.setOperand(0, X);
3177 // Pull the XOR out of the AND.
3178 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3179 InsertNewInstBefore(NewAnd, TheAnd);
3180 NewAnd->takeName(Op);
3181 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3188 case Instruction::Shl: {
3189 // We know that the AND will not produce any of the bits shifted in, so if
3190 // the anded constant includes them, clear them now!
3192 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3193 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3194 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3195 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3197 if (CI->getValue() == ShlMask) {
3198 // Masking out bits that the shift already masks
3199 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3200 } else if (CI != AndRHS) { // Reducing bits set in and.
3201 TheAnd.setOperand(1, CI);
3206 case Instruction::LShr:
3208 // We know that the AND will not produce any of the bits shifted in, so if
3209 // the anded constant includes them, clear them now! This only applies to
3210 // unsigned shifts, because a signed shr may bring in set bits!
3212 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3213 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3214 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3215 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3217 if (CI->getValue() == ShrMask) {
3218 // Masking out bits that the shift already masks.
3219 return ReplaceInstUsesWith(TheAnd, Op);
3220 } else if (CI != AndRHS) {
3221 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3226 case Instruction::AShr:
3228 // See if this is shifting in some sign extension, then masking it out
3230 if (Op->hasOneUse()) {
3231 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3232 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3233 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3234 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3235 if (C == AndRHS) { // Masking out bits shifted in.
3236 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3237 // Make the argument unsigned.
3238 Value *ShVal = Op->getOperand(0);
3239 ShVal = InsertNewInstBefore(
3240 BinaryOperator::CreateLShr(ShVal, OpRHS,
3241 Op->getName()), TheAnd);
3242 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3251 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3252 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3253 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3254 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3255 /// insert new instructions.
3256 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3257 bool isSigned, bool Inside,
3259 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3260 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3261 "Lo is not <= Hi in range emission code!");
3264 if (Lo == Hi) // Trivially false.
3265 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3267 // V >= Min && V < Hi --> V < Hi
3268 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3269 ICmpInst::Predicate pred = (isSigned ?
3270 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3271 return new ICmpInst(pred, V, Hi);
3274 // Emit V-Lo <u Hi-Lo
3275 Constant *NegLo = ConstantExpr::getNeg(Lo);
3276 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3277 InsertNewInstBefore(Add, IB);
3278 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3279 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3282 if (Lo == Hi) // Trivially true.
3283 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3285 // V < Min || V >= Hi -> V > Hi-1
3286 Hi = SubOne(cast<ConstantInt>(Hi));
3287 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3288 ICmpInst::Predicate pred = (isSigned ?
3289 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3290 return new ICmpInst(pred, V, Hi);
3293 // Emit V-Lo >u Hi-1-Lo
3294 // Note that Hi has already had one subtracted from it, above.
3295 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3296 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3297 InsertNewInstBefore(Add, IB);
3298 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3299 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3302 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3303 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3304 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3305 // not, since all 1s are not contiguous.
3306 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3307 const APInt& V = Val->getValue();
3308 uint32_t BitWidth = Val->getType()->getBitWidth();
3309 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3311 // look for the first zero bit after the run of ones
3312 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3313 // look for the first non-zero bit
3314 ME = V.getActiveBits();
3318 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3319 /// where isSub determines whether the operator is a sub. If we can fold one of
3320 /// the following xforms:
3322 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3323 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3324 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3326 /// return (A +/- B).
3328 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3329 ConstantInt *Mask, bool isSub,
3331 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3332 if (!LHSI || LHSI->getNumOperands() != 2 ||
3333 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3335 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3337 switch (LHSI->getOpcode()) {
3339 case Instruction::And:
3340 if (And(N, Mask) == Mask) {
3341 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3342 if ((Mask->getValue().countLeadingZeros() +
3343 Mask->getValue().countPopulation()) ==
3344 Mask->getValue().getBitWidth())
3347 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3348 // part, we don't need any explicit masks to take them out of A. If that
3349 // is all N is, ignore it.
3350 uint32_t MB = 0, ME = 0;
3351 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3352 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3353 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3354 if (MaskedValueIsZero(RHS, Mask))
3359 case Instruction::Or:
3360 case Instruction::Xor:
3361 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3362 if ((Mask->getValue().countLeadingZeros() +
3363 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3364 && And(N, Mask)->isZero())
3371 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3373 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3374 return InsertNewInstBefore(New, I);
3377 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3378 bool Changed = SimplifyCommutative(I);
3379 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3381 if (isa<UndefValue>(Op1)) // X & undef -> 0
3382 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3386 return ReplaceInstUsesWith(I, Op1);
3388 // See if we can simplify any instructions used by the instruction whose sole
3389 // purpose is to compute bits we don't care about.
3390 if (!isa<VectorType>(I.getType())) {
3391 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3392 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3393 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3394 KnownZero, KnownOne))
3397 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3398 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3399 return ReplaceInstUsesWith(I, I.getOperand(0));
3400 } else if (isa<ConstantAggregateZero>(Op1)) {
3401 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3405 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3406 const APInt& AndRHSMask = AndRHS->getValue();
3407 APInt NotAndRHS(~AndRHSMask);
3409 // Optimize a variety of ((val OP C1) & C2) combinations...
3410 if (isa<BinaryOperator>(Op0)) {
3411 Instruction *Op0I = cast<Instruction>(Op0);
3412 Value *Op0LHS = Op0I->getOperand(0);
3413 Value *Op0RHS = Op0I->getOperand(1);
3414 switch (Op0I->getOpcode()) {
3415 case Instruction::Xor:
3416 case Instruction::Or:
3417 // If the mask is only needed on one incoming arm, push it up.
3418 if (Op0I->hasOneUse()) {
3419 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3420 // Not masking anything out for the LHS, move to RHS.
3421 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3422 Op0RHS->getName()+".masked");
3423 InsertNewInstBefore(NewRHS, I);
3424 return BinaryOperator::Create(
3425 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3427 if (!isa<Constant>(Op0RHS) &&
3428 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3429 // Not masking anything out for the RHS, move to LHS.
3430 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3431 Op0LHS->getName()+".masked");
3432 InsertNewInstBefore(NewLHS, I);
3433 return BinaryOperator::Create(
3434 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3439 case Instruction::Add:
3440 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3441 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3442 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3443 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3444 return BinaryOperator::CreateAnd(V, AndRHS);
3445 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3446 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
3449 case Instruction::Sub:
3450 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3451 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3452 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3453 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3454 return BinaryOperator::CreateAnd(V, AndRHS);
3456 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3457 // has 1's for all bits that the subtraction with A might affect.
3458 if (Op0I->hasOneUse()) {
3459 uint32_t BitWidth = AndRHSMask.getBitWidth();
3460 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3461 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3463 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3464 if (!(A && A->isZero()) && // avoid infinite recursion.
3465 MaskedValueIsZero(Op0LHS, Mask)) {
3466 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3467 InsertNewInstBefore(NewNeg, I);
3468 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3473 case Instruction::Shl:
3474 case Instruction::LShr:
3475 // (1 << x) & 1 --> zext(x == 0)
3476 // (1 >> x) & 1 --> zext(x == 0)
3477 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3478 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3479 Constant::getNullValue(I.getType()));
3480 InsertNewInstBefore(NewICmp, I);
3481 return new ZExtInst(NewICmp, I.getType());
3486 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3487 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3489 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3490 // If this is an integer truncation or change from signed-to-unsigned, and
3491 // if the source is an and/or with immediate, transform it. This
3492 // frequently occurs for bitfield accesses.
3493 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3494 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3495 CastOp->getNumOperands() == 2)
3496 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3497 if (CastOp->getOpcode() == Instruction::And) {
3498 // Change: and (cast (and X, C1) to T), C2
3499 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3500 // This will fold the two constants together, which may allow
3501 // other simplifications.
3502 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3503 CastOp->getOperand(0), I.getType(),
3504 CastOp->getName()+".shrunk");
3505 NewCast = InsertNewInstBefore(NewCast, I);
3506 // trunc_or_bitcast(C1)&C2
3507 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3508 C3 = ConstantExpr::getAnd(C3, AndRHS);
3509 return BinaryOperator::CreateAnd(NewCast, C3);
3510 } else if (CastOp->getOpcode() == Instruction::Or) {
3511 // Change: and (cast (or X, C1) to T), C2
3512 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3513 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3514 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3515 return ReplaceInstUsesWith(I, AndRHS);
3521 // Try to fold constant and into select arguments.
3522 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3523 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3525 if (isa<PHINode>(Op0))
3526 if (Instruction *NV = FoldOpIntoPhi(I))
3530 Value *Op0NotVal = dyn_castNotVal(Op0);
3531 Value *Op1NotVal = dyn_castNotVal(Op1);
3533 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3534 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3536 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3537 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3538 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3539 I.getName()+".demorgan");
3540 InsertNewInstBefore(Or, I);
3541 return BinaryOperator::CreateNot(Or);
3545 Value *A = 0, *B = 0, *C = 0, *D = 0;
3546 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3547 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3548 return ReplaceInstUsesWith(I, Op1);
3550 // (A|B) & ~(A&B) -> A^B
3551 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3552 if ((A == C && B == D) || (A == D && B == C))
3553 return BinaryOperator::CreateXor(A, B);
3557 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3558 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3559 return ReplaceInstUsesWith(I, Op0);
3561 // ~(A&B) & (A|B) -> A^B
3562 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3563 if ((A == C && B == D) || (A == D && B == C))
3564 return BinaryOperator::CreateXor(A, B);
3568 if (Op0->hasOneUse() &&
3569 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3570 if (A == Op1) { // (A^B)&A -> A&(A^B)
3571 I.swapOperands(); // Simplify below
3572 std::swap(Op0, Op1);
3573 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3574 cast<BinaryOperator>(Op0)->swapOperands();
3575 I.swapOperands(); // Simplify below
3576 std::swap(Op0, Op1);
3579 if (Op1->hasOneUse() &&
3580 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3581 if (B == Op0) { // B&(A^B) -> B&(B^A)
3582 cast<BinaryOperator>(Op1)->swapOperands();
3585 if (A == Op0) { // A&(A^B) -> A & ~B
3586 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3587 InsertNewInstBefore(NotB, I);
3588 return BinaryOperator::CreateAnd(A, NotB);
3593 { // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3594 // where C is a power of 2
3596 ConstantInt *C1, *C2;
3597 ICmpInst::Predicate LHSCC = ICmpInst::BAD_ICMP_PREDICATE;
3598 ICmpInst::Predicate RHSCC = ICmpInst::BAD_ICMP_PREDICATE;
3599 if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3600 m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3601 if (C1 == C2 && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3602 C1->getValue().isPowerOf2()) {
3603 Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3604 InsertNewInstBefore(NewOr, I);
3605 return new ICmpInst(LHSCC, NewOr, C1);
3609 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3610 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3611 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3614 Value *LHSVal, *RHSVal;
3615 ConstantInt *LHSCst, *RHSCst;
3616 ICmpInst::Predicate LHSCC, RHSCC;
3617 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3618 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3619 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3620 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3621 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3622 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3623 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3624 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3626 // Don't try to fold ICMP_SLT + ICMP_ULT.
3627 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3628 ICmpInst::isSignedPredicate(LHSCC) ==
3629 ICmpInst::isSignedPredicate(RHSCC))) {
3630 // Ensure that the larger constant is on the RHS.
3631 ICmpInst::Predicate GT;
3632 if (ICmpInst::isSignedPredicate(LHSCC) ||
3633 (ICmpInst::isEquality(LHSCC) &&
3634 ICmpInst::isSignedPredicate(RHSCC)))
3635 GT = ICmpInst::ICMP_SGT;
3637 GT = ICmpInst::ICMP_UGT;
3639 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3640 ICmpInst *LHS = cast<ICmpInst>(Op0);
3641 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3642 std::swap(LHS, RHS);
3643 std::swap(LHSCst, RHSCst);
3644 std::swap(LHSCC, RHSCC);
3647 // At this point, we know we have have two icmp instructions
3648 // comparing a value against two constants and and'ing the result
3649 // together. Because of the above check, we know that we only have
3650 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3651 // (from the FoldICmpLogical check above), that the two constants
3652 // are not equal and that the larger constant is on the RHS
3653 assert(LHSCst != RHSCst && "Compares not folded above?");
3656 default: assert(0 && "Unknown integer condition code!");
3657 case ICmpInst::ICMP_EQ:
3659 default: assert(0 && "Unknown integer condition code!");
3660 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3661 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3662 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3663 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3664 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3665 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3666 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3667 return ReplaceInstUsesWith(I, LHS);
3669 case ICmpInst::ICMP_NE:
3671 default: assert(0 && "Unknown integer condition code!");
3672 case ICmpInst::ICMP_ULT:
3673 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3674 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3675 break; // (X != 13 & X u< 15) -> no change
3676 case ICmpInst::ICMP_SLT:
3677 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3678 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3679 break; // (X != 13 & X s< 15) -> no change
3680 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3681 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3682 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3683 return ReplaceInstUsesWith(I, RHS);
3684 case ICmpInst::ICMP_NE:
3685 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3686 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3687 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3688 LHSVal->getName()+".off");
3689 InsertNewInstBefore(Add, I);
3690 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3691 ConstantInt::get(Add->getType(), 1));
3693 break; // (X != 13 & X != 15) -> no change
3696 case ICmpInst::ICMP_ULT:
3698 default: assert(0 && "Unknown integer condition code!");
3699 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3700 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3701 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3702 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3704 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3705 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3706 return ReplaceInstUsesWith(I, LHS);
3707 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3711 case ICmpInst::ICMP_SLT:
3713 default: assert(0 && "Unknown integer condition code!");
3714 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3715 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3716 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3717 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3719 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3720 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3721 return ReplaceInstUsesWith(I, LHS);
3722 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3726 case ICmpInst::ICMP_UGT:
3728 default: assert(0 && "Unknown integer condition code!");
3729 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3730 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3731 return ReplaceInstUsesWith(I, RHS);
3732 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3734 case ICmpInst::ICMP_NE:
3735 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3736 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3737 break; // (X u> 13 & X != 15) -> no change
3738 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3739 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3741 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3745 case ICmpInst::ICMP_SGT:
3747 default: assert(0 && "Unknown integer condition code!");
3748 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3749 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3750 return ReplaceInstUsesWith(I, RHS);
3751 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3753 case ICmpInst::ICMP_NE:
3754 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3755 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3756 break; // (X s> 13 & X != 15) -> no change
3757 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3758 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3760 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3768 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3769 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3770 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3771 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3772 const Type *SrcTy = Op0C->getOperand(0)->getType();
3773 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3774 // Only do this if the casts both really cause code to be generated.
3775 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3777 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3779 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3780 Op1C->getOperand(0),
3782 InsertNewInstBefore(NewOp, I);
3783 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3787 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3788 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3789 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3790 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3791 SI0->getOperand(1) == SI1->getOperand(1) &&
3792 (SI0->hasOneUse() || SI1->hasOneUse())) {
3793 Instruction *NewOp =
3794 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3796 SI0->getName()), I);
3797 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
3798 SI1->getOperand(1));
3802 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3803 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3804 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3805 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3806 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3807 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3808 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3809 // If either of the constants are nans, then the whole thing returns
3811 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3812 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3813 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3814 RHS->getOperand(0));
3819 return Changed ? &I : 0;
3822 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3823 /// in the result. If it does, and if the specified byte hasn't been filled in
3824 /// yet, fill it in and return false.
3825 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3826 Instruction *I = dyn_cast<Instruction>(V);
3827 if (I == 0) return true;
3829 // If this is an or instruction, it is an inner node of the bswap.
3830 if (I->getOpcode() == Instruction::Or)
3831 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3832 CollectBSwapParts(I->getOperand(1), ByteValues);
3834 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3835 // If this is a shift by a constant int, and it is "24", then its operand
3836 // defines a byte. We only handle unsigned types here.
3837 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3838 // Not shifting the entire input by N-1 bytes?
3839 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3840 8*(ByteValues.size()-1))
3844 if (I->getOpcode() == Instruction::Shl) {
3845 // X << 24 defines the top byte with the lowest of the input bytes.
3846 DestNo = ByteValues.size()-1;
3848 // X >>u 24 defines the low byte with the highest of the input bytes.
3852 // If the destination byte value is already defined, the values are or'd
3853 // together, which isn't a bswap (unless it's an or of the same bits).
3854 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3856 ByteValues[DestNo] = I->getOperand(0);
3860 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3862 Value *Shift = 0, *ShiftLHS = 0;
3863 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3864 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3865 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3867 Instruction *SI = cast<Instruction>(Shift);
3869 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3870 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3871 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3874 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3876 if (AndAmt->getValue().getActiveBits() > 64)
3878 uint64_t AndAmtVal = AndAmt->getZExtValue();
3879 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3880 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3882 // Unknown mask for bswap.
3883 if (DestByte == ByteValues.size()) return true;
3885 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3887 if (SI->getOpcode() == Instruction::Shl)
3888 SrcByte = DestByte - ShiftBytes;
3890 SrcByte = DestByte + ShiftBytes;
3892 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3893 if (SrcByte != ByteValues.size()-DestByte-1)
3896 // If the destination byte value is already defined, the values are or'd
3897 // together, which isn't a bswap (unless it's an or of the same bits).
3898 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3900 ByteValues[DestByte] = SI->getOperand(0);
3904 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3905 /// If so, insert the new bswap intrinsic and return it.
3906 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3907 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3908 if (!ITy || ITy->getBitWidth() % 16)
3909 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3911 /// ByteValues - For each byte of the result, we keep track of which value
3912 /// defines each byte.
3913 SmallVector<Value*, 8> ByteValues;
3914 ByteValues.resize(ITy->getBitWidth()/8);
3916 // Try to find all the pieces corresponding to the bswap.
3917 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3918 CollectBSwapParts(I.getOperand(1), ByteValues))
3921 // Check to see if all of the bytes come from the same value.
3922 Value *V = ByteValues[0];
3923 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3925 // Check to make sure that all of the bytes come from the same value.
3926 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3927 if (ByteValues[i] != V)
3929 const Type *Tys[] = { ITy };
3930 Module *M = I.getParent()->getParent()->getParent();
3931 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3932 return CallInst::Create(F, V);
3936 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3937 bool Changed = SimplifyCommutative(I);
3938 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3940 if (isa<UndefValue>(Op1)) // X | undef -> -1
3941 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3945 return ReplaceInstUsesWith(I, Op0);
3947 // See if we can simplify any instructions used by the instruction whose sole
3948 // purpose is to compute bits we don't care about.
3949 if (!isa<VectorType>(I.getType())) {
3950 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3951 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3952 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3953 KnownZero, KnownOne))
3955 } else if (isa<ConstantAggregateZero>(Op1)) {
3956 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3957 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3958 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3959 return ReplaceInstUsesWith(I, I.getOperand(1));
3965 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3966 ConstantInt *C1 = 0; Value *X = 0;
3967 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3968 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3969 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3970 InsertNewInstBefore(Or, I);
3972 return BinaryOperator::CreateAnd(Or,
3973 ConstantInt::get(RHS->getValue() | C1->getValue()));
3976 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3977 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3978 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3979 InsertNewInstBefore(Or, I);
3981 return BinaryOperator::CreateXor(Or,
3982 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3985 // Try to fold constant and into select arguments.
3986 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3987 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3989 if (isa<PHINode>(Op0))
3990 if (Instruction *NV = FoldOpIntoPhi(I))
3994 Value *A = 0, *B = 0;
3995 ConstantInt *C1 = 0, *C2 = 0;
3997 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3998 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3999 return ReplaceInstUsesWith(I, Op1);
4000 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4001 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4002 return ReplaceInstUsesWith(I, Op0);
4004 // (A | B) | C and A | (B | C) -> bswap if possible.
4005 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4006 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4007 match(Op1, m_Or(m_Value(), m_Value())) ||
4008 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4009 match(Op1, m_Shift(m_Value(), m_Value())))) {
4010 if (Instruction *BSwap = MatchBSwap(I))
4014 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4015 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4016 MaskedValueIsZero(Op1, C1->getValue())) {
4017 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4018 InsertNewInstBefore(NOr, I);
4020 return BinaryOperator::CreateXor(NOr, C1);
4023 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4024 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4025 MaskedValueIsZero(Op0, C1->getValue())) {
4026 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4027 InsertNewInstBefore(NOr, I);
4029 return BinaryOperator::CreateXor(NOr, C1);
4033 Value *C = 0, *D = 0;
4034 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4035 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4036 Value *V1 = 0, *V2 = 0, *V3 = 0;
4037 C1 = dyn_cast<ConstantInt>(C);
4038 C2 = dyn_cast<ConstantInt>(D);
4039 if (C1 && C2) { // (A & C1)|(B & C2)
4040 // If we have: ((V + N) & C1) | (V & C2)
4041 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4042 // replace with V+N.
4043 if (C1->getValue() == ~C2->getValue()) {
4044 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4045 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4046 // Add commutes, try both ways.
4047 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4048 return ReplaceInstUsesWith(I, A);
4049 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4050 return ReplaceInstUsesWith(I, A);
4052 // Or commutes, try both ways.
4053 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4054 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4055 // Add commutes, try both ways.
4056 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4057 return ReplaceInstUsesWith(I, B);
4058 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4059 return ReplaceInstUsesWith(I, B);
4062 V1 = 0; V2 = 0; V3 = 0;
4065 // Check to see if we have any common things being and'ed. If so, find the
4066 // terms for V1 & (V2|V3).
4067 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4068 if (A == B) // (A & C)|(A & D) == A & (C|D)
4069 V1 = A, V2 = C, V3 = D;
4070 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4071 V1 = A, V2 = B, V3 = C;
4072 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4073 V1 = C, V2 = A, V3 = D;
4074 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4075 V1 = C, V2 = A, V3 = B;
4079 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4080 return BinaryOperator::CreateAnd(V1, Or);
4085 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4086 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4087 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4088 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4089 SI0->getOperand(1) == SI1->getOperand(1) &&
4090 (SI0->hasOneUse() || SI1->hasOneUse())) {
4091 Instruction *NewOp =
4092 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4094 SI0->getName()), I);
4095 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4096 SI1->getOperand(1));
4100 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4101 if (A == Op1) // ~A | A == -1
4102 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4106 // Note, A is still live here!
4107 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4109 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4111 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4112 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4113 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4114 I.getName()+".demorgan"), I);
4115 return BinaryOperator::CreateNot(And);
4119 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4120 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4121 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4124 Value *LHSVal, *RHSVal;
4125 ConstantInt *LHSCst, *RHSCst;
4126 ICmpInst::Predicate LHSCC, RHSCC;
4127 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4128 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4129 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4130 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4131 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4132 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4133 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4134 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4135 // We can't fold (ugt x, C) | (sgt x, C2).
4136 PredicatesFoldable(LHSCC, RHSCC)) {
4137 // Ensure that the larger constant is on the RHS.
4138 ICmpInst *LHS = cast<ICmpInst>(Op0);
4140 if (ICmpInst::isSignedPredicate(LHSCC))
4141 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4143 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4146 std::swap(LHS, RHS);
4147 std::swap(LHSCst, RHSCst);
4148 std::swap(LHSCC, RHSCC);
4151 // At this point, we know we have have two icmp instructions
4152 // comparing a value against two constants and or'ing the result
4153 // together. Because of the above check, we know that we only have
4154 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4155 // FoldICmpLogical check above), that the two constants are not
4157 assert(LHSCst != RHSCst && "Compares not folded above?");
4160 default: assert(0 && "Unknown integer condition code!");
4161 case ICmpInst::ICMP_EQ:
4163 default: assert(0 && "Unknown integer condition code!");
4164 case ICmpInst::ICMP_EQ:
4165 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4166 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4167 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4168 LHSVal->getName()+".off");
4169 InsertNewInstBefore(Add, I);
4170 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4171 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4173 break; // (X == 13 | X == 15) -> no change
4174 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4175 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4177 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4178 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4179 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4180 return ReplaceInstUsesWith(I, RHS);
4183 case ICmpInst::ICMP_NE:
4185 default: assert(0 && "Unknown integer condition code!");
4186 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4187 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4188 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4189 return ReplaceInstUsesWith(I, LHS);
4190 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4191 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4192 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4193 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4196 case ICmpInst::ICMP_ULT:
4198 default: assert(0 && "Unknown integer condition code!");
4199 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4201 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4202 // If RHSCst is [us]MAXINT, it is always false. Not handling
4203 // this can cause overflow.
4204 if (RHSCst->isMaxValue(false))
4205 return ReplaceInstUsesWith(I, LHS);
4206 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4208 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4210 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4211 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4212 return ReplaceInstUsesWith(I, RHS);
4213 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4217 case ICmpInst::ICMP_SLT:
4219 default: assert(0 && "Unknown integer condition code!");
4220 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4222 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4223 // If RHSCst is [us]MAXINT, it is always false. Not handling
4224 // this can cause overflow.
4225 if (RHSCst->isMaxValue(true))
4226 return ReplaceInstUsesWith(I, LHS);
4227 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4229 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4231 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4232 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4233 return ReplaceInstUsesWith(I, RHS);
4234 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4238 case ICmpInst::ICMP_UGT:
4240 default: assert(0 && "Unknown integer condition code!");
4241 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4242 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4243 return ReplaceInstUsesWith(I, LHS);
4244 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4246 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4247 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4248 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4249 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4253 case ICmpInst::ICMP_SGT:
4255 default: assert(0 && "Unknown integer condition code!");
4256 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4257 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4258 return ReplaceInstUsesWith(I, LHS);
4259 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4261 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4262 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4263 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4264 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4272 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4273 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4274 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4275 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4276 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4277 !isa<ICmpInst>(Op1C->getOperand(0))) {
4278 const Type *SrcTy = Op0C->getOperand(0)->getType();
4279 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4280 // Only do this if the casts both really cause code to be
4282 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4284 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4286 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4287 Op1C->getOperand(0),
4289 InsertNewInstBefore(NewOp, I);
4290 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4297 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4298 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4299 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4300 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4301 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4302 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4303 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4304 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4305 // If either of the constants are nans, then the whole thing returns
4307 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4308 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4310 // Otherwise, no need to compare the two constants, compare the
4312 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4313 RHS->getOperand(0));
4318 return Changed ? &I : 0;
4323 // XorSelf - Implements: X ^ X --> 0
4326 XorSelf(Value *rhs) : RHS(rhs) {}
4327 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4328 Instruction *apply(BinaryOperator &Xor) const {
4335 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4336 bool Changed = SimplifyCommutative(I);
4337 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4339 if (isa<UndefValue>(Op1)) {
4340 if (isa<UndefValue>(Op0))
4341 // Handle undef ^ undef -> 0 special case. This is a common
4343 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4344 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4347 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4348 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4349 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4350 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4353 // See if we can simplify any instructions used by the instruction whose sole
4354 // purpose is to compute bits we don't care about.
4355 if (!isa<VectorType>(I.getType())) {
4356 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4357 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4358 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4359 KnownZero, KnownOne))
4361 } else if (isa<ConstantAggregateZero>(Op1)) {
4362 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4365 // Is this a ~ operation?
4366 if (Value *NotOp = dyn_castNotVal(&I)) {
4367 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4368 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4369 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4370 if (Op0I->getOpcode() == Instruction::And ||
4371 Op0I->getOpcode() == Instruction::Or) {
4372 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4373 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4375 BinaryOperator::CreateNot(Op0I->getOperand(1),
4376 Op0I->getOperand(1)->getName()+".not");
4377 InsertNewInstBefore(NotY, I);
4378 if (Op0I->getOpcode() == Instruction::And)
4379 return BinaryOperator::CreateOr(Op0NotVal, NotY);
4381 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4388 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4389 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4390 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4391 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4392 return new ICmpInst(ICI->getInversePredicate(),
4393 ICI->getOperand(0), ICI->getOperand(1));
4395 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4396 return new FCmpInst(FCI->getInversePredicate(),
4397 FCI->getOperand(0), FCI->getOperand(1));
4400 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4401 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4402 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4403 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4404 Instruction::CastOps Opcode = Op0C->getOpcode();
4405 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4406 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4407 Op0C->getDestTy())) {
4408 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4409 CI->getOpcode(), CI->getInversePredicate(),
4410 CI->getOperand(0), CI->getOperand(1)), I);
4411 NewCI->takeName(CI);
4412 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4419 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4420 // ~(c-X) == X-c-1 == X+(-c-1)
4421 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4422 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4423 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4424 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4425 ConstantInt::get(I.getType(), 1));
4426 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4429 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4430 if (Op0I->getOpcode() == Instruction::Add) {
4431 // ~(X-c) --> (-c-1)-X
4432 if (RHS->isAllOnesValue()) {
4433 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4434 return BinaryOperator::CreateSub(
4435 ConstantExpr::getSub(NegOp0CI,
4436 ConstantInt::get(I.getType(), 1)),
4437 Op0I->getOperand(0));
4438 } else if (RHS->getValue().isSignBit()) {
4439 // (X + C) ^ signbit -> (X + C + signbit)
4440 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4441 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4444 } else if (Op0I->getOpcode() == Instruction::Or) {
4445 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4446 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4447 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4448 // Anything in both C1 and C2 is known to be zero, remove it from
4450 Constant *CommonBits = And(Op0CI, RHS);
4451 NewRHS = ConstantExpr::getAnd(NewRHS,
4452 ConstantExpr::getNot(CommonBits));
4453 AddToWorkList(Op0I);
4454 I.setOperand(0, Op0I->getOperand(0));
4455 I.setOperand(1, NewRHS);
4462 // Try to fold constant and into select arguments.
4463 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4466 if (isa<PHINode>(Op0))
4467 if (Instruction *NV = FoldOpIntoPhi(I))
4471 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4473 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4475 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4477 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4480 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4483 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4484 if (A == Op0) { // B^(B|A) == (A|B)^B
4485 Op1I->swapOperands();
4487 std::swap(Op0, Op1);
4488 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4489 I.swapOperands(); // Simplified below.
4490 std::swap(Op0, Op1);
4492 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4493 if (Op0 == A) // A^(A^B) == B
4494 return ReplaceInstUsesWith(I, B);
4495 else if (Op0 == B) // A^(B^A) == B
4496 return ReplaceInstUsesWith(I, A);
4497 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4498 if (A == Op0) { // A^(A&B) -> A^(B&A)
4499 Op1I->swapOperands();
4502 if (B == Op0) { // A^(B&A) -> (B&A)^A
4503 I.swapOperands(); // Simplified below.
4504 std::swap(Op0, Op1);
4509 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4512 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4513 if (A == Op1) // (B|A)^B == (A|B)^B
4515 if (B == Op1) { // (A|B)^B == A & ~B
4517 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4518 return BinaryOperator::CreateAnd(A, NotB);
4520 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4521 if (Op1 == A) // (A^B)^A == B
4522 return ReplaceInstUsesWith(I, B);
4523 else if (Op1 == B) // (B^A)^A == B
4524 return ReplaceInstUsesWith(I, A);
4525 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4526 if (A == Op1) // (A&B)^A -> (B&A)^A
4528 if (B == Op1 && // (B&A)^A == ~B & A
4529 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4531 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4532 return BinaryOperator::CreateAnd(N, Op1);
4537 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4538 if (Op0I && Op1I && Op0I->isShift() &&
4539 Op0I->getOpcode() == Op1I->getOpcode() &&
4540 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4541 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4542 Instruction *NewOp =
4543 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4544 Op1I->getOperand(0),
4545 Op0I->getName()), I);
4546 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
4547 Op1I->getOperand(1));
4551 Value *A, *B, *C, *D;
4552 // (A & B)^(A | B) -> A ^ B
4553 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4554 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4555 if ((A == C && B == D) || (A == D && B == C))
4556 return BinaryOperator::CreateXor(A, B);
4558 // (A | B)^(A & B) -> A ^ B
4559 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4560 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4561 if ((A == C && B == D) || (A == D && B == C))
4562 return BinaryOperator::CreateXor(A, B);
4566 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4567 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4568 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4569 // (X & Y)^(X & Y) -> (Y^Z) & X
4570 Value *X = 0, *Y = 0, *Z = 0;
4572 X = A, Y = B, Z = D;
4574 X = A, Y = B, Z = C;
4576 X = B, Y = A, Z = D;
4578 X = B, Y = A, Z = C;
4581 Instruction *NewOp =
4582 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4583 return BinaryOperator::CreateAnd(NewOp, X);
4588 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4589 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4590 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4593 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4594 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4595 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4596 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4597 const Type *SrcTy = Op0C->getOperand(0)->getType();
4598 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4599 // Only do this if the casts both really cause code to be generated.
4600 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4602 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4604 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4605 Op1C->getOperand(0),
4607 InsertNewInstBefore(NewOp, I);
4608 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4613 return Changed ? &I : 0;
4616 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4617 /// overflowed for this type.
4618 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4619 ConstantInt *In2, bool IsSigned = false) {
4620 Result = cast<ConstantInt>(Add(In1, In2));
4623 if (In2->getValue().isNegative())
4624 return Result->getValue().sgt(In1->getValue());
4626 return Result->getValue().slt(In1->getValue());
4628 return Result->getValue().ult(In1->getValue());
4631 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4632 /// code necessary to compute the offset from the base pointer (without adding
4633 /// in the base pointer). Return the result as a signed integer of intptr size.
4634 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4635 TargetData &TD = IC.getTargetData();
4636 gep_type_iterator GTI = gep_type_begin(GEP);
4637 const Type *IntPtrTy = TD.getIntPtrType();
4638 Value *Result = Constant::getNullValue(IntPtrTy);
4640 // Build a mask for high order bits.
4641 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4642 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4644 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4647 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4648 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4649 if (OpC->isZero()) continue;
4651 // Handle a struct index, which adds its field offset to the pointer.
4652 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4653 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4655 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4656 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4658 Result = IC.InsertNewInstBefore(
4659 BinaryOperator::CreateAdd(Result,
4660 ConstantInt::get(IntPtrTy, Size),
4661 GEP->getName()+".offs"), I);
4665 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4666 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4667 Scale = ConstantExpr::getMul(OC, Scale);
4668 if (Constant *RC = dyn_cast<Constant>(Result))
4669 Result = ConstantExpr::getAdd(RC, Scale);
4671 // Emit an add instruction.
4672 Result = IC.InsertNewInstBefore(
4673 BinaryOperator::CreateAdd(Result, Scale,
4674 GEP->getName()+".offs"), I);
4678 // Convert to correct type.
4679 if (Op->getType() != IntPtrTy) {
4680 if (Constant *OpC = dyn_cast<Constant>(Op))
4681 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4683 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4684 Op->getName()+".c"), I);
4687 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4688 if (Constant *OpC = dyn_cast<Constant>(Op))
4689 Op = ConstantExpr::getMul(OpC, Scale);
4690 else // We'll let instcombine(mul) convert this to a shl if possible.
4691 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4692 GEP->getName()+".idx"), I);
4695 // Emit an add instruction.
4696 if (isa<Constant>(Op) && isa<Constant>(Result))
4697 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4698 cast<Constant>(Result));
4700 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4701 GEP->getName()+".offs"), I);
4707 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4708 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4709 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4710 /// complex, and scales are involved. The above expression would also be legal
4711 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4712 /// later form is less amenable to optimization though, and we are allowed to
4713 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4715 /// If we can't emit an optimized form for this expression, this returns null.
4717 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4719 TargetData &TD = IC.getTargetData();
4720 gep_type_iterator GTI = gep_type_begin(GEP);
4722 // Check to see if this gep only has a single variable index. If so, and if
4723 // any constant indices are a multiple of its scale, then we can compute this
4724 // in terms of the scale of the variable index. For example, if the GEP
4725 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4726 // because the expression will cross zero at the same point.
4727 unsigned i, e = GEP->getNumOperands();
4729 for (i = 1; i != e; ++i, ++GTI) {
4730 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4731 // Compute the aggregate offset of constant indices.
4732 if (CI->isZero()) continue;
4734 // Handle a struct index, which adds its field offset to the pointer.
4735 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4736 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4738 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4739 Offset += Size*CI->getSExtValue();
4742 // Found our variable index.
4747 // If there are no variable indices, we must have a constant offset, just
4748 // evaluate it the general way.
4749 if (i == e) return 0;
4751 Value *VariableIdx = GEP->getOperand(i);
4752 // Determine the scale factor of the variable element. For example, this is
4753 // 4 if the variable index is into an array of i32.
4754 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4756 // Verify that there are no other variable indices. If so, emit the hard way.
4757 for (++i, ++GTI; i != e; ++i, ++GTI) {
4758 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4761 // Compute the aggregate offset of constant indices.
4762 if (CI->isZero()) continue;
4764 // Handle a struct index, which adds its field offset to the pointer.
4765 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4766 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4768 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4769 Offset += Size*CI->getSExtValue();
4773 // Okay, we know we have a single variable index, which must be a
4774 // pointer/array/vector index. If there is no offset, life is simple, return
4776 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4778 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4779 // we don't need to bother extending: the extension won't affect where the
4780 // computation crosses zero.
4781 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4782 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4783 VariableIdx->getNameStart(), &I);
4787 // Otherwise, there is an index. The computation we will do will be modulo
4788 // the pointer size, so get it.
4789 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4791 Offset &= PtrSizeMask;
4792 VariableScale &= PtrSizeMask;
4794 // To do this transformation, any constant index must be a multiple of the
4795 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4796 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4797 // multiple of the variable scale.
4798 int64_t NewOffs = Offset / (int64_t)VariableScale;
4799 if (Offset != NewOffs*(int64_t)VariableScale)
4802 // Okay, we can do this evaluation. Start by converting the index to intptr.
4803 const Type *IntPtrTy = TD.getIntPtrType();
4804 if (VariableIdx->getType() != IntPtrTy)
4805 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4807 VariableIdx->getNameStart(), &I);
4808 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4809 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4813 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4814 /// else. At this point we know that the GEP is on the LHS of the comparison.
4815 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4816 ICmpInst::Predicate Cond,
4818 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4820 // Look through bitcasts.
4821 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4822 RHS = BCI->getOperand(0);
4824 Value *PtrBase = GEPLHS->getOperand(0);
4825 if (PtrBase == RHS) {
4826 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4827 // This transformation (ignoring the base and scales) is valid because we
4828 // know pointers can't overflow. See if we can output an optimized form.
4829 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4831 // If not, synthesize the offset the hard way.
4833 Offset = EmitGEPOffset(GEPLHS, I, *this);
4834 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4835 Constant::getNullValue(Offset->getType()));
4836 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4837 // If the base pointers are different, but the indices are the same, just
4838 // compare the base pointer.
4839 if (PtrBase != GEPRHS->getOperand(0)) {
4840 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4841 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4842 GEPRHS->getOperand(0)->getType();
4844 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4845 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4846 IndicesTheSame = false;
4850 // If all indices are the same, just compare the base pointers.
4852 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4853 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4855 // Otherwise, the base pointers are different and the indices are
4856 // different, bail out.
4860 // If one of the GEPs has all zero indices, recurse.
4861 bool AllZeros = true;
4862 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4863 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4864 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4869 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4870 ICmpInst::getSwappedPredicate(Cond), I);
4872 // If the other GEP has all zero indices, recurse.
4874 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4875 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4876 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4881 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4883 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4884 // If the GEPs only differ by one index, compare it.
4885 unsigned NumDifferences = 0; // Keep track of # differences.
4886 unsigned DiffOperand = 0; // The operand that differs.
4887 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4888 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4889 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4890 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4891 // Irreconcilable differences.
4895 if (NumDifferences++) break;
4900 if (NumDifferences == 0) // SAME GEP?
4901 return ReplaceInstUsesWith(I, // No comparison is needed here.
4902 ConstantInt::get(Type::Int1Ty,
4903 ICmpInst::isTrueWhenEqual(Cond)));
4905 else if (NumDifferences == 1) {
4906 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4907 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4908 // Make sure we do a signed comparison here.
4909 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4913 // Only lower this if the icmp is the only user of the GEP or if we expect
4914 // the result to fold to a constant!
4915 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4916 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4917 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4918 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4919 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4920 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4926 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4928 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4931 if (!isa<ConstantFP>(RHSC)) return 0;
4932 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4934 // Get the width of the mantissa. We don't want to hack on conversions that
4935 // might lose information from the integer, e.g. "i64 -> float"
4936 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4937 if (MantissaWidth == -1) return 0; // Unknown.
4939 // Check to see that the input is converted from an integer type that is small
4940 // enough that preserves all bits. TODO: check here for "known" sign bits.
4941 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4942 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4944 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4945 if (isa<UIToFPInst>(LHSI))
4948 // If the conversion would lose info, don't hack on this.
4949 if ((int)InputSize > MantissaWidth)
4952 // Otherwise, we can potentially simplify the comparison. We know that it
4953 // will always come through as an integer value and we know the constant is
4954 // not a NAN (it would have been previously simplified).
4955 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4957 ICmpInst::Predicate Pred;
4958 switch (I.getPredicate()) {
4959 default: assert(0 && "Unexpected predicate!");
4960 case FCmpInst::FCMP_UEQ:
4961 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4962 case FCmpInst::FCMP_UGT:
4963 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4964 case FCmpInst::FCMP_UGE:
4965 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4966 case FCmpInst::FCMP_ULT:
4967 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4968 case FCmpInst::FCMP_ULE:
4969 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4970 case FCmpInst::FCMP_UNE:
4971 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4972 case FCmpInst::FCMP_ORD:
4973 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4974 case FCmpInst::FCMP_UNO:
4975 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4978 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4980 // Now we know that the APFloat is a normal number, zero or inf.
4982 // See if the FP constant is too large for the integer. For example,
4983 // comparing an i8 to 300.0.
4984 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4986 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4987 // and large values.
4988 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4989 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4990 APFloat::rmNearestTiesToEven);
4991 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4992 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4993 Pred == ICmpInst::ICMP_SLE)
4994 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4995 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4998 // See if the RHS value is < SignedMin.
4999 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5000 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5001 APFloat::rmNearestTiesToEven);
5002 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5003 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5004 Pred == ICmpInst::ICMP_SGE)
5005 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5006 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5009 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5010 // it may still be fractional. See if it is fractional by casting the FP
5011 // value to the integer value and back, checking for equality. Don't do this
5012 // for zero, because -0.0 is not fractional.
5013 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5014 if (!RHS.isZero() &&
5015 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5016 // If we had a comparison against a fractional value, we have to adjust
5017 // the compare predicate and sometimes the value. RHSC is rounded towards
5018 // zero at this point.
5020 default: assert(0 && "Unexpected integer comparison!");
5021 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5022 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5023 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5024 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5025 case ICmpInst::ICMP_SLE:
5026 // (float)int <= 4.4 --> int <= 4
5027 // (float)int <= -4.4 --> int < -4
5028 if (RHS.isNegative())
5029 Pred = ICmpInst::ICMP_SLT;
5031 case ICmpInst::ICMP_SLT:
5032 // (float)int < -4.4 --> int < -4
5033 // (float)int < 4.4 --> int <= 4
5034 if (!RHS.isNegative())
5035 Pred = ICmpInst::ICMP_SLE;
5037 case ICmpInst::ICMP_SGT:
5038 // (float)int > 4.4 --> int > 4
5039 // (float)int > -4.4 --> int >= -4
5040 if (RHS.isNegative())
5041 Pred = ICmpInst::ICMP_SGE;
5043 case ICmpInst::ICMP_SGE:
5044 // (float)int >= -4.4 --> int >= -4
5045 // (float)int >= 4.4 --> int > 4
5046 if (!RHS.isNegative())
5047 Pred = ICmpInst::ICMP_SGT;
5052 // Lower this FP comparison into an appropriate integer version of the
5054 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5057 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5058 bool Changed = SimplifyCompare(I);
5059 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5061 // Fold trivial predicates.
5062 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5063 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5064 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5065 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5067 // Simplify 'fcmp pred X, X'
5069 switch (I.getPredicate()) {
5070 default: assert(0 && "Unknown predicate!");
5071 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5072 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5073 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5074 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5075 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5076 case FCmpInst::FCMP_OLT: // True if ordered and less than
5077 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5078 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5080 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5081 case FCmpInst::FCMP_ULT: // True if unordered or less than
5082 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5083 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5084 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5085 I.setPredicate(FCmpInst::FCMP_UNO);
5086 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5089 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5090 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5091 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5092 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5093 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5094 I.setPredicate(FCmpInst::FCMP_ORD);
5095 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5100 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5101 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5103 // Handle fcmp with constant RHS
5104 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5105 // If the constant is a nan, see if we can fold the comparison based on it.
5106 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5107 if (CFP->getValueAPF().isNaN()) {
5108 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5109 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5110 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5111 "Comparison must be either ordered or unordered!");
5112 // True if unordered.
5113 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5117 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5118 switch (LHSI->getOpcode()) {
5119 case Instruction::PHI:
5120 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5121 // block. If in the same block, we're encouraging jump threading. If
5122 // not, we are just pessimizing the code by making an i1 phi.
5123 if (LHSI->getParent() == I.getParent())
5124 if (Instruction *NV = FoldOpIntoPhi(I))
5127 case Instruction::SIToFP:
5128 case Instruction::UIToFP:
5129 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5132 case Instruction::Select:
5133 // If either operand of the select is a constant, we can fold the
5134 // comparison into the select arms, which will cause one to be
5135 // constant folded and the select turned into a bitwise or.
5136 Value *Op1 = 0, *Op2 = 0;
5137 if (LHSI->hasOneUse()) {
5138 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5139 // Fold the known value into the constant operand.
5140 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5141 // Insert a new FCmp of the other select operand.
5142 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5143 LHSI->getOperand(2), RHSC,
5145 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5146 // Fold the known value into the constant operand.
5147 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5148 // Insert a new FCmp of the other select operand.
5149 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5150 LHSI->getOperand(1), RHSC,
5156 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5161 return Changed ? &I : 0;
5164 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5165 bool Changed = SimplifyCompare(I);
5166 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5167 const Type *Ty = Op0->getType();
5171 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5172 I.isTrueWhenEqual()));
5174 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5175 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5177 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5178 // addresses never equal each other! We already know that Op0 != Op1.
5179 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5180 isa<ConstantPointerNull>(Op0)) &&
5181 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5182 isa<ConstantPointerNull>(Op1)))
5183 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5184 !I.isTrueWhenEqual()));
5186 // icmp's with boolean values can always be turned into bitwise operations
5187 if (Ty == Type::Int1Ty) {
5188 switch (I.getPredicate()) {
5189 default: assert(0 && "Invalid icmp instruction!");
5190 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5191 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5192 InsertNewInstBefore(Xor, I);
5193 return BinaryOperator::CreateNot(Xor);
5195 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5196 return BinaryOperator::CreateXor(Op0, Op1);
5198 case ICmpInst::ICMP_UGT:
5199 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5201 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5202 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5203 InsertNewInstBefore(Not, I);
5204 return BinaryOperator::CreateAnd(Not, Op1);
5206 case ICmpInst::ICMP_SGT:
5207 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5209 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5210 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5211 InsertNewInstBefore(Not, I);
5212 return BinaryOperator::CreateAnd(Not, Op0);
5214 case ICmpInst::ICMP_UGE:
5215 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5217 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
5218 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5219 InsertNewInstBefore(Not, I);
5220 return BinaryOperator::CreateOr(Not, Op1);
5222 case ICmpInst::ICMP_SGE:
5223 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5225 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5226 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5227 InsertNewInstBefore(Not, I);
5228 return BinaryOperator::CreateOr(Not, Op0);
5233 // See if we are doing a comparison between a constant and an instruction that
5234 // can be folded into the comparison.
5235 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5238 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5239 if (I.isEquality() && CI->isNullValue() &&
5240 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5241 // (icmp cond A B) if cond is equality
5242 return new ICmpInst(I.getPredicate(), A, B);
5245 // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5246 // icmp lt or icmp gt instruction. This allows us to rely on them being
5247 // folded in the code below.
5248 switch (I.getPredicate()) {
5250 case ICmpInst::ICMP_ULE:
5251 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5252 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5253 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5254 case ICmpInst::ICMP_SLE:
5255 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5256 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5257 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5258 case ICmpInst::ICMP_UGE:
5259 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5260 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5261 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5262 case ICmpInst::ICMP_SGE:
5263 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5264 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5265 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5268 // See if we can fold the comparison based on range information we can get
5269 // by checking whether bits are known to be zero or one in the input.
5270 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5271 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5273 // If this comparison is a normal comparison, it demands all
5274 // bits, if it is a sign bit comparison, it only demands the sign bit.
5276 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5278 if (SimplifyDemandedBits(Op0,
5279 isSignBit ? APInt::getSignBit(BitWidth)
5280 : APInt::getAllOnesValue(BitWidth),
5281 KnownZero, KnownOne, 0))
5284 // Given the known and unknown bits, compute a range that the LHS could be
5285 // in. Compute the Min, Max and RHS values based on the known bits. For the
5286 // EQ and NE we use unsigned values.
5287 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5288 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5289 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5291 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5293 // If Min and Max are known to be the same, then SimplifyDemandedBits
5294 // figured out that the LHS is a constant. Just constant fold this now so
5295 // that code below can assume that Min != Max.
5297 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5298 ConstantInt::get(Min),
5301 // Based on the range information we know about the LHS, see if we can
5302 // simplify this comparison. For example, (x&4) < 8 is always true.
5303 const APInt &RHSVal = CI->getValue();
5304 switch (I.getPredicate()) { // LE/GE have been folded already.
5305 default: assert(0 && "Unknown icmp opcode!");
5306 case ICmpInst::ICMP_EQ:
5307 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5308 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5310 case ICmpInst::ICMP_NE:
5311 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5312 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5314 case ICmpInst::ICMP_ULT:
5315 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
5316 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5317 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
5318 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5319 if (RHSVal == Max) // A <u MAX -> A != MAX
5320 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5321 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5322 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5324 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5325 if (CI->isMinValue(true))
5326 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5327 ConstantInt::getAllOnesValue(Op0->getType()));
5329 case ICmpInst::ICMP_UGT:
5330 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
5331 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5332 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
5333 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5335 if (RHSVal == Min) // A >u MIN -> A != MIN
5336 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5337 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5338 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5340 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5341 if (CI->isMaxValue(true))
5342 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5343 ConstantInt::getNullValue(Op0->getType()));
5345 case ICmpInst::ICMP_SLT:
5346 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
5347 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5348 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
5349 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5350 if (RHSVal == Max) // A <s MAX -> A != MAX
5351 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5352 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
5353 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5355 case ICmpInst::ICMP_SGT:
5356 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
5357 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5358 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
5359 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5361 if (RHSVal == Min) // A >s MIN -> A != MIN
5362 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5363 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5364 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5368 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5369 // instruction, see if that instruction also has constants so that the
5370 // instruction can be folded into the icmp
5371 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5372 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5376 // Handle icmp with constant (but not simple integer constant) RHS
5377 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5378 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5379 switch (LHSI->getOpcode()) {
5380 case Instruction::GetElementPtr:
5381 if (RHSC->isNullValue()) {
5382 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5383 bool isAllZeros = true;
5384 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5385 if (!isa<Constant>(LHSI->getOperand(i)) ||
5386 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5391 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5392 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5396 case Instruction::PHI:
5397 // Only fold icmp into the PHI if the phi and fcmp are in the same
5398 // block. If in the same block, we're encouraging jump threading. If
5399 // not, we are just pessimizing the code by making an i1 phi.
5400 if (LHSI->getParent() == I.getParent())
5401 if (Instruction *NV = FoldOpIntoPhi(I))
5404 case Instruction::Select: {
5405 // If either operand of the select is a constant, we can fold the
5406 // comparison into the select arms, which will cause one to be
5407 // constant folded and the select turned into a bitwise or.
5408 Value *Op1 = 0, *Op2 = 0;
5409 if (LHSI->hasOneUse()) {
5410 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5411 // Fold the known value into the constant operand.
5412 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5413 // Insert a new ICmp of the other select operand.
5414 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5415 LHSI->getOperand(2), RHSC,
5417 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5418 // Fold the known value into the constant operand.
5419 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5420 // Insert a new ICmp of the other select operand.
5421 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5422 LHSI->getOperand(1), RHSC,
5428 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5431 case Instruction::Malloc:
5432 // If we have (malloc != null), and if the malloc has a single use, we
5433 // can assume it is successful and remove the malloc.
5434 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5435 AddToWorkList(LHSI);
5436 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5437 !I.isTrueWhenEqual()));
5443 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5444 if (User *GEP = dyn_castGetElementPtr(Op0))
5445 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5447 if (User *GEP = dyn_castGetElementPtr(Op1))
5448 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5449 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5452 // Test to see if the operands of the icmp are casted versions of other
5453 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5455 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5456 if (isa<PointerType>(Op0->getType()) &&
5457 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5458 // We keep moving the cast from the left operand over to the right
5459 // operand, where it can often be eliminated completely.
5460 Op0 = CI->getOperand(0);
5462 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5463 // so eliminate it as well.
5464 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5465 Op1 = CI2->getOperand(0);
5467 // If Op1 is a constant, we can fold the cast into the constant.
5468 if (Op0->getType() != Op1->getType()) {
5469 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5470 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5472 // Otherwise, cast the RHS right before the icmp
5473 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5476 return new ICmpInst(I.getPredicate(), Op0, Op1);
5480 if (isa<CastInst>(Op0)) {
5481 // Handle the special case of: icmp (cast bool to X), <cst>
5482 // This comes up when you have code like
5485 // For generality, we handle any zero-extension of any operand comparison
5486 // with a constant or another cast from the same type.
5487 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5488 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5492 // See if it's the same type of instruction on the left and right.
5493 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5494 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5495 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5496 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5498 switch (Op0I->getOpcode()) {
5500 case Instruction::Add:
5501 case Instruction::Sub:
5502 case Instruction::Xor:
5503 // a+x icmp eq/ne b+x --> a icmp b
5504 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5505 Op1I->getOperand(0));
5507 case Instruction::Mul:
5508 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5509 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5510 // Mask = -1 >> count-trailing-zeros(Cst).
5511 if (!CI->isZero() && !CI->isOne()) {
5512 const APInt &AP = CI->getValue();
5513 ConstantInt *Mask = ConstantInt::get(
5514 APInt::getLowBitsSet(AP.getBitWidth(),
5516 AP.countTrailingZeros()));
5517 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5519 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5521 InsertNewInstBefore(And1, I);
5522 InsertNewInstBefore(And2, I);
5523 return new ICmpInst(I.getPredicate(), And1, And2);
5532 // ~x < ~y --> y < x
5534 if (match(Op0, m_Not(m_Value(A))) &&
5535 match(Op1, m_Not(m_Value(B))))
5536 return new ICmpInst(I.getPredicate(), B, A);
5539 if (I.isEquality()) {
5540 Value *A, *B, *C, *D;
5542 // -x == -y --> x == y
5543 if (match(Op0, m_Neg(m_Value(A))) &&
5544 match(Op1, m_Neg(m_Value(B))))
5545 return new ICmpInst(I.getPredicate(), A, B);
5547 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5548 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5549 Value *OtherVal = A == Op1 ? B : A;
5550 return new ICmpInst(I.getPredicate(), OtherVal,
5551 Constant::getNullValue(A->getType()));
5554 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5555 // A^c1 == C^c2 --> A == C^(c1^c2)
5556 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5557 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5558 if (Op1->hasOneUse()) {
5559 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5560 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5561 return new ICmpInst(I.getPredicate(), A,
5562 InsertNewInstBefore(Xor, I));
5565 // A^B == A^D -> B == D
5566 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5567 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5568 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5569 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5573 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5574 (A == Op0 || B == Op0)) {
5575 // A == (A^B) -> B == 0
5576 Value *OtherVal = A == Op0 ? B : A;
5577 return new ICmpInst(I.getPredicate(), OtherVal,
5578 Constant::getNullValue(A->getType()));
5580 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5581 // (A-B) == A -> B == 0
5582 return new ICmpInst(I.getPredicate(), B,
5583 Constant::getNullValue(B->getType()));
5585 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5586 // A == (A-B) -> B == 0
5587 return new ICmpInst(I.getPredicate(), B,
5588 Constant::getNullValue(B->getType()));
5591 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5592 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5593 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5594 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5595 Value *X = 0, *Y = 0, *Z = 0;
5598 X = B; Y = D; Z = A;
5599 } else if (A == D) {
5600 X = B; Y = C; Z = A;
5601 } else if (B == C) {
5602 X = A; Y = D; Z = B;
5603 } else if (B == D) {
5604 X = A; Y = C; Z = B;
5607 if (X) { // Build (X^Y) & Z
5608 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5609 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5610 I.setOperand(0, Op1);
5611 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5616 return Changed ? &I : 0;
5620 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5621 /// and CmpRHS are both known to be integer constants.
5622 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5623 ConstantInt *DivRHS) {
5624 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5625 const APInt &CmpRHSV = CmpRHS->getValue();
5627 // FIXME: If the operand types don't match the type of the divide
5628 // then don't attempt this transform. The code below doesn't have the
5629 // logic to deal with a signed divide and an unsigned compare (and
5630 // vice versa). This is because (x /s C1) <s C2 produces different
5631 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5632 // (x /u C1) <u C2. Simply casting the operands and result won't
5633 // work. :( The if statement below tests that condition and bails
5635 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5636 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5638 if (DivRHS->isZero())
5639 return 0; // The ProdOV computation fails on divide by zero.
5641 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5642 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5643 // C2 (CI). By solving for X we can turn this into a range check
5644 // instead of computing a divide.
5645 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5647 // Determine if the product overflows by seeing if the product is
5648 // not equal to the divide. Make sure we do the same kind of divide
5649 // as in the LHS instruction that we're folding.
5650 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5651 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5653 // Get the ICmp opcode
5654 ICmpInst::Predicate Pred = ICI.getPredicate();
5656 // Figure out the interval that is being checked. For example, a comparison
5657 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5658 // Compute this interval based on the constants involved and the signedness of
5659 // the compare/divide. This computes a half-open interval, keeping track of
5660 // whether either value in the interval overflows. After analysis each
5661 // overflow variable is set to 0 if it's corresponding bound variable is valid
5662 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5663 int LoOverflow = 0, HiOverflow = 0;
5664 ConstantInt *LoBound = 0, *HiBound = 0;
5667 if (!DivIsSigned) { // udiv
5668 // e.g. X/5 op 3 --> [15, 20)
5670 HiOverflow = LoOverflow = ProdOV;
5672 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5673 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5674 if (CmpRHSV == 0) { // (X / pos) op 0
5675 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5676 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5678 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
5679 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5680 HiOverflow = LoOverflow = ProdOV;
5682 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5683 } else { // (X / pos) op neg
5684 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5685 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5686 LoOverflow = AddWithOverflow(LoBound, Prod,
5687 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5688 HiBound = AddOne(Prod);
5689 HiOverflow = ProdOV ? -1 : 0;
5691 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5692 if (CmpRHSV == 0) { // (X / neg) op 0
5693 // e.g. X/-5 op 0 --> [-4, 5)
5694 LoBound = AddOne(DivRHS);
5695 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5696 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5697 HiOverflow = 1; // [INTMIN+1, overflow)
5698 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5700 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
5701 // e.g. X/-5 op 3 --> [-19, -14)
5702 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5704 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5705 HiBound = AddOne(Prod);
5706 } else { // (X / neg) op neg
5707 // e.g. X/-5 op -3 --> [15, 20)
5709 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5710 HiBound = Subtract(Prod, DivRHS);
5713 // Dividing by a negative swaps the condition. LT <-> GT
5714 Pred = ICmpInst::getSwappedPredicate(Pred);
5717 Value *X = DivI->getOperand(0);
5719 default: assert(0 && "Unhandled icmp opcode!");
5720 case ICmpInst::ICMP_EQ:
5721 if (LoOverflow && HiOverflow)
5722 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5723 else if (HiOverflow)
5724 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5725 ICmpInst::ICMP_UGE, X, LoBound);
5726 else if (LoOverflow)
5727 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5728 ICmpInst::ICMP_ULT, X, HiBound);
5730 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5731 case ICmpInst::ICMP_NE:
5732 if (LoOverflow && HiOverflow)
5733 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5734 else if (HiOverflow)
5735 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5736 ICmpInst::ICMP_ULT, X, LoBound);
5737 else if (LoOverflow)
5738 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5739 ICmpInst::ICMP_UGE, X, HiBound);
5741 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5742 case ICmpInst::ICMP_ULT:
5743 case ICmpInst::ICMP_SLT:
5744 if (LoOverflow == +1) // Low bound is greater than input range.
5745 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5746 if (LoOverflow == -1) // Low bound is less than input range.
5747 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5748 return new ICmpInst(Pred, X, LoBound);
5749 case ICmpInst::ICMP_UGT:
5750 case ICmpInst::ICMP_SGT:
5751 if (HiOverflow == +1) // High bound greater than input range.
5752 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5753 else if (HiOverflow == -1) // High bound less than input range.
5754 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5755 if (Pred == ICmpInst::ICMP_UGT)
5756 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5758 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5763 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5765 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5768 const APInt &RHSV = RHS->getValue();
5770 switch (LHSI->getOpcode()) {
5771 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5772 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5773 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5775 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5776 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5777 Value *CompareVal = LHSI->getOperand(0);
5779 // If the sign bit of the XorCST is not set, there is no change to
5780 // the operation, just stop using the Xor.
5781 if (!XorCST->getValue().isNegative()) {
5782 ICI.setOperand(0, CompareVal);
5783 AddToWorkList(LHSI);
5787 // Was the old condition true if the operand is positive?
5788 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5790 // If so, the new one isn't.
5791 isTrueIfPositive ^= true;
5793 if (isTrueIfPositive)
5794 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5796 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5800 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5801 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5802 LHSI->getOperand(0)->hasOneUse()) {
5803 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5805 // If the LHS is an AND of a truncating cast, we can widen the
5806 // and/compare to be the input width without changing the value
5807 // produced, eliminating a cast.
5808 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5809 // We can do this transformation if either the AND constant does not
5810 // have its sign bit set or if it is an equality comparison.
5811 // Extending a relational comparison when we're checking the sign
5812 // bit would not work.
5813 if (Cast->hasOneUse() &&
5814 (ICI.isEquality() ||
5815 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5817 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5818 APInt NewCST = AndCST->getValue();
5819 NewCST.zext(BitWidth);
5821 NewCI.zext(BitWidth);
5822 Instruction *NewAnd =
5823 BinaryOperator::CreateAnd(Cast->getOperand(0),
5824 ConstantInt::get(NewCST),LHSI->getName());
5825 InsertNewInstBefore(NewAnd, ICI);
5826 return new ICmpInst(ICI.getPredicate(), NewAnd,
5827 ConstantInt::get(NewCI));
5831 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5832 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5833 // happens a LOT in code produced by the C front-end, for bitfield
5835 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5836 if (Shift && !Shift->isShift())
5840 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5841 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5842 const Type *AndTy = AndCST->getType(); // Type of the and.
5844 // We can fold this as long as we can't shift unknown bits
5845 // into the mask. This can only happen with signed shift
5846 // rights, as they sign-extend.
5848 bool CanFold = Shift->isLogicalShift();
5850 // To test for the bad case of the signed shr, see if any
5851 // of the bits shifted in could be tested after the mask.
5852 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5853 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5855 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5856 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5857 AndCST->getValue()) == 0)
5863 if (Shift->getOpcode() == Instruction::Shl)
5864 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5866 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5868 // Check to see if we are shifting out any of the bits being
5870 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5871 // If we shifted bits out, the fold is not going to work out.
5872 // As a special case, check to see if this means that the
5873 // result is always true or false now.
5874 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5875 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5876 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5877 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5879 ICI.setOperand(1, NewCst);
5880 Constant *NewAndCST;
5881 if (Shift->getOpcode() == Instruction::Shl)
5882 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5884 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5885 LHSI->setOperand(1, NewAndCST);
5886 LHSI->setOperand(0, Shift->getOperand(0));
5887 AddToWorkList(Shift); // Shift is dead.
5888 AddUsesToWorkList(ICI);
5894 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5895 // preferable because it allows the C<<Y expression to be hoisted out
5896 // of a loop if Y is invariant and X is not.
5897 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5898 ICI.isEquality() && !Shift->isArithmeticShift() &&
5899 isa<Instruction>(Shift->getOperand(0))) {
5902 if (Shift->getOpcode() == Instruction::LShr) {
5903 NS = BinaryOperator::CreateShl(AndCST,
5904 Shift->getOperand(1), "tmp");
5906 // Insert a logical shift.
5907 NS = BinaryOperator::CreateLShr(AndCST,
5908 Shift->getOperand(1), "tmp");
5910 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5912 // Compute X & (C << Y).
5913 Instruction *NewAnd =
5914 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5915 InsertNewInstBefore(NewAnd, ICI);
5917 ICI.setOperand(0, NewAnd);
5923 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5924 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5927 uint32_t TypeBits = RHSV.getBitWidth();
5929 // Check that the shift amount is in range. If not, don't perform
5930 // undefined shifts. When the shift is visited it will be
5932 if (ShAmt->uge(TypeBits))
5935 if (ICI.isEquality()) {
5936 // If we are comparing against bits always shifted out, the
5937 // comparison cannot succeed.
5939 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5940 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5941 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5942 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5943 return ReplaceInstUsesWith(ICI, Cst);
5946 if (LHSI->hasOneUse()) {
5947 // Otherwise strength reduce the shift into an and.
5948 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5950 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5953 BinaryOperator::CreateAnd(LHSI->getOperand(0),
5954 Mask, LHSI->getName()+".mask");
5955 Value *And = InsertNewInstBefore(AndI, ICI);
5956 return new ICmpInst(ICI.getPredicate(), And,
5957 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5961 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5962 bool TrueIfSigned = false;
5963 if (LHSI->hasOneUse() &&
5964 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5965 // (X << 31) <s 0 --> (X&1) != 0
5966 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5967 (TypeBits-ShAmt->getZExtValue()-1));
5969 BinaryOperator::CreateAnd(LHSI->getOperand(0),
5970 Mask, LHSI->getName()+".mask");
5971 Value *And = InsertNewInstBefore(AndI, ICI);
5973 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5974 And, Constant::getNullValue(And->getType()));
5979 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5980 case Instruction::AShr: {
5981 // Only handle equality comparisons of shift-by-constant.
5982 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5983 if (!ShAmt || !ICI.isEquality()) break;
5985 // Check that the shift amount is in range. If not, don't perform
5986 // undefined shifts. When the shift is visited it will be
5988 uint32_t TypeBits = RHSV.getBitWidth();
5989 if (ShAmt->uge(TypeBits))
5992 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5994 // If we are comparing against bits always shifted out, the
5995 // comparison cannot succeed.
5996 APInt Comp = RHSV << ShAmtVal;
5997 if (LHSI->getOpcode() == Instruction::LShr)
5998 Comp = Comp.lshr(ShAmtVal);
6000 Comp = Comp.ashr(ShAmtVal);
6002 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6003 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6004 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6005 return ReplaceInstUsesWith(ICI, Cst);
6008 // Otherwise, check to see if the bits shifted out are known to be zero.
6009 // If so, we can compare against the unshifted value:
6010 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6011 if (LHSI->hasOneUse() &&
6012 MaskedValueIsZero(LHSI->getOperand(0),
6013 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6014 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6015 ConstantExpr::getShl(RHS, ShAmt));
6018 if (LHSI->hasOneUse()) {
6019 // Otherwise strength reduce the shift into an and.
6020 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6021 Constant *Mask = ConstantInt::get(Val);
6024 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6025 Mask, LHSI->getName()+".mask");
6026 Value *And = InsertNewInstBefore(AndI, ICI);
6027 return new ICmpInst(ICI.getPredicate(), And,
6028 ConstantExpr::getShl(RHS, ShAmt));
6033 case Instruction::SDiv:
6034 case Instruction::UDiv:
6035 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6036 // Fold this div into the comparison, producing a range check.
6037 // Determine, based on the divide type, what the range is being
6038 // checked. If there is an overflow on the low or high side, remember
6039 // it, otherwise compute the range [low, hi) bounding the new value.
6040 // See: InsertRangeTest above for the kinds of replacements possible.
6041 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6042 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6047 case Instruction::Add:
6048 // Fold: icmp pred (add, X, C1), C2
6050 if (!ICI.isEquality()) {
6051 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6053 const APInt &LHSV = LHSC->getValue();
6055 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6058 if (ICI.isSignedPredicate()) {
6059 if (CR.getLower().isSignBit()) {
6060 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6061 ConstantInt::get(CR.getUpper()));
6062 } else if (CR.getUpper().isSignBit()) {
6063 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6064 ConstantInt::get(CR.getLower()));
6067 if (CR.getLower().isMinValue()) {
6068 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6069 ConstantInt::get(CR.getUpper()));
6070 } else if (CR.getUpper().isMinValue()) {
6071 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6072 ConstantInt::get(CR.getLower()));
6079 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6080 if (ICI.isEquality()) {
6081 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6083 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6084 // the second operand is a constant, simplify a bit.
6085 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6086 switch (BO->getOpcode()) {
6087 case Instruction::SRem:
6088 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6089 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6090 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6091 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6092 Instruction *NewRem =
6093 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6095 InsertNewInstBefore(NewRem, ICI);
6096 return new ICmpInst(ICI.getPredicate(), NewRem,
6097 Constant::getNullValue(BO->getType()));
6101 case Instruction::Add:
6102 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6103 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6104 if (BO->hasOneUse())
6105 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6106 Subtract(RHS, BOp1C));
6107 } else if (RHSV == 0) {
6108 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6109 // efficiently invertible, or if the add has just this one use.
6110 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6112 if (Value *NegVal = dyn_castNegVal(BOp1))
6113 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6114 else if (Value *NegVal = dyn_castNegVal(BOp0))
6115 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6116 else if (BO->hasOneUse()) {
6117 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6118 InsertNewInstBefore(Neg, ICI);
6120 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6124 case Instruction::Xor:
6125 // For the xor case, we can xor two constants together, eliminating
6126 // the explicit xor.
6127 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6128 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6129 ConstantExpr::getXor(RHS, BOC));
6132 case Instruction::Sub:
6133 // Replace (([sub|xor] A, B) != 0) with (A != B)
6135 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6139 case Instruction::Or:
6140 // If bits are being or'd in that are not present in the constant we
6141 // are comparing against, then the comparison could never succeed!
6142 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6143 Constant *NotCI = ConstantExpr::getNot(RHS);
6144 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6145 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6150 case Instruction::And:
6151 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6152 // If bits are being compared against that are and'd out, then the
6153 // comparison can never succeed!
6154 if ((RHSV & ~BOC->getValue()) != 0)
6155 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6158 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6159 if (RHS == BOC && RHSV.isPowerOf2())
6160 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6161 ICmpInst::ICMP_NE, LHSI,
6162 Constant::getNullValue(RHS->getType()));
6164 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6165 if (BOC->getValue().isSignBit()) {
6166 Value *X = BO->getOperand(0);
6167 Constant *Zero = Constant::getNullValue(X->getType());
6168 ICmpInst::Predicate pred = isICMP_NE ?
6169 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6170 return new ICmpInst(pred, X, Zero);
6173 // ((X & ~7) == 0) --> X < 8
6174 if (RHSV == 0 && isHighOnes(BOC)) {
6175 Value *X = BO->getOperand(0);
6176 Constant *NegX = ConstantExpr::getNeg(BOC);
6177 ICmpInst::Predicate pred = isICMP_NE ?
6178 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6179 return new ICmpInst(pred, X, NegX);
6184 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6185 // Handle icmp {eq|ne} <intrinsic>, intcst.
6186 if (II->getIntrinsicID() == Intrinsic::bswap) {
6188 ICI.setOperand(0, II->getOperand(1));
6189 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6193 } else { // Not a ICMP_EQ/ICMP_NE
6194 // If the LHS is a cast from an integral value of the same size,
6195 // then since we know the RHS is a constant, try to simlify.
6196 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6197 Value *CastOp = Cast->getOperand(0);
6198 const Type *SrcTy = CastOp->getType();
6199 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6200 if (SrcTy->isInteger() &&
6201 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6202 // If this is an unsigned comparison, try to make the comparison use
6203 // smaller constant values.
6204 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6205 // X u< 128 => X s> -1
6206 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6207 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6208 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6209 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6210 // X u> 127 => X s< 0
6211 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6212 Constant::getNullValue(SrcTy));
6220 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6221 /// We only handle extending casts so far.
6223 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6224 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6225 Value *LHSCIOp = LHSCI->getOperand(0);
6226 const Type *SrcTy = LHSCIOp->getType();
6227 const Type *DestTy = LHSCI->getType();
6230 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6231 // integer type is the same size as the pointer type.
6232 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6233 getTargetData().getPointerSizeInBits() ==
6234 cast<IntegerType>(DestTy)->getBitWidth()) {
6236 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6237 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6238 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6239 RHSOp = RHSC->getOperand(0);
6240 // If the pointer types don't match, insert a bitcast.
6241 if (LHSCIOp->getType() != RHSOp->getType())
6242 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6246 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6249 // The code below only handles extension cast instructions, so far.
6251 if (LHSCI->getOpcode() != Instruction::ZExt &&
6252 LHSCI->getOpcode() != Instruction::SExt)
6255 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6256 bool isSignedCmp = ICI.isSignedPredicate();
6258 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6259 // Not an extension from the same type?
6260 RHSCIOp = CI->getOperand(0);
6261 if (RHSCIOp->getType() != LHSCIOp->getType())
6264 // If the signedness of the two casts doesn't agree (i.e. one is a sext
6265 // and the other is a zext), then we can't handle this.
6266 if (CI->getOpcode() != LHSCI->getOpcode())
6269 // Deal with equality cases early.
6270 if (ICI.isEquality())
6271 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6273 // A signed comparison of sign extended values simplifies into a
6274 // signed comparison.
6275 if (isSignedCmp && isSignedExt)
6276 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6278 // The other three cases all fold into an unsigned comparison.
6279 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6282 // If we aren't dealing with a constant on the RHS, exit early
6283 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6287 // Compute the constant that would happen if we truncated to SrcTy then
6288 // reextended to DestTy.
6289 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6290 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6292 // If the re-extended constant didn't change...
6294 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6295 // For example, we might have:
6296 // %A = sext short %X to uint
6297 // %B = icmp ugt uint %A, 1330
6298 // It is incorrect to transform this into
6299 // %B = icmp ugt short %X, 1330
6300 // because %A may have negative value.
6302 // However, we allow this when the compare is EQ/NE, because they are
6304 if (isSignedExt == isSignedCmp || ICI.isEquality())
6305 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6309 // The re-extended constant changed so the constant cannot be represented
6310 // in the shorter type. Consequently, we cannot emit a simple comparison.
6312 // First, handle some easy cases. We know the result cannot be equal at this
6313 // point so handle the ICI.isEquality() cases
6314 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6315 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6316 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6317 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6319 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6320 // should have been folded away previously and not enter in here.
6323 // We're performing a signed comparison.
6324 if (cast<ConstantInt>(CI)->getValue().isNegative())
6325 Result = ConstantInt::getFalse(); // X < (small) --> false
6327 Result = ConstantInt::getTrue(); // X < (large) --> true
6329 // We're performing an unsigned comparison.
6331 // We're performing an unsigned comp with a sign extended value.
6332 // This is true if the input is >= 0. [aka >s -1]
6333 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6334 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6335 NegOne, ICI.getName()), ICI);
6337 // Unsigned extend & unsigned compare -> always true.
6338 Result = ConstantInt::getTrue();
6342 // Finally, return the value computed.
6343 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6344 ICI.getPredicate() == ICmpInst::ICMP_SLT)
6345 return ReplaceInstUsesWith(ICI, Result);
6347 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6348 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6349 "ICmp should be folded!");
6350 if (Constant *CI = dyn_cast<Constant>(Result))
6351 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6352 return BinaryOperator::CreateNot(Result);
6355 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6356 return commonShiftTransforms(I);
6359 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6360 return commonShiftTransforms(I);
6363 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6364 if (Instruction *R = commonShiftTransforms(I))
6367 Value *Op0 = I.getOperand(0);
6369 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6370 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6371 if (CSI->isAllOnesValue())
6372 return ReplaceInstUsesWith(I, CSI);
6374 // See if we can turn a signed shr into an unsigned shr.
6375 if (!isa<VectorType>(I.getType()) &&
6376 MaskedValueIsZero(Op0,
6377 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6378 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6383 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6384 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6385 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6387 // shl X, 0 == X and shr X, 0 == X
6388 // shl 0, X == 0 and shr 0, X == 0
6389 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6390 Op0 == Constant::getNullValue(Op0->getType()))
6391 return ReplaceInstUsesWith(I, Op0);
6393 if (isa<UndefValue>(Op0)) {
6394 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6395 return ReplaceInstUsesWith(I, Op0);
6396 else // undef << X -> 0, undef >>u X -> 0
6397 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6399 if (isa<UndefValue>(Op1)) {
6400 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6401 return ReplaceInstUsesWith(I, Op0);
6402 else // X << undef, X >>u undef -> 0
6403 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6406 // Try to fold constant and into select arguments.
6407 if (isa<Constant>(Op0))
6408 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6409 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6412 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6413 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6418 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6419 BinaryOperator &I) {
6420 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6422 // See if we can simplify any instructions used by the instruction whose sole
6423 // purpose is to compute bits we don't care about.
6424 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6425 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6426 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6427 KnownZero, KnownOne))
6430 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6431 // of a signed value.
6433 if (Op1->uge(TypeBits)) {
6434 if (I.getOpcode() != Instruction::AShr)
6435 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6437 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6442 // ((X*C1) << C2) == (X * (C1 << C2))
6443 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6444 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6445 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6446 return BinaryOperator::CreateMul(BO->getOperand(0),
6447 ConstantExpr::getShl(BOOp, Op1));
6449 // Try to fold constant and into select arguments.
6450 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6451 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6453 if (isa<PHINode>(Op0))
6454 if (Instruction *NV = FoldOpIntoPhi(I))
6457 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6458 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6459 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6460 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6461 // place. Don't try to do this transformation in this case. Also, we
6462 // require that the input operand is a shift-by-constant so that we have
6463 // confidence that the shifts will get folded together. We could do this
6464 // xform in more cases, but it is unlikely to be profitable.
6465 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6466 isa<ConstantInt>(TrOp->getOperand(1))) {
6467 // Okay, we'll do this xform. Make the shift of shift.
6468 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6469 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6471 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6473 // For logical shifts, the truncation has the effect of making the high
6474 // part of the register be zeros. Emulate this by inserting an AND to
6475 // clear the top bits as needed. This 'and' will usually be zapped by
6476 // other xforms later if dead.
6477 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6478 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6479 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6481 // The mask we constructed says what the trunc would do if occurring
6482 // between the shifts. We want to know the effect *after* the second
6483 // shift. We know that it is a logical shift by a constant, so adjust the
6484 // mask as appropriate.
6485 if (I.getOpcode() == Instruction::Shl)
6486 MaskV <<= Op1->getZExtValue();
6488 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6489 MaskV = MaskV.lshr(Op1->getZExtValue());
6492 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6494 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6496 // Return the value truncated to the interesting size.
6497 return new TruncInst(And, I.getType());
6501 if (Op0->hasOneUse()) {
6502 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6503 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6506 switch (Op0BO->getOpcode()) {
6508 case Instruction::Add:
6509 case Instruction::And:
6510 case Instruction::Or:
6511 case Instruction::Xor: {
6512 // These operators commute.
6513 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6514 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6515 match(Op0BO->getOperand(1),
6516 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6517 Instruction *YS = BinaryOperator::CreateShl(
6518 Op0BO->getOperand(0), Op1,
6520 InsertNewInstBefore(YS, I); // (Y << C)
6522 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6523 Op0BO->getOperand(1)->getName());
6524 InsertNewInstBefore(X, I); // (X + (Y << C))
6525 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6526 return BinaryOperator::CreateAnd(X, ConstantInt::get(
6527 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6530 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6531 Value *Op0BOOp1 = Op0BO->getOperand(1);
6532 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6534 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6535 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6537 Instruction *YS = BinaryOperator::CreateShl(
6538 Op0BO->getOperand(0), Op1,
6540 InsertNewInstBefore(YS, I); // (Y << C)
6542 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6543 V1->getName()+".mask");
6544 InsertNewInstBefore(XM, I); // X & (CC << C)
6546 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6551 case Instruction::Sub: {
6552 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6553 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6554 match(Op0BO->getOperand(0),
6555 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6556 Instruction *YS = BinaryOperator::CreateShl(
6557 Op0BO->getOperand(1), Op1,
6559 InsertNewInstBefore(YS, I); // (Y << C)
6561 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6562 Op0BO->getOperand(0)->getName());
6563 InsertNewInstBefore(X, I); // (X + (Y << C))
6564 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6565 return BinaryOperator::CreateAnd(X, ConstantInt::get(
6566 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6569 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6570 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6571 match(Op0BO->getOperand(0),
6572 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6573 m_ConstantInt(CC))) && V2 == Op1 &&
6574 cast<BinaryOperator>(Op0BO->getOperand(0))
6575 ->getOperand(0)->hasOneUse()) {
6576 Instruction *YS = BinaryOperator::CreateShl(
6577 Op0BO->getOperand(1), Op1,
6579 InsertNewInstBefore(YS, I); // (Y << C)
6581 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6582 V1->getName()+".mask");
6583 InsertNewInstBefore(XM, I); // X & (CC << C)
6585 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6593 // If the operand is an bitwise operator with a constant RHS, and the
6594 // shift is the only use, we can pull it out of the shift.
6595 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6596 bool isValid = true; // Valid only for And, Or, Xor
6597 bool highBitSet = false; // Transform if high bit of constant set?
6599 switch (Op0BO->getOpcode()) {
6600 default: isValid = false; break; // Do not perform transform!
6601 case Instruction::Add:
6602 isValid = isLeftShift;
6604 case Instruction::Or:
6605 case Instruction::Xor:
6608 case Instruction::And:
6613 // If this is a signed shift right, and the high bit is modified
6614 // by the logical operation, do not perform the transformation.
6615 // The highBitSet boolean indicates the value of the high bit of
6616 // the constant which would cause it to be modified for this
6619 if (isValid && I.getOpcode() == Instruction::AShr)
6620 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6623 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6625 Instruction *NewShift =
6626 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6627 InsertNewInstBefore(NewShift, I);
6628 NewShift->takeName(Op0BO);
6630 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6637 // Find out if this is a shift of a shift by a constant.
6638 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6639 if (ShiftOp && !ShiftOp->isShift())
6642 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6643 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6644 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6645 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6646 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6647 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6648 Value *X = ShiftOp->getOperand(0);
6650 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6651 if (AmtSum > TypeBits)
6654 const IntegerType *Ty = cast<IntegerType>(I.getType());
6656 // Check for (X << c1) << c2 and (X >> c1) >> c2
6657 if (I.getOpcode() == ShiftOp->getOpcode()) {
6658 return BinaryOperator::Create(I.getOpcode(), X,
6659 ConstantInt::get(Ty, AmtSum));
6660 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6661 I.getOpcode() == Instruction::AShr) {
6662 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6663 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6664 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6665 I.getOpcode() == Instruction::LShr) {
6666 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6667 Instruction *Shift =
6668 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6669 InsertNewInstBefore(Shift, I);
6671 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6672 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6675 // Okay, if we get here, one shift must be left, and the other shift must be
6676 // right. See if the amounts are equal.
6677 if (ShiftAmt1 == ShiftAmt2) {
6678 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6679 if (I.getOpcode() == Instruction::Shl) {
6680 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6681 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6683 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6684 if (I.getOpcode() == Instruction::LShr) {
6685 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6686 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6688 // We can simplify ((X << C) >>s C) into a trunc + sext.
6689 // NOTE: we could do this for any C, but that would make 'unusual' integer
6690 // types. For now, just stick to ones well-supported by the code
6692 const Type *SExtType = 0;
6693 switch (Ty->getBitWidth() - ShiftAmt1) {
6700 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6705 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6706 InsertNewInstBefore(NewTrunc, I);
6707 return new SExtInst(NewTrunc, Ty);
6709 // Otherwise, we can't handle it yet.
6710 } else if (ShiftAmt1 < ShiftAmt2) {
6711 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6713 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6714 if (I.getOpcode() == Instruction::Shl) {
6715 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6716 ShiftOp->getOpcode() == Instruction::AShr);
6717 Instruction *Shift =
6718 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6719 InsertNewInstBefore(Shift, I);
6721 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6722 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6725 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6726 if (I.getOpcode() == Instruction::LShr) {
6727 assert(ShiftOp->getOpcode() == Instruction::Shl);
6728 Instruction *Shift =
6729 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6730 InsertNewInstBefore(Shift, I);
6732 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6733 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6736 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6738 assert(ShiftAmt2 < ShiftAmt1);
6739 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6741 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6742 if (I.getOpcode() == Instruction::Shl) {
6743 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6744 ShiftOp->getOpcode() == Instruction::AShr);
6745 Instruction *Shift =
6746 BinaryOperator::Create(ShiftOp->getOpcode(), X,
6747 ConstantInt::get(Ty, ShiftDiff));
6748 InsertNewInstBefore(Shift, I);
6750 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6751 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6754 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6755 if (I.getOpcode() == Instruction::LShr) {
6756 assert(ShiftOp->getOpcode() == Instruction::Shl);
6757 Instruction *Shift =
6758 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6759 InsertNewInstBefore(Shift, I);
6761 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6762 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6765 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6772 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6773 /// expression. If so, decompose it, returning some value X, such that Val is
6776 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6778 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6779 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6780 Offset = CI->getZExtValue();
6782 return ConstantInt::get(Type::Int32Ty, 0);
6783 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6784 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6785 if (I->getOpcode() == Instruction::Shl) {
6786 // This is a value scaled by '1 << the shift amt'.
6787 Scale = 1U << RHS->getZExtValue();
6789 return I->getOperand(0);
6790 } else if (I->getOpcode() == Instruction::Mul) {
6791 // This value is scaled by 'RHS'.
6792 Scale = RHS->getZExtValue();
6794 return I->getOperand(0);
6795 } else if (I->getOpcode() == Instruction::Add) {
6796 // We have X+C. Check to see if we really have (X*C2)+C1,
6797 // where C1 is divisible by C2.
6800 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6801 Offset += RHS->getZExtValue();
6808 // Otherwise, we can't look past this.
6815 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6816 /// try to eliminate the cast by moving the type information into the alloc.
6817 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6818 AllocationInst &AI) {
6819 const PointerType *PTy = cast<PointerType>(CI.getType());
6821 // Remove any uses of AI that are dead.
6822 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6824 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6825 Instruction *User = cast<Instruction>(*UI++);
6826 if (isInstructionTriviallyDead(User)) {
6827 while (UI != E && *UI == User)
6828 ++UI; // If this instruction uses AI more than once, don't break UI.
6831 DOUT << "IC: DCE: " << *User;
6832 EraseInstFromFunction(*User);
6836 // Get the type really allocated and the type casted to.
6837 const Type *AllocElTy = AI.getAllocatedType();
6838 const Type *CastElTy = PTy->getElementType();
6839 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6841 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6842 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6843 if (CastElTyAlign < AllocElTyAlign) return 0;
6845 // If the allocation has multiple uses, only promote it if we are strictly
6846 // increasing the alignment of the resultant allocation. If we keep it the
6847 // same, we open the door to infinite loops of various kinds.
6848 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6850 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6851 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6852 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6854 // See if we can satisfy the modulus by pulling a scale out of the array
6856 unsigned ArraySizeScale;
6858 Value *NumElements = // See if the array size is a decomposable linear expr.
6859 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6861 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6863 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6864 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6866 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6871 // If the allocation size is constant, form a constant mul expression
6872 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6873 if (isa<ConstantInt>(NumElements))
6874 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6875 // otherwise multiply the amount and the number of elements
6876 else if (Scale != 1) {
6877 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6878 Amt = InsertNewInstBefore(Tmp, AI);
6882 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6883 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6884 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6885 Amt = InsertNewInstBefore(Tmp, AI);
6888 AllocationInst *New;
6889 if (isa<MallocInst>(AI))
6890 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6892 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6893 InsertNewInstBefore(New, AI);
6896 // If the allocation has multiple uses, insert a cast and change all things
6897 // that used it to use the new cast. This will also hack on CI, but it will
6899 if (!AI.hasOneUse()) {
6900 AddUsesToWorkList(AI);
6901 // New is the allocation instruction, pointer typed. AI is the original
6902 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6903 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6904 InsertNewInstBefore(NewCast, AI);
6905 AI.replaceAllUsesWith(NewCast);
6907 return ReplaceInstUsesWith(CI, New);
6910 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6911 /// and return it as type Ty without inserting any new casts and without
6912 /// changing the computed value. This is used by code that tries to decide
6913 /// whether promoting or shrinking integer operations to wider or smaller types
6914 /// will allow us to eliminate a truncate or extend.
6916 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6917 /// extension operation if Ty is larger.
6919 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
6920 /// should return true if trunc(V) can be computed by computing V in the smaller
6921 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
6922 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6923 /// efficiently truncated.
6925 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6926 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6927 /// the final result.
6928 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6930 int &NumCastsRemoved) {
6931 // We can always evaluate constants in another type.
6932 if (isa<ConstantInt>(V))
6935 Instruction *I = dyn_cast<Instruction>(V);
6936 if (!I) return false;
6938 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6940 // If this is an extension or truncate, we can often eliminate it.
6941 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6942 // If this is a cast from the destination type, we can trivially eliminate
6943 // it, and this will remove a cast overall.
6944 if (I->getOperand(0)->getType() == Ty) {
6945 // If the first operand is itself a cast, and is eliminable, do not count
6946 // this as an eliminable cast. We would prefer to eliminate those two
6948 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6954 // We can't extend or shrink something that has multiple uses: doing so would
6955 // require duplicating the instruction in general, which isn't profitable.
6956 if (!I->hasOneUse()) return false;
6958 switch (I->getOpcode()) {
6959 case Instruction::Add:
6960 case Instruction::Sub:
6961 case Instruction::Mul:
6962 case Instruction::And:
6963 case Instruction::Or:
6964 case Instruction::Xor:
6965 // These operators can all arbitrarily be extended or truncated.
6966 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6968 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6971 case Instruction::Shl:
6972 // If we are truncating the result of this SHL, and if it's a shift of a
6973 // constant amount, we can always perform a SHL in a smaller type.
6974 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6975 uint32_t BitWidth = Ty->getBitWidth();
6976 if (BitWidth < OrigTy->getBitWidth() &&
6977 CI->getLimitedValue(BitWidth) < BitWidth)
6978 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6982 case Instruction::LShr:
6983 // If this is a truncate of a logical shr, we can truncate it to a smaller
6984 // lshr iff we know that the bits we would otherwise be shifting in are
6986 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6987 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6988 uint32_t BitWidth = Ty->getBitWidth();
6989 if (BitWidth < OrigBitWidth &&
6990 MaskedValueIsZero(I->getOperand(0),
6991 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6992 CI->getLimitedValue(BitWidth) < BitWidth) {
6993 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6998 case Instruction::ZExt:
6999 case Instruction::SExt:
7000 case Instruction::Trunc:
7001 // If this is the same kind of case as our original (e.g. zext+zext), we
7002 // can safely replace it. Note that replacing it does not reduce the number
7003 // of casts in the input.
7004 if (I->getOpcode() == CastOpc)
7007 case Instruction::Select: {
7008 SelectInst *SI = cast<SelectInst>(I);
7009 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7011 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7014 case Instruction::PHI: {
7015 // We can change a phi if we can change all operands.
7016 PHINode *PN = cast<PHINode>(I);
7017 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7018 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7024 // TODO: Can handle more cases here.
7031 /// EvaluateInDifferentType - Given an expression that
7032 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7033 /// evaluate the expression.
7034 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7036 if (Constant *C = dyn_cast<Constant>(V))
7037 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7039 // Otherwise, it must be an instruction.
7040 Instruction *I = cast<Instruction>(V);
7041 Instruction *Res = 0;
7042 switch (I->getOpcode()) {
7043 case Instruction::Add:
7044 case Instruction::Sub:
7045 case Instruction::Mul:
7046 case Instruction::And:
7047 case Instruction::Or:
7048 case Instruction::Xor:
7049 case Instruction::AShr:
7050 case Instruction::LShr:
7051 case Instruction::Shl: {
7052 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7053 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7054 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7058 case Instruction::Trunc:
7059 case Instruction::ZExt:
7060 case Instruction::SExt:
7061 // If the source type of the cast is the type we're trying for then we can
7062 // just return the source. There's no need to insert it because it is not
7064 if (I->getOperand(0)->getType() == Ty)
7065 return I->getOperand(0);
7067 // Otherwise, must be the same type of cast, so just reinsert a new one.
7068 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7071 case Instruction::Select: {
7072 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7073 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7074 Res = SelectInst::Create(I->getOperand(0), True, False);
7077 case Instruction::PHI: {
7078 PHINode *OPN = cast<PHINode>(I);
7079 PHINode *NPN = PHINode::Create(Ty);
7080 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7081 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7082 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7088 // TODO: Can handle more cases here.
7089 assert(0 && "Unreachable!");
7094 return InsertNewInstBefore(Res, *I);
7097 /// @brief Implement the transforms common to all CastInst visitors.
7098 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7099 Value *Src = CI.getOperand(0);
7101 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7102 // eliminate it now.
7103 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7104 if (Instruction::CastOps opc =
7105 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7106 // The first cast (CSrc) is eliminable so we need to fix up or replace
7107 // the second cast (CI). CSrc will then have a good chance of being dead.
7108 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7112 // If we are casting a select then fold the cast into the select
7113 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7114 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7117 // If we are casting a PHI then fold the cast into the PHI
7118 if (isa<PHINode>(Src))
7119 if (Instruction *NV = FoldOpIntoPhi(CI))
7125 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7126 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7127 Value *Src = CI.getOperand(0);
7129 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7130 // If casting the result of a getelementptr instruction with no offset, turn
7131 // this into a cast of the original pointer!
7132 if (GEP->hasAllZeroIndices()) {
7133 // Changing the cast operand is usually not a good idea but it is safe
7134 // here because the pointer operand is being replaced with another
7135 // pointer operand so the opcode doesn't need to change.
7137 CI.setOperand(0, GEP->getOperand(0));
7141 // If the GEP has a single use, and the base pointer is a bitcast, and the
7142 // GEP computes a constant offset, see if we can convert these three
7143 // instructions into fewer. This typically happens with unions and other
7144 // non-type-safe code.
7145 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7146 if (GEP->hasAllConstantIndices()) {
7147 // We are guaranteed to get a constant from EmitGEPOffset.
7148 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7149 int64_t Offset = OffsetV->getSExtValue();
7151 // Get the base pointer input of the bitcast, and the type it points to.
7152 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7153 const Type *GEPIdxTy =
7154 cast<PointerType>(OrigBase->getType())->getElementType();
7155 if (GEPIdxTy->isSized()) {
7156 SmallVector<Value*, 8> NewIndices;
7158 // Start with the index over the outer type. Note that the type size
7159 // might be zero (even if the offset isn't zero) if the indexed type
7160 // is something like [0 x {int, int}]
7161 const Type *IntPtrTy = TD->getIntPtrType();
7162 int64_t FirstIdx = 0;
7163 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7164 FirstIdx = Offset/TySize;
7167 // Handle silly modulus not returning values values [0..TySize).
7171 assert(Offset >= 0);
7173 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7176 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7178 // Index into the types. If we fail, set OrigBase to null.
7180 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7181 const StructLayout *SL = TD->getStructLayout(STy);
7182 if (Offset < (int64_t)SL->getSizeInBytes()) {
7183 unsigned Elt = SL->getElementContainingOffset(Offset);
7184 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7186 Offset -= SL->getElementOffset(Elt);
7187 GEPIdxTy = STy->getElementType(Elt);
7189 // Otherwise, we can't index into this, bail out.
7193 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7194 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7195 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7196 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7199 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7201 GEPIdxTy = STy->getElementType();
7203 // Otherwise, we can't index into this, bail out.
7209 // If we were able to index down into an element, create the GEP
7210 // and bitcast the result. This eliminates one bitcast, potentially
7212 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7214 NewIndices.end(), "");
7215 InsertNewInstBefore(NGEP, CI);
7216 NGEP->takeName(GEP);
7218 if (isa<BitCastInst>(CI))
7219 return new BitCastInst(NGEP, CI.getType());
7220 assert(isa<PtrToIntInst>(CI));
7221 return new PtrToIntInst(NGEP, CI.getType());
7228 return commonCastTransforms(CI);
7233 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7234 /// integer types. This function implements the common transforms for all those
7236 /// @brief Implement the transforms common to CastInst with integer operands
7237 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7238 if (Instruction *Result = commonCastTransforms(CI))
7241 Value *Src = CI.getOperand(0);
7242 const Type *SrcTy = Src->getType();
7243 const Type *DestTy = CI.getType();
7244 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7245 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7247 // See if we can simplify any instructions used by the LHS whose sole
7248 // purpose is to compute bits we don't care about.
7249 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7250 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7251 KnownZero, KnownOne))
7254 // If the source isn't an instruction or has more than one use then we
7255 // can't do anything more.
7256 Instruction *SrcI = dyn_cast<Instruction>(Src);
7257 if (!SrcI || !Src->hasOneUse())
7260 // Attempt to propagate the cast into the instruction for int->int casts.
7261 int NumCastsRemoved = 0;
7262 if (!isa<BitCastInst>(CI) &&
7263 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7264 CI.getOpcode(), NumCastsRemoved)) {
7265 // If this cast is a truncate, evaluting in a different type always
7266 // eliminates the cast, so it is always a win. If this is a zero-extension,
7267 // we need to do an AND to maintain the clear top-part of the computation,
7268 // so we require that the input have eliminated at least one cast. If this
7269 // is a sign extension, we insert two new casts (to do the extension) so we
7270 // require that two casts have been eliminated.
7272 switch (CI.getOpcode()) {
7274 // All the others use floating point so we shouldn't actually
7275 // get here because of the check above.
7276 assert(0 && "Unknown cast type");
7277 case Instruction::Trunc:
7280 case Instruction::ZExt:
7281 DoXForm = NumCastsRemoved >= 1;
7283 case Instruction::SExt:
7284 DoXForm = NumCastsRemoved >= 2;
7289 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7290 CI.getOpcode() == Instruction::SExt);
7291 assert(Res->getType() == DestTy);
7292 switch (CI.getOpcode()) {
7293 default: assert(0 && "Unknown cast type!");
7294 case Instruction::Trunc:
7295 case Instruction::BitCast:
7296 // Just replace this cast with the result.
7297 return ReplaceInstUsesWith(CI, Res);
7298 case Instruction::ZExt: {
7299 // We need to emit an AND to clear the high bits.
7300 assert(SrcBitSize < DestBitSize && "Not a zext?");
7301 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7303 return BinaryOperator::CreateAnd(Res, C);
7305 case Instruction::SExt:
7306 // We need to emit a cast to truncate, then a cast to sext.
7307 return CastInst::Create(Instruction::SExt,
7308 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7314 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7315 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7317 switch (SrcI->getOpcode()) {
7318 case Instruction::Add:
7319 case Instruction::Mul:
7320 case Instruction::And:
7321 case Instruction::Or:
7322 case Instruction::Xor:
7323 // If we are discarding information, rewrite.
7324 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7325 // Don't insert two casts if they cannot be eliminated. We allow
7326 // two casts to be inserted if the sizes are the same. This could
7327 // only be converting signedness, which is a noop.
7328 if (DestBitSize == SrcBitSize ||
7329 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7330 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7331 Instruction::CastOps opcode = CI.getOpcode();
7332 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7333 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7334 return BinaryOperator::Create(
7335 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7339 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7340 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7341 SrcI->getOpcode() == Instruction::Xor &&
7342 Op1 == ConstantInt::getTrue() &&
7343 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7344 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7345 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7348 case Instruction::SDiv:
7349 case Instruction::UDiv:
7350 case Instruction::SRem:
7351 case Instruction::URem:
7352 // If we are just changing the sign, rewrite.
7353 if (DestBitSize == SrcBitSize) {
7354 // Don't insert two casts if they cannot be eliminated. We allow
7355 // two casts to be inserted if the sizes are the same. This could
7356 // only be converting signedness, which is a noop.
7357 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7358 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7359 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7361 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7363 return BinaryOperator::Create(
7364 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7369 case Instruction::Shl:
7370 // Allow changing the sign of the source operand. Do not allow
7371 // changing the size of the shift, UNLESS the shift amount is a
7372 // constant. We must not change variable sized shifts to a smaller
7373 // size, because it is undefined to shift more bits out than exist
7375 if (DestBitSize == SrcBitSize ||
7376 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7377 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7378 Instruction::BitCast : Instruction::Trunc);
7379 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7380 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7381 return BinaryOperator::CreateShl(Op0c, Op1c);
7384 case Instruction::AShr:
7385 // If this is a signed shr, and if all bits shifted in are about to be
7386 // truncated off, turn it into an unsigned shr to allow greater
7388 if (DestBitSize < SrcBitSize &&
7389 isa<ConstantInt>(Op1)) {
7390 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7391 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7392 // Insert the new logical shift right.
7393 return BinaryOperator::CreateLShr(Op0, Op1);
7401 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7402 if (Instruction *Result = commonIntCastTransforms(CI))
7405 Value *Src = CI.getOperand(0);
7406 const Type *Ty = CI.getType();
7407 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7408 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7410 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7411 switch (SrcI->getOpcode()) {
7413 case Instruction::LShr:
7414 // We can shrink lshr to something smaller if we know the bits shifted in
7415 // are already zeros.
7416 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7417 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7419 // Get a mask for the bits shifting in.
7420 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7421 Value* SrcIOp0 = SrcI->getOperand(0);
7422 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7423 if (ShAmt >= DestBitWidth) // All zeros.
7424 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7426 // Okay, we can shrink this. Truncate the input, then return a new
7428 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7429 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7431 return BinaryOperator::CreateLShr(V1, V2);
7433 } else { // This is a variable shr.
7435 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7436 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7437 // loop-invariant and CSE'd.
7438 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7439 Value *One = ConstantInt::get(SrcI->getType(), 1);
7441 Value *V = InsertNewInstBefore(
7442 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7444 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7445 SrcI->getOperand(0),
7447 Value *Zero = Constant::getNullValue(V->getType());
7448 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7458 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7459 /// in order to eliminate the icmp.
7460 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7462 // If we are just checking for a icmp eq of a single bit and zext'ing it
7463 // to an integer, then shift the bit to the appropriate place and then
7464 // cast to integer to avoid the comparison.
7465 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7466 const APInt &Op1CV = Op1C->getValue();
7468 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7469 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7470 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7471 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7472 if (!DoXform) return ICI;
7474 Value *In = ICI->getOperand(0);
7475 Value *Sh = ConstantInt::get(In->getType(),
7476 In->getType()->getPrimitiveSizeInBits()-1);
7477 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7478 In->getName()+".lobit"),
7480 if (In->getType() != CI.getType())
7481 In = CastInst::CreateIntegerCast(In, CI.getType(),
7482 false/*ZExt*/, "tmp", &CI);
7484 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7485 Constant *One = ConstantInt::get(In->getType(), 1);
7486 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7487 In->getName()+".not"),
7491 return ReplaceInstUsesWith(CI, In);
7496 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7497 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7498 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7499 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7500 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7501 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7502 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7503 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7504 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7505 // This only works for EQ and NE
7506 ICI->isEquality()) {
7507 // If Op1C some other power of two, convert:
7508 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7509 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7510 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7511 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7513 APInt KnownZeroMask(~KnownZero);
7514 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7515 if (!DoXform) return ICI;
7517 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7518 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7519 // (X&4) == 2 --> false
7520 // (X&4) != 2 --> true
7521 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7522 Res = ConstantExpr::getZExt(Res, CI.getType());
7523 return ReplaceInstUsesWith(CI, Res);
7526 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7527 Value *In = ICI->getOperand(0);
7529 // Perform a logical shr by shiftamt.
7530 // Insert the shift to put the result in the low bit.
7531 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7532 ConstantInt::get(In->getType(), ShiftAmt),
7533 In->getName()+".lobit"), CI);
7536 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7537 Constant *One = ConstantInt::get(In->getType(), 1);
7538 In = BinaryOperator::CreateXor(In, One, "tmp");
7539 InsertNewInstBefore(cast<Instruction>(In), CI);
7542 if (CI.getType() == In->getType())
7543 return ReplaceInstUsesWith(CI, In);
7545 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7553 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7554 // If one of the common conversion will work ..
7555 if (Instruction *Result = commonIntCastTransforms(CI))
7558 Value *Src = CI.getOperand(0);
7560 // If this is a cast of a cast
7561 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7562 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7563 // types and if the sizes are just right we can convert this into a logical
7564 // 'and' which will be much cheaper than the pair of casts.
7565 if (isa<TruncInst>(CSrc)) {
7566 // Get the sizes of the types involved
7567 Value *A = CSrc->getOperand(0);
7568 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7569 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7570 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7571 // If we're actually extending zero bits and the trunc is a no-op
7572 if (MidSize < DstSize && SrcSize == DstSize) {
7573 // Replace both of the casts with an And of the type mask.
7574 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7575 Constant *AndConst = ConstantInt::get(AndValue);
7577 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7578 // Unfortunately, if the type changed, we need to cast it back.
7579 if (And->getType() != CI.getType()) {
7580 And->setName(CSrc->getName()+".mask");
7581 InsertNewInstBefore(And, CI);
7582 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7589 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7590 return transformZExtICmp(ICI, CI);
7592 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7593 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7594 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7595 // of the (zext icmp) will be transformed.
7596 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7597 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7598 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7599 (transformZExtICmp(LHS, CI, false) ||
7600 transformZExtICmp(RHS, CI, false))) {
7601 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7602 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7603 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7610 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7611 if (Instruction *I = commonIntCastTransforms(CI))
7614 Value *Src = CI.getOperand(0);
7616 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7617 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7618 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7619 // If we are just checking for a icmp eq of a single bit and zext'ing it
7620 // to an integer, then shift the bit to the appropriate place and then
7621 // cast to integer to avoid the comparison.
7622 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7623 const APInt &Op1CV = Op1C->getValue();
7625 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7626 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7627 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7628 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7629 Value *In = ICI->getOperand(0);
7630 Value *Sh = ConstantInt::get(In->getType(),
7631 In->getType()->getPrimitiveSizeInBits()-1);
7632 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7633 In->getName()+".lobit"),
7635 if (In->getType() != CI.getType())
7636 In = CastInst::CreateIntegerCast(In, CI.getType(),
7637 true/*SExt*/, "tmp", &CI);
7639 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7640 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7641 In->getName()+".not"), CI);
7643 return ReplaceInstUsesWith(CI, In);
7648 // See if the value being truncated is already sign extended. If so, just
7649 // eliminate the trunc/sext pair.
7650 if (getOpcode(Src) == Instruction::Trunc) {
7651 Value *Op = cast<User>(Src)->getOperand(0);
7652 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7653 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7654 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7655 unsigned NumSignBits = ComputeNumSignBits(Op);
7657 if (OpBits == DestBits) {
7658 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7659 // bits, it is already ready.
7660 if (NumSignBits > DestBits-MidBits)
7661 return ReplaceInstUsesWith(CI, Op);
7662 } else if (OpBits < DestBits) {
7663 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7664 // bits, just sext from i32.
7665 if (NumSignBits > OpBits-MidBits)
7666 return new SExtInst(Op, CI.getType(), "tmp");
7668 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7669 // bits, just truncate to i32.
7670 if (NumSignBits > OpBits-MidBits)
7671 return new TruncInst(Op, CI.getType(), "tmp");
7675 // If the input is a shl/ashr pair of a same constant, then this is a sign
7676 // extension from a smaller value. If we could trust arbitrary bitwidth
7677 // integers, we could turn this into a truncate to the smaller bit and then
7678 // use a sext for the whole extension. Since we don't, look deeper and check
7679 // for a truncate. If the source and dest are the same type, eliminate the
7680 // trunc and extend and just do shifts. For example, turn:
7681 // %a = trunc i32 %i to i8
7682 // %b = shl i8 %a, 6
7683 // %c = ashr i8 %b, 6
7684 // %d = sext i8 %c to i32
7686 // %a = shl i32 %i, 30
7687 // %d = ashr i32 %a, 30
7689 ConstantInt *BA = 0, *CA = 0;
7690 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
7691 m_ConstantInt(CA))) &&
7692 BA == CA && isa<TruncInst>(A)) {
7693 Value *I = cast<TruncInst>(A)->getOperand(0);
7694 if (I->getType() == CI.getType()) {
7695 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
7696 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
7697 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
7698 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
7699 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
7701 return BinaryOperator::CreateAShr(I, ShAmtV);
7708 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7709 /// in the specified FP type without changing its value.
7710 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7711 APFloat F = CFP->getValueAPF();
7712 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7713 return ConstantFP::get(F);
7717 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7718 /// through it until we get the source value.
7719 static Value *LookThroughFPExtensions(Value *V) {
7720 if (Instruction *I = dyn_cast<Instruction>(V))
7721 if (I->getOpcode() == Instruction::FPExt)
7722 return LookThroughFPExtensions(I->getOperand(0));
7724 // If this value is a constant, return the constant in the smallest FP type
7725 // that can accurately represent it. This allows us to turn
7726 // (float)((double)X+2.0) into x+2.0f.
7727 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7728 if (CFP->getType() == Type::PPC_FP128Ty)
7729 return V; // No constant folding of this.
7730 // See if the value can be truncated to float and then reextended.
7731 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7733 if (CFP->getType() == Type::DoubleTy)
7734 return V; // Won't shrink.
7735 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7737 // Don't try to shrink to various long double types.
7743 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7744 if (Instruction *I = commonCastTransforms(CI))
7747 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7748 // smaller than the destination type, we can eliminate the truncate by doing
7749 // the add as the smaller type. This applies to add/sub/mul/div as well as
7750 // many builtins (sqrt, etc).
7751 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7752 if (OpI && OpI->hasOneUse()) {
7753 switch (OpI->getOpcode()) {
7755 case Instruction::Add:
7756 case Instruction::Sub:
7757 case Instruction::Mul:
7758 case Instruction::FDiv:
7759 case Instruction::FRem:
7760 const Type *SrcTy = OpI->getType();
7761 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7762 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7763 if (LHSTrunc->getType() != SrcTy &&
7764 RHSTrunc->getType() != SrcTy) {
7765 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7766 // If the source types were both smaller than the destination type of
7767 // the cast, do this xform.
7768 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7769 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7770 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7772 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7774 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7783 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7784 return commonCastTransforms(CI);
7787 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7788 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7790 return commonCastTransforms(FI);
7792 // fptoui(uitofp(X)) --> X
7793 // fptoui(sitofp(X)) --> X
7794 // This is safe if the intermediate type has enough bits in its mantissa to
7795 // accurately represent all values of X. For example, do not do this with
7796 // i64->float->i64. This is also safe for sitofp case, because any negative
7797 // 'X' value would cause an undefined result for the fptoui.
7798 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7799 OpI->getOperand(0)->getType() == FI.getType() &&
7800 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7801 OpI->getType()->getFPMantissaWidth())
7802 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
7804 return commonCastTransforms(FI);
7807 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7808 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7810 return commonCastTransforms(FI);
7812 // fptosi(sitofp(X)) --> X
7813 // fptosi(uitofp(X)) --> X
7814 // This is safe if the intermediate type has enough bits in its mantissa to
7815 // accurately represent all values of X. For example, do not do this with
7816 // i64->float->i64. This is also safe for sitofp case, because any negative
7817 // 'X' value would cause an undefined result for the fptoui.
7818 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7819 OpI->getOperand(0)->getType() == FI.getType() &&
7820 (int)FI.getType()->getPrimitiveSizeInBits() <=
7821 OpI->getType()->getFPMantissaWidth())
7822 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
7824 return commonCastTransforms(FI);
7827 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7828 return commonCastTransforms(CI);
7831 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7832 return commonCastTransforms(CI);
7835 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7836 return commonPointerCastTransforms(CI);
7839 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7840 if (Instruction *I = commonCastTransforms(CI))
7843 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7844 if (!DestPointee->isSized()) return 0;
7846 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7849 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7850 m_ConstantInt(Cst)))) {
7851 // If the source and destination operands have the same type, see if this
7852 // is a single-index GEP.
7853 if (X->getType() == CI.getType()) {
7854 // Get the size of the pointee type.
7855 uint64_t Size = TD->getABITypeSize(DestPointee);
7857 // Convert the constant to intptr type.
7858 APInt Offset = Cst->getValue();
7859 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7861 // If Offset is evenly divisible by Size, we can do this xform.
7862 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7863 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7864 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7867 // TODO: Could handle other cases, e.g. where add is indexing into field of
7869 } else if (CI.getOperand(0)->hasOneUse() &&
7870 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7871 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7872 // "inttoptr+GEP" instead of "add+intptr".
7874 // Get the size of the pointee type.
7875 uint64_t Size = TD->getABITypeSize(DestPointee);
7877 // Convert the constant to intptr type.
7878 APInt Offset = Cst->getValue();
7879 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7881 // If Offset is evenly divisible by Size, we can do this xform.
7882 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7883 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7885 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7887 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7893 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7894 // If the operands are integer typed then apply the integer transforms,
7895 // otherwise just apply the common ones.
7896 Value *Src = CI.getOperand(0);
7897 const Type *SrcTy = Src->getType();
7898 const Type *DestTy = CI.getType();
7900 if (SrcTy->isInteger() && DestTy->isInteger()) {
7901 if (Instruction *Result = commonIntCastTransforms(CI))
7903 } else if (isa<PointerType>(SrcTy)) {
7904 if (Instruction *I = commonPointerCastTransforms(CI))
7907 if (Instruction *Result = commonCastTransforms(CI))
7912 // Get rid of casts from one type to the same type. These are useless and can
7913 // be replaced by the operand.
7914 if (DestTy == Src->getType())
7915 return ReplaceInstUsesWith(CI, Src);
7917 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7918 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7919 const Type *DstElTy = DstPTy->getElementType();
7920 const Type *SrcElTy = SrcPTy->getElementType();
7922 // If the address spaces don't match, don't eliminate the bitcast, which is
7923 // required for changing types.
7924 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7927 // If we are casting a malloc or alloca to a pointer to a type of the same
7928 // size, rewrite the allocation instruction to allocate the "right" type.
7929 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7930 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7933 // If the source and destination are pointers, and this cast is equivalent
7934 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7935 // This can enhance SROA and other transforms that want type-safe pointers.
7936 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7937 unsigned NumZeros = 0;
7938 while (SrcElTy != DstElTy &&
7939 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7940 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7941 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7945 // If we found a path from the src to dest, create the getelementptr now.
7946 if (SrcElTy == DstElTy) {
7947 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7948 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7949 ((Instruction*) NULL));
7953 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7954 if (SVI->hasOneUse()) {
7955 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7956 // a bitconvert to a vector with the same # elts.
7957 if (isa<VectorType>(DestTy) &&
7958 cast<VectorType>(DestTy)->getNumElements() ==
7959 SVI->getType()->getNumElements()) {
7961 // If either of the operands is a cast from CI.getType(), then
7962 // evaluating the shuffle in the casted destination's type will allow
7963 // us to eliminate at least one cast.
7964 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7965 Tmp->getOperand(0)->getType() == DestTy) ||
7966 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7967 Tmp->getOperand(0)->getType() == DestTy)) {
7968 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7969 SVI->getOperand(0), DestTy, &CI);
7970 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7971 SVI->getOperand(1), DestTy, &CI);
7972 // Return a new shuffle vector. Use the same element ID's, as we
7973 // know the vector types match #elts.
7974 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7982 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7984 /// %D = select %cond, %C, %A
7986 /// %C = select %cond, %B, 0
7989 /// Assuming that the specified instruction is an operand to the select, return
7990 /// a bitmask indicating which operands of this instruction are foldable if they
7991 /// equal the other incoming value of the select.
7993 static unsigned GetSelectFoldableOperands(Instruction *I) {
7994 switch (I->getOpcode()) {
7995 case Instruction::Add:
7996 case Instruction::Mul:
7997 case Instruction::And:
7998 case Instruction::Or:
7999 case Instruction::Xor:
8000 return 3; // Can fold through either operand.
8001 case Instruction::Sub: // Can only fold on the amount subtracted.
8002 case Instruction::Shl: // Can only fold on the shift amount.
8003 case Instruction::LShr:
8004 case Instruction::AShr:
8007 return 0; // Cannot fold
8011 /// GetSelectFoldableConstant - For the same transformation as the previous
8012 /// function, return the identity constant that goes into the select.
8013 static Constant *GetSelectFoldableConstant(Instruction *I) {
8014 switch (I->getOpcode()) {
8015 default: assert(0 && "This cannot happen!"); abort();
8016 case Instruction::Add:
8017 case Instruction::Sub:
8018 case Instruction::Or:
8019 case Instruction::Xor:
8020 case Instruction::Shl:
8021 case Instruction::LShr:
8022 case Instruction::AShr:
8023 return Constant::getNullValue(I->getType());
8024 case Instruction::And:
8025 return Constant::getAllOnesValue(I->getType());
8026 case Instruction::Mul:
8027 return ConstantInt::get(I->getType(), 1);
8031 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8032 /// have the same opcode and only one use each. Try to simplify this.
8033 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8035 if (TI->getNumOperands() == 1) {
8036 // If this is a non-volatile load or a cast from the same type,
8039 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8042 return 0; // unknown unary op.
8045 // Fold this by inserting a select from the input values.
8046 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8047 FI->getOperand(0), SI.getName()+".v");
8048 InsertNewInstBefore(NewSI, SI);
8049 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
8053 // Only handle binary operators here.
8054 if (!isa<BinaryOperator>(TI))
8057 // Figure out if the operations have any operands in common.
8058 Value *MatchOp, *OtherOpT, *OtherOpF;
8060 if (TI->getOperand(0) == FI->getOperand(0)) {
8061 MatchOp = TI->getOperand(0);
8062 OtherOpT = TI->getOperand(1);
8063 OtherOpF = FI->getOperand(1);
8064 MatchIsOpZero = true;
8065 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8066 MatchOp = TI->getOperand(1);
8067 OtherOpT = TI->getOperand(0);
8068 OtherOpF = FI->getOperand(0);
8069 MatchIsOpZero = false;
8070 } else if (!TI->isCommutative()) {
8072 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8073 MatchOp = TI->getOperand(0);
8074 OtherOpT = TI->getOperand(1);
8075 OtherOpF = FI->getOperand(0);
8076 MatchIsOpZero = true;
8077 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8078 MatchOp = TI->getOperand(1);
8079 OtherOpT = TI->getOperand(0);
8080 OtherOpF = FI->getOperand(1);
8081 MatchIsOpZero = true;
8086 // If we reach here, they do have operations in common.
8087 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8088 OtherOpF, SI.getName()+".v");
8089 InsertNewInstBefore(NewSI, SI);
8091 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8093 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8095 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8097 assert(0 && "Shouldn't get here");
8101 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8102 Value *CondVal = SI.getCondition();
8103 Value *TrueVal = SI.getTrueValue();
8104 Value *FalseVal = SI.getFalseValue();
8106 // select true, X, Y -> X
8107 // select false, X, Y -> Y
8108 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8109 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8111 // select C, X, X -> X
8112 if (TrueVal == FalseVal)
8113 return ReplaceInstUsesWith(SI, TrueVal);
8115 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8116 return ReplaceInstUsesWith(SI, FalseVal);
8117 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8118 return ReplaceInstUsesWith(SI, TrueVal);
8119 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8120 if (isa<Constant>(TrueVal))
8121 return ReplaceInstUsesWith(SI, TrueVal);
8123 return ReplaceInstUsesWith(SI, FalseVal);
8126 if (SI.getType() == Type::Int1Ty) {
8127 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8128 if (C->getZExtValue()) {
8129 // Change: A = select B, true, C --> A = or B, C
8130 return BinaryOperator::CreateOr(CondVal, FalseVal);
8132 // Change: A = select B, false, C --> A = and !B, C
8134 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8135 "not."+CondVal->getName()), SI);
8136 return BinaryOperator::CreateAnd(NotCond, FalseVal);
8138 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8139 if (C->getZExtValue() == false) {
8140 // Change: A = select B, C, false --> A = and B, C
8141 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8143 // Change: A = select B, C, true --> A = or !B, C
8145 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8146 "not."+CondVal->getName()), SI);
8147 return BinaryOperator::CreateOr(NotCond, TrueVal);
8151 // select a, b, a -> a&b
8152 // select a, a, b -> a|b
8153 if (CondVal == TrueVal)
8154 return BinaryOperator::CreateOr(CondVal, FalseVal);
8155 else if (CondVal == FalseVal)
8156 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8159 // Selecting between two integer constants?
8160 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8161 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8162 // select C, 1, 0 -> zext C to int
8163 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8164 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8165 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8166 // select C, 0, 1 -> zext !C to int
8168 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8169 "not."+CondVal->getName()), SI);
8170 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8173 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8175 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8177 // (x <s 0) ? -1 : 0 -> ashr x, 31
8178 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8179 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8180 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8181 // The comparison constant and the result are not neccessarily the
8182 // same width. Make an all-ones value by inserting a AShr.
8183 Value *X = IC->getOperand(0);
8184 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8185 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8186 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8188 InsertNewInstBefore(SRA, SI);
8190 // Finally, convert to the type of the select RHS. We figure out
8191 // if this requires a SExt, Trunc or BitCast based on the sizes.
8192 Instruction::CastOps opc = Instruction::BitCast;
8193 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8194 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8195 if (SRASize < SISize)
8196 opc = Instruction::SExt;
8197 else if (SRASize > SISize)
8198 opc = Instruction::Trunc;
8199 return CastInst::Create(opc, SRA, SI.getType());
8204 // If one of the constants is zero (we know they can't both be) and we
8205 // have an icmp instruction with zero, and we have an 'and' with the
8206 // non-constant value, eliminate this whole mess. This corresponds to
8207 // cases like this: ((X & 27) ? 27 : 0)
8208 if (TrueValC->isZero() || FalseValC->isZero())
8209 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8210 cast<Constant>(IC->getOperand(1))->isNullValue())
8211 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8212 if (ICA->getOpcode() == Instruction::And &&
8213 isa<ConstantInt>(ICA->getOperand(1)) &&
8214 (ICA->getOperand(1) == TrueValC ||
8215 ICA->getOperand(1) == FalseValC) &&
8216 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8217 // Okay, now we know that everything is set up, we just don't
8218 // know whether we have a icmp_ne or icmp_eq and whether the
8219 // true or false val is the zero.
8220 bool ShouldNotVal = !TrueValC->isZero();
8221 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8224 V = InsertNewInstBefore(BinaryOperator::Create(
8225 Instruction::Xor, V, ICA->getOperand(1)), SI);
8226 return ReplaceInstUsesWith(SI, V);
8231 // See if we are selecting two values based on a comparison of the two values.
8232 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8233 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8234 // Transform (X == Y) ? X : Y -> Y
8235 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8236 // This is not safe in general for floating point:
8237 // consider X== -0, Y== +0.
8238 // It becomes safe if either operand is a nonzero constant.
8239 ConstantFP *CFPt, *CFPf;
8240 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8241 !CFPt->getValueAPF().isZero()) ||
8242 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8243 !CFPf->getValueAPF().isZero()))
8244 return ReplaceInstUsesWith(SI, FalseVal);
8246 // Transform (X != Y) ? X : Y -> X
8247 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8248 return ReplaceInstUsesWith(SI, TrueVal);
8249 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8251 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8252 // Transform (X == Y) ? Y : X -> X
8253 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8254 // This is not safe in general for floating point:
8255 // consider X== -0, Y== +0.
8256 // It becomes safe if either operand is a nonzero constant.
8257 ConstantFP *CFPt, *CFPf;
8258 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8259 !CFPt->getValueAPF().isZero()) ||
8260 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8261 !CFPf->getValueAPF().isZero()))
8262 return ReplaceInstUsesWith(SI, FalseVal);
8264 // Transform (X != Y) ? Y : X -> Y
8265 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8266 return ReplaceInstUsesWith(SI, TrueVal);
8267 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8271 // See if we are selecting two values based on a comparison of the two values.
8272 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8273 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8274 // Transform (X == Y) ? X : Y -> Y
8275 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8276 return ReplaceInstUsesWith(SI, FalseVal);
8277 // Transform (X != Y) ? X : Y -> X
8278 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8279 return ReplaceInstUsesWith(SI, TrueVal);
8280 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8282 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8283 // Transform (X == Y) ? Y : X -> X
8284 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8285 return ReplaceInstUsesWith(SI, FalseVal);
8286 // Transform (X != Y) ? Y : X -> Y
8287 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8288 return ReplaceInstUsesWith(SI, TrueVal);
8289 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8293 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8294 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8295 if (TI->hasOneUse() && FI->hasOneUse()) {
8296 Instruction *AddOp = 0, *SubOp = 0;
8298 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8299 if (TI->getOpcode() == FI->getOpcode())
8300 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8303 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8304 // even legal for FP.
8305 if (TI->getOpcode() == Instruction::Sub &&
8306 FI->getOpcode() == Instruction::Add) {
8307 AddOp = FI; SubOp = TI;
8308 } else if (FI->getOpcode() == Instruction::Sub &&
8309 TI->getOpcode() == Instruction::Add) {
8310 AddOp = TI; SubOp = FI;
8314 Value *OtherAddOp = 0;
8315 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8316 OtherAddOp = AddOp->getOperand(1);
8317 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8318 OtherAddOp = AddOp->getOperand(0);
8322 // So at this point we know we have (Y -> OtherAddOp):
8323 // select C, (add X, Y), (sub X, Z)
8324 Value *NegVal; // Compute -Z
8325 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8326 NegVal = ConstantExpr::getNeg(C);
8328 NegVal = InsertNewInstBefore(
8329 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8332 Value *NewTrueOp = OtherAddOp;
8333 Value *NewFalseOp = NegVal;
8335 std::swap(NewTrueOp, NewFalseOp);
8336 Instruction *NewSel =
8337 SelectInst::Create(CondVal, NewTrueOp,
8338 NewFalseOp, SI.getName() + ".p");
8340 NewSel = InsertNewInstBefore(NewSel, SI);
8341 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8346 // See if we can fold the select into one of our operands.
8347 if (SI.getType()->isInteger()) {
8348 // See the comment above GetSelectFoldableOperands for a description of the
8349 // transformation we are doing here.
8350 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8351 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8352 !isa<Constant>(FalseVal))
8353 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8354 unsigned OpToFold = 0;
8355 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8357 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8362 Constant *C = GetSelectFoldableConstant(TVI);
8363 Instruction *NewSel =
8364 SelectInst::Create(SI.getCondition(),
8365 TVI->getOperand(2-OpToFold), C);
8366 InsertNewInstBefore(NewSel, SI);
8367 NewSel->takeName(TVI);
8368 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8369 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8371 assert(0 && "Unknown instruction!!");
8376 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8377 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8378 !isa<Constant>(TrueVal))
8379 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8380 unsigned OpToFold = 0;
8381 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8383 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8388 Constant *C = GetSelectFoldableConstant(FVI);
8389 Instruction *NewSel =
8390 SelectInst::Create(SI.getCondition(), C,
8391 FVI->getOperand(2-OpToFold));
8392 InsertNewInstBefore(NewSel, SI);
8393 NewSel->takeName(FVI);
8394 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8395 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8397 assert(0 && "Unknown instruction!!");
8402 if (BinaryOperator::isNot(CondVal)) {
8403 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8404 SI.setOperand(1, FalseVal);
8405 SI.setOperand(2, TrueVal);
8412 /// EnforceKnownAlignment - If the specified pointer points to an object that
8413 /// we control, modify the object's alignment to PrefAlign. This isn't
8414 /// often possible though. If alignment is important, a more reliable approach
8415 /// is to simply align all global variables and allocation instructions to
8416 /// their preferred alignment from the beginning.
8418 static unsigned EnforceKnownAlignment(Value *V,
8419 unsigned Align, unsigned PrefAlign) {
8421 User *U = dyn_cast<User>(V);
8422 if (!U) return Align;
8424 switch (getOpcode(U)) {
8426 case Instruction::BitCast:
8427 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8428 case Instruction::GetElementPtr: {
8429 // If all indexes are zero, it is just the alignment of the base pointer.
8430 bool AllZeroOperands = true;
8431 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8432 if (!isa<Constant>(*i) ||
8433 !cast<Constant>(*i)->isNullValue()) {
8434 AllZeroOperands = false;
8438 if (AllZeroOperands) {
8439 // Treat this like a bitcast.
8440 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8446 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8447 // If there is a large requested alignment and we can, bump up the alignment
8449 if (!GV->isDeclaration()) {
8450 GV->setAlignment(PrefAlign);
8453 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8454 // If there is a requested alignment and if this is an alloca, round up. We
8455 // don't do this for malloc, because some systems can't respect the request.
8456 if (isa<AllocaInst>(AI)) {
8457 AI->setAlignment(PrefAlign);
8465 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8466 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8467 /// and it is more than the alignment of the ultimate object, see if we can
8468 /// increase the alignment of the ultimate object, making this check succeed.
8469 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8470 unsigned PrefAlign) {
8471 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8472 sizeof(PrefAlign) * CHAR_BIT;
8473 APInt Mask = APInt::getAllOnesValue(BitWidth);
8474 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8475 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8476 unsigned TrailZ = KnownZero.countTrailingOnes();
8477 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8479 if (PrefAlign > Align)
8480 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8482 // We don't need to make any adjustment.
8486 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8487 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8488 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8489 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8490 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8492 if (CopyAlign < MinAlign) {
8493 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8497 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8499 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8500 if (MemOpLength == 0) return 0;
8502 // Source and destination pointer types are always "i8*" for intrinsic. See
8503 // if the size is something we can handle with a single primitive load/store.
8504 // A single load+store correctly handles overlapping memory in the memmove
8506 unsigned Size = MemOpLength->getZExtValue();
8507 if (Size == 0) return MI; // Delete this mem transfer.
8509 if (Size > 8 || (Size&(Size-1)))
8510 return 0; // If not 1/2/4/8 bytes, exit.
8512 // Use an integer load+store unless we can find something better.
8513 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8515 // Memcpy forces the use of i8* for the source and destination. That means
8516 // that if you're using memcpy to move one double around, you'll get a cast
8517 // from double* to i8*. We'd much rather use a double load+store rather than
8518 // an i64 load+store, here because this improves the odds that the source or
8519 // dest address will be promotable. See if we can find a better type than the
8520 // integer datatype.
8521 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8522 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8523 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8524 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8525 // down through these levels if so.
8526 while (!SrcETy->isSingleValueType()) {
8527 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8528 if (STy->getNumElements() == 1)
8529 SrcETy = STy->getElementType(0);
8532 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8533 if (ATy->getNumElements() == 1)
8534 SrcETy = ATy->getElementType();
8541 if (SrcETy->isSingleValueType())
8542 NewPtrTy = PointerType::getUnqual(SrcETy);
8547 // If the memcpy/memmove provides better alignment info than we can
8549 SrcAlign = std::max(SrcAlign, CopyAlign);
8550 DstAlign = std::max(DstAlign, CopyAlign);
8552 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8553 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8554 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8555 InsertNewInstBefore(L, *MI);
8556 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8558 // Set the size of the copy to 0, it will be deleted on the next iteration.
8559 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8563 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8564 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8565 if (MI->getAlignment()->getZExtValue() < Alignment) {
8566 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8570 // Extract the length and alignment and fill if they are constant.
8571 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8572 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8573 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8575 uint64_t Len = LenC->getZExtValue();
8576 Alignment = MI->getAlignment()->getZExtValue();
8578 // If the length is zero, this is a no-op
8579 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8581 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8582 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8583 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8585 Value *Dest = MI->getDest();
8586 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8588 // Alignment 0 is identity for alignment 1 for memset, but not store.
8589 if (Alignment == 0) Alignment = 1;
8591 // Extract the fill value and store.
8592 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8593 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8596 // Set the size of the copy to 0, it will be deleted on the next iteration.
8597 MI->setLength(Constant::getNullValue(LenC->getType()));
8605 /// visitCallInst - CallInst simplification. This mostly only handles folding
8606 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8607 /// the heavy lifting.
8609 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8610 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8611 if (!II) return visitCallSite(&CI);
8613 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8615 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8616 bool Changed = false;
8618 // memmove/cpy/set of zero bytes is a noop.
8619 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8620 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8622 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8623 if (CI->getZExtValue() == 1) {
8624 // Replace the instruction with just byte operations. We would
8625 // transform other cases to loads/stores, but we don't know if
8626 // alignment is sufficient.
8630 // If we have a memmove and the source operation is a constant global,
8631 // then the source and dest pointers can't alias, so we can change this
8632 // into a call to memcpy.
8633 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8634 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8635 if (GVSrc->isConstant()) {
8636 Module *M = CI.getParent()->getParent()->getParent();
8637 Intrinsic::ID MemCpyID;
8638 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8639 MemCpyID = Intrinsic::memcpy_i32;
8641 MemCpyID = Intrinsic::memcpy_i64;
8642 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8646 // memmove(x,x,size) -> noop.
8647 if (MMI->getSource() == MMI->getDest())
8648 return EraseInstFromFunction(CI);
8651 // If we can determine a pointer alignment that is bigger than currently
8652 // set, update the alignment.
8653 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8654 if (Instruction *I = SimplifyMemTransfer(MI))
8656 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8657 if (Instruction *I = SimplifyMemSet(MSI))
8661 if (Changed) return II;
8664 switch (II->getIntrinsicID()) {
8666 case Intrinsic::bswap:
8667 // bswap(bswap(x)) -> x
8668 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8669 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8670 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8672 case Intrinsic::ppc_altivec_lvx:
8673 case Intrinsic::ppc_altivec_lvxl:
8674 case Intrinsic::x86_sse_loadu_ps:
8675 case Intrinsic::x86_sse2_loadu_pd:
8676 case Intrinsic::x86_sse2_loadu_dq:
8677 // Turn PPC lvx -> load if the pointer is known aligned.
8678 // Turn X86 loadups -> load if the pointer is known aligned.
8679 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8680 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8681 PointerType::getUnqual(II->getType()),
8683 return new LoadInst(Ptr);
8686 case Intrinsic::ppc_altivec_stvx:
8687 case Intrinsic::ppc_altivec_stvxl:
8688 // Turn stvx -> store if the pointer is known aligned.
8689 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8690 const Type *OpPtrTy =
8691 PointerType::getUnqual(II->getOperand(1)->getType());
8692 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8693 return new StoreInst(II->getOperand(1), Ptr);
8696 case Intrinsic::x86_sse_storeu_ps:
8697 case Intrinsic::x86_sse2_storeu_pd:
8698 case Intrinsic::x86_sse2_storeu_dq:
8699 // Turn X86 storeu -> store if the pointer is known aligned.
8700 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8701 const Type *OpPtrTy =
8702 PointerType::getUnqual(II->getOperand(2)->getType());
8703 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8704 return new StoreInst(II->getOperand(2), Ptr);
8708 case Intrinsic::x86_sse_cvttss2si: {
8709 // These intrinsics only demands the 0th element of its input vector. If
8710 // we can simplify the input based on that, do so now.
8712 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8714 II->setOperand(1, V);
8720 case Intrinsic::ppc_altivec_vperm:
8721 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8722 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8723 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8725 // Check that all of the elements are integer constants or undefs.
8726 bool AllEltsOk = true;
8727 for (unsigned i = 0; i != 16; ++i) {
8728 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8729 !isa<UndefValue>(Mask->getOperand(i))) {
8736 // Cast the input vectors to byte vectors.
8737 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8738 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8739 Value *Result = UndefValue::get(Op0->getType());
8741 // Only extract each element once.
8742 Value *ExtractedElts[32];
8743 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8745 for (unsigned i = 0; i != 16; ++i) {
8746 if (isa<UndefValue>(Mask->getOperand(i)))
8748 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8749 Idx &= 31; // Match the hardware behavior.
8751 if (ExtractedElts[Idx] == 0) {
8753 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8754 InsertNewInstBefore(Elt, CI);
8755 ExtractedElts[Idx] = Elt;
8758 // Insert this value into the result vector.
8759 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8761 InsertNewInstBefore(cast<Instruction>(Result), CI);
8763 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8768 case Intrinsic::stackrestore: {
8769 // If the save is right next to the restore, remove the restore. This can
8770 // happen when variable allocas are DCE'd.
8771 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8772 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8773 BasicBlock::iterator BI = SS;
8775 return EraseInstFromFunction(CI);
8779 // Scan down this block to see if there is another stack restore in the
8780 // same block without an intervening call/alloca.
8781 BasicBlock::iterator BI = II;
8782 TerminatorInst *TI = II->getParent()->getTerminator();
8783 bool CannotRemove = false;
8784 for (++BI; &*BI != TI; ++BI) {
8785 if (isa<AllocaInst>(BI)) {
8786 CannotRemove = true;
8789 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8790 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8791 // If there is a stackrestore below this one, remove this one.
8792 if (II->getIntrinsicID() == Intrinsic::stackrestore)
8793 return EraseInstFromFunction(CI);
8794 // Otherwise, ignore the intrinsic.
8796 // If we found a non-intrinsic call, we can't remove the stack
8798 CannotRemove = true;
8804 // If the stack restore is in a return/unwind block and if there are no
8805 // allocas or calls between the restore and the return, nuke the restore.
8806 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8807 return EraseInstFromFunction(CI);
8812 return visitCallSite(II);
8815 // InvokeInst simplification
8817 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8818 return visitCallSite(&II);
8821 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
8822 /// passed through the varargs area, we can eliminate the use of the cast.
8823 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8824 const CastInst * const CI,
8825 const TargetData * const TD,
8827 if (!CI->isLosslessCast())
8830 // The size of ByVal arguments is derived from the type, so we
8831 // can't change to a type with a different size. If the size were
8832 // passed explicitly we could avoid this check.
8833 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8837 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8838 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8839 if (!SrcTy->isSized() || !DstTy->isSized())
8841 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8846 // visitCallSite - Improvements for call and invoke instructions.
8848 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8849 bool Changed = false;
8851 // If the callee is a constexpr cast of a function, attempt to move the cast
8852 // to the arguments of the call/invoke.
8853 if (transformConstExprCastCall(CS)) return 0;
8855 Value *Callee = CS.getCalledValue();
8857 if (Function *CalleeF = dyn_cast<Function>(Callee))
8858 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8859 Instruction *OldCall = CS.getInstruction();
8860 // If the call and callee calling conventions don't match, this call must
8861 // be unreachable, as the call is undefined.
8862 new StoreInst(ConstantInt::getTrue(),
8863 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8865 if (!OldCall->use_empty())
8866 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8867 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8868 return EraseInstFromFunction(*OldCall);
8872 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8873 // This instruction is not reachable, just remove it. We insert a store to
8874 // undef so that we know that this code is not reachable, despite the fact
8875 // that we can't modify the CFG here.
8876 new StoreInst(ConstantInt::getTrue(),
8877 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8878 CS.getInstruction());
8880 if (!CS.getInstruction()->use_empty())
8881 CS.getInstruction()->
8882 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8884 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8885 // Don't break the CFG, insert a dummy cond branch.
8886 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8887 ConstantInt::getTrue(), II);
8889 return EraseInstFromFunction(*CS.getInstruction());
8892 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8893 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8894 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8895 return transformCallThroughTrampoline(CS);
8897 const PointerType *PTy = cast<PointerType>(Callee->getType());
8898 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8899 if (FTy->isVarArg()) {
8900 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8901 // See if we can optimize any arguments passed through the varargs area of
8903 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8904 E = CS.arg_end(); I != E; ++I, ++ix) {
8905 CastInst *CI = dyn_cast<CastInst>(*I);
8906 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8907 *I = CI->getOperand(0);
8913 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8914 // Inline asm calls cannot throw - mark them 'nounwind'.
8915 CS.setDoesNotThrow();
8919 return Changed ? CS.getInstruction() : 0;
8922 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8923 // attempt to move the cast to the arguments of the call/invoke.
8925 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8926 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8927 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8928 if (CE->getOpcode() != Instruction::BitCast ||
8929 !isa<Function>(CE->getOperand(0)))
8931 Function *Callee = cast<Function>(CE->getOperand(0));
8932 Instruction *Caller = CS.getInstruction();
8933 const PAListPtr &CallerPAL = CS.getParamAttrs();
8935 // Okay, this is a cast from a function to a different type. Unless doing so
8936 // would cause a type conversion of one of our arguments, change this call to
8937 // be a direct call with arguments casted to the appropriate types.
8939 const FunctionType *FT = Callee->getFunctionType();
8940 const Type *OldRetTy = Caller->getType();
8941 const Type *NewRetTy = FT->getReturnType();
8943 if (isa<StructType>(NewRetTy))
8944 return false; // TODO: Handle multiple return values.
8946 // Check to see if we are changing the return type...
8947 if (OldRetTy != NewRetTy) {
8948 if (Callee->isDeclaration() &&
8949 // Conversion is ok if changing from one pointer type to another or from
8950 // a pointer to an integer of the same size.
8951 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8952 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8953 return false; // Cannot transform this return value.
8955 if (!Caller->use_empty() &&
8956 // void -> non-void is handled specially
8957 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8958 return false; // Cannot transform this return value.
8960 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8961 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8962 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8963 return false; // Attribute not compatible with transformed value.
8966 // If the callsite is an invoke instruction, and the return value is used by
8967 // a PHI node in a successor, we cannot change the return type of the call
8968 // because there is no place to put the cast instruction (without breaking
8969 // the critical edge). Bail out in this case.
8970 if (!Caller->use_empty())
8971 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8972 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8974 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8975 if (PN->getParent() == II->getNormalDest() ||
8976 PN->getParent() == II->getUnwindDest())
8980 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8981 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8983 CallSite::arg_iterator AI = CS.arg_begin();
8984 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8985 const Type *ParamTy = FT->getParamType(i);
8986 const Type *ActTy = (*AI)->getType();
8988 if (!CastInst::isCastable(ActTy, ParamTy))
8989 return false; // Cannot transform this parameter value.
8991 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8992 return false; // Attribute not compatible with transformed value.
8994 // Converting from one pointer type to another or between a pointer and an
8995 // integer of the same size is safe even if we do not have a body.
8996 bool isConvertible = ActTy == ParamTy ||
8997 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8998 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8999 if (Callee->isDeclaration() && !isConvertible) return false;
9002 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9003 Callee->isDeclaration())
9004 return false; // Do not delete arguments unless we have a function body.
9006 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9007 !CallerPAL.isEmpty())
9008 // In this case we have more arguments than the new function type, but we
9009 // won't be dropping them. Check that these extra arguments have attributes
9010 // that are compatible with being a vararg call argument.
9011 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9012 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9014 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9015 if (PAttrs & ParamAttr::VarArgsIncompatible)
9019 // Okay, we decided that this is a safe thing to do: go ahead and start
9020 // inserting cast instructions as necessary...
9021 std::vector<Value*> Args;
9022 Args.reserve(NumActualArgs);
9023 SmallVector<ParamAttrsWithIndex, 8> attrVec;
9024 attrVec.reserve(NumCommonArgs);
9026 // Get any return attributes.
9027 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9029 // If the return value is not being used, the type may not be compatible
9030 // with the existing attributes. Wipe out any problematic attributes.
9031 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
9033 // Add the new return attributes.
9035 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9037 AI = CS.arg_begin();
9038 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9039 const Type *ParamTy = FT->getParamType(i);
9040 if ((*AI)->getType() == ParamTy) {
9041 Args.push_back(*AI);
9043 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9044 false, ParamTy, false);
9045 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9046 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9049 // Add any parameter attributes.
9050 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9051 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9054 // If the function takes more arguments than the call was taking, add them
9056 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9057 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9059 // If we are removing arguments to the function, emit an obnoxious warning...
9060 if (FT->getNumParams() < NumActualArgs) {
9061 if (!FT->isVarArg()) {
9062 cerr << "WARNING: While resolving call to function '"
9063 << Callee->getName() << "' arguments were dropped!\n";
9065 // Add all of the arguments in their promoted form to the arg list...
9066 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9067 const Type *PTy = getPromotedType((*AI)->getType());
9068 if (PTy != (*AI)->getType()) {
9069 // Must promote to pass through va_arg area!
9070 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9072 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9073 InsertNewInstBefore(Cast, *Caller);
9074 Args.push_back(Cast);
9076 Args.push_back(*AI);
9079 // Add any parameter attributes.
9080 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9081 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9086 if (NewRetTy == Type::VoidTy)
9087 Caller->setName(""); // Void type should not have a name.
9089 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9092 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9093 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9094 Args.begin(), Args.end(),
9095 Caller->getName(), Caller);
9096 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9097 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9099 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9100 Caller->getName(), Caller);
9101 CallInst *CI = cast<CallInst>(Caller);
9102 if (CI->isTailCall())
9103 cast<CallInst>(NC)->setTailCall();
9104 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9105 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9108 // Insert a cast of the return type as necessary.
9110 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9111 if (NV->getType() != Type::VoidTy) {
9112 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
9114 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9116 // If this is an invoke instruction, we should insert it after the first
9117 // non-phi, instruction in the normal successor block.
9118 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9119 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9120 InsertNewInstBefore(NC, *I);
9122 // Otherwise, it's a call, just insert cast right after the call instr
9123 InsertNewInstBefore(NC, *Caller);
9125 AddUsersToWorkList(*Caller);
9127 NV = UndefValue::get(Caller->getType());
9131 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9132 Caller->replaceAllUsesWith(NV);
9133 Caller->eraseFromParent();
9134 RemoveFromWorkList(Caller);
9138 // transformCallThroughTrampoline - Turn a call to a function created by the
9139 // init_trampoline intrinsic into a direct call to the underlying function.
9141 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9142 Value *Callee = CS.getCalledValue();
9143 const PointerType *PTy = cast<PointerType>(Callee->getType());
9144 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9145 const PAListPtr &Attrs = CS.getParamAttrs();
9147 // If the call already has the 'nest' attribute somewhere then give up -
9148 // otherwise 'nest' would occur twice after splicing in the chain.
9149 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9152 IntrinsicInst *Tramp =
9153 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9155 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9156 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9157 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9159 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9160 if (!NestAttrs.isEmpty()) {
9161 unsigned NestIdx = 1;
9162 const Type *NestTy = 0;
9163 ParameterAttributes NestAttr = ParamAttr::None;
9165 // Look for a parameter marked with the 'nest' attribute.
9166 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9167 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9168 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9169 // Record the parameter type and any other attributes.
9171 NestAttr = NestAttrs.getParamAttrs(NestIdx);
9176 Instruction *Caller = CS.getInstruction();
9177 std::vector<Value*> NewArgs;
9178 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9180 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9181 NewAttrs.reserve(Attrs.getNumSlots() + 1);
9183 // Insert the nest argument into the call argument list, which may
9184 // mean appending it. Likewise for attributes.
9186 // Add any function result attributes.
9187 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9188 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9192 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9194 if (Idx == NestIdx) {
9195 // Add the chain argument and attributes.
9196 Value *NestVal = Tramp->getOperand(3);
9197 if (NestVal->getType() != NestTy)
9198 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9199 NewArgs.push_back(NestVal);
9200 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9206 // Add the original argument and attributes.
9207 NewArgs.push_back(*I);
9208 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9210 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9216 // The trampoline may have been bitcast to a bogus type (FTy).
9217 // Handle this by synthesizing a new function type, equal to FTy
9218 // with the chain parameter inserted.
9220 std::vector<const Type*> NewTypes;
9221 NewTypes.reserve(FTy->getNumParams()+1);
9223 // Insert the chain's type into the list of parameter types, which may
9224 // mean appending it.
9227 FunctionType::param_iterator I = FTy->param_begin(),
9228 E = FTy->param_end();
9232 // Add the chain's type.
9233 NewTypes.push_back(NestTy);
9238 // Add the original type.
9239 NewTypes.push_back(*I);
9245 // Replace the trampoline call with a direct call. Let the generic
9246 // code sort out any function type mismatches.
9247 FunctionType *NewFTy =
9248 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9249 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9250 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9251 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9253 Instruction *NewCaller;
9254 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9255 NewCaller = InvokeInst::Create(NewCallee,
9256 II->getNormalDest(), II->getUnwindDest(),
9257 NewArgs.begin(), NewArgs.end(),
9258 Caller->getName(), Caller);
9259 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9260 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9262 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9263 Caller->getName(), Caller);
9264 if (cast<CallInst>(Caller)->isTailCall())
9265 cast<CallInst>(NewCaller)->setTailCall();
9266 cast<CallInst>(NewCaller)->
9267 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9268 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9270 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9271 Caller->replaceAllUsesWith(NewCaller);
9272 Caller->eraseFromParent();
9273 RemoveFromWorkList(Caller);
9278 // Replace the trampoline call with a direct call. Since there is no 'nest'
9279 // parameter, there is no need to adjust the argument list. Let the generic
9280 // code sort out any function type mismatches.
9281 Constant *NewCallee =
9282 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9283 CS.setCalledFunction(NewCallee);
9284 return CS.getInstruction();
9287 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9288 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9289 /// and a single binop.
9290 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9291 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9292 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9293 isa<CmpInst>(FirstInst));
9294 unsigned Opc = FirstInst->getOpcode();
9295 Value *LHSVal = FirstInst->getOperand(0);
9296 Value *RHSVal = FirstInst->getOperand(1);
9298 const Type *LHSType = LHSVal->getType();
9299 const Type *RHSType = RHSVal->getType();
9301 // Scan to see if all operands are the same opcode, all have one use, and all
9302 // kill their operands (i.e. the operands have one use).
9303 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9304 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9305 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9306 // Verify type of the LHS matches so we don't fold cmp's of different
9307 // types or GEP's with different index types.
9308 I->getOperand(0)->getType() != LHSType ||
9309 I->getOperand(1)->getType() != RHSType)
9312 // If they are CmpInst instructions, check their predicates
9313 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9314 if (cast<CmpInst>(I)->getPredicate() !=
9315 cast<CmpInst>(FirstInst)->getPredicate())
9318 // Keep track of which operand needs a phi node.
9319 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9320 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9323 // Otherwise, this is safe to transform, determine if it is profitable.
9325 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9326 // Indexes are often folded into load/store instructions, so we don't want to
9327 // hide them behind a phi.
9328 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9331 Value *InLHS = FirstInst->getOperand(0);
9332 Value *InRHS = FirstInst->getOperand(1);
9333 PHINode *NewLHS = 0, *NewRHS = 0;
9335 NewLHS = PHINode::Create(LHSType,
9336 FirstInst->getOperand(0)->getName() + ".pn");
9337 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9338 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9339 InsertNewInstBefore(NewLHS, PN);
9344 NewRHS = PHINode::Create(RHSType,
9345 FirstInst->getOperand(1)->getName() + ".pn");
9346 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9347 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9348 InsertNewInstBefore(NewRHS, PN);
9352 // Add all operands to the new PHIs.
9353 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9355 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9356 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9359 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9360 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9364 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9365 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9366 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9367 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9370 assert(isa<GetElementPtrInst>(FirstInst));
9371 return GetElementPtrInst::Create(LHSVal, RHSVal);
9375 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9376 /// of the block that defines it. This means that it must be obvious the value
9377 /// of the load is not changed from the point of the load to the end of the
9380 /// Finally, it is safe, but not profitable, to sink a load targetting a
9381 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
9383 static bool isSafeToSinkLoad(LoadInst *L) {
9384 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9386 for (++BBI; BBI != E; ++BBI)
9387 if (BBI->mayWriteToMemory())
9390 // Check for non-address taken alloca. If not address-taken already, it isn't
9391 // profitable to do this xform.
9392 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9393 bool isAddressTaken = false;
9394 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9396 if (isa<LoadInst>(UI)) continue;
9397 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9398 // If storing TO the alloca, then the address isn't taken.
9399 if (SI->getOperand(1) == AI) continue;
9401 isAddressTaken = true;
9405 if (!isAddressTaken)
9413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9414 // operator and they all are only used by the PHI, PHI together their
9415 // inputs, and do the operation once, to the result of the PHI.
9416 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9417 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9419 // Scan the instruction, looking for input operations that can be folded away.
9420 // If all input operands to the phi are the same instruction (e.g. a cast from
9421 // the same type or "+42") we can pull the operation through the PHI, reducing
9422 // code size and simplifying code.
9423 Constant *ConstantOp = 0;
9424 const Type *CastSrcTy = 0;
9425 bool isVolatile = false;
9426 if (isa<CastInst>(FirstInst)) {
9427 CastSrcTy = FirstInst->getOperand(0)->getType();
9428 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9429 // Can fold binop, compare or shift here if the RHS is a constant,
9430 // otherwise call FoldPHIArgBinOpIntoPHI.
9431 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9432 if (ConstantOp == 0)
9433 return FoldPHIArgBinOpIntoPHI(PN);
9434 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9435 isVolatile = LI->isVolatile();
9436 // We can't sink the load if the loaded value could be modified between the
9437 // load and the PHI.
9438 if (LI->getParent() != PN.getIncomingBlock(0) ||
9439 !isSafeToSinkLoad(LI))
9442 // If the PHI is of volatile loads and the load block has multiple
9443 // successors, sinking it would remove a load of the volatile value from
9444 // the path through the other successor.
9446 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9449 } else if (isa<GetElementPtrInst>(FirstInst)) {
9450 if (FirstInst->getNumOperands() == 2)
9451 return FoldPHIArgBinOpIntoPHI(PN);
9452 // Can't handle general GEPs yet.
9455 return 0; // Cannot fold this operation.
9458 // Check to see if all arguments are the same operation.
9459 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9460 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9461 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9462 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9465 if (I->getOperand(0)->getType() != CastSrcTy)
9466 return 0; // Cast operation must match.
9467 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9468 // We can't sink the load if the loaded value could be modified between
9469 // the load and the PHI.
9470 if (LI->isVolatile() != isVolatile ||
9471 LI->getParent() != PN.getIncomingBlock(i) ||
9472 !isSafeToSinkLoad(LI))
9475 // If the PHI is of volatile loads and the load block has multiple
9476 // successors, sinking it would remove a load of the volatile value from
9477 // the path through the other successor.
9479 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9483 } else if (I->getOperand(1) != ConstantOp) {
9488 // Okay, they are all the same operation. Create a new PHI node of the
9489 // correct type, and PHI together all of the LHS's of the instructions.
9490 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9491 PN.getName()+".in");
9492 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9494 Value *InVal = FirstInst->getOperand(0);
9495 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9497 // Add all operands to the new PHI.
9498 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9499 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9500 if (NewInVal != InVal)
9502 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9507 // The new PHI unions all of the same values together. This is really
9508 // common, so we handle it intelligently here for compile-time speed.
9512 InsertNewInstBefore(NewPN, PN);
9516 // Insert and return the new operation.
9517 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9518 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9519 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9520 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9521 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9522 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
9523 PhiVal, ConstantOp);
9524 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9526 // If this was a volatile load that we are merging, make sure to loop through
9527 // and mark all the input loads as non-volatile. If we don't do this, we will
9528 // insert a new volatile load and the old ones will not be deletable.
9530 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9531 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9533 return new LoadInst(PhiVal, "", isVolatile);
9536 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9538 static bool DeadPHICycle(PHINode *PN,
9539 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9540 if (PN->use_empty()) return true;
9541 if (!PN->hasOneUse()) return false;
9543 // Remember this node, and if we find the cycle, return.
9544 if (!PotentiallyDeadPHIs.insert(PN))
9547 // Don't scan crazily complex things.
9548 if (PotentiallyDeadPHIs.size() == 16)
9551 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9552 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9557 /// PHIsEqualValue - Return true if this phi node is always equal to
9558 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9559 /// z = some value; x = phi (y, z); y = phi (x, z)
9560 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9561 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9562 // See if we already saw this PHI node.
9563 if (!ValueEqualPHIs.insert(PN))
9566 // Don't scan crazily complex things.
9567 if (ValueEqualPHIs.size() == 16)
9570 // Scan the operands to see if they are either phi nodes or are equal to
9572 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9573 Value *Op = PN->getIncomingValue(i);
9574 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9575 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9577 } else if (Op != NonPhiInVal)
9585 // PHINode simplification
9587 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9588 // If LCSSA is around, don't mess with Phi nodes
9589 if (MustPreserveLCSSA) return 0;
9591 if (Value *V = PN.hasConstantValue())
9592 return ReplaceInstUsesWith(PN, V);
9594 // If all PHI operands are the same operation, pull them through the PHI,
9595 // reducing code size.
9596 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9597 PN.getIncomingValue(0)->hasOneUse())
9598 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9601 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9602 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9603 // PHI)... break the cycle.
9604 if (PN.hasOneUse()) {
9605 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9606 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9607 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9608 PotentiallyDeadPHIs.insert(&PN);
9609 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9610 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9613 // If this phi has a single use, and if that use just computes a value for
9614 // the next iteration of a loop, delete the phi. This occurs with unused
9615 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9616 // common case here is good because the only other things that catch this
9617 // are induction variable analysis (sometimes) and ADCE, which is only run
9619 if (PHIUser->hasOneUse() &&
9620 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9621 PHIUser->use_back() == &PN) {
9622 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9626 // We sometimes end up with phi cycles that non-obviously end up being the
9627 // same value, for example:
9628 // z = some value; x = phi (y, z); y = phi (x, z)
9629 // where the phi nodes don't necessarily need to be in the same block. Do a
9630 // quick check to see if the PHI node only contains a single non-phi value, if
9631 // so, scan to see if the phi cycle is actually equal to that value.
9633 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9634 // Scan for the first non-phi operand.
9635 while (InValNo != NumOperandVals &&
9636 isa<PHINode>(PN.getIncomingValue(InValNo)))
9639 if (InValNo != NumOperandVals) {
9640 Value *NonPhiInVal = PN.getOperand(InValNo);
9642 // Scan the rest of the operands to see if there are any conflicts, if so
9643 // there is no need to recursively scan other phis.
9644 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9645 Value *OpVal = PN.getIncomingValue(InValNo);
9646 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9650 // If we scanned over all operands, then we have one unique value plus
9651 // phi values. Scan PHI nodes to see if they all merge in each other or
9653 if (InValNo == NumOperandVals) {
9654 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9655 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9656 return ReplaceInstUsesWith(PN, NonPhiInVal);
9663 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9664 Instruction *InsertPoint,
9666 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9667 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9668 // We must cast correctly to the pointer type. Ensure that we
9669 // sign extend the integer value if it is smaller as this is
9670 // used for address computation.
9671 Instruction::CastOps opcode =
9672 (VTySize < PtrSize ? Instruction::SExt :
9673 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9674 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9678 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9679 Value *PtrOp = GEP.getOperand(0);
9680 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9681 // If so, eliminate the noop.
9682 if (GEP.getNumOperands() == 1)
9683 return ReplaceInstUsesWith(GEP, PtrOp);
9685 if (isa<UndefValue>(GEP.getOperand(0)))
9686 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9688 bool HasZeroPointerIndex = false;
9689 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9690 HasZeroPointerIndex = C->isNullValue();
9692 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9693 return ReplaceInstUsesWith(GEP, PtrOp);
9695 // Eliminate unneeded casts for indices.
9696 bool MadeChange = false;
9698 gep_type_iterator GTI = gep_type_begin(GEP);
9699 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9700 i != e; ++i, ++GTI) {
9701 if (isa<SequentialType>(*GTI)) {
9702 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9703 if (CI->getOpcode() == Instruction::ZExt ||
9704 CI->getOpcode() == Instruction::SExt) {
9705 const Type *SrcTy = CI->getOperand(0)->getType();
9706 // We can eliminate a cast from i32 to i64 iff the target
9707 // is a 32-bit pointer target.
9708 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9710 *i = CI->getOperand(0);
9714 // If we are using a wider index than needed for this platform, shrink it
9715 // to what we need. If the incoming value needs a cast instruction,
9716 // insert it. This explicit cast can make subsequent optimizations more
9719 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9720 if (Constant *C = dyn_cast<Constant>(Op)) {
9721 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9724 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9732 if (MadeChange) return &GEP;
9734 // If this GEP instruction doesn't move the pointer, and if the input operand
9735 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9736 // real input to the dest type.
9737 if (GEP.hasAllZeroIndices()) {
9738 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9739 // If the bitcast is of an allocation, and the allocation will be
9740 // converted to match the type of the cast, don't touch this.
9741 if (isa<AllocationInst>(BCI->getOperand(0))) {
9742 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9743 if (Instruction *I = visitBitCast(*BCI)) {
9746 BCI->getParent()->getInstList().insert(BCI, I);
9747 ReplaceInstUsesWith(*BCI, I);
9752 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9756 // Combine Indices - If the source pointer to this getelementptr instruction
9757 // is a getelementptr instruction, combine the indices of the two
9758 // getelementptr instructions into a single instruction.
9760 SmallVector<Value*, 8> SrcGEPOperands;
9761 if (User *Src = dyn_castGetElementPtr(PtrOp))
9762 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9764 if (!SrcGEPOperands.empty()) {
9765 // Note that if our source is a gep chain itself that we wait for that
9766 // chain to be resolved before we perform this transformation. This
9767 // avoids us creating a TON of code in some cases.
9769 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9770 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9771 return 0; // Wait until our source is folded to completion.
9773 SmallVector<Value*, 8> Indices;
9775 // Find out whether the last index in the source GEP is a sequential idx.
9776 bool EndsWithSequential = false;
9777 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9778 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9779 EndsWithSequential = !isa<StructType>(*I);
9781 // Can we combine the two pointer arithmetics offsets?
9782 if (EndsWithSequential) {
9783 // Replace: gep (gep %P, long B), long A, ...
9784 // With: T = long A+B; gep %P, T, ...
9786 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9787 if (SO1 == Constant::getNullValue(SO1->getType())) {
9789 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9792 // If they aren't the same type, convert both to an integer of the
9793 // target's pointer size.
9794 if (SO1->getType() != GO1->getType()) {
9795 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9796 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9797 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9798 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9800 unsigned PS = TD->getPointerSizeInBits();
9801 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9802 // Convert GO1 to SO1's type.
9803 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9805 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9806 // Convert SO1 to GO1's type.
9807 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9809 const Type *PT = TD->getIntPtrType();
9810 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9811 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9815 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9816 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9818 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9819 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9823 // Recycle the GEP we already have if possible.
9824 if (SrcGEPOperands.size() == 2) {
9825 GEP.setOperand(0, SrcGEPOperands[0]);
9826 GEP.setOperand(1, Sum);
9829 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9830 SrcGEPOperands.end()-1);
9831 Indices.push_back(Sum);
9832 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9834 } else if (isa<Constant>(*GEP.idx_begin()) &&
9835 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9836 SrcGEPOperands.size() != 1) {
9837 // Otherwise we can do the fold if the first index of the GEP is a zero
9838 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9839 SrcGEPOperands.end());
9840 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9843 if (!Indices.empty())
9844 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9845 Indices.end(), GEP.getName());
9847 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9848 // GEP of global variable. If all of the indices for this GEP are
9849 // constants, we can promote this to a constexpr instead of an instruction.
9851 // Scan for nonconstants...
9852 SmallVector<Constant*, 8> Indices;
9853 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9854 for (; I != E && isa<Constant>(*I); ++I)
9855 Indices.push_back(cast<Constant>(*I));
9857 if (I == E) { // If they are all constants...
9858 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9859 &Indices[0],Indices.size());
9861 // Replace all uses of the GEP with the new constexpr...
9862 return ReplaceInstUsesWith(GEP, CE);
9864 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9865 if (!isa<PointerType>(X->getType())) {
9866 // Not interesting. Source pointer must be a cast from pointer.
9867 } else if (HasZeroPointerIndex) {
9868 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9869 // into : GEP [10 x i8]* X, i32 0, ...
9871 // This occurs when the program declares an array extern like "int X[];"
9873 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9874 const PointerType *XTy = cast<PointerType>(X->getType());
9875 if (const ArrayType *XATy =
9876 dyn_cast<ArrayType>(XTy->getElementType()))
9877 if (const ArrayType *CATy =
9878 dyn_cast<ArrayType>(CPTy->getElementType()))
9879 if (CATy->getElementType() == XATy->getElementType()) {
9880 // At this point, we know that the cast source type is a pointer
9881 // to an array of the same type as the destination pointer
9882 // array. Because the array type is never stepped over (there
9883 // is a leading zero) we can fold the cast into this GEP.
9884 GEP.setOperand(0, X);
9887 } else if (GEP.getNumOperands() == 2) {
9888 // Transform things like:
9889 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9890 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9891 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9892 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9893 if (isa<ArrayType>(SrcElTy) &&
9894 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9895 TD->getABITypeSize(ResElTy)) {
9897 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9898 Idx[1] = GEP.getOperand(1);
9899 Value *V = InsertNewInstBefore(
9900 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9901 // V and GEP are both pointer types --> BitCast
9902 return new BitCastInst(V, GEP.getType());
9905 // Transform things like:
9906 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9907 // (where tmp = 8*tmp2) into:
9908 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9910 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9911 uint64_t ArrayEltSize =
9912 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9914 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9915 // allow either a mul, shift, or constant here.
9917 ConstantInt *Scale = 0;
9918 if (ArrayEltSize == 1) {
9919 NewIdx = GEP.getOperand(1);
9920 Scale = ConstantInt::get(NewIdx->getType(), 1);
9921 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9922 NewIdx = ConstantInt::get(CI->getType(), 1);
9924 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9925 if (Inst->getOpcode() == Instruction::Shl &&
9926 isa<ConstantInt>(Inst->getOperand(1))) {
9927 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9928 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9929 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9930 NewIdx = Inst->getOperand(0);
9931 } else if (Inst->getOpcode() == Instruction::Mul &&
9932 isa<ConstantInt>(Inst->getOperand(1))) {
9933 Scale = cast<ConstantInt>(Inst->getOperand(1));
9934 NewIdx = Inst->getOperand(0);
9938 // If the index will be to exactly the right offset with the scale taken
9939 // out, perform the transformation. Note, we don't know whether Scale is
9940 // signed or not. We'll use unsigned version of division/modulo
9941 // operation after making sure Scale doesn't have the sign bit set.
9942 if (Scale && Scale->getSExtValue() >= 0LL &&
9943 Scale->getZExtValue() % ArrayEltSize == 0) {
9944 Scale = ConstantInt::get(Scale->getType(),
9945 Scale->getZExtValue() / ArrayEltSize);
9946 if (Scale->getZExtValue() != 1) {
9947 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9949 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9950 NewIdx = InsertNewInstBefore(Sc, GEP);
9953 // Insert the new GEP instruction.
9955 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9957 Instruction *NewGEP =
9958 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9959 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9960 // The NewGEP must be pointer typed, so must the old one -> BitCast
9961 return new BitCastInst(NewGEP, GEP.getType());
9970 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9971 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9972 if (AI.isArrayAllocation()) { // Check C != 1
9973 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9975 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9976 AllocationInst *New = 0;
9978 // Create and insert the replacement instruction...
9979 if (isa<MallocInst>(AI))
9980 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9982 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9983 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9986 InsertNewInstBefore(New, AI);
9988 // Scan to the end of the allocation instructions, to skip over a block of
9989 // allocas if possible...
9991 BasicBlock::iterator It = New;
9992 while (isa<AllocationInst>(*It)) ++It;
9994 // Now that I is pointing to the first non-allocation-inst in the block,
9995 // insert our getelementptr instruction...
9997 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10001 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10002 New->getName()+".sub", It);
10004 // Now make everything use the getelementptr instead of the original
10006 return ReplaceInstUsesWith(AI, V);
10007 } else if (isa<UndefValue>(AI.getArraySize())) {
10008 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10012 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10013 // Note that we only do this for alloca's, because malloc should allocate and
10014 // return a unique pointer, even for a zero byte allocation.
10015 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10016 TD->getABITypeSize(AI.getAllocatedType()) == 0)
10017 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10022 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10023 Value *Op = FI.getOperand(0);
10025 // free undef -> unreachable.
10026 if (isa<UndefValue>(Op)) {
10027 // Insert a new store to null because we cannot modify the CFG here.
10028 new StoreInst(ConstantInt::getTrue(),
10029 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10030 return EraseInstFromFunction(FI);
10033 // If we have 'free null' delete the instruction. This can happen in stl code
10034 // when lots of inlining happens.
10035 if (isa<ConstantPointerNull>(Op))
10036 return EraseInstFromFunction(FI);
10038 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10039 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10040 FI.setOperand(0, CI->getOperand(0));
10044 // Change free (gep X, 0,0,0,0) into free(X)
10045 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10046 if (GEPI->hasAllZeroIndices()) {
10047 AddToWorkList(GEPI);
10048 FI.setOperand(0, GEPI->getOperand(0));
10053 // Change free(malloc) into nothing, if the malloc has a single use.
10054 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10055 if (MI->hasOneUse()) {
10056 EraseInstFromFunction(FI);
10057 return EraseInstFromFunction(*MI);
10064 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10065 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10066 const TargetData *TD) {
10067 User *CI = cast<User>(LI.getOperand(0));
10068 Value *CastOp = CI->getOperand(0);
10070 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10071 // Instead of loading constant c string, use corresponding integer value
10072 // directly if string length is small enough.
10074 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10075 unsigned len = Str.length();
10076 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10077 unsigned numBits = Ty->getPrimitiveSizeInBits();
10078 // Replace LI with immediate integer store.
10079 if ((numBits >> 3) == len + 1) {
10080 APInt StrVal(numBits, 0);
10081 APInt SingleChar(numBits, 0);
10082 if (TD->isLittleEndian()) {
10083 for (signed i = len-1; i >= 0; i--) {
10084 SingleChar = (uint64_t) Str[i];
10085 StrVal = (StrVal << 8) | SingleChar;
10088 for (unsigned i = 0; i < len; i++) {
10089 SingleChar = (uint64_t) Str[i];
10090 StrVal = (StrVal << 8) | SingleChar;
10092 // Append NULL at the end.
10094 StrVal = (StrVal << 8) | SingleChar;
10096 Value *NL = ConstantInt::get(StrVal);
10097 return IC.ReplaceInstUsesWith(LI, NL);
10102 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10103 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10104 const Type *SrcPTy = SrcTy->getElementType();
10106 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10107 isa<VectorType>(DestPTy)) {
10108 // If the source is an array, the code below will not succeed. Check to
10109 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10111 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10112 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10113 if (ASrcTy->getNumElements() != 0) {
10115 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10116 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10117 SrcTy = cast<PointerType>(CastOp->getType());
10118 SrcPTy = SrcTy->getElementType();
10121 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10122 isa<VectorType>(SrcPTy)) &&
10123 // Do not allow turning this into a load of an integer, which is then
10124 // casted to a pointer, this pessimizes pointer analysis a lot.
10125 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10126 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10127 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10129 // Okay, we are casting from one integer or pointer type to another of
10130 // the same size. Instead of casting the pointer before the load, cast
10131 // the result of the loaded value.
10132 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10134 LI.isVolatile()),LI);
10135 // Now cast the result of the load.
10136 return new BitCastInst(NewLoad, LI.getType());
10143 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10144 /// from this value cannot trap. If it is not obviously safe to load from the
10145 /// specified pointer, we do a quick local scan of the basic block containing
10146 /// ScanFrom, to determine if the address is already accessed.
10147 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10148 // If it is an alloca it is always safe to load from.
10149 if (isa<AllocaInst>(V)) return true;
10151 // If it is a global variable it is mostly safe to load from.
10152 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10153 // Don't try to evaluate aliases. External weak GV can be null.
10154 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10156 // Otherwise, be a little bit agressive by scanning the local block where we
10157 // want to check to see if the pointer is already being loaded or stored
10158 // from/to. If so, the previous load or store would have already trapped,
10159 // so there is no harm doing an extra load (also, CSE will later eliminate
10160 // the load entirely).
10161 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10166 // If we see a free or a call (which might do a free) the pointer could be
10168 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10171 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10172 if (LI->getOperand(0) == V) return true;
10173 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10174 if (SI->getOperand(1) == V) return true;
10181 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10182 /// until we find the underlying object a pointer is referring to or something
10183 /// we don't understand. Note that the returned pointer may be offset from the
10184 /// input, because we ignore GEP indices.
10185 static Value *GetUnderlyingObject(Value *Ptr) {
10187 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10188 if (CE->getOpcode() == Instruction::BitCast ||
10189 CE->getOpcode() == Instruction::GetElementPtr)
10190 Ptr = CE->getOperand(0);
10193 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10194 Ptr = BCI->getOperand(0);
10195 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10196 Ptr = GEP->getOperand(0);
10203 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10204 Value *Op = LI.getOperand(0);
10206 // Attempt to improve the alignment.
10207 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10209 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10210 LI.getAlignment()))
10211 LI.setAlignment(KnownAlign);
10213 // load (cast X) --> cast (load X) iff safe
10214 if (isa<CastInst>(Op))
10215 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10218 // None of the following transforms are legal for volatile loads.
10219 if (LI.isVolatile()) return 0;
10221 if (&LI.getParent()->front() != &LI) {
10222 BasicBlock::iterator BBI = &LI; --BBI;
10223 // If the instruction immediately before this is a store to the same
10224 // address, do a simple form of store->load forwarding.
10225 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10226 if (SI->getOperand(1) == LI.getOperand(0))
10227 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10228 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10229 if (LIB->getOperand(0) == LI.getOperand(0))
10230 return ReplaceInstUsesWith(LI, LIB);
10233 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10234 const Value *GEPI0 = GEPI->getOperand(0);
10235 // TODO: Consider a target hook for valid address spaces for this xform.
10236 if (isa<ConstantPointerNull>(GEPI0) &&
10237 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10238 // Insert a new store to null instruction before the load to indicate
10239 // that this code is not reachable. We do this instead of inserting
10240 // an unreachable instruction directly because we cannot modify the
10242 new StoreInst(UndefValue::get(LI.getType()),
10243 Constant::getNullValue(Op->getType()), &LI);
10244 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10248 if (Constant *C = dyn_cast<Constant>(Op)) {
10249 // load null/undef -> undef
10250 // TODO: Consider a target hook for valid address spaces for this xform.
10251 if (isa<UndefValue>(C) || (C->isNullValue() &&
10252 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10253 // Insert a new store to null instruction before the load to indicate that
10254 // this code is not reachable. We do this instead of inserting an
10255 // unreachable instruction directly because we cannot modify the CFG.
10256 new StoreInst(UndefValue::get(LI.getType()),
10257 Constant::getNullValue(Op->getType()), &LI);
10258 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10261 // Instcombine load (constant global) into the value loaded.
10262 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10263 if (GV->isConstant() && !GV->isDeclaration())
10264 return ReplaceInstUsesWith(LI, GV->getInitializer());
10266 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10267 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10268 if (CE->getOpcode() == Instruction::GetElementPtr) {
10269 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10270 if (GV->isConstant() && !GV->isDeclaration())
10272 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10273 return ReplaceInstUsesWith(LI, V);
10274 if (CE->getOperand(0)->isNullValue()) {
10275 // Insert a new store to null instruction before the load to indicate
10276 // that this code is not reachable. We do this instead of inserting
10277 // an unreachable instruction directly because we cannot modify the
10279 new StoreInst(UndefValue::get(LI.getType()),
10280 Constant::getNullValue(Op->getType()), &LI);
10281 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10284 } else if (CE->isCast()) {
10285 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10291 // If this load comes from anywhere in a constant global, and if the global
10292 // is all undef or zero, we know what it loads.
10293 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10294 if (GV->isConstant() && GV->hasInitializer()) {
10295 if (GV->getInitializer()->isNullValue())
10296 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10297 else if (isa<UndefValue>(GV->getInitializer()))
10298 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10302 if (Op->hasOneUse()) {
10303 // Change select and PHI nodes to select values instead of addresses: this
10304 // helps alias analysis out a lot, allows many others simplifications, and
10305 // exposes redundancy in the code.
10307 // Note that we cannot do the transformation unless we know that the
10308 // introduced loads cannot trap! Something like this is valid as long as
10309 // the condition is always false: load (select bool %C, int* null, int* %G),
10310 // but it would not be valid if we transformed it to load from null
10311 // unconditionally.
10313 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10314 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10315 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10316 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10317 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10318 SI->getOperand(1)->getName()+".val"), LI);
10319 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10320 SI->getOperand(2)->getName()+".val"), LI);
10321 return SelectInst::Create(SI->getCondition(), V1, V2);
10324 // load (select (cond, null, P)) -> load P
10325 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10326 if (C->isNullValue()) {
10327 LI.setOperand(0, SI->getOperand(2));
10331 // load (select (cond, P, null)) -> load P
10332 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10333 if (C->isNullValue()) {
10334 LI.setOperand(0, SI->getOperand(1));
10342 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10344 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10345 User *CI = cast<User>(SI.getOperand(1));
10346 Value *CastOp = CI->getOperand(0);
10348 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10349 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10350 const Type *SrcPTy = SrcTy->getElementType();
10352 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10353 // If the source is an array, the code below will not succeed. Check to
10354 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10356 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10357 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10358 if (ASrcTy->getNumElements() != 0) {
10360 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10361 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10362 SrcTy = cast<PointerType>(CastOp->getType());
10363 SrcPTy = SrcTy->getElementType();
10366 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10367 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10368 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10370 // Okay, we are casting from one integer or pointer type to another of
10371 // the same size. Instead of casting the pointer before
10372 // the store, cast the value to be stored.
10374 Value *SIOp0 = SI.getOperand(0);
10375 Instruction::CastOps opcode = Instruction::BitCast;
10376 const Type* CastSrcTy = SIOp0->getType();
10377 const Type* CastDstTy = SrcPTy;
10378 if (isa<PointerType>(CastDstTy)) {
10379 if (CastSrcTy->isInteger())
10380 opcode = Instruction::IntToPtr;
10381 } else if (isa<IntegerType>(CastDstTy)) {
10382 if (isa<PointerType>(SIOp0->getType()))
10383 opcode = Instruction::PtrToInt;
10385 if (Constant *C = dyn_cast<Constant>(SIOp0))
10386 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10388 NewCast = IC.InsertNewInstBefore(
10389 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10391 return new StoreInst(NewCast, CastOp);
10398 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10399 Value *Val = SI.getOperand(0);
10400 Value *Ptr = SI.getOperand(1);
10402 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10403 EraseInstFromFunction(SI);
10408 // If the RHS is an alloca with a single use, zapify the store, making the
10410 if (Ptr->hasOneUse() && !SI.isVolatile()) {
10411 if (isa<AllocaInst>(Ptr)) {
10412 EraseInstFromFunction(SI);
10417 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10418 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10419 GEP->getOperand(0)->hasOneUse()) {
10420 EraseInstFromFunction(SI);
10426 // Attempt to improve the alignment.
10427 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10429 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10430 SI.getAlignment()))
10431 SI.setAlignment(KnownAlign);
10433 // Do really simple DSE, to catch cases where there are several consequtive
10434 // stores to the same location, separated by a few arithmetic operations. This
10435 // situation often occurs with bitfield accesses.
10436 BasicBlock::iterator BBI = &SI;
10437 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10441 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10442 // Prev store isn't volatile, and stores to the same location?
10443 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10446 EraseInstFromFunction(*PrevSI);
10452 // If this is a load, we have to stop. However, if the loaded value is from
10453 // the pointer we're loading and is producing the pointer we're storing,
10454 // then *this* store is dead (X = load P; store X -> P).
10455 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10456 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10457 EraseInstFromFunction(SI);
10461 // Otherwise, this is a load from some other location. Stores before it
10462 // may not be dead.
10466 // Don't skip over loads or things that can modify memory.
10467 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10472 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10474 // store X, null -> turns into 'unreachable' in SimplifyCFG
10475 if (isa<ConstantPointerNull>(Ptr)) {
10476 if (!isa<UndefValue>(Val)) {
10477 SI.setOperand(0, UndefValue::get(Val->getType()));
10478 if (Instruction *U = dyn_cast<Instruction>(Val))
10479 AddToWorkList(U); // Dropped a use.
10482 return 0; // Do not modify these!
10485 // store undef, Ptr -> noop
10486 if (isa<UndefValue>(Val)) {
10487 EraseInstFromFunction(SI);
10492 // If the pointer destination is a cast, see if we can fold the cast into the
10494 if (isa<CastInst>(Ptr))
10495 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10497 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10499 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10503 // If this store is the last instruction in the basic block, and if the block
10504 // ends with an unconditional branch, try to move it to the successor block.
10506 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10507 if (BI->isUnconditional())
10508 if (SimplifyStoreAtEndOfBlock(SI))
10509 return 0; // xform done!
10514 /// SimplifyStoreAtEndOfBlock - Turn things like:
10515 /// if () { *P = v1; } else { *P = v2 }
10516 /// into a phi node with a store in the successor.
10518 /// Simplify things like:
10519 /// *P = v1; if () { *P = v2; }
10520 /// into a phi node with a store in the successor.
10522 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10523 BasicBlock *StoreBB = SI.getParent();
10525 // Check to see if the successor block has exactly two incoming edges. If
10526 // so, see if the other predecessor contains a store to the same location.
10527 // if so, insert a PHI node (if needed) and move the stores down.
10528 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10530 // Determine whether Dest has exactly two predecessors and, if so, compute
10531 // the other predecessor.
10532 pred_iterator PI = pred_begin(DestBB);
10533 BasicBlock *OtherBB = 0;
10534 if (*PI != StoreBB)
10537 if (PI == pred_end(DestBB))
10540 if (*PI != StoreBB) {
10545 if (++PI != pred_end(DestBB))
10548 // Bail out if all the relevant blocks aren't distinct (this can happen,
10549 // for example, if SI is in an infinite loop)
10550 if (StoreBB == DestBB || OtherBB == DestBB)
10553 // Verify that the other block ends in a branch and is not otherwise empty.
10554 BasicBlock::iterator BBI = OtherBB->getTerminator();
10555 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10556 if (!OtherBr || BBI == OtherBB->begin())
10559 // If the other block ends in an unconditional branch, check for the 'if then
10560 // else' case. there is an instruction before the branch.
10561 StoreInst *OtherStore = 0;
10562 if (OtherBr->isUnconditional()) {
10563 // If this isn't a store, or isn't a store to the same location, bail out.
10565 OtherStore = dyn_cast<StoreInst>(BBI);
10566 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10569 // Otherwise, the other block ended with a conditional branch. If one of the
10570 // destinations is StoreBB, then we have the if/then case.
10571 if (OtherBr->getSuccessor(0) != StoreBB &&
10572 OtherBr->getSuccessor(1) != StoreBB)
10575 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10576 // if/then triangle. See if there is a store to the same ptr as SI that
10577 // lives in OtherBB.
10579 // Check to see if we find the matching store.
10580 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10581 if (OtherStore->getOperand(1) != SI.getOperand(1))
10585 // If we find something that may be using or overwriting the stored
10586 // value, or if we run out of instructions, we can't do the xform.
10587 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10588 BBI == OtherBB->begin())
10592 // In order to eliminate the store in OtherBr, we have to
10593 // make sure nothing reads or overwrites the stored value in
10595 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10596 // FIXME: This should really be AA driven.
10597 if (I->mayReadFromMemory() || I->mayWriteToMemory())
10602 // Insert a PHI node now if we need it.
10603 Value *MergedVal = OtherStore->getOperand(0);
10604 if (MergedVal != SI.getOperand(0)) {
10605 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10606 PN->reserveOperandSpace(2);
10607 PN->addIncoming(SI.getOperand(0), SI.getParent());
10608 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10609 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10612 // Advance to a place where it is safe to insert the new store and
10614 BBI = DestBB->getFirstNonPHI();
10615 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10616 OtherStore->isVolatile()), *BBI);
10618 // Nuke the old stores.
10619 EraseInstFromFunction(SI);
10620 EraseInstFromFunction(*OtherStore);
10626 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10627 // Change br (not X), label True, label False to: br X, label False, True
10629 BasicBlock *TrueDest;
10630 BasicBlock *FalseDest;
10631 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10632 !isa<Constant>(X)) {
10633 // Swap Destinations and condition...
10634 BI.setCondition(X);
10635 BI.setSuccessor(0, FalseDest);
10636 BI.setSuccessor(1, TrueDest);
10640 // Cannonicalize fcmp_one -> fcmp_oeq
10641 FCmpInst::Predicate FPred; Value *Y;
10642 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10643 TrueDest, FalseDest)))
10644 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10645 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10646 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10647 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10648 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10649 NewSCC->takeName(I);
10650 // Swap Destinations and condition...
10651 BI.setCondition(NewSCC);
10652 BI.setSuccessor(0, FalseDest);
10653 BI.setSuccessor(1, TrueDest);
10654 RemoveFromWorkList(I);
10655 I->eraseFromParent();
10656 AddToWorkList(NewSCC);
10660 // Cannonicalize icmp_ne -> icmp_eq
10661 ICmpInst::Predicate IPred;
10662 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10663 TrueDest, FalseDest)))
10664 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10665 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10666 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10667 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10668 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10669 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10670 NewSCC->takeName(I);
10671 // Swap Destinations and condition...
10672 BI.setCondition(NewSCC);
10673 BI.setSuccessor(0, FalseDest);
10674 BI.setSuccessor(1, TrueDest);
10675 RemoveFromWorkList(I);
10676 I->eraseFromParent();;
10677 AddToWorkList(NewSCC);
10684 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10685 Value *Cond = SI.getCondition();
10686 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10687 if (I->getOpcode() == Instruction::Add)
10688 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10689 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10690 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10691 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10693 SI.setOperand(0, I->getOperand(0));
10701 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10702 Value *Agg = EV.getAggregateOperand();
10704 if (!EV.hasIndices())
10705 return ReplaceInstUsesWith(EV, Agg);
10707 if (Constant *C = dyn_cast<Constant>(Agg)) {
10708 if (isa<UndefValue>(C))
10709 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
10711 if (isa<ConstantAggregateZero>(C))
10712 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
10714 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
10715 // Extract the element indexed by the first index out of the constant
10716 Value *V = C->getOperand(*EV.idx_begin());
10717 if (EV.getNumIndices() > 1)
10718 // Extract the remaining indices out of the constant indexed by the
10720 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
10722 return ReplaceInstUsesWith(EV, V);
10724 return 0; // Can't handle other constants
10726 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
10727 // We're extracting from an insertvalue instruction, compare the indices
10728 const unsigned *exti, *exte, *insi, *inse;
10729 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
10730 exte = EV.idx_end(), inse = IV->idx_end();
10731 exti != exte && insi != inse;
10733 if (*insi != *exti)
10734 // The insert and extract both reference distinctly different elements.
10735 // This means the extract is not influenced by the insert, and we can
10736 // replace the aggregate operand of the extract with the aggregate
10737 // operand of the insert. i.e., replace
10738 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10739 // %E = extractvalue { i32, { i32 } } %I, 0
10741 // %E = extractvalue { i32, { i32 } } %A, 0
10742 return ExtractValueInst::Create(IV->getAggregateOperand(),
10743 EV.idx_begin(), EV.idx_end());
10745 if (exti == exte && insi == inse)
10746 // Both iterators are at the end: Index lists are identical. Replace
10747 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10748 // %C = extractvalue { i32, { i32 } } %B, 1, 0
10750 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
10751 if (exti == exte) {
10752 // The extract list is a prefix of the insert list. i.e. replace
10753 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10754 // %E = extractvalue { i32, { i32 } } %I, 1
10756 // %X = extractvalue { i32, { i32 } } %A, 1
10757 // %E = insertvalue { i32 } %X, i32 42, 0
10758 // by switching the order of the insert and extract (though the
10759 // insertvalue should be left in, since it may have other uses).
10760 Value *NewEV = InsertNewInstBefore(
10761 ExtractValueInst::Create(IV->getAggregateOperand(),
10762 EV.idx_begin(), EV.idx_end()),
10764 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
10768 // The insert list is a prefix of the extract list
10769 // We can simply remove the common indices from the extract and make it
10770 // operate on the inserted value instead of the insertvalue result.
10772 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10773 // %E = extractvalue { i32, { i32 } } %I, 1, 0
10775 // %E extractvalue { i32 } { i32 42 }, 0
10776 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
10779 // Can't simplify extracts from other values. Note that nested extracts are
10780 // already simplified implicitely by the above (extract ( extract (insert) )
10781 // will be translated into extract ( insert ( extract ) ) first and then just
10782 // the value inserted, if appropriate).
10786 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10787 /// is to leave as a vector operation.
10788 static bool CheapToScalarize(Value *V, bool isConstant) {
10789 if (isa<ConstantAggregateZero>(V))
10791 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10792 if (isConstant) return true;
10793 // If all elts are the same, we can extract.
10794 Constant *Op0 = C->getOperand(0);
10795 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10796 if (C->getOperand(i) != Op0)
10800 Instruction *I = dyn_cast<Instruction>(V);
10801 if (!I) return false;
10803 // Insert element gets simplified to the inserted element or is deleted if
10804 // this is constant idx extract element and its a constant idx insertelt.
10805 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10806 isa<ConstantInt>(I->getOperand(2)))
10808 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10810 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10811 if (BO->hasOneUse() &&
10812 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10813 CheapToScalarize(BO->getOperand(1), isConstant)))
10815 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10816 if (CI->hasOneUse() &&
10817 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10818 CheapToScalarize(CI->getOperand(1), isConstant)))
10824 /// Read and decode a shufflevector mask.
10826 /// It turns undef elements into values that are larger than the number of
10827 /// elements in the input.
10828 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10829 unsigned NElts = SVI->getType()->getNumElements();
10830 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10831 return std::vector<unsigned>(NElts, 0);
10832 if (isa<UndefValue>(SVI->getOperand(2)))
10833 return std::vector<unsigned>(NElts, 2*NElts);
10835 std::vector<unsigned> Result;
10836 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10837 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10838 if (isa<UndefValue>(*i))
10839 Result.push_back(NElts*2); // undef -> 8
10841 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10845 /// FindScalarElement - Given a vector and an element number, see if the scalar
10846 /// value is already around as a register, for example if it were inserted then
10847 /// extracted from the vector.
10848 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10849 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10850 const VectorType *PTy = cast<VectorType>(V->getType());
10851 unsigned Width = PTy->getNumElements();
10852 if (EltNo >= Width) // Out of range access.
10853 return UndefValue::get(PTy->getElementType());
10855 if (isa<UndefValue>(V))
10856 return UndefValue::get(PTy->getElementType());
10857 else if (isa<ConstantAggregateZero>(V))
10858 return Constant::getNullValue(PTy->getElementType());
10859 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10860 return CP->getOperand(EltNo);
10861 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10862 // If this is an insert to a variable element, we don't know what it is.
10863 if (!isa<ConstantInt>(III->getOperand(2)))
10865 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10867 // If this is an insert to the element we are looking for, return the
10869 if (EltNo == IIElt)
10870 return III->getOperand(1);
10872 // Otherwise, the insertelement doesn't modify the value, recurse on its
10874 return FindScalarElement(III->getOperand(0), EltNo);
10875 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10876 unsigned InEl = getShuffleMask(SVI)[EltNo];
10878 return FindScalarElement(SVI->getOperand(0), InEl);
10879 else if (InEl < Width*2)
10880 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10882 return UndefValue::get(PTy->getElementType());
10885 // Otherwise, we don't know.
10889 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10890 // If vector val is undef, replace extract with scalar undef.
10891 if (isa<UndefValue>(EI.getOperand(0)))
10892 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10894 // If vector val is constant 0, replace extract with scalar 0.
10895 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10896 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10898 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10899 // If vector val is constant with all elements the same, replace EI with
10900 // that element. When the elements are not identical, we cannot replace yet
10901 // (we do that below, but only when the index is constant).
10902 Constant *op0 = C->getOperand(0);
10903 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10904 if (C->getOperand(i) != op0) {
10909 return ReplaceInstUsesWith(EI, op0);
10912 // If extracting a specified index from the vector, see if we can recursively
10913 // find a previously computed scalar that was inserted into the vector.
10914 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10915 unsigned IndexVal = IdxC->getZExtValue();
10916 unsigned VectorWidth =
10917 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10919 // If this is extracting an invalid index, turn this into undef, to avoid
10920 // crashing the code below.
10921 if (IndexVal >= VectorWidth)
10922 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10924 // This instruction only demands the single element from the input vector.
10925 // If the input vector has a single use, simplify it based on this use
10927 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10928 uint64_t UndefElts;
10929 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10932 EI.setOperand(0, V);
10937 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10938 return ReplaceInstUsesWith(EI, Elt);
10940 // If the this extractelement is directly using a bitcast from a vector of
10941 // the same number of elements, see if we can find the source element from
10942 // it. In this case, we will end up needing to bitcast the scalars.
10943 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10944 if (const VectorType *VT =
10945 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10946 if (VT->getNumElements() == VectorWidth)
10947 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10948 return new BitCastInst(Elt, EI.getType());
10952 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10953 if (I->hasOneUse()) {
10954 // Push extractelement into predecessor operation if legal and
10955 // profitable to do so
10956 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10957 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10958 if (CheapToScalarize(BO, isConstantElt)) {
10959 ExtractElementInst *newEI0 =
10960 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10961 EI.getName()+".lhs");
10962 ExtractElementInst *newEI1 =
10963 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10964 EI.getName()+".rhs");
10965 InsertNewInstBefore(newEI0, EI);
10966 InsertNewInstBefore(newEI1, EI);
10967 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10969 } else if (isa<LoadInst>(I)) {
10971 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10972 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10973 PointerType::get(EI.getType(), AS),EI);
10974 GetElementPtrInst *GEP =
10975 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10976 InsertNewInstBefore(GEP, EI);
10977 return new LoadInst(GEP);
10980 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10981 // Extracting the inserted element?
10982 if (IE->getOperand(2) == EI.getOperand(1))
10983 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10984 // If the inserted and extracted elements are constants, they must not
10985 // be the same value, extract from the pre-inserted value instead.
10986 if (isa<Constant>(IE->getOperand(2)) &&
10987 isa<Constant>(EI.getOperand(1))) {
10988 AddUsesToWorkList(EI);
10989 EI.setOperand(0, IE->getOperand(0));
10992 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10993 // If this is extracting an element from a shufflevector, figure out where
10994 // it came from and extract from the appropriate input element instead.
10995 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10996 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10998 if (SrcIdx < SVI->getType()->getNumElements())
10999 Src = SVI->getOperand(0);
11000 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11001 SrcIdx -= SVI->getType()->getNumElements();
11002 Src = SVI->getOperand(1);
11004 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11006 return new ExtractElementInst(Src, SrcIdx);
11013 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11014 /// elements from either LHS or RHS, return the shuffle mask and true.
11015 /// Otherwise, return false.
11016 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11017 std::vector<Constant*> &Mask) {
11018 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11019 "Invalid CollectSingleShuffleElements");
11020 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11022 if (isa<UndefValue>(V)) {
11023 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11025 } else if (V == LHS) {
11026 for (unsigned i = 0; i != NumElts; ++i)
11027 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11029 } else if (V == RHS) {
11030 for (unsigned i = 0; i != NumElts; ++i)
11031 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11033 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11034 // If this is an insert of an extract from some other vector, include it.
11035 Value *VecOp = IEI->getOperand(0);
11036 Value *ScalarOp = IEI->getOperand(1);
11037 Value *IdxOp = IEI->getOperand(2);
11039 if (!isa<ConstantInt>(IdxOp))
11041 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11043 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11044 // Okay, we can handle this if the vector we are insertinting into is
11045 // transitively ok.
11046 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11047 // If so, update the mask to reflect the inserted undef.
11048 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11051 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11052 if (isa<ConstantInt>(EI->getOperand(1)) &&
11053 EI->getOperand(0)->getType() == V->getType()) {
11054 unsigned ExtractedIdx =
11055 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11057 // This must be extracting from either LHS or RHS.
11058 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11059 // Okay, we can handle this if the vector we are insertinting into is
11060 // transitively ok.
11061 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11062 // If so, update the mask to reflect the inserted value.
11063 if (EI->getOperand(0) == LHS) {
11064 Mask[InsertedIdx % NumElts] =
11065 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11067 assert(EI->getOperand(0) == RHS);
11068 Mask[InsertedIdx % NumElts] =
11069 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11078 // TODO: Handle shufflevector here!
11083 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11084 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11085 /// that computes V and the LHS value of the shuffle.
11086 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11088 assert(isa<VectorType>(V->getType()) &&
11089 (RHS == 0 || V->getType() == RHS->getType()) &&
11090 "Invalid shuffle!");
11091 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11093 if (isa<UndefValue>(V)) {
11094 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11096 } else if (isa<ConstantAggregateZero>(V)) {
11097 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11099 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11100 // If this is an insert of an extract from some other vector, include it.
11101 Value *VecOp = IEI->getOperand(0);
11102 Value *ScalarOp = IEI->getOperand(1);
11103 Value *IdxOp = IEI->getOperand(2);
11105 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11106 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11107 EI->getOperand(0)->getType() == V->getType()) {
11108 unsigned ExtractedIdx =
11109 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11110 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11112 // Either the extracted from or inserted into vector must be RHSVec,
11113 // otherwise we'd end up with a shuffle of three inputs.
11114 if (EI->getOperand(0) == RHS || RHS == 0) {
11115 RHS = EI->getOperand(0);
11116 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11117 Mask[InsertedIdx % NumElts] =
11118 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11122 if (VecOp == RHS) {
11123 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11124 // Everything but the extracted element is replaced with the RHS.
11125 for (unsigned i = 0; i != NumElts; ++i) {
11126 if (i != InsertedIdx)
11127 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11132 // If this insertelement is a chain that comes from exactly these two
11133 // vectors, return the vector and the effective shuffle.
11134 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11135 return EI->getOperand(0);
11140 // TODO: Handle shufflevector here!
11142 // Otherwise, can't do anything fancy. Return an identity vector.
11143 for (unsigned i = 0; i != NumElts; ++i)
11144 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11148 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11149 Value *VecOp = IE.getOperand(0);
11150 Value *ScalarOp = IE.getOperand(1);
11151 Value *IdxOp = IE.getOperand(2);
11153 // Inserting an undef or into an undefined place, remove this.
11154 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11155 ReplaceInstUsesWith(IE, VecOp);
11157 // If the inserted element was extracted from some other vector, and if the
11158 // indexes are constant, try to turn this into a shufflevector operation.
11159 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11160 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11161 EI->getOperand(0)->getType() == IE.getType()) {
11162 unsigned NumVectorElts = IE.getType()->getNumElements();
11163 unsigned ExtractedIdx =
11164 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11165 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11167 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11168 return ReplaceInstUsesWith(IE, VecOp);
11170 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11171 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11173 // If we are extracting a value from a vector, then inserting it right
11174 // back into the same place, just use the input vector.
11175 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11176 return ReplaceInstUsesWith(IE, VecOp);
11178 // We could theoretically do this for ANY input. However, doing so could
11179 // turn chains of insertelement instructions into a chain of shufflevector
11180 // instructions, and right now we do not merge shufflevectors. As such,
11181 // only do this in a situation where it is clear that there is benefit.
11182 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11183 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11184 // the values of VecOp, except then one read from EIOp0.
11185 // Build a new shuffle mask.
11186 std::vector<Constant*> Mask;
11187 if (isa<UndefValue>(VecOp))
11188 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11190 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11191 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11194 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11195 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11196 ConstantVector::get(Mask));
11199 // If this insertelement isn't used by some other insertelement, turn it
11200 // (and any insertelements it points to), into one big shuffle.
11201 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11202 std::vector<Constant*> Mask;
11204 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11205 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11206 // We now have a shuffle of LHS, RHS, Mask.
11207 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11216 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11217 Value *LHS = SVI.getOperand(0);
11218 Value *RHS = SVI.getOperand(1);
11219 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11221 bool MadeChange = false;
11223 // Undefined shuffle mask -> undefined value.
11224 if (isa<UndefValue>(SVI.getOperand(2)))
11225 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11227 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11228 // the undef, change them to undefs.
11229 if (isa<UndefValue>(SVI.getOperand(1))) {
11230 // Scan to see if there are any references to the RHS. If so, replace them
11231 // with undef element refs and set MadeChange to true.
11232 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11233 if (Mask[i] >= e && Mask[i] != 2*e) {
11240 // Remap any references to RHS to use LHS.
11241 std::vector<Constant*> Elts;
11242 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11243 if (Mask[i] == 2*e)
11244 Elts.push_back(UndefValue::get(Type::Int32Ty));
11246 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11248 SVI.setOperand(2, ConstantVector::get(Elts));
11252 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11253 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11254 if (LHS == RHS || isa<UndefValue>(LHS)) {
11255 if (isa<UndefValue>(LHS) && LHS == RHS) {
11256 // shuffle(undef,undef,mask) -> undef.
11257 return ReplaceInstUsesWith(SVI, LHS);
11260 // Remap any references to RHS to use LHS.
11261 std::vector<Constant*> Elts;
11262 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11263 if (Mask[i] >= 2*e)
11264 Elts.push_back(UndefValue::get(Type::Int32Ty));
11266 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11267 (Mask[i] < e && isa<UndefValue>(LHS))) {
11268 Mask[i] = 2*e; // Turn into undef.
11269 Elts.push_back(UndefValue::get(Type::Int32Ty));
11271 Mask[i] = Mask[i] % e; // Force to LHS.
11272 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11276 SVI.setOperand(0, SVI.getOperand(1));
11277 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11278 SVI.setOperand(2, ConstantVector::get(Elts));
11279 LHS = SVI.getOperand(0);
11280 RHS = SVI.getOperand(1);
11284 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11285 bool isLHSID = true, isRHSID = true;
11287 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11288 if (Mask[i] >= e*2) continue; // Ignore undef values.
11289 // Is this an identity shuffle of the LHS value?
11290 isLHSID &= (Mask[i] == i);
11292 // Is this an identity shuffle of the RHS value?
11293 isRHSID &= (Mask[i]-e == i);
11296 // Eliminate identity shuffles.
11297 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11298 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11300 // If the LHS is a shufflevector itself, see if we can combine it with this
11301 // one without producing an unusual shuffle. Here we are really conservative:
11302 // we are absolutely afraid of producing a shuffle mask not in the input
11303 // program, because the code gen may not be smart enough to turn a merged
11304 // shuffle into two specific shuffles: it may produce worse code. As such,
11305 // we only merge two shuffles if the result is one of the two input shuffle
11306 // masks. In this case, merging the shuffles just removes one instruction,
11307 // which we know is safe. This is good for things like turning:
11308 // (splat(splat)) -> splat.
11309 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11310 if (isa<UndefValue>(RHS)) {
11311 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11313 std::vector<unsigned> NewMask;
11314 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11315 if (Mask[i] >= 2*e)
11316 NewMask.push_back(2*e);
11318 NewMask.push_back(LHSMask[Mask[i]]);
11320 // If the result mask is equal to the src shuffle or this shuffle mask, do
11321 // the replacement.
11322 if (NewMask == LHSMask || NewMask == Mask) {
11323 std::vector<Constant*> Elts;
11324 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11325 if (NewMask[i] >= e*2) {
11326 Elts.push_back(UndefValue::get(Type::Int32Ty));
11328 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11331 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11332 LHSSVI->getOperand(1),
11333 ConstantVector::get(Elts));
11338 return MadeChange ? &SVI : 0;
11344 /// TryToSinkInstruction - Try to move the specified instruction from its
11345 /// current block into the beginning of DestBlock, which can only happen if it's
11346 /// safe to move the instruction past all of the instructions between it and the
11347 /// end of its block.
11348 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11349 assert(I->hasOneUse() && "Invariants didn't hold!");
11351 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11352 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11355 // Do not sink alloca instructions out of the entry block.
11356 if (isa<AllocaInst>(I) && I->getParent() ==
11357 &DestBlock->getParent()->getEntryBlock())
11360 // We can only sink load instructions if there is nothing between the load and
11361 // the end of block that could change the value.
11362 if (I->mayReadFromMemory()) {
11363 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11365 if (Scan->mayWriteToMemory())
11369 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11371 I->moveBefore(InsertPos);
11377 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11378 /// all reachable code to the worklist.
11380 /// This has a couple of tricks to make the code faster and more powerful. In
11381 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11382 /// them to the worklist (this significantly speeds up instcombine on code where
11383 /// many instructions are dead or constant). Additionally, if we find a branch
11384 /// whose condition is a known constant, we only visit the reachable successors.
11386 static void AddReachableCodeToWorklist(BasicBlock *BB,
11387 SmallPtrSet<BasicBlock*, 64> &Visited,
11389 const TargetData *TD) {
11390 SmallVector<BasicBlock*, 256> Worklist;
11391 Worklist.push_back(BB);
11393 while (!Worklist.empty()) {
11394 BB = Worklist.back();
11395 Worklist.pop_back();
11397 // We have now visited this block! If we've already been here, ignore it.
11398 if (!Visited.insert(BB)) continue;
11400 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11401 Instruction *Inst = BBI++;
11403 // DCE instruction if trivially dead.
11404 if (isInstructionTriviallyDead(Inst)) {
11406 DOUT << "IC: DCE: " << *Inst;
11407 Inst->eraseFromParent();
11411 // ConstantProp instruction if trivially constant.
11412 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11413 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11414 Inst->replaceAllUsesWith(C);
11416 Inst->eraseFromParent();
11420 IC.AddToWorkList(Inst);
11423 // Recursively visit successors. If this is a branch or switch on a
11424 // constant, only visit the reachable successor.
11425 TerminatorInst *TI = BB->getTerminator();
11426 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11427 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11428 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11429 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11430 Worklist.push_back(ReachableBB);
11433 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11434 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11435 // See if this is an explicit destination.
11436 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11437 if (SI->getCaseValue(i) == Cond) {
11438 BasicBlock *ReachableBB = SI->getSuccessor(i);
11439 Worklist.push_back(ReachableBB);
11443 // Otherwise it is the default destination.
11444 Worklist.push_back(SI->getSuccessor(0));
11449 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11450 Worklist.push_back(TI->getSuccessor(i));
11454 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11455 bool Changed = false;
11456 TD = &getAnalysis<TargetData>();
11458 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11459 << F.getNameStr() << "\n");
11462 // Do a depth-first traversal of the function, populate the worklist with
11463 // the reachable instructions. Ignore blocks that are not reachable. Keep
11464 // track of which blocks we visit.
11465 SmallPtrSet<BasicBlock*, 64> Visited;
11466 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11468 // Do a quick scan over the function. If we find any blocks that are
11469 // unreachable, remove any instructions inside of them. This prevents
11470 // the instcombine code from having to deal with some bad special cases.
11471 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11472 if (!Visited.count(BB)) {
11473 Instruction *Term = BB->getTerminator();
11474 while (Term != BB->begin()) { // Remove instrs bottom-up
11475 BasicBlock::iterator I = Term; --I;
11477 DOUT << "IC: DCE: " << *I;
11480 if (!I->use_empty())
11481 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11482 I->eraseFromParent();
11487 while (!Worklist.empty()) {
11488 Instruction *I = RemoveOneFromWorkList();
11489 if (I == 0) continue; // skip null values.
11491 // Check to see if we can DCE the instruction.
11492 if (isInstructionTriviallyDead(I)) {
11493 // Add operands to the worklist.
11494 if (I->getNumOperands() < 4)
11495 AddUsesToWorkList(*I);
11498 DOUT << "IC: DCE: " << *I;
11500 I->eraseFromParent();
11501 RemoveFromWorkList(I);
11505 // Instruction isn't dead, see if we can constant propagate it.
11506 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11507 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11509 // Add operands to the worklist.
11510 AddUsesToWorkList(*I);
11511 ReplaceInstUsesWith(*I, C);
11514 I->eraseFromParent();
11515 RemoveFromWorkList(I);
11519 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11520 // See if we can constant fold its operands.
11521 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11522 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11523 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11529 // See if we can trivially sink this instruction to a successor basic block.
11530 if (I->hasOneUse()) {
11531 BasicBlock *BB = I->getParent();
11532 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11533 if (UserParent != BB) {
11534 bool UserIsSuccessor = false;
11535 // See if the user is one of our successors.
11536 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11537 if (*SI == UserParent) {
11538 UserIsSuccessor = true;
11542 // If the user is one of our immediate successors, and if that successor
11543 // only has us as a predecessors (we'd have to split the critical edge
11544 // otherwise), we can keep going.
11545 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11546 next(pred_begin(UserParent)) == pred_end(UserParent))
11547 // Okay, the CFG is simple enough, try to sink this instruction.
11548 Changed |= TryToSinkInstruction(I, UserParent);
11552 // Now that we have an instruction, try combining it to simplify it...
11556 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11557 if (Instruction *Result = visit(*I)) {
11559 // Should we replace the old instruction with a new one?
11561 DOUT << "IC: Old = " << *I
11562 << " New = " << *Result;
11564 // Everything uses the new instruction now.
11565 I->replaceAllUsesWith(Result);
11567 // Push the new instruction and any users onto the worklist.
11568 AddToWorkList(Result);
11569 AddUsersToWorkList(*Result);
11571 // Move the name to the new instruction first.
11572 Result->takeName(I);
11574 // Insert the new instruction into the basic block...
11575 BasicBlock *InstParent = I->getParent();
11576 BasicBlock::iterator InsertPos = I;
11578 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11579 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11582 InstParent->getInstList().insert(InsertPos, Result);
11584 // Make sure that we reprocess all operands now that we reduced their
11586 AddUsesToWorkList(*I);
11588 // Instructions can end up on the worklist more than once. Make sure
11589 // we do not process an instruction that has been deleted.
11590 RemoveFromWorkList(I);
11592 // Erase the old instruction.
11593 InstParent->getInstList().erase(I);
11596 DOUT << "IC: Mod = " << OrigI
11597 << " New = " << *I;
11600 // If the instruction was modified, it's possible that it is now dead.
11601 // if so, remove it.
11602 if (isInstructionTriviallyDead(I)) {
11603 // Make sure we process all operands now that we are reducing their
11605 AddUsesToWorkList(*I);
11607 // Instructions may end up in the worklist more than once. Erase all
11608 // occurrences of this instruction.
11609 RemoveFromWorkList(I);
11610 I->eraseFromParent();
11613 AddUsersToWorkList(*I);
11620 assert(WorklistMap.empty() && "Worklist empty, but map not?");
11622 // Do an explicit clear, this shrinks the map if needed.
11623 WorklistMap.clear();
11628 bool InstCombiner::runOnFunction(Function &F) {
11629 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11631 bool EverMadeChange = false;
11633 // Iterate while there is work to do.
11634 unsigned Iteration = 0;
11635 while (DoOneIteration(F, Iteration++))
11636 EverMadeChange = true;
11637 return EverMadeChange;
11640 FunctionPass *llvm::createInstructionCombiningPass() {
11641 return new InstCombiner();