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(&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 *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
184 Instruction *visitAnd(BinaryOperator &I);
185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
186 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
187 Value *A, Value *B, Value *C);
188 Instruction *visitOr (BinaryOperator &I);
189 Instruction *visitXor(BinaryOperator &I);
190 Instruction *visitShl(BinaryOperator &I);
191 Instruction *visitAShr(BinaryOperator &I);
192 Instruction *visitLShr(BinaryOperator &I);
193 Instruction *commonShiftTransforms(BinaryOperator &I);
194 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
196 Instruction *visitFCmpInst(FCmpInst &I);
197 Instruction *visitICmpInst(ICmpInst &I);
198 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
202 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203 ConstantInt *DivRHS);
205 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206 ICmpInst::Predicate Cond, Instruction &I);
207 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
209 Instruction *commonCastTransforms(CastInst &CI);
210 Instruction *commonIntCastTransforms(CastInst &CI);
211 Instruction *commonPointerCastTransforms(CastInst &CI);
212 Instruction *visitTrunc(TruncInst &CI);
213 Instruction *visitZExt(ZExtInst &CI);
214 Instruction *visitSExt(SExtInst &CI);
215 Instruction *visitFPTrunc(FPTruncInst &CI);
216 Instruction *visitFPExt(CastInst &CI);
217 Instruction *visitFPToUI(FPToUIInst &FI);
218 Instruction *visitFPToSI(FPToSIInst &FI);
219 Instruction *visitUIToFP(CastInst &CI);
220 Instruction *visitSIToFP(CastInst &CI);
221 Instruction *visitPtrToInt(CastInst &CI);
222 Instruction *visitIntToPtr(IntToPtrInst &CI);
223 Instruction *visitBitCast(BitCastInst &CI);
224 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
226 Instruction *visitSelectInst(SelectInst &SI);
227 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
228 Instruction *visitCallInst(CallInst &CI);
229 Instruction *visitInvokeInst(InvokeInst &II);
230 Instruction *visitPHINode(PHINode &PN);
231 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232 Instruction *visitAllocationInst(AllocationInst &AI);
233 Instruction *visitFreeInst(FreeInst &FI);
234 Instruction *visitLoadInst(LoadInst &LI);
235 Instruction *visitStoreInst(StoreInst &SI);
236 Instruction *visitBranchInst(BranchInst &BI);
237 Instruction *visitSwitchInst(SwitchInst &SI);
238 Instruction *visitInsertElementInst(InsertElementInst &IE);
239 Instruction *visitExtractElementInst(ExtractElementInst &EI);
240 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
241 Instruction *visitExtractValueInst(ExtractValueInst &EV);
243 // visitInstruction - Specify what to return for unhandled instructions...
244 Instruction *visitInstruction(Instruction &I) { return 0; }
247 Instruction *visitCallSite(CallSite CS);
248 bool transformConstExprCastCall(CallSite CS);
249 Instruction *transformCallThroughTrampoline(CallSite CS);
250 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251 bool DoXform = true);
252 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
255 // InsertNewInstBefore - insert an instruction New before instruction Old
256 // in the program. Add the new instruction to the worklist.
258 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
259 assert(New && New->getParent() == 0 &&
260 "New instruction already inserted into a basic block!");
261 BasicBlock *BB = Old.getParent();
262 BB->getInstList().insert(&Old, New); // Insert inst
267 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268 /// This also adds the cast to the worklist. Finally, this returns the
270 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
272 if (V->getType() == Ty) return V;
274 if (Constant *CV = dyn_cast<Constant>(V))
275 return ConstantExpr::getCast(opc, CV, Ty);
277 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
282 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
287 // ReplaceInstUsesWith - This method is to be used when an instruction is
288 // found to be dead, replacable with another preexisting expression. Here
289 // we add all uses of I to the worklist, replace all uses of I with the new
290 // value, then return I, so that the inst combiner will know that I was
293 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
294 AddUsersToWorkList(I); // Add all modified instrs to worklist
296 I.replaceAllUsesWith(V);
299 // If we are replacing the instruction with itself, this must be in a
300 // segment of unreachable code, so just clobber the instruction.
301 I.replaceAllUsesWith(UndefValue::get(I.getType()));
306 // UpdateValueUsesWith - This method is to be used when an value is
307 // found to be replacable with another preexisting expression or was
308 // updated. Here we add all uses of I to the worklist, replace all uses of
309 // I with the new value (unless the instruction was just updated), then
310 // return true, so that the inst combiner will know that I was modified.
312 bool UpdateValueUsesWith(Value *Old, Value *New) {
313 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
315 Old->replaceAllUsesWith(New);
316 if (Instruction *I = dyn_cast<Instruction>(Old))
318 if (Instruction *I = dyn_cast<Instruction>(New))
323 // EraseInstFromFunction - When dealing with an instruction that has side
324 // effects or produces a void value, we can't rely on DCE to delete the
325 // instruction. Instead, visit methods should return the value returned by
327 Instruction *EraseInstFromFunction(Instruction &I) {
328 assert(I.use_empty() && "Cannot erase instruction that is used!");
329 AddUsesToWorkList(I);
330 RemoveFromWorkList(&I);
332 return 0; // Don't do anything with FI
335 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
336 APInt &KnownOne, unsigned Depth = 0) const {
337 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
340 bool MaskedValueIsZero(Value *V, const APInt &Mask,
341 unsigned Depth = 0) const {
342 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
344 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
345 return llvm::ComputeNumSignBits(Op, TD, Depth);
350 /// SimplifyCommutative - This performs a few simplifications for
351 /// commutative operators.
352 bool SimplifyCommutative(BinaryOperator &I);
354 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
355 /// most-complex to least-complex order.
356 bool SimplifyCompare(CmpInst &I);
358 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
359 /// on the demanded bits.
360 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
361 APInt& KnownZero, APInt& KnownOne,
364 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
365 uint64_t &UndefElts, unsigned Depth = 0);
367 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368 // PHI node as operand #0, see if we can fold the instruction into the PHI
369 // (which is only possible if all operands to the PHI are constants).
370 Instruction *FoldOpIntoPhi(Instruction &I);
372 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373 // operator and they all are only used by the PHI, PHI together their
374 // inputs, and do the operation once, to the result of the PHI.
375 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
376 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
377 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384 bool isSub, Instruction &I);
385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386 bool isSigned, bool Inside, Instruction &IB);
387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388 Instruction *MatchBSwap(BinaryOperator &I);
389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391 Instruction *SimplifyMemSet(MemSetInst *MI);
394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
396 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397 unsigned CastOpc, int &NumCastsRemoved);
398 unsigned GetOrEnforceKnownAlignment(Value *V,
399 unsigned PrefAlign = 0);
404 char InstCombiner::ID = 0;
405 static RegisterPass<InstCombiner>
406 X("instcombine", "Combine redundant instructions");
408 // getComplexity: Assign a complexity or rank value to LLVM Values...
409 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
410 static unsigned getComplexity(Value *V) {
411 if (isa<Instruction>(V)) {
412 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
416 if (isa<Argument>(V)) return 3;
417 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
420 // isOnlyUse - Return true if this instruction will be deleted if we stop using
422 static bool isOnlyUse(Value *V) {
423 return V->hasOneUse() || isa<Constant>(V);
426 // getPromotedType - Return the specified type promoted as it would be to pass
427 // though a va_arg area...
428 static const Type *getPromotedType(const Type *Ty) {
429 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
430 if (ITy->getBitWidth() < 32)
431 return Type::Int32Ty;
436 /// getBitCastOperand - If the specified operand is a CastInst, a constant
437 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
438 /// operand value, otherwise return null.
439 static Value *getBitCastOperand(Value *V) {
440 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
442 return I->getOperand(0);
443 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
444 // GetElementPtrInst?
445 if (GEP->hasAllZeroIndices())
446 return GEP->getOperand(0);
447 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
448 if (CE->getOpcode() == Instruction::BitCast)
449 // BitCast ConstantExp?
450 return CE->getOperand(0);
451 else if (CE->getOpcode() == Instruction::GetElementPtr) {
452 // GetElementPtr ConstantExp?
453 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
455 ConstantInt *CI = dyn_cast<ConstantInt>(I);
456 if (!CI || !CI->isZero())
457 // Any non-zero indices? Not cast-like.
460 // All-zero indices? This is just like casting.
461 return CE->getOperand(0);
467 /// This function is a wrapper around CastInst::isEliminableCastPair. It
468 /// simply extracts arguments and returns what that function returns.
469 static Instruction::CastOps
470 isEliminableCastPair(
471 const CastInst *CI, ///< The first cast instruction
472 unsigned opcode, ///< The opcode of the second cast instruction
473 const Type *DstTy, ///< The target type for the second cast instruction
474 TargetData *TD ///< The target data for pointer size
477 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
478 const Type *MidTy = CI->getType(); // B from above
480 // Get the opcodes of the two Cast instructions
481 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
482 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
484 return Instruction::CastOps(
485 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
486 DstTy, TD->getIntPtrType()));
489 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490 /// in any code being generated. It does not require codegen if V is simple
491 /// enough or if the cast can be folded into other casts.
492 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
493 const Type *Ty, TargetData *TD) {
494 if (V->getType() == Ty || isa<Constant>(V)) return false;
496 // If this is another cast that can be eliminated, it isn't codegen either.
497 if (const CastInst *CI = dyn_cast<CastInst>(V))
498 if (isEliminableCastPair(CI, opcode, Ty, TD))
503 // SimplifyCommutative - This performs a few simplifications for commutative
506 // 1. Order operands such that they are listed from right (least complex) to
507 // left (most complex). This puts constants before unary operators before
510 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
513 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
514 bool Changed = false;
515 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
516 Changed = !I.swapOperands();
518 if (!I.isAssociative()) return Changed;
519 Instruction::BinaryOps Opcode = I.getOpcode();
520 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
521 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
522 if (isa<Constant>(I.getOperand(1))) {
523 Constant *Folded = ConstantExpr::get(I.getOpcode(),
524 cast<Constant>(I.getOperand(1)),
525 cast<Constant>(Op->getOperand(1)));
526 I.setOperand(0, Op->getOperand(0));
527 I.setOperand(1, Folded);
529 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
530 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
531 isOnlyUse(Op) && isOnlyUse(Op1)) {
532 Constant *C1 = cast<Constant>(Op->getOperand(1));
533 Constant *C2 = cast<Constant>(Op1->getOperand(1));
535 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
536 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
537 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
541 I.setOperand(0, New);
542 I.setOperand(1, Folded);
549 /// SimplifyCompare - For a CmpInst this function just orders the operands
550 /// so that theyare listed from right (least complex) to left (most complex).
551 /// This puts constants before unary operators before binary operators.
552 bool InstCombiner::SimplifyCompare(CmpInst &I) {
553 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
556 // Compare instructions are not associative so there's nothing else we can do.
560 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561 // if the LHS is a constant zero (which is the 'negate' form).
563 static inline Value *dyn_castNegVal(Value *V) {
564 if (BinaryOperator::isNeg(V))
565 return BinaryOperator::getNegArgument(V);
567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
569 return ConstantExpr::getNeg(C);
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
573 return ConstantExpr::getNeg(C);
578 static inline Value *dyn_castNotVal(Value *V) {
579 if (BinaryOperator::isNot(V))
580 return BinaryOperator::getNotArgument(V);
582 // Constants can be considered to be not'ed values...
583 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
584 return ConstantInt::get(~C->getValue());
588 // dyn_castFoldableMul - If this value is a multiply that can be folded into
589 // other computations (because it has a constant operand), return the
590 // non-constant operand of the multiply, and set CST to point to the multiplier.
591 // Otherwise, return null.
593 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
594 if (V->hasOneUse() && V->getType()->isInteger())
595 if (Instruction *I = dyn_cast<Instruction>(V)) {
596 if (I->getOpcode() == Instruction::Mul)
597 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
598 return I->getOperand(0);
599 if (I->getOpcode() == Instruction::Shl)
600 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
601 // The multiplier is really 1 << CST.
602 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
603 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
604 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
605 return I->getOperand(0);
611 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
612 /// expression, return it.
613 static User *dyn_castGetElementPtr(Value *V) {
614 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
615 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
616 if (CE->getOpcode() == Instruction::GetElementPtr)
617 return cast<User>(V);
621 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
622 /// opcode value. Otherwise return UserOp1.
623 static unsigned getOpcode(const Value *V) {
624 if (const Instruction *I = dyn_cast<Instruction>(V))
625 return I->getOpcode();
626 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
627 return CE->getOpcode();
628 // Use UserOp1 to mean there's no opcode.
629 return Instruction::UserOp1;
632 /// AddOne - Add one to a ConstantInt
633 static ConstantInt *AddOne(ConstantInt *C) {
634 APInt Val(C->getValue());
635 return ConstantInt::get(++Val);
637 /// SubOne - Subtract one from a ConstantInt
638 static ConstantInt *SubOne(ConstantInt *C) {
639 APInt Val(C->getValue());
640 return ConstantInt::get(--Val);
642 /// Add - Add two ConstantInts together
643 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() + C2->getValue());
646 /// And - Bitwise AND two ConstantInts together
647 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
648 return ConstantInt::get(C1->getValue() & C2->getValue());
650 /// Subtract - Subtract one ConstantInt from another
651 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
652 return ConstantInt::get(C1->getValue() - C2->getValue());
654 /// Multiply - Multiply two ConstantInts together
655 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
656 return ConstantInt::get(C1->getValue() * C2->getValue());
658 /// MultiplyOverflows - True if the multiply can not be expressed in an int
660 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
661 uint32_t W = C1->getBitWidth();
662 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
671 APInt MulExt = LHSExt * RHSExt;
674 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
675 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
676 return MulExt.slt(Min) || MulExt.sgt(Max);
678 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
682 /// ShrinkDemandedConstant - Check to see if the specified operand of the
683 /// specified instruction is a constant integer. If so, check to see if there
684 /// are any bits set in the constant that are not demanded. If so, shrink the
685 /// constant and return true.
686 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
688 assert(I && "No instruction?");
689 assert(OpNo < I->getNumOperands() && "Operand index too large");
691 // If the operand is not a constant integer, nothing to do.
692 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
693 if (!OpC) return false;
695 // If there are no bits set that aren't demanded, nothing to do.
696 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
697 if ((~Demanded & OpC->getValue()) == 0)
700 // This instruction is producing bits that are not demanded. Shrink the RHS.
701 Demanded &= OpC->getValue();
702 I->setOperand(OpNo, ConstantInt::get(Demanded));
706 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
707 // set of known zero and one bits, compute the maximum and minimum values that
708 // could have the specified known zero and known one bits, returning them in
710 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
711 const APInt& KnownZero,
712 const APInt& KnownOne,
713 APInt& Min, APInt& Max) {
714 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
715 assert(KnownZero.getBitWidth() == BitWidth &&
716 KnownOne.getBitWidth() == BitWidth &&
717 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
718 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
719 APInt UnknownBits = ~(KnownZero|KnownOne);
721 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
722 // bit if it is unknown.
724 Max = KnownOne|UnknownBits;
726 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
728 Max.clear(BitWidth-1);
732 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
733 // a set of known zero and one bits, compute the maximum and minimum values that
734 // could have the specified known zero and known one bits, returning them in
736 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
737 const APInt &KnownZero,
738 const APInt &KnownOne,
739 APInt &Min, APInt &Max) {
740 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
741 assert(KnownZero.getBitWidth() == BitWidth &&
742 KnownOne.getBitWidth() == BitWidth &&
743 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
744 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
745 APInt UnknownBits = ~(KnownZero|KnownOne);
747 // The minimum value is when the unknown bits are all zeros.
749 // The maximum value is when the unknown bits are all ones.
750 Max = KnownOne|UnknownBits;
753 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
754 /// value based on the demanded bits. When this function is called, it is known
755 /// that only the bits set in DemandedMask of the result of V are ever used
756 /// downstream. Consequently, depending on the mask and V, it may be possible
757 /// to replace V with a constant or one of its operands. In such cases, this
758 /// function does the replacement and returns true. In all other cases, it
759 /// returns false after analyzing the expression and setting KnownOne and known
760 /// to be one in the expression. KnownZero contains all the bits that are known
761 /// to be zero in the expression. These are provided to potentially allow the
762 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
763 /// the expression. KnownOne and KnownZero always follow the invariant that
764 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
765 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
766 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
767 /// and KnownOne must all be the same.
768 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
769 APInt& KnownZero, APInt& KnownOne,
771 assert(V != 0 && "Null pointer of Value???");
772 assert(Depth <= 6 && "Limit Search Depth");
773 uint32_t BitWidth = DemandedMask.getBitWidth();
774 const IntegerType *VTy = cast<IntegerType>(V->getType());
775 assert(VTy->getBitWidth() == BitWidth &&
776 KnownZero.getBitWidth() == BitWidth &&
777 KnownOne.getBitWidth() == BitWidth &&
778 "Value *V, DemandedMask, KnownZero and KnownOne \
779 must have same BitWidth");
780 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
781 // We know all of the bits for a constant!
782 KnownOne = CI->getValue() & DemandedMask;
783 KnownZero = ~KnownOne & DemandedMask;
789 if (!V->hasOneUse()) { // Other users may use these bits.
790 if (Depth != 0) { // Not at the root.
791 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
792 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
795 // If this is the root being simplified, allow it to have multiple uses,
796 // just set the DemandedMask to all bits.
797 DemandedMask = APInt::getAllOnesValue(BitWidth);
798 } else if (DemandedMask == 0) { // Not demanding any bits from V.
799 if (V != UndefValue::get(VTy))
800 return UpdateValueUsesWith(V, UndefValue::get(VTy));
802 } else if (Depth == 6) { // Limit search depth.
806 Instruction *I = dyn_cast<Instruction>(V);
807 if (!I) return false; // Only analyze instructions.
809 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
810 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
811 switch (I->getOpcode()) {
813 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
815 case Instruction::And:
816 // If either the LHS or the RHS are Zero, the result is zero.
817 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
818 RHSKnownZero, RHSKnownOne, Depth+1))
820 assert((RHSKnownZero & RHSKnownOne) == 0 &&
821 "Bits known to be one AND zero?");
823 // If something is known zero on the RHS, the bits aren't demanded on the
825 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
826 LHSKnownZero, LHSKnownOne, Depth+1))
828 assert((LHSKnownZero & LHSKnownOne) == 0 &&
829 "Bits known to be one AND zero?");
831 // If all of the demanded bits are known 1 on one side, return the other.
832 // These bits cannot contribute to the result of the 'and'.
833 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
834 (DemandedMask & ~LHSKnownZero))
835 return UpdateValueUsesWith(I, I->getOperand(0));
836 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
837 (DemandedMask & ~RHSKnownZero))
838 return UpdateValueUsesWith(I, I->getOperand(1));
840 // If all of the demanded bits in the inputs are known zeros, return zero.
841 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
842 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
844 // If the RHS is a constant, see if we can simplify it.
845 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
846 return UpdateValueUsesWith(I, I);
848 // Output known-1 bits are only known if set in both the LHS & RHS.
849 RHSKnownOne &= LHSKnownOne;
850 // Output known-0 are known to be clear if zero in either the LHS | RHS.
851 RHSKnownZero |= LHSKnownZero;
853 case Instruction::Or:
854 // If either the LHS or the RHS are One, the result is One.
855 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
856 RHSKnownZero, RHSKnownOne, Depth+1))
858 assert((RHSKnownZero & RHSKnownOne) == 0 &&
859 "Bits known to be one AND zero?");
860 // If something is known one on the RHS, the bits aren't demanded on the
862 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
863 LHSKnownZero, LHSKnownOne, Depth+1))
865 assert((LHSKnownZero & LHSKnownOne) == 0 &&
866 "Bits known to be one AND zero?");
868 // If all of the demanded bits are known zero on one side, return the other.
869 // These bits cannot contribute to the result of the 'or'.
870 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
871 (DemandedMask & ~LHSKnownOne))
872 return UpdateValueUsesWith(I, I->getOperand(0));
873 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
874 (DemandedMask & ~RHSKnownOne))
875 return UpdateValueUsesWith(I, I->getOperand(1));
877 // If all of the potentially set bits on one side are known to be set on
878 // the other side, just use the 'other' side.
879 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
880 (DemandedMask & (~RHSKnownZero)))
881 return UpdateValueUsesWith(I, I->getOperand(0));
882 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
883 (DemandedMask & (~LHSKnownZero)))
884 return UpdateValueUsesWith(I, I->getOperand(1));
886 // If the RHS is a constant, see if we can simplify it.
887 if (ShrinkDemandedConstant(I, 1, DemandedMask))
888 return UpdateValueUsesWith(I, I);
890 // Output known-0 bits are only known if clear in both the LHS & RHS.
891 RHSKnownZero &= LHSKnownZero;
892 // Output known-1 are known to be set if set in either the LHS | RHS.
893 RHSKnownOne |= LHSKnownOne;
895 case Instruction::Xor: {
896 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
897 RHSKnownZero, RHSKnownOne, Depth+1))
899 assert((RHSKnownZero & RHSKnownOne) == 0 &&
900 "Bits known to be one AND zero?");
901 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
902 LHSKnownZero, LHSKnownOne, Depth+1))
904 assert((LHSKnownZero & LHSKnownOne) == 0 &&
905 "Bits known to be one AND zero?");
907 // If all of the demanded bits are known zero on one side, return the other.
908 // These bits cannot contribute to the result of the 'xor'.
909 if ((DemandedMask & RHSKnownZero) == DemandedMask)
910 return UpdateValueUsesWith(I, I->getOperand(0));
911 if ((DemandedMask & LHSKnownZero) == DemandedMask)
912 return UpdateValueUsesWith(I, I->getOperand(1));
914 // Output known-0 bits are known if clear or set in both the LHS & RHS.
915 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
916 (RHSKnownOne & LHSKnownOne);
917 // Output known-1 are known to be set if set in only one of the LHS, RHS.
918 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
919 (RHSKnownOne & LHSKnownZero);
921 // If all of the demanded bits are known to be zero on one side or the
922 // other, turn this into an *inclusive* or.
923 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
924 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
926 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
928 InsertNewInstBefore(Or, *I);
929 return UpdateValueUsesWith(I, Or);
932 // If all of the demanded bits on one side are known, and all of the set
933 // bits on that side are also known to be set on the other side, turn this
934 // into an AND, as we know the bits will be cleared.
935 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
936 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
938 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
939 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
941 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
942 InsertNewInstBefore(And, *I);
943 return UpdateValueUsesWith(I, And);
947 // If the RHS is a constant, see if we can simplify it.
948 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
949 if (ShrinkDemandedConstant(I, 1, DemandedMask))
950 return UpdateValueUsesWith(I, I);
952 RHSKnownZero = KnownZeroOut;
953 RHSKnownOne = KnownOneOut;
956 case Instruction::Select:
957 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
958 RHSKnownZero, RHSKnownOne, Depth+1))
960 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
961 LHSKnownZero, LHSKnownOne, Depth+1))
963 assert((RHSKnownZero & RHSKnownOne) == 0 &&
964 "Bits known to be one AND zero?");
965 assert((LHSKnownZero & LHSKnownOne) == 0 &&
966 "Bits known to be one AND zero?");
968 // If the operands are constants, see if we can simplify them.
969 if (ShrinkDemandedConstant(I, 1, DemandedMask))
970 return UpdateValueUsesWith(I, I);
971 if (ShrinkDemandedConstant(I, 2, DemandedMask))
972 return UpdateValueUsesWith(I, I);
974 // Only known if known in both the LHS and RHS.
975 RHSKnownOne &= LHSKnownOne;
976 RHSKnownZero &= LHSKnownZero;
978 case Instruction::Trunc: {
980 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
981 DemandedMask.zext(truncBf);
982 RHSKnownZero.zext(truncBf);
983 RHSKnownOne.zext(truncBf);
984 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
985 RHSKnownZero, RHSKnownOne, Depth+1))
987 DemandedMask.trunc(BitWidth);
988 RHSKnownZero.trunc(BitWidth);
989 RHSKnownOne.trunc(BitWidth);
990 assert((RHSKnownZero & RHSKnownOne) == 0 &&
991 "Bits known to be one AND zero?");
994 case Instruction::BitCast:
995 if (!I->getOperand(0)->getType()->isInteger())
998 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999 RHSKnownZero, RHSKnownOne, Depth+1))
1001 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1002 "Bits known to be one AND zero?");
1004 case Instruction::ZExt: {
1005 // Compute the bits in the result that are not present in the input.
1006 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1007 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1009 DemandedMask.trunc(SrcBitWidth);
1010 RHSKnownZero.trunc(SrcBitWidth);
1011 RHSKnownOne.trunc(SrcBitWidth);
1012 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1013 RHSKnownZero, RHSKnownOne, Depth+1))
1015 DemandedMask.zext(BitWidth);
1016 RHSKnownZero.zext(BitWidth);
1017 RHSKnownOne.zext(BitWidth);
1018 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1019 "Bits known to be one AND zero?");
1020 // The top bits are known to be zero.
1021 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1024 case Instruction::SExt: {
1025 // Compute the bits in the result that are not present in the input.
1026 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1027 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1029 APInt InputDemandedBits = DemandedMask &
1030 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1032 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1033 // If any of the sign extended bits are demanded, we know that the sign
1035 if ((NewBits & DemandedMask) != 0)
1036 InputDemandedBits.set(SrcBitWidth-1);
1038 InputDemandedBits.trunc(SrcBitWidth);
1039 RHSKnownZero.trunc(SrcBitWidth);
1040 RHSKnownOne.trunc(SrcBitWidth);
1041 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1042 RHSKnownZero, RHSKnownOne, Depth+1))
1044 InputDemandedBits.zext(BitWidth);
1045 RHSKnownZero.zext(BitWidth);
1046 RHSKnownOne.zext(BitWidth);
1047 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1048 "Bits known to be one AND zero?");
1050 // If the sign bit of the input is known set or clear, then we know the
1051 // top bits of the result.
1053 // If the input sign bit is known zero, or if the NewBits are not demanded
1054 // convert this into a zero extension.
1055 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1057 // Convert to ZExt cast
1058 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1059 return UpdateValueUsesWith(I, NewCast);
1060 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1061 RHSKnownOne |= NewBits;
1065 case Instruction::Add: {
1066 // Figure out what the input bits are. If the top bits of the and result
1067 // are not demanded, then the add doesn't demand them from its input
1069 uint32_t NLZ = DemandedMask.countLeadingZeros();
1071 // If there is a constant on the RHS, there are a variety of xformations
1073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1074 // If null, this should be simplified elsewhere. Some of the xforms here
1075 // won't work if the RHS is zero.
1079 // If the top bit of the output is demanded, demand everything from the
1080 // input. Otherwise, we demand all the input bits except NLZ top bits.
1081 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1083 // Find information about known zero/one bits in the input.
1084 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1085 LHSKnownZero, LHSKnownOne, Depth+1))
1088 // If the RHS of the add has bits set that can't affect the input, reduce
1090 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1091 return UpdateValueUsesWith(I, I);
1093 // Avoid excess work.
1094 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1097 // Turn it into OR if input bits are zero.
1098 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1100 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1102 InsertNewInstBefore(Or, *I);
1103 return UpdateValueUsesWith(I, Or);
1106 // We can say something about the output known-zero and known-one bits,
1107 // depending on potential carries from the input constant and the
1108 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1109 // bits set and the RHS constant is 0x01001, then we know we have a known
1110 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1112 // To compute this, we first compute the potential carry bits. These are
1113 // the bits which may be modified. I'm not aware of a better way to do
1115 const APInt& RHSVal = RHS->getValue();
1116 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1118 // Now that we know which bits have carries, compute the known-1/0 sets.
1120 // Bits are known one if they are known zero in one operand and one in the
1121 // other, and there is no input carry.
1122 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1123 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1125 // Bits are known zero if they are known zero in both operands and there
1126 // is no input carry.
1127 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1129 // If the high-bits of this ADD are not demanded, then it does not demand
1130 // the high bits of its LHS or RHS.
1131 if (DemandedMask[BitWidth-1] == 0) {
1132 // Right fill the mask of bits for this ADD to demand the most
1133 // significant bit and all those below it.
1134 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1135 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1136 LHSKnownZero, LHSKnownOne, Depth+1))
1138 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1139 LHSKnownZero, LHSKnownOne, Depth+1))
1145 case Instruction::Sub:
1146 // If the high-bits of this SUB are not demanded, then it does not demand
1147 // the high bits of its LHS or RHS.
1148 if (DemandedMask[BitWidth-1] == 0) {
1149 // Right fill the mask of bits for this SUB to demand the most
1150 // significant bit and all those below it.
1151 uint32_t NLZ = DemandedMask.countLeadingZeros();
1152 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1153 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1154 LHSKnownZero, LHSKnownOne, Depth+1))
1156 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1157 LHSKnownZero, LHSKnownOne, Depth+1))
1160 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1161 // the known zeros and ones.
1162 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1164 case Instruction::Shl:
1165 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1166 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1167 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1168 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1169 RHSKnownZero, RHSKnownOne, Depth+1))
1171 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1172 "Bits known to be one AND zero?");
1173 RHSKnownZero <<= ShiftAmt;
1174 RHSKnownOne <<= ShiftAmt;
1175 // low bits known zero.
1177 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1180 case Instruction::LShr:
1181 // For a logical shift right
1182 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1183 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1185 // Unsigned shift right.
1186 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1187 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1188 RHSKnownZero, RHSKnownOne, Depth+1))
1190 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1191 "Bits known to be one AND zero?");
1192 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1193 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1195 // Compute the new bits that are at the top now.
1196 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1197 RHSKnownZero |= HighBits; // high bits known zero.
1201 case Instruction::AShr:
1202 // If this is an arithmetic shift right and only the low-bit is set, we can
1203 // always convert this into a logical shr, even if the shift amount is
1204 // variable. The low bit of the shift cannot be an input sign bit unless
1205 // the shift amount is >= the size of the datatype, which is undefined.
1206 if (DemandedMask == 1) {
1207 // Perform the logical shift right.
1208 Value *NewVal = BinaryOperator::CreateLShr(
1209 I->getOperand(0), I->getOperand(1), I->getName());
1210 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1211 return UpdateValueUsesWith(I, NewVal);
1214 // If the sign bit is the only bit demanded by this ashr, then there is no
1215 // need to do it, the shift doesn't change the high bit.
1216 if (DemandedMask.isSignBit())
1217 return UpdateValueUsesWith(I, I->getOperand(0));
1219 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1220 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1222 // Signed shift right.
1223 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1224 // If any of the "high bits" are demanded, we should set the sign bit as
1226 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1227 DemandedMaskIn.set(BitWidth-1);
1228 if (SimplifyDemandedBits(I->getOperand(0),
1230 RHSKnownZero, RHSKnownOne, Depth+1))
1232 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1233 "Bits known to be one AND zero?");
1234 // Compute the new bits that are at the top now.
1235 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1236 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1237 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1239 // Handle the sign bits.
1240 APInt SignBit(APInt::getSignBit(BitWidth));
1241 // Adjust to where it is now in the mask.
1242 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1244 // If the input sign bit is known to be zero, or if none of the top bits
1245 // are demanded, turn this into an unsigned shift right.
1246 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1247 (HighBits & ~DemandedMask) == HighBits) {
1248 // Perform the logical shift right.
1249 Value *NewVal = BinaryOperator::CreateLShr(
1250 I->getOperand(0), SA, I->getName());
1251 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1252 return UpdateValueUsesWith(I, NewVal);
1253 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1254 RHSKnownOne |= HighBits;
1258 case Instruction::SRem:
1259 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1260 APInt RA = Rem->getValue().abs();
1261 if (RA.isPowerOf2()) {
1262 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1263 return UpdateValueUsesWith(I, I->getOperand(0));
1265 APInt LowBits = RA - 1;
1266 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1267 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1268 LHSKnownZero, LHSKnownOne, Depth+1))
1271 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1272 LHSKnownZero |= ~LowBits;
1274 KnownZero |= LHSKnownZero & DemandedMask;
1276 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1280 case Instruction::URem: {
1281 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1282 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1283 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1284 KnownZero2, KnownOne2, Depth+1))
1287 uint32_t Leaders = KnownZero2.countLeadingOnes();
1288 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1289 KnownZero2, KnownOne2, Depth+1))
1292 Leaders = std::max(Leaders,
1293 KnownZero2.countLeadingOnes());
1294 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1297 case Instruction::Call:
1298 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1299 switch (II->getIntrinsicID()) {
1301 case Intrinsic::bswap: {
1302 // If the only bits demanded come from one byte of the bswap result,
1303 // just shift the input byte into position to eliminate the bswap.
1304 unsigned NLZ = DemandedMask.countLeadingZeros();
1305 unsigned NTZ = DemandedMask.countTrailingZeros();
1307 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1308 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1309 // have 14 leading zeros, round to 8.
1312 // If we need exactly one byte, we can do this transformation.
1313 if (BitWidth-NLZ-NTZ == 8) {
1314 unsigned ResultBit = NTZ;
1315 unsigned InputBit = BitWidth-NTZ-8;
1317 // Replace this with either a left or right shift to get the byte into
1319 Instruction *NewVal;
1320 if (InputBit > ResultBit)
1321 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1322 ConstantInt::get(I->getType(), InputBit-ResultBit));
1324 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1325 ConstantInt::get(I->getType(), ResultBit-InputBit));
1326 NewVal->takeName(I);
1327 InsertNewInstBefore(NewVal, *I);
1328 return UpdateValueUsesWith(I, NewVal);
1331 // TODO: Could compute known zero/one bits based on the input.
1336 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1340 // If the client is only demanding bits that we know, return the known
1342 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1343 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1348 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1349 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1350 /// actually used by the caller. This method analyzes which elements of the
1351 /// operand are undef and returns that information in UndefElts.
1353 /// If the information about demanded elements can be used to simplify the
1354 /// operation, the operation is simplified, then the resultant value is
1355 /// returned. This returns null if no change was made.
1356 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1357 uint64_t &UndefElts,
1359 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1360 assert(VWidth <= 64 && "Vector too wide to analyze!");
1361 uint64_t EltMask = ~0ULL >> (64-VWidth);
1362 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1364 if (isa<UndefValue>(V)) {
1365 // If the entire vector is undefined, just return this info.
1366 UndefElts = EltMask;
1368 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1369 UndefElts = EltMask;
1370 return UndefValue::get(V->getType());
1374 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1375 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1376 Constant *Undef = UndefValue::get(EltTy);
1378 std::vector<Constant*> Elts;
1379 for (unsigned i = 0; i != VWidth; ++i)
1380 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1381 Elts.push_back(Undef);
1382 UndefElts |= (1ULL << i);
1383 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1384 Elts.push_back(Undef);
1385 UndefElts |= (1ULL << i);
1386 } else { // Otherwise, defined.
1387 Elts.push_back(CP->getOperand(i));
1390 // If we changed the constant, return it.
1391 Constant *NewCP = ConstantVector::get(Elts);
1392 return NewCP != CP ? NewCP : 0;
1393 } else if (isa<ConstantAggregateZero>(V)) {
1394 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1397 // Check if this is identity. If so, return 0 since we are not simplifying
1399 if (DemandedElts == ((1ULL << VWidth) -1))
1402 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1403 Constant *Zero = Constant::getNullValue(EltTy);
1404 Constant *Undef = UndefValue::get(EltTy);
1405 std::vector<Constant*> Elts;
1406 for (unsigned i = 0; i != VWidth; ++i)
1407 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1408 UndefElts = DemandedElts ^ EltMask;
1409 return ConstantVector::get(Elts);
1412 // Limit search depth.
1416 // If multiple users are using the root value, procede with
1417 // simplification conservatively assuming that all elements
1419 if (!V->hasOneUse()) {
1420 // Quit if we find multiple users of a non-root value though.
1421 // They'll be handled when it's their turn to be visited by
1422 // the main instcombine process.
1424 // TODO: Just compute the UndefElts information recursively.
1427 // Conservatively assume that all elements are needed.
1428 DemandedElts = EltMask;
1431 Instruction *I = dyn_cast<Instruction>(V);
1432 if (!I) return false; // Only analyze instructions.
1434 bool MadeChange = false;
1435 uint64_t UndefElts2;
1437 switch (I->getOpcode()) {
1440 case Instruction::InsertElement: {
1441 // If this is a variable index, we don't know which element it overwrites.
1442 // demand exactly the same input as we produce.
1443 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1445 // Note that we can't propagate undef elt info, because we don't know
1446 // which elt is getting updated.
1447 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1448 UndefElts2, Depth+1);
1449 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1453 // If this is inserting an element that isn't demanded, remove this
1455 unsigned IdxNo = Idx->getZExtValue();
1456 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1457 return AddSoonDeadInstToWorklist(*I, 0);
1459 // Otherwise, the element inserted overwrites whatever was there, so the
1460 // input demanded set is simpler than the output set.
1461 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1462 DemandedElts & ~(1ULL << IdxNo),
1463 UndefElts, Depth+1);
1464 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1466 // The inserted element is defined.
1467 UndefElts &= ~(1ULL << IdxNo);
1470 case Instruction::ShuffleVector: {
1471 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1472 uint64_t LHSVWidth =
1473 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1474 uint64_t LeftDemanded = 0, RightDemanded = 0;
1475 for (unsigned i = 0; i < VWidth; i++) {
1476 if (DemandedElts & (1ULL << i)) {
1477 unsigned MaskVal = Shuffle->getMaskValue(i);
1478 if (MaskVal != -1u) {
1479 assert(MaskVal < LHSVWidth * 2 &&
1480 "shufflevector mask index out of range!");
1481 if (MaskVal < LHSVWidth)
1482 LeftDemanded |= 1ULL << MaskVal;
1484 RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1489 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1490 UndefElts2, Depth+1);
1491 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1493 uint64_t UndefElts3;
1494 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1495 UndefElts3, Depth+1);
1496 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1498 bool NewUndefElts = false;
1499 for (unsigned i = 0; i < VWidth; i++) {
1500 unsigned MaskVal = Shuffle->getMaskValue(i);
1501 if (MaskVal == -1u) {
1502 uint64_t NewBit = 1ULL << i;
1503 UndefElts |= NewBit;
1504 } else if (MaskVal < LHSVWidth) {
1505 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1506 NewUndefElts |= NewBit;
1507 UndefElts |= NewBit;
1509 uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1510 NewUndefElts |= NewBit;
1511 UndefElts |= NewBit;
1516 // Add additional discovered undefs.
1517 std::vector<Constant*> Elts;
1518 for (unsigned i = 0; i < VWidth; ++i) {
1519 if (UndefElts & (1ULL << i))
1520 Elts.push_back(UndefValue::get(Type::Int32Ty));
1522 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1523 Shuffle->getMaskValue(i)));
1525 I->setOperand(2, ConstantVector::get(Elts));
1530 case Instruction::BitCast: {
1531 // Vector->vector casts only.
1532 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1534 unsigned InVWidth = VTy->getNumElements();
1535 uint64_t InputDemandedElts = 0;
1538 if (VWidth == InVWidth) {
1539 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1540 // elements as are demanded of us.
1542 InputDemandedElts = DemandedElts;
1543 } else if (VWidth > InVWidth) {
1547 // If there are more elements in the result than there are in the source,
1548 // then an input element is live if any of the corresponding output
1549 // elements are live.
1550 Ratio = VWidth/InVWidth;
1551 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1552 if (DemandedElts & (1ULL << OutIdx))
1553 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1559 // If there are more elements in the source than there are in the result,
1560 // then an input element is live if the corresponding output element is
1562 Ratio = InVWidth/VWidth;
1563 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1564 if (DemandedElts & (1ULL << InIdx/Ratio))
1565 InputDemandedElts |= 1ULL << InIdx;
1568 // div/rem demand all inputs, because they don't want divide by zero.
1569 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1570 UndefElts2, Depth+1);
1572 I->setOperand(0, TmpV);
1576 UndefElts = UndefElts2;
1577 if (VWidth > InVWidth) {
1578 assert(0 && "Unimp");
1579 // If there are more elements in the result than there are in the source,
1580 // then an output element is undef if the corresponding input element is
1582 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1583 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1584 UndefElts |= 1ULL << OutIdx;
1585 } else if (VWidth < InVWidth) {
1586 assert(0 && "Unimp");
1587 // If there are more elements in the source than there are in the result,
1588 // then a result element is undef if all of the corresponding input
1589 // elements are undef.
1590 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1591 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1592 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1593 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1597 case Instruction::And:
1598 case Instruction::Or:
1599 case Instruction::Xor:
1600 case Instruction::Add:
1601 case Instruction::Sub:
1602 case Instruction::Mul:
1603 // div/rem demand all inputs, because they don't want divide by zero.
1604 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1605 UndefElts, Depth+1);
1606 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1607 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1608 UndefElts2, Depth+1);
1609 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1611 // Output elements are undefined if both are undefined. Consider things
1612 // like undef&0. The result is known zero, not undef.
1613 UndefElts &= UndefElts2;
1616 case Instruction::Call: {
1617 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1619 switch (II->getIntrinsicID()) {
1622 // Binary vector operations that work column-wise. A dest element is a
1623 // function of the corresponding input elements from the two inputs.
1624 case Intrinsic::x86_sse_sub_ss:
1625 case Intrinsic::x86_sse_mul_ss:
1626 case Intrinsic::x86_sse_min_ss:
1627 case Intrinsic::x86_sse_max_ss:
1628 case Intrinsic::x86_sse2_sub_sd:
1629 case Intrinsic::x86_sse2_mul_sd:
1630 case Intrinsic::x86_sse2_min_sd:
1631 case Intrinsic::x86_sse2_max_sd:
1632 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1633 UndefElts, Depth+1);
1634 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1635 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1636 UndefElts2, Depth+1);
1637 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1639 // If only the low elt is demanded and this is a scalarizable intrinsic,
1640 // scalarize it now.
1641 if (DemandedElts == 1) {
1642 switch (II->getIntrinsicID()) {
1644 case Intrinsic::x86_sse_sub_ss:
1645 case Intrinsic::x86_sse_mul_ss:
1646 case Intrinsic::x86_sse2_sub_sd:
1647 case Intrinsic::x86_sse2_mul_sd:
1648 // TODO: Lower MIN/MAX/ABS/etc
1649 Value *LHS = II->getOperand(1);
1650 Value *RHS = II->getOperand(2);
1651 // Extract the element as scalars.
1652 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1653 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1655 switch (II->getIntrinsicID()) {
1656 default: assert(0 && "Case stmts out of sync!");
1657 case Intrinsic::x86_sse_sub_ss:
1658 case Intrinsic::x86_sse2_sub_sd:
1659 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1660 II->getName()), *II);
1662 case Intrinsic::x86_sse_mul_ss:
1663 case Intrinsic::x86_sse2_mul_sd:
1664 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1665 II->getName()), *II);
1670 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1672 InsertNewInstBefore(New, *II);
1673 AddSoonDeadInstToWorklist(*II, 0);
1678 // Output elements are undefined if both are undefined. Consider things
1679 // like undef&0. The result is known zero, not undef.
1680 UndefElts &= UndefElts2;
1686 return MadeChange ? I : 0;
1690 /// AssociativeOpt - Perform an optimization on an associative operator. This
1691 /// function is designed to check a chain of associative operators for a
1692 /// potential to apply a certain optimization. Since the optimization may be
1693 /// applicable if the expression was reassociated, this checks the chain, then
1694 /// reassociates the expression as necessary to expose the optimization
1695 /// opportunity. This makes use of a special Functor, which must define
1696 /// 'shouldApply' and 'apply' methods.
1698 template<typename Functor>
1699 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1700 unsigned Opcode = Root.getOpcode();
1701 Value *LHS = Root.getOperand(0);
1703 // Quick check, see if the immediate LHS matches...
1704 if (F.shouldApply(LHS))
1705 return F.apply(Root);
1707 // Otherwise, if the LHS is not of the same opcode as the root, return.
1708 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1709 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1710 // Should we apply this transform to the RHS?
1711 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1713 // If not to the RHS, check to see if we should apply to the LHS...
1714 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1715 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1719 // If the functor wants to apply the optimization to the RHS of LHSI,
1720 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1722 // Now all of the instructions are in the current basic block, go ahead
1723 // and perform the reassociation.
1724 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1726 // First move the selected RHS to the LHS of the root...
1727 Root.setOperand(0, LHSI->getOperand(1));
1729 // Make what used to be the LHS of the root be the user of the root...
1730 Value *ExtraOperand = TmpLHSI->getOperand(1);
1731 if (&Root == TmpLHSI) {
1732 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1735 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1736 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1737 BasicBlock::iterator ARI = &Root; ++ARI;
1738 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1741 // Now propagate the ExtraOperand down the chain of instructions until we
1743 while (TmpLHSI != LHSI) {
1744 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1745 // Move the instruction to immediately before the chain we are
1746 // constructing to avoid breaking dominance properties.
1747 NextLHSI->moveBefore(ARI);
1750 Value *NextOp = NextLHSI->getOperand(1);
1751 NextLHSI->setOperand(1, ExtraOperand);
1753 ExtraOperand = NextOp;
1756 // Now that the instructions are reassociated, have the functor perform
1757 // the transformation...
1758 return F.apply(Root);
1761 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1768 // AddRHS - Implements: X + X --> X << 1
1771 AddRHS(Value *rhs) : RHS(rhs) {}
1772 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1773 Instruction *apply(BinaryOperator &Add) const {
1774 return BinaryOperator::CreateShl(Add.getOperand(0),
1775 ConstantInt::get(Add.getType(), 1));
1779 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1781 struct AddMaskingAnd {
1783 AddMaskingAnd(Constant *c) : C2(c) {}
1784 bool shouldApply(Value *LHS) const {
1786 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1787 ConstantExpr::getAnd(C1, C2)->isNullValue();
1789 Instruction *apply(BinaryOperator &Add) const {
1790 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1796 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1798 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1799 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1802 // Figure out if the constant is the left or the right argument.
1803 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1804 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1806 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1808 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1809 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1812 Value *Op0 = SO, *Op1 = ConstOperand;
1814 std::swap(Op0, Op1);
1816 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1817 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1818 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1819 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1820 SO->getName()+".cmp");
1822 assert(0 && "Unknown binary instruction type!");
1825 return IC->InsertNewInstBefore(New, I);
1828 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1829 // constant as the other operand, try to fold the binary operator into the
1830 // select arguments. This also works for Cast instructions, which obviously do
1831 // not have a second operand.
1832 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1834 // Don't modify shared select instructions
1835 if (!SI->hasOneUse()) return 0;
1836 Value *TV = SI->getOperand(1);
1837 Value *FV = SI->getOperand(2);
1839 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1840 // Bool selects with constant operands can be folded to logical ops.
1841 if (SI->getType() == Type::Int1Ty) return 0;
1843 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1844 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1846 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1853 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1854 /// node as operand #0, see if we can fold the instruction into the PHI (which
1855 /// is only possible if all operands to the PHI are constants).
1856 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1857 PHINode *PN = cast<PHINode>(I.getOperand(0));
1858 unsigned NumPHIValues = PN->getNumIncomingValues();
1859 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1861 // Check to see if all of the operands of the PHI are constants. If there is
1862 // one non-constant value, remember the BB it is. If there is more than one
1863 // or if *it* is a PHI, bail out.
1864 BasicBlock *NonConstBB = 0;
1865 for (unsigned i = 0; i != NumPHIValues; ++i)
1866 if (!isa<Constant>(PN->getIncomingValue(i))) {
1867 if (NonConstBB) return 0; // More than one non-const value.
1868 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1869 NonConstBB = PN->getIncomingBlock(i);
1871 // If the incoming non-constant value is in I's block, we have an infinite
1873 if (NonConstBB == I.getParent())
1877 // If there is exactly one non-constant value, we can insert a copy of the
1878 // operation in that block. However, if this is a critical edge, we would be
1879 // inserting the computation one some other paths (e.g. inside a loop). Only
1880 // do this if the pred block is unconditionally branching into the phi block.
1882 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1883 if (!BI || !BI->isUnconditional()) return 0;
1886 // Okay, we can do the transformation: create the new PHI node.
1887 PHINode *NewPN = PHINode::Create(I.getType(), "");
1888 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1889 InsertNewInstBefore(NewPN, *PN);
1890 NewPN->takeName(PN);
1892 // Next, add all of the operands to the PHI.
1893 if (I.getNumOperands() == 2) {
1894 Constant *C = cast<Constant>(I.getOperand(1));
1895 for (unsigned i = 0; i != NumPHIValues; ++i) {
1897 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1898 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1899 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1901 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1903 assert(PN->getIncomingBlock(i) == NonConstBB);
1904 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1905 InV = BinaryOperator::Create(BO->getOpcode(),
1906 PN->getIncomingValue(i), C, "phitmp",
1907 NonConstBB->getTerminator());
1908 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1909 InV = CmpInst::Create(CI->getOpcode(),
1911 PN->getIncomingValue(i), C, "phitmp",
1912 NonConstBB->getTerminator());
1914 assert(0 && "Unknown binop!");
1916 AddToWorkList(cast<Instruction>(InV));
1918 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1921 CastInst *CI = cast<CastInst>(&I);
1922 const Type *RetTy = CI->getType();
1923 for (unsigned i = 0; i != NumPHIValues; ++i) {
1925 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1926 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1928 assert(PN->getIncomingBlock(i) == NonConstBB);
1929 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
1930 I.getType(), "phitmp",
1931 NonConstBB->getTerminator());
1932 AddToWorkList(cast<Instruction>(InV));
1934 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1937 return ReplaceInstUsesWith(I, NewPN);
1941 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1942 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1943 /// This basically requires proving that the add in the original type would not
1944 /// overflow to change the sign bit or have a carry out.
1945 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1946 // There are different heuristics we can use for this. Here are some simple
1949 // Add has the property that adding any two 2's complement numbers can only
1950 // have one carry bit which can change a sign. As such, if LHS and RHS each
1951 // have at least two sign bits, we know that the addition of the two values will
1952 // sign extend fine.
1953 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1957 // If one of the operands only has one non-zero bit, and if the other operand
1958 // has a known-zero bit in a more significant place than it (not including the
1959 // sign bit) the ripple may go up to and fill the zero, but won't change the
1960 // sign. For example, (X & ~4) + 1.
1968 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1969 bool Changed = SimplifyCommutative(I);
1970 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1972 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1973 // X + undef -> undef
1974 if (isa<UndefValue>(RHS))
1975 return ReplaceInstUsesWith(I, RHS);
1978 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1979 if (RHSC->isNullValue())
1980 return ReplaceInstUsesWith(I, LHS);
1981 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1982 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1983 (I.getType())->getValueAPF()))
1984 return ReplaceInstUsesWith(I, LHS);
1987 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1988 // X + (signbit) --> X ^ signbit
1989 const APInt& Val = CI->getValue();
1990 uint32_t BitWidth = Val.getBitWidth();
1991 if (Val == APInt::getSignBit(BitWidth))
1992 return BinaryOperator::CreateXor(LHS, RHS);
1994 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1995 // (X & 254)+1 -> (X&254)|1
1996 if (!isa<VectorType>(I.getType())) {
1997 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1998 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1999 KnownZero, KnownOne))
2003 // zext(i1) - 1 -> select i1, 0, -1
2004 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2005 if (CI->isAllOnesValue() &&
2006 ZI->getOperand(0)->getType() == Type::Int1Ty)
2007 return SelectInst::Create(ZI->getOperand(0),
2008 Constant::getNullValue(I.getType()),
2009 ConstantInt::getAllOnesValue(I.getType()));
2012 if (isa<PHINode>(LHS))
2013 if (Instruction *NV = FoldOpIntoPhi(I))
2016 ConstantInt *XorRHS = 0;
2018 if (isa<ConstantInt>(RHSC) &&
2019 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2020 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2021 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2023 uint32_t Size = TySizeBits / 2;
2024 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2025 APInt CFF80Val(-C0080Val);
2027 if (TySizeBits > Size) {
2028 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2029 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2030 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2031 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2032 // This is a sign extend if the top bits are known zero.
2033 if (!MaskedValueIsZero(XorLHS,
2034 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2035 Size = 0; // Not a sign ext, but can't be any others either.
2040 C0080Val = APIntOps::lshr(C0080Val, Size);
2041 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2042 } while (Size >= 1);
2044 // FIXME: This shouldn't be necessary. When the backends can handle types
2045 // with funny bit widths then this switch statement should be removed. It
2046 // is just here to get the size of the "middle" type back up to something
2047 // that the back ends can handle.
2048 const Type *MiddleType = 0;
2051 case 32: MiddleType = Type::Int32Ty; break;
2052 case 16: MiddleType = Type::Int16Ty; break;
2053 case 8: MiddleType = Type::Int8Ty; break;
2056 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2057 InsertNewInstBefore(NewTrunc, I);
2058 return new SExtInst(NewTrunc, I.getType(), I.getName());
2063 if (I.getType() == Type::Int1Ty)
2064 return BinaryOperator::CreateXor(LHS, RHS);
2067 if (I.getType()->isInteger()) {
2068 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2070 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2071 if (RHSI->getOpcode() == Instruction::Sub)
2072 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2073 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2075 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2076 if (LHSI->getOpcode() == Instruction::Sub)
2077 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2078 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2083 // -A + -B --> -(A + B)
2084 if (Value *LHSV = dyn_castNegVal(LHS)) {
2085 if (LHS->getType()->isIntOrIntVector()) {
2086 if (Value *RHSV = dyn_castNegVal(RHS)) {
2087 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2088 InsertNewInstBefore(NewAdd, I);
2089 return BinaryOperator::CreateNeg(NewAdd);
2093 return BinaryOperator::CreateSub(RHS, LHSV);
2097 if (!isa<Constant>(RHS))
2098 if (Value *V = dyn_castNegVal(RHS))
2099 return BinaryOperator::CreateSub(LHS, V);
2103 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2104 if (X == RHS) // X*C + X --> X * (C+1)
2105 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2107 // X*C1 + X*C2 --> X * (C1+C2)
2109 if (X == dyn_castFoldableMul(RHS, C1))
2110 return BinaryOperator::CreateMul(X, Add(C1, C2));
2113 // X + X*C --> X * (C+1)
2114 if (dyn_castFoldableMul(RHS, C2) == LHS)
2115 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2117 // X + ~X --> -1 since ~X = -X-1
2118 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2119 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2122 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2123 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2124 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2127 // A+B --> A|B iff A and B have no bits set in common.
2128 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2129 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2130 APInt LHSKnownOne(IT->getBitWidth(), 0);
2131 APInt LHSKnownZero(IT->getBitWidth(), 0);
2132 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2133 if (LHSKnownZero != 0) {
2134 APInt RHSKnownOne(IT->getBitWidth(), 0);
2135 APInt RHSKnownZero(IT->getBitWidth(), 0);
2136 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2138 // No bits in common -> bitwise or.
2139 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2140 return BinaryOperator::CreateOr(LHS, RHS);
2144 // W*X + Y*Z --> W * (X+Z) iff W == Y
2145 if (I.getType()->isIntOrIntVector()) {
2146 Value *W, *X, *Y, *Z;
2147 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2148 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2152 } else if (Y == X) {
2154 } else if (X == Z) {
2161 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2162 LHS->getName()), I);
2163 return BinaryOperator::CreateMul(W, NewAdd);
2168 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2170 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2171 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2173 // (X & FF00) + xx00 -> (X+xx00) & FF00
2174 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2175 Constant *Anded = And(CRHS, C2);
2176 if (Anded == CRHS) {
2177 // See if all bits from the first bit set in the Add RHS up are included
2178 // in the mask. First, get the rightmost bit.
2179 const APInt& AddRHSV = CRHS->getValue();
2181 // Form a mask of all bits from the lowest bit added through the top.
2182 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2184 // See if the and mask includes all of these bits.
2185 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2187 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2188 // Okay, the xform is safe. Insert the new add pronto.
2189 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2190 LHS->getName()), I);
2191 return BinaryOperator::CreateAnd(NewAdd, C2);
2196 // Try to fold constant add into select arguments.
2197 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2198 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2202 // add (cast *A to intptrtype) B ->
2203 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
2205 CastInst *CI = dyn_cast<CastInst>(LHS);
2208 CI = dyn_cast<CastInst>(RHS);
2211 if (CI && CI->getType()->isSized() &&
2212 (CI->getType()->getPrimitiveSizeInBits() ==
2213 TD->getIntPtrType()->getPrimitiveSizeInBits())
2214 && isa<PointerType>(CI->getOperand(0)->getType())) {
2216 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2217 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2218 PointerType::get(Type::Int8Ty, AS), I);
2219 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2220 return new PtrToIntInst(I2, CI->getType());
2224 // add (select X 0 (sub n A)) A --> select X A n
2226 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2229 SI = dyn_cast<SelectInst>(RHS);
2232 if (SI && SI->hasOneUse()) {
2233 Value *TV = SI->getTrueValue();
2234 Value *FV = SI->getFalseValue();
2237 // Can we fold the add into the argument of the select?
2238 // We check both true and false select arguments for a matching subtract.
2239 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2240 // Fold the add into the true select value.
2241 return SelectInst::Create(SI->getCondition(), N, A);
2242 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2243 // Fold the add into the false select value.
2244 return SelectInst::Create(SI->getCondition(), A, N);
2248 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2249 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2250 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2251 return ReplaceInstUsesWith(I, LHS);
2253 // Check for (add (sext x), y), see if we can merge this into an
2254 // integer add followed by a sext.
2255 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2256 // (add (sext x), cst) --> (sext (add x, cst'))
2257 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2259 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2260 if (LHSConv->hasOneUse() &&
2261 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2262 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2263 // Insert the new, smaller add.
2264 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2266 InsertNewInstBefore(NewAdd, I);
2267 return new SExtInst(NewAdd, I.getType());
2271 // (add (sext x), (sext y)) --> (sext (add int x, y))
2272 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2273 // Only do this if x/y have the same type, if at last one of them has a
2274 // single use (so we don't increase the number of sexts), and if the
2275 // integer add will not overflow.
2276 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2277 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2278 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2279 RHSConv->getOperand(0))) {
2280 // Insert the new integer add.
2281 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2282 RHSConv->getOperand(0),
2284 InsertNewInstBefore(NewAdd, I);
2285 return new SExtInst(NewAdd, I.getType());
2290 // Check for (add double (sitofp x), y), see if we can merge this into an
2291 // integer add followed by a promotion.
2292 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2293 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2294 // ... if the constant fits in the integer value. This is useful for things
2295 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2296 // requires a constant pool load, and generally allows the add to be better
2298 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2300 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2301 if (LHSConv->hasOneUse() &&
2302 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2303 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2304 // Insert the new integer add.
2305 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2307 InsertNewInstBefore(NewAdd, I);
2308 return new SIToFPInst(NewAdd, I.getType());
2312 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2313 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2314 // Only do this if x/y have the same type, if at last one of them has a
2315 // single use (so we don't increase the number of int->fp conversions),
2316 // and if the integer add will not overflow.
2317 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2318 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2319 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2320 RHSConv->getOperand(0))) {
2321 // Insert the new integer add.
2322 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2323 RHSConv->getOperand(0),
2325 InsertNewInstBefore(NewAdd, I);
2326 return new SIToFPInst(NewAdd, I.getType());
2331 return Changed ? &I : 0;
2334 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2337 if (Op0 == Op1 && // sub X, X -> 0
2338 !I.getType()->isFPOrFPVector())
2339 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2341 // If this is a 'B = x-(-A)', change to B = x+A...
2342 if (Value *V = dyn_castNegVal(Op1))
2343 return BinaryOperator::CreateAdd(Op0, V);
2345 if (isa<UndefValue>(Op0))
2346 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2347 if (isa<UndefValue>(Op1))
2348 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2350 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2351 // Replace (-1 - A) with (~A)...
2352 if (C->isAllOnesValue())
2353 return BinaryOperator::CreateNot(Op1);
2355 // C - ~X == X + (1+C)
2357 if (match(Op1, m_Not(m_Value(X))))
2358 return BinaryOperator::CreateAdd(X, AddOne(C));
2360 // -(X >>u 31) -> (X >>s 31)
2361 // -(X >>s 31) -> (X >>u 31)
2363 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2364 if (SI->getOpcode() == Instruction::LShr) {
2365 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2366 // Check to see if we are shifting out everything but the sign bit.
2367 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2368 SI->getType()->getPrimitiveSizeInBits()-1) {
2369 // Ok, the transformation is safe. Insert AShr.
2370 return BinaryOperator::Create(Instruction::AShr,
2371 SI->getOperand(0), CU, SI->getName());
2375 else if (SI->getOpcode() == Instruction::AShr) {
2376 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2377 // Check to see if we are shifting out everything but the sign bit.
2378 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2379 SI->getType()->getPrimitiveSizeInBits()-1) {
2380 // Ok, the transformation is safe. Insert LShr.
2381 return BinaryOperator::CreateLShr(
2382 SI->getOperand(0), CU, SI->getName());
2389 // Try to fold constant sub into select arguments.
2390 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2391 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2395 if (I.getType() == Type::Int1Ty)
2396 return BinaryOperator::CreateXor(Op0, Op1);
2398 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2399 if (Op1I->getOpcode() == Instruction::Add &&
2400 !Op0->getType()->isFPOrFPVector()) {
2401 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2402 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2403 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2404 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2405 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2406 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2407 // C1-(X+C2) --> (C1-C2)-X
2408 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
2409 Op1I->getOperand(0));
2413 if (Op1I->hasOneUse()) {
2414 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2415 // is not used by anyone else...
2417 if (Op1I->getOpcode() == Instruction::Sub &&
2418 !Op1I->getType()->isFPOrFPVector()) {
2419 // Swap the two operands of the subexpr...
2420 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2421 Op1I->setOperand(0, IIOp1);
2422 Op1I->setOperand(1, IIOp0);
2424 // Create the new top level add instruction...
2425 return BinaryOperator::CreateAdd(Op0, Op1);
2428 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2430 if (Op1I->getOpcode() == Instruction::And &&
2431 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2432 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2435 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2436 return BinaryOperator::CreateAnd(Op0, NewNot);
2439 // 0 - (X sdiv C) -> (X sdiv -C)
2440 if (Op1I->getOpcode() == Instruction::SDiv)
2441 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2443 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2444 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2445 ConstantExpr::getNeg(DivRHS));
2447 // X - X*C --> X * (1-C)
2448 ConstantInt *C2 = 0;
2449 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2450 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2451 return BinaryOperator::CreateMul(Op0, CP1);
2456 if (!Op0->getType()->isFPOrFPVector())
2457 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2458 if (Op0I->getOpcode() == Instruction::Add) {
2459 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2460 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2461 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2462 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2463 } else if (Op0I->getOpcode() == Instruction::Sub) {
2464 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2465 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2470 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2471 if (X == Op1) // X*C - X --> X * (C-1)
2472 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2474 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2475 if (X == dyn_castFoldableMul(Op1, C2))
2476 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2481 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2482 /// comparison only checks the sign bit. If it only checks the sign bit, set
2483 /// TrueIfSigned if the result of the comparison is true when the input value is
2485 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2486 bool &TrueIfSigned) {
2488 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2489 TrueIfSigned = true;
2490 return RHS->isZero();
2491 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2492 TrueIfSigned = true;
2493 return RHS->isAllOnesValue();
2494 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2495 TrueIfSigned = false;
2496 return RHS->isAllOnesValue();
2497 case ICmpInst::ICMP_UGT:
2498 // True if LHS u> RHS and RHS == high-bit-mask - 1
2499 TrueIfSigned = true;
2500 return RHS->getValue() ==
2501 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2502 case ICmpInst::ICMP_UGE:
2503 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2504 TrueIfSigned = true;
2505 return RHS->getValue().isSignBit();
2511 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2512 bool Changed = SimplifyCommutative(I);
2513 Value *Op0 = I.getOperand(0);
2515 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2516 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2518 // Simplify mul instructions with a constant RHS...
2519 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2520 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2522 // ((X << C1)*C2) == (X * (C2 << C1))
2523 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2524 if (SI->getOpcode() == Instruction::Shl)
2525 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2526 return BinaryOperator::CreateMul(SI->getOperand(0),
2527 ConstantExpr::getShl(CI, ShOp));
2530 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2531 if (CI->equalsInt(1)) // X * 1 == X
2532 return ReplaceInstUsesWith(I, Op0);
2533 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2534 return BinaryOperator::CreateNeg(Op0, I.getName());
2536 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2537 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2538 return BinaryOperator::CreateShl(Op0,
2539 ConstantInt::get(Op0->getType(), Val.logBase2()));
2541 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2542 if (Op1F->isNullValue())
2543 return ReplaceInstUsesWith(I, Op1);
2545 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2546 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2547 if (Op1F->isExactlyValue(1.0))
2548 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2549 } else if (isa<VectorType>(Op1->getType())) {
2550 if (isa<ConstantAggregateZero>(Op1))
2551 return ReplaceInstUsesWith(I, Op1);
2553 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2554 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2555 return BinaryOperator::CreateNeg(Op0, I.getName());
2557 // As above, vector X*splat(1.0) -> X in all defined cases.
2558 if (Constant *Splat = Op1V->getSplatValue()) {
2559 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2560 if (F->isExactlyValue(1.0))
2561 return ReplaceInstUsesWith(I, Op0);
2562 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2563 if (CI->equalsInt(1))
2564 return ReplaceInstUsesWith(I, Op0);
2569 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2570 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2571 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2572 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2573 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2575 InsertNewInstBefore(Add, I);
2576 Value *C1C2 = ConstantExpr::getMul(Op1,
2577 cast<Constant>(Op0I->getOperand(1)));
2578 return BinaryOperator::CreateAdd(Add, C1C2);
2582 // Try to fold constant mul into select arguments.
2583 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2584 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2587 if (isa<PHINode>(Op0))
2588 if (Instruction *NV = FoldOpIntoPhi(I))
2592 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2593 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2594 return BinaryOperator::CreateMul(Op0v, Op1v);
2596 // (X / Y) * Y = X - (X % Y)
2597 // (X / Y) * -Y = (X % Y) - X
2599 Value *Op1 = I.getOperand(1);
2600 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2602 (BO->getOpcode() != Instruction::UDiv &&
2603 BO->getOpcode() != Instruction::SDiv)) {
2605 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2607 Value *Neg = dyn_castNegVal(Op1);
2608 if (BO && BO->hasOneUse() &&
2609 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2610 (BO->getOpcode() == Instruction::UDiv ||
2611 BO->getOpcode() == Instruction::SDiv)) {
2612 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2615 if (BO->getOpcode() == Instruction::UDiv)
2616 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2618 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2620 InsertNewInstBefore(Rem, I);
2624 return BinaryOperator::CreateSub(Op0BO, Rem);
2626 return BinaryOperator::CreateSub(Rem, Op0BO);
2630 if (I.getType() == Type::Int1Ty)
2631 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2633 // If one of the operands of the multiply is a cast from a boolean value, then
2634 // we know the bool is either zero or one, so this is a 'masking' multiply.
2635 // See if we can simplify things based on how the boolean was originally
2637 CastInst *BoolCast = 0;
2638 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2639 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2642 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2643 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2646 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2647 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2648 const Type *SCOpTy = SCIOp0->getType();
2651 // If the icmp is true iff the sign bit of X is set, then convert this
2652 // multiply into a shift/and combination.
2653 if (isa<ConstantInt>(SCIOp1) &&
2654 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2656 // Shift the X value right to turn it into "all signbits".
2657 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2658 SCOpTy->getPrimitiveSizeInBits()-1);
2660 InsertNewInstBefore(
2661 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2662 BoolCast->getOperand(0)->getName()+
2665 // If the multiply type is not the same as the source type, sign extend
2666 // or truncate to the multiply type.
2667 if (I.getType() != V->getType()) {
2668 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2669 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2670 Instruction::CastOps opcode =
2671 (SrcBits == DstBits ? Instruction::BitCast :
2672 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2673 V = InsertCastBefore(opcode, V, I.getType(), I);
2676 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2677 return BinaryOperator::CreateAnd(V, OtherOp);
2682 return Changed ? &I : 0;
2685 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2687 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2688 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2690 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2691 int NonNullOperand = -1;
2692 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2693 if (ST->isNullValue())
2695 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2696 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2697 if (ST->isNullValue())
2700 if (NonNullOperand == -1)
2703 Value *SelectCond = SI->getOperand(0);
2705 // Change the div/rem to use 'Y' instead of the select.
2706 I.setOperand(1, SI->getOperand(NonNullOperand));
2708 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2709 // problem. However, the select, or the condition of the select may have
2710 // multiple uses. Based on our knowledge that the operand must be non-zero,
2711 // propagate the known value for the select into other uses of it, and
2712 // propagate a known value of the condition into its other users.
2714 // If the select and condition only have a single use, don't bother with this,
2716 if (SI->use_empty() && SelectCond->hasOneUse())
2719 // Scan the current block backward, looking for other uses of SI.
2720 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2722 while (BBI != BBFront) {
2724 // If we found a call to a function, we can't assume it will return, so
2725 // information from below it cannot be propagated above it.
2726 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2729 // Replace uses of the select or its condition with the known values.
2730 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2733 *I = SI->getOperand(NonNullOperand);
2735 } else if (*I == SelectCond) {
2736 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2737 ConstantInt::getFalse();
2742 // If we past the instruction, quit looking for it.
2745 if (&*BBI == SelectCond)
2748 // If we ran out of things to eliminate, break out of the loop.
2749 if (SelectCond == 0 && SI == 0)
2757 /// This function implements the transforms on div instructions that work
2758 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2759 /// used by the visitors to those instructions.
2760 /// @brief Transforms common to all three div instructions
2761 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2762 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2764 // undef / X -> 0 for integer.
2765 // undef / X -> undef for FP (the undef could be a snan).
2766 if (isa<UndefValue>(Op0)) {
2767 if (Op0->getType()->isFPOrFPVector())
2768 return ReplaceInstUsesWith(I, Op0);
2769 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2772 // X / undef -> undef
2773 if (isa<UndefValue>(Op1))
2774 return ReplaceInstUsesWith(I, Op1);
2779 /// This function implements the transforms common to both integer division
2780 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2781 /// division instructions.
2782 /// @brief Common integer divide transforms
2783 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2786 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2788 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2789 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2790 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2791 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2794 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2795 return ReplaceInstUsesWith(I, CI);
2798 if (Instruction *Common = commonDivTransforms(I))
2801 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2802 // This does not apply for fdiv.
2803 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2806 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2808 if (RHS->equalsInt(1))
2809 return ReplaceInstUsesWith(I, Op0);
2811 // (X / C1) / C2 -> X / (C1*C2)
2812 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2813 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2814 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2815 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2816 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2818 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2819 Multiply(RHS, LHSRHS));
2822 if (!RHS->isZero()) { // avoid X udiv 0
2823 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2824 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2826 if (isa<PHINode>(Op0))
2827 if (Instruction *NV = FoldOpIntoPhi(I))
2832 // 0 / X == 0, we don't need to preserve faults!
2833 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2834 if (LHS->equalsInt(0))
2835 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2837 // It can't be division by zero, hence it must be division by one.
2838 if (I.getType() == Type::Int1Ty)
2839 return ReplaceInstUsesWith(I, Op0);
2841 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2842 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2845 return ReplaceInstUsesWith(I, Op0);
2851 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2852 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2854 // Handle the integer div common cases
2855 if (Instruction *Common = commonIDivTransforms(I))
2858 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2859 // X udiv C^2 -> X >> C
2860 // Check to see if this is an unsigned division with an exact power of 2,
2861 // if so, convert to a right shift.
2862 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2863 return BinaryOperator::CreateLShr(Op0,
2864 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2866 // X udiv C, where C >= signbit
2867 if (C->getValue().isNegative()) {
2868 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2870 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2871 ConstantInt::get(I.getType(), 1));
2875 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2876 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2877 if (RHSI->getOpcode() == Instruction::Shl &&
2878 isa<ConstantInt>(RHSI->getOperand(0))) {
2879 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2880 if (C1.isPowerOf2()) {
2881 Value *N = RHSI->getOperand(1);
2882 const Type *NTy = N->getType();
2883 if (uint32_t C2 = C1.logBase2()) {
2884 Constant *C2V = ConstantInt::get(NTy, C2);
2885 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2887 return BinaryOperator::CreateLShr(Op0, N);
2892 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2893 // where C1&C2 are powers of two.
2894 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2895 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2896 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2897 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2898 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2899 // Compute the shift amounts
2900 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2901 // Construct the "on true" case of the select
2902 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2903 Instruction *TSI = BinaryOperator::CreateLShr(
2904 Op0, TC, SI->getName()+".t");
2905 TSI = InsertNewInstBefore(TSI, I);
2907 // Construct the "on false" case of the select
2908 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2909 Instruction *FSI = BinaryOperator::CreateLShr(
2910 Op0, FC, SI->getName()+".f");
2911 FSI = InsertNewInstBefore(FSI, I);
2913 // construct the select instruction and return it.
2914 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2920 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2921 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2923 // Handle the integer div common cases
2924 if (Instruction *Common = commonIDivTransforms(I))
2927 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2929 if (RHS->isAllOnesValue())
2930 return BinaryOperator::CreateNeg(Op0);
2933 // If the sign bits of both operands are zero (i.e. we can prove they are
2934 // unsigned inputs), turn this into a udiv.
2935 if (I.getType()->isInteger()) {
2936 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2937 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2938 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2939 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2946 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2947 return commonDivTransforms(I);
2950 /// This function implements the transforms on rem instructions that work
2951 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2952 /// is used by the visitors to those instructions.
2953 /// @brief Transforms common to all three rem instructions
2954 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2955 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2957 // 0 % X == 0 for integer, we don't need to preserve faults!
2958 if (Constant *LHS = dyn_cast<Constant>(Op0))
2959 if (LHS->isNullValue())
2960 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2962 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2963 if (I.getType()->isFPOrFPVector())
2964 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
2965 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2967 if (isa<UndefValue>(Op1))
2968 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2970 // Handle cases involving: rem X, (select Cond, Y, Z)
2971 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2977 /// This function implements the transforms common to both integer remainder
2978 /// instructions (urem and srem). It is called by the visitors to those integer
2979 /// remainder instructions.
2980 /// @brief Common integer remainder transforms
2981 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2982 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2984 if (Instruction *common = commonRemTransforms(I))
2987 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2988 // X % 0 == undef, we don't need to preserve faults!
2989 if (RHS->equalsInt(0))
2990 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2992 if (RHS->equalsInt(1)) // X % 1 == 0
2993 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2995 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2996 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2997 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2999 } else if (isa<PHINode>(Op0I)) {
3000 if (Instruction *NV = FoldOpIntoPhi(I))
3004 // See if we can fold away this rem instruction.
3005 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3006 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3007 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3008 KnownZero, KnownOne))
3016 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3017 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3019 if (Instruction *common = commonIRemTransforms(I))
3022 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3023 // X urem C^2 -> X and C
3024 // Check to see if this is an unsigned remainder with an exact power of 2,
3025 // if so, convert to a bitwise and.
3026 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3027 if (C->getValue().isPowerOf2())
3028 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3031 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3032 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3033 if (RHSI->getOpcode() == Instruction::Shl &&
3034 isa<ConstantInt>(RHSI->getOperand(0))) {
3035 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3036 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3037 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3039 return BinaryOperator::CreateAnd(Op0, Add);
3044 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3045 // where C1&C2 are powers of two.
3046 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3047 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3048 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3049 // STO == 0 and SFO == 0 handled above.
3050 if ((STO->getValue().isPowerOf2()) &&
3051 (SFO->getValue().isPowerOf2())) {
3052 Value *TrueAnd = InsertNewInstBefore(
3053 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3054 Value *FalseAnd = InsertNewInstBefore(
3055 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3056 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3064 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3065 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3067 // Handle the integer rem common cases
3068 if (Instruction *common = commonIRemTransforms(I))
3071 if (Value *RHSNeg = dyn_castNegVal(Op1))
3072 if (!isa<Constant>(RHSNeg) ||
3073 (isa<ConstantInt>(RHSNeg) &&
3074 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3076 AddUsesToWorkList(I);
3077 I.setOperand(1, RHSNeg);
3081 // If the sign bits of both operands are zero (i.e. we can prove they are
3082 // unsigned inputs), turn this into a urem.
3083 if (I.getType()->isInteger()) {
3084 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3085 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3086 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3087 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3091 // If it's a constant vector, flip any negative values positive.
3092 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3093 unsigned VWidth = RHSV->getNumOperands();
3095 bool hasNegative = false;
3096 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3097 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3098 if (RHS->getValue().isNegative())
3102 std::vector<Constant *> Elts(VWidth);
3103 for (unsigned i = 0; i != VWidth; ++i) {
3104 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3105 if (RHS->getValue().isNegative())
3106 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3112 Constant *NewRHSV = ConstantVector::get(Elts);
3113 if (NewRHSV != RHSV) {
3114 AddUsesToWorkList(I);
3115 I.setOperand(1, NewRHSV);
3124 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3125 return commonRemTransforms(I);
3128 // isOneBitSet - Return true if there is exactly one bit set in the specified
3130 static bool isOneBitSet(const ConstantInt *CI) {
3131 return CI->getValue().isPowerOf2();
3134 // isHighOnes - Return true if the constant is of the form 1+0+.
3135 // This is the same as lowones(~X).
3136 static bool isHighOnes(const ConstantInt *CI) {
3137 return (~CI->getValue() + 1).isPowerOf2();
3140 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3141 /// are carefully arranged to allow folding of expressions such as:
3143 /// (A < B) | (A > B) --> (A != B)
3145 /// Note that this is only valid if the first and second predicates have the
3146 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3148 /// Three bits are used to represent the condition, as follows:
3153 /// <=> Value Definition
3154 /// 000 0 Always false
3161 /// 111 7 Always true
3163 static unsigned getICmpCode(const ICmpInst *ICI) {
3164 switch (ICI->getPredicate()) {
3166 case ICmpInst::ICMP_UGT: return 1; // 001
3167 case ICmpInst::ICMP_SGT: return 1; // 001
3168 case ICmpInst::ICMP_EQ: return 2; // 010
3169 case ICmpInst::ICMP_UGE: return 3; // 011
3170 case ICmpInst::ICMP_SGE: return 3; // 011
3171 case ICmpInst::ICMP_ULT: return 4; // 100
3172 case ICmpInst::ICMP_SLT: return 4; // 100
3173 case ICmpInst::ICMP_NE: return 5; // 101
3174 case ICmpInst::ICMP_ULE: return 6; // 110
3175 case ICmpInst::ICMP_SLE: return 6; // 110
3178 assert(0 && "Invalid ICmp predicate!");
3183 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3184 /// predicate into a three bit mask. It also returns whether it is an ordered
3185 /// predicate by reference.
3186 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3189 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3190 case FCmpInst::FCMP_UNO: return 0; // 000
3191 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3192 case FCmpInst::FCMP_UGT: return 1; // 001
3193 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3194 case FCmpInst::FCMP_UEQ: return 2; // 010
3195 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3196 case FCmpInst::FCMP_UGE: return 3; // 011
3197 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3198 case FCmpInst::FCMP_ULT: return 4; // 100
3199 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3200 case FCmpInst::FCMP_UNE: return 5; // 101
3201 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3202 case FCmpInst::FCMP_ULE: return 6; // 110
3205 // Not expecting FCMP_FALSE and FCMP_TRUE;
3206 assert(0 && "Unexpected FCmp predicate!");
3211 /// getICmpValue - This is the complement of getICmpCode, which turns an
3212 /// opcode and two operands into either a constant true or false, or a brand
3213 /// new ICmp instruction. The sign is passed in to determine which kind
3214 /// of predicate to use in the new icmp instruction.
3215 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3217 default: assert(0 && "Illegal ICmp code!");
3218 case 0: return ConstantInt::getFalse();
3221 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3223 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3224 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3227 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3229 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3232 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3234 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3235 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3238 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3240 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3241 case 7: return ConstantInt::getTrue();
3245 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3246 /// opcode and two operands into either a FCmp instruction. isordered is passed
3247 /// in to determine which kind of predicate to use in the new fcmp instruction.
3248 static Value *getFCmpValue(bool isordered, unsigned code,
3249 Value *LHS, Value *RHS) {
3251 default: assert(0 && "Illegal FCmp code!");
3254 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3256 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3259 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3261 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3264 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3266 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3269 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3271 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3274 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3276 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3279 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3281 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3284 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3286 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3287 case 7: return ConstantInt::getTrue();
3291 /// PredicatesFoldable - Return true if both predicates match sign or if at
3292 /// least one of them is an equality comparison (which is signless).
3293 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3294 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3295 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3296 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3300 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3301 struct FoldICmpLogical {
3304 ICmpInst::Predicate pred;
3305 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3306 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3307 pred(ICI->getPredicate()) {}
3308 bool shouldApply(Value *V) const {
3309 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3310 if (PredicatesFoldable(pred, ICI->getPredicate()))
3311 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3312 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3315 Instruction *apply(Instruction &Log) const {
3316 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3317 if (ICI->getOperand(0) != LHS) {
3318 assert(ICI->getOperand(1) == LHS);
3319 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3322 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3323 unsigned LHSCode = getICmpCode(ICI);
3324 unsigned RHSCode = getICmpCode(RHSICI);
3326 switch (Log.getOpcode()) {
3327 case Instruction::And: Code = LHSCode & RHSCode; break;
3328 case Instruction::Or: Code = LHSCode | RHSCode; break;
3329 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3330 default: assert(0 && "Illegal logical opcode!"); return 0;
3333 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3334 ICmpInst::isSignedPredicate(ICI->getPredicate());
3336 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3337 if (Instruction *I = dyn_cast<Instruction>(RV))
3339 // Otherwise, it's a constant boolean value...
3340 return IC.ReplaceInstUsesWith(Log, RV);
3343 } // end anonymous namespace
3345 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3346 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3347 // guaranteed to be a binary operator.
3348 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3350 ConstantInt *AndRHS,
3351 BinaryOperator &TheAnd) {
3352 Value *X = Op->getOperand(0);
3353 Constant *Together = 0;
3355 Together = And(AndRHS, OpRHS);
3357 switch (Op->getOpcode()) {
3358 case Instruction::Xor:
3359 if (Op->hasOneUse()) {
3360 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3361 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3362 InsertNewInstBefore(And, TheAnd);
3364 return BinaryOperator::CreateXor(And, Together);
3367 case Instruction::Or:
3368 if (Together == AndRHS) // (X | C) & C --> C
3369 return ReplaceInstUsesWith(TheAnd, AndRHS);
3371 if (Op->hasOneUse() && Together != OpRHS) {
3372 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3373 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3374 InsertNewInstBefore(Or, TheAnd);
3376 return BinaryOperator::CreateAnd(Or, AndRHS);
3379 case Instruction::Add:
3380 if (Op->hasOneUse()) {
3381 // Adding a one to a single bit bit-field should be turned into an XOR
3382 // of the bit. First thing to check is to see if this AND is with a
3383 // single bit constant.
3384 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3386 // If there is only one bit set...
3387 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3388 // Ok, at this point, we know that we are masking the result of the
3389 // ADD down to exactly one bit. If the constant we are adding has
3390 // no bits set below this bit, then we can eliminate the ADD.
3391 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3393 // Check to see if any bits below the one bit set in AndRHSV are set.
3394 if ((AddRHS & (AndRHSV-1)) == 0) {
3395 // If not, the only thing that can effect the output of the AND is
3396 // the bit specified by AndRHSV. If that bit is set, the effect of
3397 // the XOR is to toggle the bit. If it is clear, then the ADD has
3399 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3400 TheAnd.setOperand(0, X);
3403 // Pull the XOR out of the AND.
3404 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3405 InsertNewInstBefore(NewAnd, TheAnd);
3406 NewAnd->takeName(Op);
3407 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3414 case Instruction::Shl: {
3415 // We know that the AND will not produce any of the bits shifted in, so if
3416 // the anded constant includes them, clear them now!
3418 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3419 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3420 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3421 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3423 if (CI->getValue() == ShlMask) {
3424 // Masking out bits that the shift already masks
3425 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3426 } else if (CI != AndRHS) { // Reducing bits set in and.
3427 TheAnd.setOperand(1, CI);
3432 case Instruction::LShr:
3434 // We know that the AND will not produce any of the bits shifted in, so if
3435 // the anded constant includes them, clear them now! This only applies to
3436 // unsigned shifts, because a signed shr may bring in set bits!
3438 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3439 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3440 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3441 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3443 if (CI->getValue() == ShrMask) {
3444 // Masking out bits that the shift already masks.
3445 return ReplaceInstUsesWith(TheAnd, Op);
3446 } else if (CI != AndRHS) {
3447 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3452 case Instruction::AShr:
3454 // See if this is shifting in some sign extension, then masking it out
3456 if (Op->hasOneUse()) {
3457 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3458 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3459 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3460 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3461 if (C == AndRHS) { // Masking out bits shifted in.
3462 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3463 // Make the argument unsigned.
3464 Value *ShVal = Op->getOperand(0);
3465 ShVal = InsertNewInstBefore(
3466 BinaryOperator::CreateLShr(ShVal, OpRHS,
3467 Op->getName()), TheAnd);
3468 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3477 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3478 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3479 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3480 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3481 /// insert new instructions.
3482 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3483 bool isSigned, bool Inside,
3485 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3486 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3487 "Lo is not <= Hi in range emission code!");
3490 if (Lo == Hi) // Trivially false.
3491 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3493 // V >= Min && V < Hi --> V < Hi
3494 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3495 ICmpInst::Predicate pred = (isSigned ?
3496 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3497 return new ICmpInst(pred, V, Hi);
3500 // Emit V-Lo <u Hi-Lo
3501 Constant *NegLo = ConstantExpr::getNeg(Lo);
3502 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3503 InsertNewInstBefore(Add, IB);
3504 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3505 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3508 if (Lo == Hi) // Trivially true.
3509 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3511 // V < Min || V >= Hi -> V > Hi-1
3512 Hi = SubOne(cast<ConstantInt>(Hi));
3513 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3514 ICmpInst::Predicate pred = (isSigned ?
3515 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3516 return new ICmpInst(pred, V, Hi);
3519 // Emit V-Lo >u Hi-1-Lo
3520 // Note that Hi has already had one subtracted from it, above.
3521 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3522 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3523 InsertNewInstBefore(Add, IB);
3524 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3525 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3528 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3529 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3530 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3531 // not, since all 1s are not contiguous.
3532 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3533 const APInt& V = Val->getValue();
3534 uint32_t BitWidth = Val->getType()->getBitWidth();
3535 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3537 // look for the first zero bit after the run of ones
3538 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3539 // look for the first non-zero bit
3540 ME = V.getActiveBits();
3544 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3545 /// where isSub determines whether the operator is a sub. If we can fold one of
3546 /// the following xforms:
3548 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3549 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3550 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3552 /// return (A +/- B).
3554 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3555 ConstantInt *Mask, bool isSub,
3557 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3558 if (!LHSI || LHSI->getNumOperands() != 2 ||
3559 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3561 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3563 switch (LHSI->getOpcode()) {
3565 case Instruction::And:
3566 if (And(N, Mask) == Mask) {
3567 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3568 if ((Mask->getValue().countLeadingZeros() +
3569 Mask->getValue().countPopulation()) ==
3570 Mask->getValue().getBitWidth())
3573 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3574 // part, we don't need any explicit masks to take them out of A. If that
3575 // is all N is, ignore it.
3576 uint32_t MB = 0, ME = 0;
3577 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3578 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3579 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3580 if (MaskedValueIsZero(RHS, Mask))
3585 case Instruction::Or:
3586 case Instruction::Xor:
3587 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3588 if ((Mask->getValue().countLeadingZeros() +
3589 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3590 && And(N, Mask)->isZero())
3597 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3599 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3600 return InsertNewInstBefore(New, I);
3603 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3604 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3605 ICmpInst *LHS, ICmpInst *RHS) {
3607 ConstantInt *LHSCst, *RHSCst;
3608 ICmpInst::Predicate LHSCC, RHSCC;
3610 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3611 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3612 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3615 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3616 // where C is a power of 2
3617 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3618 LHSCst->getValue().isPowerOf2()) {
3619 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3620 InsertNewInstBefore(NewOr, I);
3621 return new ICmpInst(LHSCC, NewOr, LHSCst);
3624 // From here on, we only handle:
3625 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3626 if (Val != Val2) return 0;
3628 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3629 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3630 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3631 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3632 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3635 // We can't fold (ugt x, C) & (sgt x, C2).
3636 if (!PredicatesFoldable(LHSCC, RHSCC))
3639 // Ensure that the larger constant is on the RHS.
3641 if (ICmpInst::isSignedPredicate(LHSCC) ||
3642 (ICmpInst::isEquality(LHSCC) &&
3643 ICmpInst::isSignedPredicate(RHSCC)))
3644 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3646 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3649 std::swap(LHS, RHS);
3650 std::swap(LHSCst, RHSCst);
3651 std::swap(LHSCC, RHSCC);
3654 // At this point, we know we have have two icmp instructions
3655 // comparing a value against two constants and and'ing the result
3656 // together. Because of the above check, we know that we only have
3657 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3658 // (from the FoldICmpLogical check above), that the two constants
3659 // are not equal and that the larger constant is on the RHS
3660 assert(LHSCst != RHSCst && "Compares not folded above?");
3663 default: assert(0 && "Unknown integer condition code!");
3664 case ICmpInst::ICMP_EQ:
3666 default: assert(0 && "Unknown integer condition code!");
3667 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3668 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3669 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3670 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3671 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3672 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3673 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3674 return ReplaceInstUsesWith(I, LHS);
3676 case ICmpInst::ICMP_NE:
3678 default: assert(0 && "Unknown integer condition code!");
3679 case ICmpInst::ICMP_ULT:
3680 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3681 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3682 break; // (X != 13 & X u< 15) -> no change
3683 case ICmpInst::ICMP_SLT:
3684 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3685 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3686 break; // (X != 13 & X s< 15) -> no change
3687 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3688 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3689 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3690 return ReplaceInstUsesWith(I, RHS);
3691 case ICmpInst::ICMP_NE:
3692 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3693 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3694 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3695 Val->getName()+".off");
3696 InsertNewInstBefore(Add, I);
3697 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3698 ConstantInt::get(Add->getType(), 1));
3700 break; // (X != 13 & X != 15) -> no change
3703 case ICmpInst::ICMP_ULT:
3705 default: assert(0 && "Unknown integer condition code!");
3706 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3707 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3709 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3711 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3712 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3713 return ReplaceInstUsesWith(I, LHS);
3714 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3718 case ICmpInst::ICMP_SLT:
3720 default: assert(0 && "Unknown integer condition code!");
3721 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3722 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3723 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3724 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3726 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3727 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3728 return ReplaceInstUsesWith(I, LHS);
3729 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3733 case ICmpInst::ICMP_UGT:
3735 default: assert(0 && "Unknown integer condition code!");
3736 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3737 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3738 return ReplaceInstUsesWith(I, RHS);
3739 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3741 case ICmpInst::ICMP_NE:
3742 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3743 return new ICmpInst(LHSCC, Val, RHSCst);
3744 break; // (X u> 13 & X != 15) -> no change
3745 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3746 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3747 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3751 case ICmpInst::ICMP_SGT:
3753 default: assert(0 && "Unknown integer condition code!");
3754 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3755 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3756 return ReplaceInstUsesWith(I, RHS);
3757 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3759 case ICmpInst::ICMP_NE:
3760 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3761 return new ICmpInst(LHSCC, Val, RHSCst);
3762 break; // (X s> 13 & X != 15) -> no change
3763 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3764 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3765 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3775 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3776 bool Changed = SimplifyCommutative(I);
3777 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3779 if (isa<UndefValue>(Op1)) // X & undef -> 0
3780 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3784 return ReplaceInstUsesWith(I, Op1);
3786 // See if we can simplify any instructions used by the instruction whose sole
3787 // purpose is to compute bits we don't care about.
3788 if (!isa<VectorType>(I.getType())) {
3789 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3790 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3791 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3792 KnownZero, KnownOne))
3795 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3796 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3797 return ReplaceInstUsesWith(I, I.getOperand(0));
3798 } else if (isa<ConstantAggregateZero>(Op1)) {
3799 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3803 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3804 const APInt& AndRHSMask = AndRHS->getValue();
3805 APInt NotAndRHS(~AndRHSMask);
3807 // Optimize a variety of ((val OP C1) & C2) combinations...
3808 if (isa<BinaryOperator>(Op0)) {
3809 Instruction *Op0I = cast<Instruction>(Op0);
3810 Value *Op0LHS = Op0I->getOperand(0);
3811 Value *Op0RHS = Op0I->getOperand(1);
3812 switch (Op0I->getOpcode()) {
3813 case Instruction::Xor:
3814 case Instruction::Or:
3815 // If the mask is only needed on one incoming arm, push it up.
3816 if (Op0I->hasOneUse()) {
3817 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3818 // Not masking anything out for the LHS, move to RHS.
3819 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3820 Op0RHS->getName()+".masked");
3821 InsertNewInstBefore(NewRHS, I);
3822 return BinaryOperator::Create(
3823 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3825 if (!isa<Constant>(Op0RHS) &&
3826 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3827 // Not masking anything out for the RHS, move to LHS.
3828 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3829 Op0LHS->getName()+".masked");
3830 InsertNewInstBefore(NewLHS, I);
3831 return BinaryOperator::Create(
3832 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3837 case Instruction::Add:
3838 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3839 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3840 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3841 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3842 return BinaryOperator::CreateAnd(V, AndRHS);
3843 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3844 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
3847 case Instruction::Sub:
3848 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3849 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3850 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3851 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3852 return BinaryOperator::CreateAnd(V, AndRHS);
3854 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3855 // has 1's for all bits that the subtraction with A might affect.
3856 if (Op0I->hasOneUse()) {
3857 uint32_t BitWidth = AndRHSMask.getBitWidth();
3858 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3859 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3861 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3862 if (!(A && A->isZero()) && // avoid infinite recursion.
3863 MaskedValueIsZero(Op0LHS, Mask)) {
3864 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3865 InsertNewInstBefore(NewNeg, I);
3866 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3871 case Instruction::Shl:
3872 case Instruction::LShr:
3873 // (1 << x) & 1 --> zext(x == 0)
3874 // (1 >> x) & 1 --> zext(x == 0)
3875 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3876 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3877 Constant::getNullValue(I.getType()));
3878 InsertNewInstBefore(NewICmp, I);
3879 return new ZExtInst(NewICmp, I.getType());
3884 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3885 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3887 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3888 // If this is an integer truncation or change from signed-to-unsigned, and
3889 // if the source is an and/or with immediate, transform it. This
3890 // frequently occurs for bitfield accesses.
3891 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3892 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3893 CastOp->getNumOperands() == 2)
3894 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3895 if (CastOp->getOpcode() == Instruction::And) {
3896 // Change: and (cast (and X, C1) to T), C2
3897 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3898 // This will fold the two constants together, which may allow
3899 // other simplifications.
3900 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3901 CastOp->getOperand(0), I.getType(),
3902 CastOp->getName()+".shrunk");
3903 NewCast = InsertNewInstBefore(NewCast, I);
3904 // trunc_or_bitcast(C1)&C2
3905 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3906 C3 = ConstantExpr::getAnd(C3, AndRHS);
3907 return BinaryOperator::CreateAnd(NewCast, C3);
3908 } else if (CastOp->getOpcode() == Instruction::Or) {
3909 // Change: and (cast (or X, C1) to T), C2
3910 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3911 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3912 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3913 return ReplaceInstUsesWith(I, AndRHS);
3919 // Try to fold constant and into select arguments.
3920 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3921 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3923 if (isa<PHINode>(Op0))
3924 if (Instruction *NV = FoldOpIntoPhi(I))
3928 Value *Op0NotVal = dyn_castNotVal(Op0);
3929 Value *Op1NotVal = dyn_castNotVal(Op1);
3931 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3932 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3934 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3935 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3936 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3937 I.getName()+".demorgan");
3938 InsertNewInstBefore(Or, I);
3939 return BinaryOperator::CreateNot(Or);
3943 Value *A = 0, *B = 0, *C = 0, *D = 0;
3944 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3945 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3946 return ReplaceInstUsesWith(I, Op1);
3948 // (A|B) & ~(A&B) -> A^B
3949 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3950 if ((A == C && B == D) || (A == D && B == C))
3951 return BinaryOperator::CreateXor(A, B);
3955 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3956 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3957 return ReplaceInstUsesWith(I, Op0);
3959 // ~(A&B) & (A|B) -> A^B
3960 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3961 if ((A == C && B == D) || (A == D && B == C))
3962 return BinaryOperator::CreateXor(A, B);
3966 if (Op0->hasOneUse() &&
3967 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3968 if (A == Op1) { // (A^B)&A -> A&(A^B)
3969 I.swapOperands(); // Simplify below
3970 std::swap(Op0, Op1);
3971 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3972 cast<BinaryOperator>(Op0)->swapOperands();
3973 I.swapOperands(); // Simplify below
3974 std::swap(Op0, Op1);
3978 if (Op1->hasOneUse() &&
3979 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3980 if (B == Op0) { // B&(A^B) -> B&(B^A)
3981 cast<BinaryOperator>(Op1)->swapOperands();
3984 if (A == Op0) { // A&(A^B) -> A & ~B
3985 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3986 InsertNewInstBefore(NotB, I);
3987 return BinaryOperator::CreateAnd(A, NotB);
3991 // (A&((~A)|B)) -> A&B
3992 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3993 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3994 return BinaryOperator::CreateAnd(A, Op1);
3995 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3996 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3997 return BinaryOperator::CreateAnd(A, Op0);
4000 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4001 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4002 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4005 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4006 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4010 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4011 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4012 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4013 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4014 const Type *SrcTy = Op0C->getOperand(0)->getType();
4015 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4016 // Only do this if the casts both really cause code to be generated.
4017 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4019 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4021 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4022 Op1C->getOperand(0),
4024 InsertNewInstBefore(NewOp, I);
4025 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4029 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4030 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4031 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4032 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4033 SI0->getOperand(1) == SI1->getOperand(1) &&
4034 (SI0->hasOneUse() || SI1->hasOneUse())) {
4035 Instruction *NewOp =
4036 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4038 SI0->getName()), I);
4039 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4040 SI1->getOperand(1));
4044 // If and'ing two fcmp, try combine them into one.
4045 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4046 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4047 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4048 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4049 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4050 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4051 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4052 // If either of the constants are nans, then the whole thing returns
4054 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4055 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4056 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4057 RHS->getOperand(0));
4060 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4061 FCmpInst::Predicate Op0CC, Op1CC;
4062 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4063 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4064 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4065 // Swap RHS operands to match LHS.
4066 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4067 std::swap(Op1LHS, Op1RHS);
4069 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4070 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4072 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4073 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4074 Op1CC == FCmpInst::FCMP_FALSE)
4075 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4076 else if (Op0CC == FCmpInst::FCMP_TRUE)
4077 return ReplaceInstUsesWith(I, Op1);
4078 else if (Op1CC == FCmpInst::FCMP_TRUE)
4079 return ReplaceInstUsesWith(I, Op0);
4082 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4083 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4085 std::swap(Op0, Op1);
4086 std::swap(Op0Pred, Op1Pred);
4087 std::swap(Op0Ordered, Op1Ordered);
4090 // uno && ueq -> uno && (uno || eq) -> ueq
4091 // ord && olt -> ord && (ord && lt) -> olt
4092 if (Op0Ordered == Op1Ordered)
4093 return ReplaceInstUsesWith(I, Op1);
4094 // uno && oeq -> uno && (ord && eq) -> false
4095 // uno && ord -> false
4097 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4098 // ord && ueq -> ord && (uno || eq) -> oeq
4099 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4108 return Changed ? &I : 0;
4111 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4112 /// capable of providing pieces of a bswap. The subexpression provides pieces
4113 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4114 /// the expression came from the corresponding "byte swapped" byte in some other
4115 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4116 /// we know that the expression deposits the low byte of %X into the high byte
4117 /// of the bswap result and that all other bytes are zero. This expression is
4118 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4121 /// This function returns true if the match was unsuccessful and false if so.
4122 /// On entry to the function the "OverallLeftShift" is a signed integer value
4123 /// indicating the number of bytes that the subexpression is later shifted. For
4124 /// example, if the expression is later right shifted by 16 bits, the
4125 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4126 /// byte of ByteValues is actually being set.
4128 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4129 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4130 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4131 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4132 /// always in the local (OverallLeftShift) coordinate space.
4134 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4135 SmallVector<Value*, 8> &ByteValues) {
4136 if (Instruction *I = dyn_cast<Instruction>(V)) {
4137 // If this is an or instruction, it may be an inner node of the bswap.
4138 if (I->getOpcode() == Instruction::Or) {
4139 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4141 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4145 // If this is a logical shift by a constant multiple of 8, recurse with
4146 // OverallLeftShift and ByteMask adjusted.
4147 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4149 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4150 // Ensure the shift amount is defined and of a byte value.
4151 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4154 unsigned ByteShift = ShAmt >> 3;
4155 if (I->getOpcode() == Instruction::Shl) {
4156 // X << 2 -> collect(X, +2)
4157 OverallLeftShift += ByteShift;
4158 ByteMask >>= ByteShift;
4160 // X >>u 2 -> collect(X, -2)
4161 OverallLeftShift -= ByteShift;
4162 ByteMask <<= ByteShift;
4163 ByteMask &= (~0U >> (32-ByteValues.size()));
4166 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4167 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4169 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4173 // If this is a logical 'and' with a mask that clears bytes, clear the
4174 // corresponding bytes in ByteMask.
4175 if (I->getOpcode() == Instruction::And &&
4176 isa<ConstantInt>(I->getOperand(1))) {
4177 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4178 unsigned NumBytes = ByteValues.size();
4179 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4180 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4182 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4183 // If this byte is masked out by a later operation, we don't care what
4185 if ((ByteMask & (1 << i)) == 0)
4188 // If the AndMask is all zeros for this byte, clear the bit.
4189 APInt MaskB = AndMask & Byte;
4191 ByteMask &= ~(1U << i);
4195 // If the AndMask is not all ones for this byte, it's not a bytezap.
4199 // Otherwise, this byte is kept.
4202 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4207 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4208 // the input value to the bswap. Some observations: 1) if more than one byte
4209 // is demanded from this input, then it could not be successfully assembled
4210 // into a byteswap. At least one of the two bytes would not be aligned with
4211 // their ultimate destination.
4212 if (!isPowerOf2_32(ByteMask)) return true;
4213 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4215 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4216 // is demanded, it needs to go into byte 0 of the result. This means that the
4217 // byte needs to be shifted until it lands in the right byte bucket. The
4218 // shift amount depends on the position: if the byte is coming from the high
4219 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4220 // low part, it must be shifted left.
4221 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4222 if (InputByteNo < ByteValues.size()/2) {
4223 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4226 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4230 // If the destination byte value is already defined, the values are or'd
4231 // together, which isn't a bswap (unless it's an or of the same bits).
4232 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4234 ByteValues[DestByteNo] = V;
4238 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4239 /// If so, insert the new bswap intrinsic and return it.
4240 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4241 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4242 if (!ITy || ITy->getBitWidth() % 16 ||
4243 // ByteMask only allows up to 32-byte values.
4244 ITy->getBitWidth() > 32*8)
4245 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4247 /// ByteValues - For each byte of the result, we keep track of which value
4248 /// defines each byte.
4249 SmallVector<Value*, 8> ByteValues;
4250 ByteValues.resize(ITy->getBitWidth()/8);
4252 // Try to find all the pieces corresponding to the bswap.
4253 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4254 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4257 // Check to see if all of the bytes come from the same value.
4258 Value *V = ByteValues[0];
4259 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4261 // Check to make sure that all of the bytes come from the same value.
4262 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4263 if (ByteValues[i] != V)
4265 const Type *Tys[] = { ITy };
4266 Module *M = I.getParent()->getParent()->getParent();
4267 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4268 return CallInst::Create(F, V);
4271 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4272 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4273 /// we can simplify this expression to "cond ? C : D or B".
4274 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4275 Value *C, Value *D) {
4276 // If A is not a select of -1/0, this cannot match.
4278 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4281 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4282 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4283 return SelectInst::Create(Cond, C, B);
4284 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4285 return SelectInst::Create(Cond, C, B);
4286 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4287 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4288 return SelectInst::Create(Cond, C, D);
4289 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4290 return SelectInst::Create(Cond, C, D);
4294 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4295 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4296 ICmpInst *LHS, ICmpInst *RHS) {
4298 ConstantInt *LHSCst, *RHSCst;
4299 ICmpInst::Predicate LHSCC, RHSCC;
4301 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4302 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4303 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4306 // From here on, we only handle:
4307 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4308 if (Val != Val2) return 0;
4310 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4311 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4312 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4313 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4314 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4317 // We can't fold (ugt x, C) | (sgt x, C2).
4318 if (!PredicatesFoldable(LHSCC, RHSCC))
4321 // Ensure that the larger constant is on the RHS.
4323 if (ICmpInst::isSignedPredicate(LHSCC) ||
4324 (ICmpInst::isEquality(LHSCC) &&
4325 ICmpInst::isSignedPredicate(RHSCC)))
4326 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4328 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4331 std::swap(LHS, RHS);
4332 std::swap(LHSCst, RHSCst);
4333 std::swap(LHSCC, RHSCC);
4336 // At this point, we know we have have two icmp instructions
4337 // comparing a value against two constants and or'ing the result
4338 // together. Because of the above check, we know that we only have
4339 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4340 // FoldICmpLogical check above), that the two constants are not
4342 assert(LHSCst != RHSCst && "Compares not folded above?");
4345 default: assert(0 && "Unknown integer condition code!");
4346 case ICmpInst::ICMP_EQ:
4348 default: assert(0 && "Unknown integer condition code!");
4349 case ICmpInst::ICMP_EQ:
4350 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4351 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4352 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4353 Val->getName()+".off");
4354 InsertNewInstBefore(Add, I);
4355 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4356 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4358 break; // (X == 13 | X == 15) -> no change
4359 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4360 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4362 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4363 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4364 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4365 return ReplaceInstUsesWith(I, RHS);
4368 case ICmpInst::ICMP_NE:
4370 default: assert(0 && "Unknown integer condition code!");
4371 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4372 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4373 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4374 return ReplaceInstUsesWith(I, LHS);
4375 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4376 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4377 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4378 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4381 case ICmpInst::ICMP_ULT:
4383 default: assert(0 && "Unknown integer condition code!");
4384 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4386 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4387 // If RHSCst is [us]MAXINT, it is always false. Not handling
4388 // this can cause overflow.
4389 if (RHSCst->isMaxValue(false))
4390 return ReplaceInstUsesWith(I, LHS);
4391 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4392 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4394 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4395 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4396 return ReplaceInstUsesWith(I, RHS);
4397 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4401 case ICmpInst::ICMP_SLT:
4403 default: assert(0 && "Unknown integer condition code!");
4404 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4406 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4407 // If RHSCst is [us]MAXINT, it is always false. Not handling
4408 // this can cause overflow.
4409 if (RHSCst->isMaxValue(true))
4410 return ReplaceInstUsesWith(I, LHS);
4411 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4412 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4414 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4415 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4416 return ReplaceInstUsesWith(I, RHS);
4417 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4421 case ICmpInst::ICMP_UGT:
4423 default: assert(0 && "Unknown integer condition code!");
4424 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4425 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4426 return ReplaceInstUsesWith(I, LHS);
4427 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4429 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4430 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4431 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4432 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4436 case ICmpInst::ICMP_SGT:
4438 default: assert(0 && "Unknown integer condition code!");
4439 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4440 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4441 return ReplaceInstUsesWith(I, LHS);
4442 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4444 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4445 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4446 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4447 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4455 /// FoldOrWithConstants - This helper function folds:
4457 /// ((A | B) & C1) | (B & C2)
4463 /// when the XOR of the two constants is "all ones" (-1).
4464 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4465 Value *A, Value *B, Value *C) {
4466 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4470 ConstantInt *CI2 = 0;
4471 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4473 APInt Xor = CI1->getValue() ^ CI2->getValue();
4474 if (!Xor.isAllOnesValue()) return 0;
4476 if (V1 == A || V1 == B) {
4477 Instruction *NewOp =
4478 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4479 return BinaryOperator::CreateOr(NewOp, V1);
4485 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4486 bool Changed = SimplifyCommutative(I);
4487 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4489 if (isa<UndefValue>(Op1)) // X | undef -> -1
4490 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4494 return ReplaceInstUsesWith(I, Op0);
4496 // See if we can simplify any instructions used by the instruction whose sole
4497 // purpose is to compute bits we don't care about.
4498 if (!isa<VectorType>(I.getType())) {
4499 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4500 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4501 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4502 KnownZero, KnownOne))
4504 } else if (isa<ConstantAggregateZero>(Op1)) {
4505 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4506 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4507 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4508 return ReplaceInstUsesWith(I, I.getOperand(1));
4514 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4515 ConstantInt *C1 = 0; Value *X = 0;
4516 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4517 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4518 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4519 InsertNewInstBefore(Or, I);
4521 return BinaryOperator::CreateAnd(Or,
4522 ConstantInt::get(RHS->getValue() | C1->getValue()));
4525 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4526 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4527 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4528 InsertNewInstBefore(Or, I);
4530 return BinaryOperator::CreateXor(Or,
4531 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4534 // Try to fold constant and into select arguments.
4535 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4536 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4538 if (isa<PHINode>(Op0))
4539 if (Instruction *NV = FoldOpIntoPhi(I))
4543 Value *A = 0, *B = 0;
4544 ConstantInt *C1 = 0, *C2 = 0;
4546 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4547 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4548 return ReplaceInstUsesWith(I, Op1);
4549 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4550 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4551 return ReplaceInstUsesWith(I, Op0);
4553 // (A | B) | C and A | (B | C) -> bswap if possible.
4554 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4555 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4556 match(Op1, m_Or(m_Value(), m_Value())) ||
4557 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4558 match(Op1, m_Shift(m_Value(), m_Value())))) {
4559 if (Instruction *BSwap = MatchBSwap(I))
4563 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4564 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4565 MaskedValueIsZero(Op1, C1->getValue())) {
4566 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4567 InsertNewInstBefore(NOr, I);
4569 return BinaryOperator::CreateXor(NOr, C1);
4572 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4573 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4574 MaskedValueIsZero(Op0, C1->getValue())) {
4575 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4576 InsertNewInstBefore(NOr, I);
4578 return BinaryOperator::CreateXor(NOr, C1);
4582 Value *C = 0, *D = 0;
4583 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4584 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4585 Value *V1 = 0, *V2 = 0, *V3 = 0;
4586 C1 = dyn_cast<ConstantInt>(C);
4587 C2 = dyn_cast<ConstantInt>(D);
4588 if (C1 && C2) { // (A & C1)|(B & C2)
4589 // If we have: ((V + N) & C1) | (V & C2)
4590 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4591 // replace with V+N.
4592 if (C1->getValue() == ~C2->getValue()) {
4593 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4594 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4595 // Add commutes, try both ways.
4596 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4597 return ReplaceInstUsesWith(I, A);
4598 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4599 return ReplaceInstUsesWith(I, A);
4601 // Or commutes, try both ways.
4602 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4603 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4604 // Add commutes, try both ways.
4605 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4606 return ReplaceInstUsesWith(I, B);
4607 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4608 return ReplaceInstUsesWith(I, B);
4611 V1 = 0; V2 = 0; V3 = 0;
4614 // Check to see if we have any common things being and'ed. If so, find the
4615 // terms for V1 & (V2|V3).
4616 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4617 if (A == B) // (A & C)|(A & D) == A & (C|D)
4618 V1 = A, V2 = C, V3 = D;
4619 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4620 V1 = A, V2 = B, V3 = C;
4621 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4622 V1 = C, V2 = A, V3 = D;
4623 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4624 V1 = C, V2 = A, V3 = B;
4628 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4629 return BinaryOperator::CreateAnd(V1, Or);
4633 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4634 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4636 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4638 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4640 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4643 // ((A&~B)|(~A&B)) -> A^B
4644 if ((match(C, m_Not(m_Specific(D))) &&
4645 match(B, m_Not(m_Specific(A)))))
4646 return BinaryOperator::CreateXor(A, D);
4647 // ((~B&A)|(~A&B)) -> A^B
4648 if ((match(A, m_Not(m_Specific(D))) &&
4649 match(B, m_Not(m_Specific(C)))))
4650 return BinaryOperator::CreateXor(C, D);
4651 // ((A&~B)|(B&~A)) -> A^B
4652 if ((match(C, m_Not(m_Specific(B))) &&
4653 match(D, m_Not(m_Specific(A)))))
4654 return BinaryOperator::CreateXor(A, B);
4655 // ((~B&A)|(B&~A)) -> A^B
4656 if ((match(A, m_Not(m_Specific(B))) &&
4657 match(D, m_Not(m_Specific(C)))))
4658 return BinaryOperator::CreateXor(C, B);
4661 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4662 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4663 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4664 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4665 SI0->getOperand(1) == SI1->getOperand(1) &&
4666 (SI0->hasOneUse() || SI1->hasOneUse())) {
4667 Instruction *NewOp =
4668 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4670 SI0->getName()), I);
4671 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4672 SI1->getOperand(1));
4676 // ((A|B)&1)|(B&-2) -> (A&1) | B
4677 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4678 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4679 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4680 if (Ret) return Ret;
4682 // (B&-2)|((A|B)&1) -> (A&1) | B
4683 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4684 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4685 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4686 if (Ret) return Ret;
4689 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4690 if (A == Op1) // ~A | A == -1
4691 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4695 // Note, A is still live here!
4696 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4698 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4700 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4701 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4702 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4703 I.getName()+".demorgan"), I);
4704 return BinaryOperator::CreateNot(And);
4708 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4709 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4710 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4713 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4714 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4718 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4719 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4720 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4721 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4722 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4723 !isa<ICmpInst>(Op1C->getOperand(0))) {
4724 const Type *SrcTy = Op0C->getOperand(0)->getType();
4725 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4726 // Only do this if the casts both really cause code to be
4728 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4730 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4732 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4733 Op1C->getOperand(0),
4735 InsertNewInstBefore(NewOp, I);
4736 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4743 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4744 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4745 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4746 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4747 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4748 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4749 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4750 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4751 // If either of the constants are nans, then the whole thing returns
4753 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4754 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4756 // Otherwise, no need to compare the two constants, compare the
4758 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4759 RHS->getOperand(0));
4762 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4763 FCmpInst::Predicate Op0CC, Op1CC;
4764 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4765 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4766 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4767 // Swap RHS operands to match LHS.
4768 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4769 std::swap(Op1LHS, Op1RHS);
4771 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4772 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4774 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4775 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4776 Op1CC == FCmpInst::FCMP_TRUE)
4777 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4778 else if (Op0CC == FCmpInst::FCMP_FALSE)
4779 return ReplaceInstUsesWith(I, Op1);
4780 else if (Op1CC == FCmpInst::FCMP_FALSE)
4781 return ReplaceInstUsesWith(I, Op0);
4784 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4785 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4786 if (Op0Ordered == Op1Ordered) {
4787 // If both are ordered or unordered, return a new fcmp with
4788 // or'ed predicates.
4789 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4791 if (Instruction *I = dyn_cast<Instruction>(RV))
4793 // Otherwise, it's a constant boolean value...
4794 return ReplaceInstUsesWith(I, RV);
4802 return Changed ? &I : 0;
4807 // XorSelf - Implements: X ^ X --> 0
4810 XorSelf(Value *rhs) : RHS(rhs) {}
4811 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4812 Instruction *apply(BinaryOperator &Xor) const {
4819 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4820 bool Changed = SimplifyCommutative(I);
4821 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4823 if (isa<UndefValue>(Op1)) {
4824 if (isa<UndefValue>(Op0))
4825 // Handle undef ^ undef -> 0 special case. This is a common
4827 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4828 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4831 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4832 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4833 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4834 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4837 // See if we can simplify any instructions used by the instruction whose sole
4838 // purpose is to compute bits we don't care about.
4839 if (!isa<VectorType>(I.getType())) {
4840 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4841 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4842 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4843 KnownZero, KnownOne))
4845 } else if (isa<ConstantAggregateZero>(Op1)) {
4846 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4849 // Is this a ~ operation?
4850 if (Value *NotOp = dyn_castNotVal(&I)) {
4851 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4852 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4853 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4854 if (Op0I->getOpcode() == Instruction::And ||
4855 Op0I->getOpcode() == Instruction::Or) {
4856 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4857 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4859 BinaryOperator::CreateNot(Op0I->getOperand(1),
4860 Op0I->getOperand(1)->getName()+".not");
4861 InsertNewInstBefore(NotY, I);
4862 if (Op0I->getOpcode() == Instruction::And)
4863 return BinaryOperator::CreateOr(Op0NotVal, NotY);
4865 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4872 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4873 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4874 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4875 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4876 return new ICmpInst(ICI->getInversePredicate(),
4877 ICI->getOperand(0), ICI->getOperand(1));
4879 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4880 return new FCmpInst(FCI->getInversePredicate(),
4881 FCI->getOperand(0), FCI->getOperand(1));
4884 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4885 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4886 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4887 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4888 Instruction::CastOps Opcode = Op0C->getOpcode();
4889 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4890 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4891 Op0C->getDestTy())) {
4892 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4893 CI->getOpcode(), CI->getInversePredicate(),
4894 CI->getOperand(0), CI->getOperand(1)), I);
4895 NewCI->takeName(CI);
4896 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4903 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4904 // ~(c-X) == X-c-1 == X+(-c-1)
4905 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4906 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4907 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4908 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4909 ConstantInt::get(I.getType(), 1));
4910 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4913 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4914 if (Op0I->getOpcode() == Instruction::Add) {
4915 // ~(X-c) --> (-c-1)-X
4916 if (RHS->isAllOnesValue()) {
4917 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4918 return BinaryOperator::CreateSub(
4919 ConstantExpr::getSub(NegOp0CI,
4920 ConstantInt::get(I.getType(), 1)),
4921 Op0I->getOperand(0));
4922 } else if (RHS->getValue().isSignBit()) {
4923 // (X + C) ^ signbit -> (X + C + signbit)
4924 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4925 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4928 } else if (Op0I->getOpcode() == Instruction::Or) {
4929 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4930 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4931 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4932 // Anything in both C1 and C2 is known to be zero, remove it from
4934 Constant *CommonBits = And(Op0CI, RHS);
4935 NewRHS = ConstantExpr::getAnd(NewRHS,
4936 ConstantExpr::getNot(CommonBits));
4937 AddToWorkList(Op0I);
4938 I.setOperand(0, Op0I->getOperand(0));
4939 I.setOperand(1, NewRHS);
4946 // Try to fold constant and into select arguments.
4947 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4948 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4950 if (isa<PHINode>(Op0))
4951 if (Instruction *NV = FoldOpIntoPhi(I))
4955 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4957 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4959 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4961 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4964 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4967 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4968 if (A == Op0) { // B^(B|A) == (A|B)^B
4969 Op1I->swapOperands();
4971 std::swap(Op0, Op1);
4972 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4973 I.swapOperands(); // Simplified below.
4974 std::swap(Op0, Op1);
4976 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4977 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
4978 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4979 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
4980 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4981 if (A == Op0) { // A^(A&B) -> A^(B&A)
4982 Op1I->swapOperands();
4985 if (B == Op0) { // A^(B&A) -> (B&A)^A
4986 I.swapOperands(); // Simplified below.
4987 std::swap(Op0, Op1);
4992 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4995 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4996 if (A == Op1) // (B|A)^B == (A|B)^B
4998 if (B == Op1) { // (A|B)^B == A & ~B
5000 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5001 return BinaryOperator::CreateAnd(A, NotB);
5003 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5004 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5005 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5006 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5007 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5008 if (A == Op1) // (A&B)^A -> (B&A)^A
5010 if (B == Op1 && // (B&A)^A == ~B & A
5011 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5013 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5014 return BinaryOperator::CreateAnd(N, Op1);
5019 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5020 if (Op0I && Op1I && Op0I->isShift() &&
5021 Op0I->getOpcode() == Op1I->getOpcode() &&
5022 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5023 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5024 Instruction *NewOp =
5025 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5026 Op1I->getOperand(0),
5027 Op0I->getName()), I);
5028 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5029 Op1I->getOperand(1));
5033 Value *A, *B, *C, *D;
5034 // (A & B)^(A | B) -> A ^ B
5035 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5036 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5037 if ((A == C && B == D) || (A == D && B == C))
5038 return BinaryOperator::CreateXor(A, B);
5040 // (A | B)^(A & B) -> A ^ B
5041 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5042 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5043 if ((A == C && B == D) || (A == D && B == C))
5044 return BinaryOperator::CreateXor(A, B);
5048 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5049 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5050 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5051 // (X & Y)^(X & Y) -> (Y^Z) & X
5052 Value *X = 0, *Y = 0, *Z = 0;
5054 X = A, Y = B, Z = D;
5056 X = A, Y = B, Z = C;
5058 X = B, Y = A, Z = D;
5060 X = B, Y = A, Z = C;
5063 Instruction *NewOp =
5064 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5065 return BinaryOperator::CreateAnd(NewOp, X);
5070 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5071 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5072 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5075 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5076 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5077 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5078 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5079 const Type *SrcTy = Op0C->getOperand(0)->getType();
5080 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5081 // Only do this if the casts both really cause code to be generated.
5082 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5084 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5086 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5087 Op1C->getOperand(0),
5089 InsertNewInstBefore(NewOp, I);
5090 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5095 return Changed ? &I : 0;
5098 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5099 /// overflowed for this type.
5100 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5101 ConstantInt *In2, bool IsSigned = false) {
5102 Result = cast<ConstantInt>(Add(In1, In2));
5105 if (In2->getValue().isNegative())
5106 return Result->getValue().sgt(In1->getValue());
5108 return Result->getValue().slt(In1->getValue());
5110 return Result->getValue().ult(In1->getValue());
5113 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5114 /// overflowed for this type.
5115 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5116 ConstantInt *In2, bool IsSigned = false) {
5117 Result = cast<ConstantInt>(Subtract(In1, In2));
5120 if (In2->getValue().isNegative())
5121 return Result->getValue().slt(In1->getValue());
5123 return Result->getValue().sgt(In1->getValue());
5125 return Result->getValue().ugt(In1->getValue());
5128 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5129 /// code necessary to compute the offset from the base pointer (without adding
5130 /// in the base pointer). Return the result as a signed integer of intptr size.
5131 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5132 TargetData &TD = IC.getTargetData();
5133 gep_type_iterator GTI = gep_type_begin(GEP);
5134 const Type *IntPtrTy = TD.getIntPtrType();
5135 Value *Result = Constant::getNullValue(IntPtrTy);
5137 // Build a mask for high order bits.
5138 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5139 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5141 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5144 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
5145 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5146 if (OpC->isZero()) continue;
5148 // Handle a struct index, which adds its field offset to the pointer.
5149 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5150 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5152 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5153 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5155 Result = IC.InsertNewInstBefore(
5156 BinaryOperator::CreateAdd(Result,
5157 ConstantInt::get(IntPtrTy, Size),
5158 GEP->getName()+".offs"), I);
5162 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5163 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5164 Scale = ConstantExpr::getMul(OC, Scale);
5165 if (Constant *RC = dyn_cast<Constant>(Result))
5166 Result = ConstantExpr::getAdd(RC, Scale);
5168 // Emit an add instruction.
5169 Result = IC.InsertNewInstBefore(
5170 BinaryOperator::CreateAdd(Result, Scale,
5171 GEP->getName()+".offs"), I);
5175 // Convert to correct type.
5176 if (Op->getType() != IntPtrTy) {
5177 if (Constant *OpC = dyn_cast<Constant>(Op))
5178 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5180 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5181 Op->getName()+".c"), I);
5184 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5185 if (Constant *OpC = dyn_cast<Constant>(Op))
5186 Op = ConstantExpr::getMul(OpC, Scale);
5187 else // We'll let instcombine(mul) convert this to a shl if possible.
5188 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5189 GEP->getName()+".idx"), I);
5192 // Emit an add instruction.
5193 if (isa<Constant>(Op) && isa<Constant>(Result))
5194 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5195 cast<Constant>(Result));
5197 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5198 GEP->getName()+".offs"), I);
5204 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5205 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5206 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5207 /// complex, and scales are involved. The above expression would also be legal
5208 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5209 /// later form is less amenable to optimization though, and we are allowed to
5210 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5212 /// If we can't emit an optimized form for this expression, this returns null.
5214 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5216 TargetData &TD = IC.getTargetData();
5217 gep_type_iterator GTI = gep_type_begin(GEP);
5219 // Check to see if this gep only has a single variable index. If so, and if
5220 // any constant indices are a multiple of its scale, then we can compute this
5221 // in terms of the scale of the variable index. For example, if the GEP
5222 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5223 // because the expression will cross zero at the same point.
5224 unsigned i, e = GEP->getNumOperands();
5226 for (i = 1; i != e; ++i, ++GTI) {
5227 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5228 // Compute the aggregate offset of constant indices.
5229 if (CI->isZero()) continue;
5231 // Handle a struct index, which adds its field offset to the pointer.
5232 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5233 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5235 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5236 Offset += Size*CI->getSExtValue();
5239 // Found our variable index.
5244 // If there are no variable indices, we must have a constant offset, just
5245 // evaluate it the general way.
5246 if (i == e) return 0;
5248 Value *VariableIdx = GEP->getOperand(i);
5249 // Determine the scale factor of the variable element. For example, this is
5250 // 4 if the variable index is into an array of i32.
5251 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
5253 // Verify that there are no other variable indices. If so, emit the hard way.
5254 for (++i, ++GTI; i != e; ++i, ++GTI) {
5255 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5258 // Compute the aggregate offset of constant indices.
5259 if (CI->isZero()) continue;
5261 // Handle a struct index, which adds its field offset to the pointer.
5262 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5263 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5265 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5266 Offset += Size*CI->getSExtValue();
5270 // Okay, we know we have a single variable index, which must be a
5271 // pointer/array/vector index. If there is no offset, life is simple, return
5273 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5275 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5276 // we don't need to bother extending: the extension won't affect where the
5277 // computation crosses zero.
5278 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5279 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5280 VariableIdx->getNameStart(), &I);
5284 // Otherwise, there is an index. The computation we will do will be modulo
5285 // the pointer size, so get it.
5286 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5288 Offset &= PtrSizeMask;
5289 VariableScale &= PtrSizeMask;
5291 // To do this transformation, any constant index must be a multiple of the
5292 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5293 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5294 // multiple of the variable scale.
5295 int64_t NewOffs = Offset / (int64_t)VariableScale;
5296 if (Offset != NewOffs*(int64_t)VariableScale)
5299 // Okay, we can do this evaluation. Start by converting the index to intptr.
5300 const Type *IntPtrTy = TD.getIntPtrType();
5301 if (VariableIdx->getType() != IntPtrTy)
5302 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5304 VariableIdx->getNameStart(), &I);
5305 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5306 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5310 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5311 /// else. At this point we know that the GEP is on the LHS of the comparison.
5312 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5313 ICmpInst::Predicate Cond,
5315 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5317 // Look through bitcasts.
5318 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5319 RHS = BCI->getOperand(0);
5321 Value *PtrBase = GEPLHS->getOperand(0);
5322 if (PtrBase == RHS) {
5323 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5324 // This transformation (ignoring the base and scales) is valid because we
5325 // know pointers can't overflow. See if we can output an optimized form.
5326 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5328 // If not, synthesize the offset the hard way.
5330 Offset = EmitGEPOffset(GEPLHS, I, *this);
5331 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5332 Constant::getNullValue(Offset->getType()));
5333 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5334 // If the base pointers are different, but the indices are the same, just
5335 // compare the base pointer.
5336 if (PtrBase != GEPRHS->getOperand(0)) {
5337 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5338 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5339 GEPRHS->getOperand(0)->getType();
5341 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5342 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5343 IndicesTheSame = false;
5347 // If all indices are the same, just compare the base pointers.
5349 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5350 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5352 // Otherwise, the base pointers are different and the indices are
5353 // different, bail out.
5357 // If one of the GEPs has all zero indices, recurse.
5358 bool AllZeros = true;
5359 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5360 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5361 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5366 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5367 ICmpInst::getSwappedPredicate(Cond), I);
5369 // If the other GEP has all zero indices, recurse.
5371 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5372 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5373 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5378 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5380 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5381 // If the GEPs only differ by one index, compare it.
5382 unsigned NumDifferences = 0; // Keep track of # differences.
5383 unsigned DiffOperand = 0; // The operand that differs.
5384 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5385 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5386 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5387 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5388 // Irreconcilable differences.
5392 if (NumDifferences++) break;
5397 if (NumDifferences == 0) // SAME GEP?
5398 return ReplaceInstUsesWith(I, // No comparison is needed here.
5399 ConstantInt::get(Type::Int1Ty,
5400 ICmpInst::isTrueWhenEqual(Cond)));
5402 else if (NumDifferences == 1) {
5403 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5404 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5405 // Make sure we do a signed comparison here.
5406 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5410 // Only lower this if the icmp is the only user of the GEP or if we expect
5411 // the result to fold to a constant!
5412 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5413 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5414 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5415 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5416 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5417 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5423 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5425 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5428 if (!isa<ConstantFP>(RHSC)) return 0;
5429 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5431 // Get the width of the mantissa. We don't want to hack on conversions that
5432 // might lose information from the integer, e.g. "i64 -> float"
5433 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5434 if (MantissaWidth == -1) return 0; // Unknown.
5436 // Check to see that the input is converted from an integer type that is small
5437 // enough that preserves all bits. TODO: check here for "known" sign bits.
5438 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5439 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5441 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5442 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5446 // If the conversion would lose info, don't hack on this.
5447 if ((int)InputSize > MantissaWidth)
5450 // Otherwise, we can potentially simplify the comparison. We know that it
5451 // will always come through as an integer value and we know the constant is
5452 // not a NAN (it would have been previously simplified).
5453 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5455 ICmpInst::Predicate Pred;
5456 switch (I.getPredicate()) {
5457 default: assert(0 && "Unexpected predicate!");
5458 case FCmpInst::FCMP_UEQ:
5459 case FCmpInst::FCMP_OEQ:
5460 Pred = ICmpInst::ICMP_EQ;
5462 case FCmpInst::FCMP_UGT:
5463 case FCmpInst::FCMP_OGT:
5464 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5466 case FCmpInst::FCMP_UGE:
5467 case FCmpInst::FCMP_OGE:
5468 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5470 case FCmpInst::FCMP_ULT:
5471 case FCmpInst::FCMP_OLT:
5472 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5474 case FCmpInst::FCMP_ULE:
5475 case FCmpInst::FCMP_OLE:
5476 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5478 case FCmpInst::FCMP_UNE:
5479 case FCmpInst::FCMP_ONE:
5480 Pred = ICmpInst::ICMP_NE;
5482 case FCmpInst::FCMP_ORD:
5483 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5484 case FCmpInst::FCMP_UNO:
5485 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5488 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5490 // Now we know that the APFloat is a normal number, zero or inf.
5492 // See if the FP constant is too large for the integer. For example,
5493 // comparing an i8 to 300.0.
5494 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5497 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5498 // and large values.
5499 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5500 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5501 APFloat::rmNearestTiesToEven);
5502 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5503 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5504 Pred == ICmpInst::ICMP_SLE)
5505 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5506 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5509 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5510 // +INF and large values.
5511 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5512 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5513 APFloat::rmNearestTiesToEven);
5514 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5515 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5516 Pred == ICmpInst::ICMP_ULE)
5517 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5518 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5523 // See if the RHS value is < SignedMin.
5524 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5525 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5526 APFloat::rmNearestTiesToEven);
5527 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5528 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5529 Pred == ICmpInst::ICMP_SGE)
5530 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5531 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5535 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5536 // [0, UMAX], but it may still be fractional. See if it is fractional by
5537 // casting the FP value to the integer value and back, checking for equality.
5538 // Don't do this for zero, because -0.0 is not fractional.
5539 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5540 if (!RHS.isZero() &&
5541 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5542 // If we had a comparison against a fractional value, we have to adjust the
5543 // compare predicate and sometimes the value. RHSC is rounded towards zero
5546 default: assert(0 && "Unexpected integer comparison!");
5547 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5548 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5549 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5550 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5551 case ICmpInst::ICMP_ULE:
5552 // (float)int <= 4.4 --> int <= 4
5553 // (float)int <= -4.4 --> false
5554 if (RHS.isNegative())
5555 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5557 case ICmpInst::ICMP_SLE:
5558 // (float)int <= 4.4 --> int <= 4
5559 // (float)int <= -4.4 --> int < -4
5560 if (RHS.isNegative())
5561 Pred = ICmpInst::ICMP_SLT;
5563 case ICmpInst::ICMP_ULT:
5564 // (float)int < -4.4 --> false
5565 // (float)int < 4.4 --> int <= 4
5566 if (RHS.isNegative())
5567 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5568 Pred = ICmpInst::ICMP_ULE;
5570 case ICmpInst::ICMP_SLT:
5571 // (float)int < -4.4 --> int < -4
5572 // (float)int < 4.4 --> int <= 4
5573 if (!RHS.isNegative())
5574 Pred = ICmpInst::ICMP_SLE;
5576 case ICmpInst::ICMP_UGT:
5577 // (float)int > 4.4 --> int > 4
5578 // (float)int > -4.4 --> true
5579 if (RHS.isNegative())
5580 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5582 case ICmpInst::ICMP_SGT:
5583 // (float)int > 4.4 --> int > 4
5584 // (float)int > -4.4 --> int >= -4
5585 if (RHS.isNegative())
5586 Pred = ICmpInst::ICMP_SGE;
5588 case ICmpInst::ICMP_UGE:
5589 // (float)int >= -4.4 --> true
5590 // (float)int >= 4.4 --> int > 4
5591 if (!RHS.isNegative())
5592 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5593 Pred = ICmpInst::ICMP_UGT;
5595 case ICmpInst::ICMP_SGE:
5596 // (float)int >= -4.4 --> int >= -4
5597 // (float)int >= 4.4 --> int > 4
5598 if (!RHS.isNegative())
5599 Pred = ICmpInst::ICMP_SGT;
5604 // Lower this FP comparison into an appropriate integer version of the
5606 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5609 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5610 bool Changed = SimplifyCompare(I);
5611 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5613 // Fold trivial predicates.
5614 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5615 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5616 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5617 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5619 // Simplify 'fcmp pred X, X'
5621 switch (I.getPredicate()) {
5622 default: assert(0 && "Unknown predicate!");
5623 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5624 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5625 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5626 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5627 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5628 case FCmpInst::FCMP_OLT: // True if ordered and less than
5629 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5630 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5632 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5633 case FCmpInst::FCMP_ULT: // True if unordered or less than
5634 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5635 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5636 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5637 I.setPredicate(FCmpInst::FCMP_UNO);
5638 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5641 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5642 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5643 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5644 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5645 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5646 I.setPredicate(FCmpInst::FCMP_ORD);
5647 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5652 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5653 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5655 // Handle fcmp with constant RHS
5656 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5657 // If the constant is a nan, see if we can fold the comparison based on it.
5658 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5659 if (CFP->getValueAPF().isNaN()) {
5660 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5661 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5662 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5663 "Comparison must be either ordered or unordered!");
5664 // True if unordered.
5665 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5669 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5670 switch (LHSI->getOpcode()) {
5671 case Instruction::PHI:
5672 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5673 // block. If in the same block, we're encouraging jump threading. If
5674 // not, we are just pessimizing the code by making an i1 phi.
5675 if (LHSI->getParent() == I.getParent())
5676 if (Instruction *NV = FoldOpIntoPhi(I))
5679 case Instruction::SIToFP:
5680 case Instruction::UIToFP:
5681 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5684 case Instruction::Select:
5685 // If either operand of the select is a constant, we can fold the
5686 // comparison into the select arms, which will cause one to be
5687 // constant folded and the select turned into a bitwise or.
5688 Value *Op1 = 0, *Op2 = 0;
5689 if (LHSI->hasOneUse()) {
5690 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5691 // Fold the known value into the constant operand.
5692 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5693 // Insert a new FCmp of the other select operand.
5694 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5695 LHSI->getOperand(2), RHSC,
5697 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5698 // Fold the known value into the constant operand.
5699 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5700 // Insert a new FCmp of the other select operand.
5701 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5702 LHSI->getOperand(1), RHSC,
5708 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5713 return Changed ? &I : 0;
5716 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5717 bool Changed = SimplifyCompare(I);
5718 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5719 const Type *Ty = Op0->getType();
5723 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5724 I.isTrueWhenEqual()));
5726 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5727 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5729 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5730 // addresses never equal each other! We already know that Op0 != Op1.
5731 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5732 isa<ConstantPointerNull>(Op0)) &&
5733 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5734 isa<ConstantPointerNull>(Op1)))
5735 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5736 !I.isTrueWhenEqual()));
5738 // icmp's with boolean values can always be turned into bitwise operations
5739 if (Ty == Type::Int1Ty) {
5740 switch (I.getPredicate()) {
5741 default: assert(0 && "Invalid icmp instruction!");
5742 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5743 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5744 InsertNewInstBefore(Xor, I);
5745 return BinaryOperator::CreateNot(Xor);
5747 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5748 return BinaryOperator::CreateXor(Op0, Op1);
5750 case ICmpInst::ICMP_UGT:
5751 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5753 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5754 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5755 InsertNewInstBefore(Not, I);
5756 return BinaryOperator::CreateAnd(Not, Op1);
5758 case ICmpInst::ICMP_SGT:
5759 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5761 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5762 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5763 InsertNewInstBefore(Not, I);
5764 return BinaryOperator::CreateAnd(Not, Op0);
5766 case ICmpInst::ICMP_UGE:
5767 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5769 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
5770 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5771 InsertNewInstBefore(Not, I);
5772 return BinaryOperator::CreateOr(Not, Op1);
5774 case ICmpInst::ICMP_SGE:
5775 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5777 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5778 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5779 InsertNewInstBefore(Not, I);
5780 return BinaryOperator::CreateOr(Not, Op0);
5785 // See if we are doing a comparison with a constant.
5786 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5789 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5790 if (I.isEquality() && CI->isNullValue() &&
5791 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5792 // (icmp cond A B) if cond is equality
5793 return new ICmpInst(I.getPredicate(), A, B);
5796 // If we have an icmp le or icmp ge instruction, turn it into the
5797 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5798 // them being folded in the code below.
5799 switch (I.getPredicate()) {
5801 case ICmpInst::ICMP_ULE:
5802 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5803 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5804 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5805 case ICmpInst::ICMP_SLE:
5806 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5807 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5808 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5809 case ICmpInst::ICMP_UGE:
5810 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5811 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5812 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5813 case ICmpInst::ICMP_SGE:
5814 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5815 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5816 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5819 // See if we can fold the comparison based on range information we can get
5820 // by checking whether bits are known to be zero or one in the input.
5821 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5822 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5824 // If this comparison is a normal comparison, it demands all
5825 // bits, if it is a sign bit comparison, it only demands the sign bit.
5827 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5829 if (SimplifyDemandedBits(Op0,
5830 isSignBit ? APInt::getSignBit(BitWidth)
5831 : APInt::getAllOnesValue(BitWidth),
5832 KnownZero, KnownOne, 0))
5835 // Given the known and unknown bits, compute a range that the LHS could be
5836 // in. Compute the Min, Max and RHS values based on the known bits. For the
5837 // EQ and NE we use unsigned values.
5838 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5839 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5840 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5842 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5844 // If Min and Max are known to be the same, then SimplifyDemandedBits
5845 // figured out that the LHS is a constant. Just constant fold this now so
5846 // that code below can assume that Min != Max.
5848 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5849 ConstantInt::get(Min),
5852 // Based on the range information we know about the LHS, see if we can
5853 // simplify this comparison. For example, (x&4) < 8 is always true.
5854 const APInt &RHSVal = CI->getValue();
5855 switch (I.getPredicate()) { // LE/GE have been folded already.
5856 default: assert(0 && "Unknown icmp opcode!");
5857 case ICmpInst::ICMP_EQ:
5858 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5859 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5861 case ICmpInst::ICMP_NE:
5862 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5863 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5865 case ICmpInst::ICMP_ULT:
5866 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
5867 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5868 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
5869 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5870 if (RHSVal == Max) // A <u MAX -> A != MAX
5871 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5872 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5873 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5875 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5876 if (CI->isMinValue(true))
5877 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5878 ConstantInt::getAllOnesValue(Op0->getType()));
5880 case ICmpInst::ICMP_UGT:
5881 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
5882 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5883 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
5884 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5886 if (RHSVal == Min) // A >u MIN -> A != MIN
5887 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5888 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5889 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5891 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5892 if (CI->isMaxValue(true))
5893 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5894 ConstantInt::getNullValue(Op0->getType()));
5896 case ICmpInst::ICMP_SLT:
5897 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
5898 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5899 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
5900 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5901 if (RHSVal == Max) // A <s MAX -> A != MAX
5902 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5903 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
5904 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5906 case ICmpInst::ICMP_SGT:
5907 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
5908 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5909 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
5910 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5912 if (RHSVal == Min) // A >s MIN -> A != MIN
5913 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5914 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5915 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5920 // Test if the ICmpInst instruction is used exclusively by a select as
5921 // part of a minimum or maximum operation. If so, refrain from doing
5922 // any other folding. This helps out other analyses which understand
5923 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5924 // and CodeGen. And in this case, at least one of the comparison
5925 // operands has at least one user besides the compare (the select),
5926 // which would often largely negate the benefit of folding anyway.
5928 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5929 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5930 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5933 // See if we are doing a comparison between a constant and an instruction that
5934 // can be folded into the comparison.
5935 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5936 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5937 // instruction, see if that instruction also has constants so that the
5938 // instruction can be folded into the icmp
5939 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5940 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5944 // Handle icmp with constant (but not simple integer constant) RHS
5945 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5946 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5947 switch (LHSI->getOpcode()) {
5948 case Instruction::GetElementPtr:
5949 if (RHSC->isNullValue()) {
5950 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5951 bool isAllZeros = true;
5952 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5953 if (!isa<Constant>(LHSI->getOperand(i)) ||
5954 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5959 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5960 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5964 case Instruction::PHI:
5965 // Only fold icmp into the PHI if the phi and fcmp are in the same
5966 // block. If in the same block, we're encouraging jump threading. If
5967 // not, we are just pessimizing the code by making an i1 phi.
5968 if (LHSI->getParent() == I.getParent())
5969 if (Instruction *NV = FoldOpIntoPhi(I))
5972 case Instruction::Select: {
5973 // If either operand of the select is a constant, we can fold the
5974 // comparison into the select arms, which will cause one to be
5975 // constant folded and the select turned into a bitwise or.
5976 Value *Op1 = 0, *Op2 = 0;
5977 if (LHSI->hasOneUse()) {
5978 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5979 // Fold the known value into the constant operand.
5980 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5981 // Insert a new ICmp of the other select operand.
5982 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5983 LHSI->getOperand(2), RHSC,
5985 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5986 // Fold the known value into the constant operand.
5987 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5988 // Insert a new ICmp of the other select operand.
5989 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5990 LHSI->getOperand(1), RHSC,
5996 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5999 case Instruction::Malloc:
6000 // If we have (malloc != null), and if the malloc has a single use, we
6001 // can assume it is successful and remove the malloc.
6002 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6003 AddToWorkList(LHSI);
6004 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6005 !I.isTrueWhenEqual()));
6011 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6012 if (User *GEP = dyn_castGetElementPtr(Op0))
6013 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6015 if (User *GEP = dyn_castGetElementPtr(Op1))
6016 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6017 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6020 // Test to see if the operands of the icmp are casted versions of other
6021 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6023 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6024 if (isa<PointerType>(Op0->getType()) &&
6025 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6026 // We keep moving the cast from the left operand over to the right
6027 // operand, where it can often be eliminated completely.
6028 Op0 = CI->getOperand(0);
6030 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6031 // so eliminate it as well.
6032 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6033 Op1 = CI2->getOperand(0);
6035 // If Op1 is a constant, we can fold the cast into the constant.
6036 if (Op0->getType() != Op1->getType()) {
6037 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6038 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6040 // Otherwise, cast the RHS right before the icmp
6041 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6044 return new ICmpInst(I.getPredicate(), Op0, Op1);
6048 if (isa<CastInst>(Op0)) {
6049 // Handle the special case of: icmp (cast bool to X), <cst>
6050 // This comes up when you have code like
6053 // For generality, we handle any zero-extension of any operand comparison
6054 // with a constant or another cast from the same type.
6055 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6056 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6060 // See if it's the same type of instruction on the left and right.
6061 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6062 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6063 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6064 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6066 switch (Op0I->getOpcode()) {
6068 case Instruction::Add:
6069 case Instruction::Sub:
6070 case Instruction::Xor:
6071 // a+x icmp eq/ne b+x --> a icmp b
6072 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6073 Op1I->getOperand(0));
6075 case Instruction::Mul:
6076 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6077 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6078 // Mask = -1 >> count-trailing-zeros(Cst).
6079 if (!CI->isZero() && !CI->isOne()) {
6080 const APInt &AP = CI->getValue();
6081 ConstantInt *Mask = ConstantInt::get(
6082 APInt::getLowBitsSet(AP.getBitWidth(),
6084 AP.countTrailingZeros()));
6085 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6087 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6089 InsertNewInstBefore(And1, I);
6090 InsertNewInstBefore(And2, I);
6091 return new ICmpInst(I.getPredicate(), And1, And2);
6100 // ~x < ~y --> y < x
6102 if (match(Op0, m_Not(m_Value(A))) &&
6103 match(Op1, m_Not(m_Value(B))))
6104 return new ICmpInst(I.getPredicate(), B, A);
6107 if (I.isEquality()) {
6108 Value *A, *B, *C, *D;
6110 // -x == -y --> x == y
6111 if (match(Op0, m_Neg(m_Value(A))) &&
6112 match(Op1, m_Neg(m_Value(B))))
6113 return new ICmpInst(I.getPredicate(), A, B);
6115 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6116 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6117 Value *OtherVal = A == Op1 ? B : A;
6118 return new ICmpInst(I.getPredicate(), OtherVal,
6119 Constant::getNullValue(A->getType()));
6122 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6123 // A^c1 == C^c2 --> A == C^(c1^c2)
6124 ConstantInt *C1, *C2;
6125 if (match(B, m_ConstantInt(C1)) &&
6126 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6127 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6128 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6129 return new ICmpInst(I.getPredicate(), A,
6130 InsertNewInstBefore(Xor, I));
6133 // A^B == A^D -> B == D
6134 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6135 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6136 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6137 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6141 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6142 (A == Op0 || B == Op0)) {
6143 // A == (A^B) -> B == 0
6144 Value *OtherVal = A == Op0 ? B : A;
6145 return new ICmpInst(I.getPredicate(), OtherVal,
6146 Constant::getNullValue(A->getType()));
6149 // (A-B) == A -> B == 0
6150 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6151 return new ICmpInst(I.getPredicate(), B,
6152 Constant::getNullValue(B->getType()));
6154 // A == (A-B) -> B == 0
6155 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6156 return new ICmpInst(I.getPredicate(), B,
6157 Constant::getNullValue(B->getType()));
6159 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6160 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6161 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6162 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6163 Value *X = 0, *Y = 0, *Z = 0;
6166 X = B; Y = D; Z = A;
6167 } else if (A == D) {
6168 X = B; Y = C; Z = A;
6169 } else if (B == C) {
6170 X = A; Y = D; Z = B;
6171 } else if (B == D) {
6172 X = A; Y = C; Z = B;
6175 if (X) { // Build (X^Y) & Z
6176 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6177 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6178 I.setOperand(0, Op1);
6179 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6184 return Changed ? &I : 0;
6188 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6189 /// and CmpRHS are both known to be integer constants.
6190 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6191 ConstantInt *DivRHS) {
6192 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6193 const APInt &CmpRHSV = CmpRHS->getValue();
6195 // FIXME: If the operand types don't match the type of the divide
6196 // then don't attempt this transform. The code below doesn't have the
6197 // logic to deal with a signed divide and an unsigned compare (and
6198 // vice versa). This is because (x /s C1) <s C2 produces different
6199 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6200 // (x /u C1) <u C2. Simply casting the operands and result won't
6201 // work. :( The if statement below tests that condition and bails
6203 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6204 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6206 if (DivRHS->isZero())
6207 return 0; // The ProdOV computation fails on divide by zero.
6208 if (DivIsSigned && DivRHS->isAllOnesValue())
6209 return 0; // The overflow computation also screws up here
6210 if (DivRHS->isOne())
6211 return 0; // Not worth bothering, and eliminates some funny cases
6214 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6215 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6216 // C2 (CI). By solving for X we can turn this into a range check
6217 // instead of computing a divide.
6218 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6220 // Determine if the product overflows by seeing if the product is
6221 // not equal to the divide. Make sure we do the same kind of divide
6222 // as in the LHS instruction that we're folding.
6223 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6224 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6226 // Get the ICmp opcode
6227 ICmpInst::Predicate Pred = ICI.getPredicate();
6229 // Figure out the interval that is being checked. For example, a comparison
6230 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6231 // Compute this interval based on the constants involved and the signedness of
6232 // the compare/divide. This computes a half-open interval, keeping track of
6233 // whether either value in the interval overflows. After analysis each
6234 // overflow variable is set to 0 if it's corresponding bound variable is valid
6235 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6236 int LoOverflow = 0, HiOverflow = 0;
6237 ConstantInt *LoBound = 0, *HiBound = 0;
6239 if (!DivIsSigned) { // udiv
6240 // e.g. X/5 op 3 --> [15, 20)
6242 HiOverflow = LoOverflow = ProdOV;
6244 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6245 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6246 if (CmpRHSV == 0) { // (X / pos) op 0
6247 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6248 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6250 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6251 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6252 HiOverflow = LoOverflow = ProdOV;
6254 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6255 } else { // (X / pos) op neg
6256 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6257 HiBound = AddOne(Prod);
6258 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6260 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6261 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6265 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6266 if (CmpRHSV == 0) { // (X / neg) op 0
6267 // e.g. X/-5 op 0 --> [-4, 5)
6268 LoBound = AddOne(DivRHS);
6269 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6270 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6271 HiOverflow = 1; // [INTMIN+1, overflow)
6272 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6274 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6275 // e.g. X/-5 op 3 --> [-19, -14)
6276 HiBound = AddOne(Prod);
6277 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6279 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6280 } else { // (X / neg) op neg
6281 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6282 LoOverflow = HiOverflow = ProdOV;
6284 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6287 // Dividing by a negative swaps the condition. LT <-> GT
6288 Pred = ICmpInst::getSwappedPredicate(Pred);
6291 Value *X = DivI->getOperand(0);
6293 default: assert(0 && "Unhandled icmp opcode!");
6294 case ICmpInst::ICMP_EQ:
6295 if (LoOverflow && HiOverflow)
6296 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6297 else if (HiOverflow)
6298 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6299 ICmpInst::ICMP_UGE, X, LoBound);
6300 else if (LoOverflow)
6301 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6302 ICmpInst::ICMP_ULT, X, HiBound);
6304 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6305 case ICmpInst::ICMP_NE:
6306 if (LoOverflow && HiOverflow)
6307 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6308 else if (HiOverflow)
6309 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6310 ICmpInst::ICMP_ULT, X, LoBound);
6311 else if (LoOverflow)
6312 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6313 ICmpInst::ICMP_UGE, X, HiBound);
6315 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6316 case ICmpInst::ICMP_ULT:
6317 case ICmpInst::ICMP_SLT:
6318 if (LoOverflow == +1) // Low bound is greater than input range.
6319 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6320 if (LoOverflow == -1) // Low bound is less than input range.
6321 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6322 return new ICmpInst(Pred, X, LoBound);
6323 case ICmpInst::ICMP_UGT:
6324 case ICmpInst::ICMP_SGT:
6325 if (HiOverflow == +1) // High bound greater than input range.
6326 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6327 else if (HiOverflow == -1) // High bound less than input range.
6328 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6329 if (Pred == ICmpInst::ICMP_UGT)
6330 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6332 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6337 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6339 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6342 const APInt &RHSV = RHS->getValue();
6344 switch (LHSI->getOpcode()) {
6345 case Instruction::Trunc:
6346 if (ICI.isEquality() && LHSI->hasOneUse()) {
6347 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6348 // of the high bits truncated out of x are known.
6349 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6350 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6351 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6352 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6353 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6355 // If all the high bits are known, we can do this xform.
6356 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6357 // Pull in the high bits from known-ones set.
6358 APInt NewRHS(RHS->getValue());
6359 NewRHS.zext(SrcBits);
6361 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6362 ConstantInt::get(NewRHS));
6367 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6368 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6369 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6371 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6372 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6373 Value *CompareVal = LHSI->getOperand(0);
6375 // If the sign bit of the XorCST is not set, there is no change to
6376 // the operation, just stop using the Xor.
6377 if (!XorCST->getValue().isNegative()) {
6378 ICI.setOperand(0, CompareVal);
6379 AddToWorkList(LHSI);
6383 // Was the old condition true if the operand is positive?
6384 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6386 // If so, the new one isn't.
6387 isTrueIfPositive ^= true;
6389 if (isTrueIfPositive)
6390 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6392 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6396 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6397 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6398 LHSI->getOperand(0)->hasOneUse()) {
6399 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6401 // If the LHS is an AND of a truncating cast, we can widen the
6402 // and/compare to be the input width without changing the value
6403 // produced, eliminating a cast.
6404 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6405 // We can do this transformation if either the AND constant does not
6406 // have its sign bit set or if it is an equality comparison.
6407 // Extending a relational comparison when we're checking the sign
6408 // bit would not work.
6409 if (Cast->hasOneUse() &&
6410 (ICI.isEquality() ||
6411 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6413 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6414 APInt NewCST = AndCST->getValue();
6415 NewCST.zext(BitWidth);
6417 NewCI.zext(BitWidth);
6418 Instruction *NewAnd =
6419 BinaryOperator::CreateAnd(Cast->getOperand(0),
6420 ConstantInt::get(NewCST),LHSI->getName());
6421 InsertNewInstBefore(NewAnd, ICI);
6422 return new ICmpInst(ICI.getPredicate(), NewAnd,
6423 ConstantInt::get(NewCI));
6427 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6428 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6429 // happens a LOT in code produced by the C front-end, for bitfield
6431 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6432 if (Shift && !Shift->isShift())
6436 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6437 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6438 const Type *AndTy = AndCST->getType(); // Type of the and.
6440 // We can fold this as long as we can't shift unknown bits
6441 // into the mask. This can only happen with signed shift
6442 // rights, as they sign-extend.
6444 bool CanFold = Shift->isLogicalShift();
6446 // To test for the bad case of the signed shr, see if any
6447 // of the bits shifted in could be tested after the mask.
6448 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6449 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6451 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6452 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6453 AndCST->getValue()) == 0)
6459 if (Shift->getOpcode() == Instruction::Shl)
6460 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6462 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6464 // Check to see if we are shifting out any of the bits being
6466 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6467 // If we shifted bits out, the fold is not going to work out.
6468 // As a special case, check to see if this means that the
6469 // result is always true or false now.
6470 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6471 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6472 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6473 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6475 ICI.setOperand(1, NewCst);
6476 Constant *NewAndCST;
6477 if (Shift->getOpcode() == Instruction::Shl)
6478 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6480 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6481 LHSI->setOperand(1, NewAndCST);
6482 LHSI->setOperand(0, Shift->getOperand(0));
6483 AddToWorkList(Shift); // Shift is dead.
6484 AddUsesToWorkList(ICI);
6490 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6491 // preferable because it allows the C<<Y expression to be hoisted out
6492 // of a loop if Y is invariant and X is not.
6493 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6494 ICI.isEquality() && !Shift->isArithmeticShift() &&
6495 isa<Instruction>(Shift->getOperand(0))) {
6498 if (Shift->getOpcode() == Instruction::LShr) {
6499 NS = BinaryOperator::CreateShl(AndCST,
6500 Shift->getOperand(1), "tmp");
6502 // Insert a logical shift.
6503 NS = BinaryOperator::CreateLShr(AndCST,
6504 Shift->getOperand(1), "tmp");
6506 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6508 // Compute X & (C << Y).
6509 Instruction *NewAnd =
6510 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6511 InsertNewInstBefore(NewAnd, ICI);
6513 ICI.setOperand(0, NewAnd);
6519 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6520 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6523 uint32_t TypeBits = RHSV.getBitWidth();
6525 // Check that the shift amount is in range. If not, don't perform
6526 // undefined shifts. When the shift is visited it will be
6528 if (ShAmt->uge(TypeBits))
6531 if (ICI.isEquality()) {
6532 // If we are comparing against bits always shifted out, the
6533 // comparison cannot succeed.
6535 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6536 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6537 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6538 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6539 return ReplaceInstUsesWith(ICI, Cst);
6542 if (LHSI->hasOneUse()) {
6543 // Otherwise strength reduce the shift into an and.
6544 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6546 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6549 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6550 Mask, LHSI->getName()+".mask");
6551 Value *And = InsertNewInstBefore(AndI, ICI);
6552 return new ICmpInst(ICI.getPredicate(), And,
6553 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6557 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6558 bool TrueIfSigned = false;
6559 if (LHSI->hasOneUse() &&
6560 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6561 // (X << 31) <s 0 --> (X&1) != 0
6562 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6563 (TypeBits-ShAmt->getZExtValue()-1));
6565 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6566 Mask, LHSI->getName()+".mask");
6567 Value *And = InsertNewInstBefore(AndI, ICI);
6569 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6570 And, Constant::getNullValue(And->getType()));
6575 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6576 case Instruction::AShr: {
6577 // Only handle equality comparisons of shift-by-constant.
6578 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6579 if (!ShAmt || !ICI.isEquality()) break;
6581 // Check that the shift amount is in range. If not, don't perform
6582 // undefined shifts. When the shift is visited it will be
6584 uint32_t TypeBits = RHSV.getBitWidth();
6585 if (ShAmt->uge(TypeBits))
6588 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6590 // If we are comparing against bits always shifted out, the
6591 // comparison cannot succeed.
6592 APInt Comp = RHSV << ShAmtVal;
6593 if (LHSI->getOpcode() == Instruction::LShr)
6594 Comp = Comp.lshr(ShAmtVal);
6596 Comp = Comp.ashr(ShAmtVal);
6598 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6599 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6600 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6601 return ReplaceInstUsesWith(ICI, Cst);
6604 // Otherwise, check to see if the bits shifted out are known to be zero.
6605 // If so, we can compare against the unshifted value:
6606 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6607 if (LHSI->hasOneUse() &&
6608 MaskedValueIsZero(LHSI->getOperand(0),
6609 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6610 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6611 ConstantExpr::getShl(RHS, ShAmt));
6614 if (LHSI->hasOneUse()) {
6615 // Otherwise strength reduce the shift into an and.
6616 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6617 Constant *Mask = ConstantInt::get(Val);
6620 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6621 Mask, LHSI->getName()+".mask");
6622 Value *And = InsertNewInstBefore(AndI, ICI);
6623 return new ICmpInst(ICI.getPredicate(), And,
6624 ConstantExpr::getShl(RHS, ShAmt));
6629 case Instruction::SDiv:
6630 case Instruction::UDiv:
6631 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6632 // Fold this div into the comparison, producing a range check.
6633 // Determine, based on the divide type, what the range is being
6634 // checked. If there is an overflow on the low or high side, remember
6635 // it, otherwise compute the range [low, hi) bounding the new value.
6636 // See: InsertRangeTest above for the kinds of replacements possible.
6637 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6638 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6643 case Instruction::Add:
6644 // Fold: icmp pred (add, X, C1), C2
6646 if (!ICI.isEquality()) {
6647 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6649 const APInt &LHSV = LHSC->getValue();
6651 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6654 if (ICI.isSignedPredicate()) {
6655 if (CR.getLower().isSignBit()) {
6656 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6657 ConstantInt::get(CR.getUpper()));
6658 } else if (CR.getUpper().isSignBit()) {
6659 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6660 ConstantInt::get(CR.getLower()));
6663 if (CR.getLower().isMinValue()) {
6664 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6665 ConstantInt::get(CR.getUpper()));
6666 } else if (CR.getUpper().isMinValue()) {
6667 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6668 ConstantInt::get(CR.getLower()));
6675 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6676 if (ICI.isEquality()) {
6677 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6679 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6680 // the second operand is a constant, simplify a bit.
6681 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6682 switch (BO->getOpcode()) {
6683 case Instruction::SRem:
6684 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6685 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6686 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6687 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6688 Instruction *NewRem =
6689 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6691 InsertNewInstBefore(NewRem, ICI);
6692 return new ICmpInst(ICI.getPredicate(), NewRem,
6693 Constant::getNullValue(BO->getType()));
6697 case Instruction::Add:
6698 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6699 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6700 if (BO->hasOneUse())
6701 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6702 Subtract(RHS, BOp1C));
6703 } else if (RHSV == 0) {
6704 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6705 // efficiently invertible, or if the add has just this one use.
6706 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6708 if (Value *NegVal = dyn_castNegVal(BOp1))
6709 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6710 else if (Value *NegVal = dyn_castNegVal(BOp0))
6711 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6712 else if (BO->hasOneUse()) {
6713 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6714 InsertNewInstBefore(Neg, ICI);
6716 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6720 case Instruction::Xor:
6721 // For the xor case, we can xor two constants together, eliminating
6722 // the explicit xor.
6723 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6724 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6725 ConstantExpr::getXor(RHS, BOC));
6728 case Instruction::Sub:
6729 // Replace (([sub|xor] A, B) != 0) with (A != B)
6731 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6735 case Instruction::Or:
6736 // If bits are being or'd in that are not present in the constant we
6737 // are comparing against, then the comparison could never succeed!
6738 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6739 Constant *NotCI = ConstantExpr::getNot(RHS);
6740 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6741 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6746 case Instruction::And:
6747 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6748 // If bits are being compared against that are and'd out, then the
6749 // comparison can never succeed!
6750 if ((RHSV & ~BOC->getValue()) != 0)
6751 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6754 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6755 if (RHS == BOC && RHSV.isPowerOf2())
6756 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6757 ICmpInst::ICMP_NE, LHSI,
6758 Constant::getNullValue(RHS->getType()));
6760 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6761 if (BOC->getValue().isSignBit()) {
6762 Value *X = BO->getOperand(0);
6763 Constant *Zero = Constant::getNullValue(X->getType());
6764 ICmpInst::Predicate pred = isICMP_NE ?
6765 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6766 return new ICmpInst(pred, X, Zero);
6769 // ((X & ~7) == 0) --> X < 8
6770 if (RHSV == 0 && isHighOnes(BOC)) {
6771 Value *X = BO->getOperand(0);
6772 Constant *NegX = ConstantExpr::getNeg(BOC);
6773 ICmpInst::Predicate pred = isICMP_NE ?
6774 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6775 return new ICmpInst(pred, X, NegX);
6780 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6781 // Handle icmp {eq|ne} <intrinsic>, intcst.
6782 if (II->getIntrinsicID() == Intrinsic::bswap) {
6784 ICI.setOperand(0, II->getOperand(1));
6785 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6793 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6794 /// We only handle extending casts so far.
6796 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6797 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6798 Value *LHSCIOp = LHSCI->getOperand(0);
6799 const Type *SrcTy = LHSCIOp->getType();
6800 const Type *DestTy = LHSCI->getType();
6803 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6804 // integer type is the same size as the pointer type.
6805 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6806 getTargetData().getPointerSizeInBits() ==
6807 cast<IntegerType>(DestTy)->getBitWidth()) {
6809 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6810 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6811 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6812 RHSOp = RHSC->getOperand(0);
6813 // If the pointer types don't match, insert a bitcast.
6814 if (LHSCIOp->getType() != RHSOp->getType())
6815 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6819 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6822 // The code below only handles extension cast instructions, so far.
6824 if (LHSCI->getOpcode() != Instruction::ZExt &&
6825 LHSCI->getOpcode() != Instruction::SExt)
6828 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6829 bool isSignedCmp = ICI.isSignedPredicate();
6831 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6832 // Not an extension from the same type?
6833 RHSCIOp = CI->getOperand(0);
6834 if (RHSCIOp->getType() != LHSCIOp->getType())
6837 // If the signedness of the two casts doesn't agree (i.e. one is a sext
6838 // and the other is a zext), then we can't handle this.
6839 if (CI->getOpcode() != LHSCI->getOpcode())
6842 // Deal with equality cases early.
6843 if (ICI.isEquality())
6844 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6846 // A signed comparison of sign extended values simplifies into a
6847 // signed comparison.
6848 if (isSignedCmp && isSignedExt)
6849 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6851 // The other three cases all fold into an unsigned comparison.
6852 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6855 // If we aren't dealing with a constant on the RHS, exit early
6856 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6860 // Compute the constant that would happen if we truncated to SrcTy then
6861 // reextended to DestTy.
6862 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6863 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6865 // If the re-extended constant didn't change...
6867 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6868 // For example, we might have:
6869 // %A = sext short %X to uint
6870 // %B = icmp ugt uint %A, 1330
6871 // It is incorrect to transform this into
6872 // %B = icmp ugt short %X, 1330
6873 // because %A may have negative value.
6875 // However, we allow this when the compare is EQ/NE, because they are
6877 if (isSignedExt == isSignedCmp || ICI.isEquality())
6878 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6882 // The re-extended constant changed so the constant cannot be represented
6883 // in the shorter type. Consequently, we cannot emit a simple comparison.
6885 // First, handle some easy cases. We know the result cannot be equal at this
6886 // point so handle the ICI.isEquality() cases
6887 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6888 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6889 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6890 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6892 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6893 // should have been folded away previously and not enter in here.
6896 // We're performing a signed comparison.
6897 if (cast<ConstantInt>(CI)->getValue().isNegative())
6898 Result = ConstantInt::getFalse(); // X < (small) --> false
6900 Result = ConstantInt::getTrue(); // X < (large) --> true
6902 // We're performing an unsigned comparison.
6904 // We're performing an unsigned comp with a sign extended value.
6905 // This is true if the input is >= 0. [aka >s -1]
6906 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6907 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6908 NegOne, ICI.getName()), ICI);
6910 // Unsigned extend & unsigned compare -> always true.
6911 Result = ConstantInt::getTrue();
6915 // Finally, return the value computed.
6916 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6917 ICI.getPredicate() == ICmpInst::ICMP_SLT)
6918 return ReplaceInstUsesWith(ICI, Result);
6920 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6921 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6922 "ICmp should be folded!");
6923 if (Constant *CI = dyn_cast<Constant>(Result))
6924 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6925 return BinaryOperator::CreateNot(Result);
6928 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6929 return commonShiftTransforms(I);
6932 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6933 return commonShiftTransforms(I);
6936 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6937 if (Instruction *R = commonShiftTransforms(I))
6940 Value *Op0 = I.getOperand(0);
6942 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6943 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6944 if (CSI->isAllOnesValue())
6945 return ReplaceInstUsesWith(I, CSI);
6947 // See if we can turn a signed shr into an unsigned shr.
6948 if (!isa<VectorType>(I.getType()) &&
6949 MaskedValueIsZero(Op0,
6950 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6951 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6956 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6957 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6958 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6960 // shl X, 0 == X and shr X, 0 == X
6961 // shl 0, X == 0 and shr 0, X == 0
6962 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6963 Op0 == Constant::getNullValue(Op0->getType()))
6964 return ReplaceInstUsesWith(I, Op0);
6966 if (isa<UndefValue>(Op0)) {
6967 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6968 return ReplaceInstUsesWith(I, Op0);
6969 else // undef << X -> 0, undef >>u X -> 0
6970 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6972 if (isa<UndefValue>(Op1)) {
6973 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6974 return ReplaceInstUsesWith(I, Op0);
6975 else // X << undef, X >>u undef -> 0
6976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6979 // Try to fold constant and into select arguments.
6980 if (isa<Constant>(Op0))
6981 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6982 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6985 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6986 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6991 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6992 BinaryOperator &I) {
6993 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6995 // See if we can simplify any instructions used by the instruction whose sole
6996 // purpose is to compute bits we don't care about.
6997 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6998 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6999 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
7000 KnownZero, KnownOne))
7003 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7004 // of a signed value.
7006 if (Op1->uge(TypeBits)) {
7007 if (I.getOpcode() != Instruction::AShr)
7008 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7010 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7015 // ((X*C1) << C2) == (X * (C1 << C2))
7016 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7017 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7018 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7019 return BinaryOperator::CreateMul(BO->getOperand(0),
7020 ConstantExpr::getShl(BOOp, Op1));
7022 // Try to fold constant and into select arguments.
7023 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7024 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7026 if (isa<PHINode>(Op0))
7027 if (Instruction *NV = FoldOpIntoPhi(I))
7030 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7031 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7032 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7033 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7034 // place. Don't try to do this transformation in this case. Also, we
7035 // require that the input operand is a shift-by-constant so that we have
7036 // confidence that the shifts will get folded together. We could do this
7037 // xform in more cases, but it is unlikely to be profitable.
7038 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7039 isa<ConstantInt>(TrOp->getOperand(1))) {
7040 // Okay, we'll do this xform. Make the shift of shift.
7041 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7042 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7044 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7046 // For logical shifts, the truncation has the effect of making the high
7047 // part of the register be zeros. Emulate this by inserting an AND to
7048 // clear the top bits as needed. This 'and' will usually be zapped by
7049 // other xforms later if dead.
7050 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7051 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7052 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7054 // The mask we constructed says what the trunc would do if occurring
7055 // between the shifts. We want to know the effect *after* the second
7056 // shift. We know that it is a logical shift by a constant, so adjust the
7057 // mask as appropriate.
7058 if (I.getOpcode() == Instruction::Shl)
7059 MaskV <<= Op1->getZExtValue();
7061 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7062 MaskV = MaskV.lshr(Op1->getZExtValue());
7065 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7067 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7069 // Return the value truncated to the interesting size.
7070 return new TruncInst(And, I.getType());
7074 if (Op0->hasOneUse()) {
7075 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7076 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7079 switch (Op0BO->getOpcode()) {
7081 case Instruction::Add:
7082 case Instruction::And:
7083 case Instruction::Or:
7084 case Instruction::Xor: {
7085 // These operators commute.
7086 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7087 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7088 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7089 Instruction *YS = BinaryOperator::CreateShl(
7090 Op0BO->getOperand(0), Op1,
7092 InsertNewInstBefore(YS, I); // (Y << C)
7094 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7095 Op0BO->getOperand(1)->getName());
7096 InsertNewInstBefore(X, I); // (X + (Y << C))
7097 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7098 return BinaryOperator::CreateAnd(X, ConstantInt::get(
7099 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7102 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7103 Value *Op0BOOp1 = Op0BO->getOperand(1);
7104 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7106 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7107 m_ConstantInt(CC))) &&
7108 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7109 Instruction *YS = BinaryOperator::CreateShl(
7110 Op0BO->getOperand(0), Op1,
7112 InsertNewInstBefore(YS, I); // (Y << C)
7114 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7115 V1->getName()+".mask");
7116 InsertNewInstBefore(XM, I); // X & (CC << C)
7118 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7123 case Instruction::Sub: {
7124 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7125 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7126 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7127 Instruction *YS = BinaryOperator::CreateShl(
7128 Op0BO->getOperand(1), Op1,
7130 InsertNewInstBefore(YS, I); // (Y << C)
7132 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7133 Op0BO->getOperand(0)->getName());
7134 InsertNewInstBefore(X, I); // (X + (Y << C))
7135 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7136 return BinaryOperator::CreateAnd(X, ConstantInt::get(
7137 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7140 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7141 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7142 match(Op0BO->getOperand(0),
7143 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7144 m_ConstantInt(CC))) && V2 == Op1 &&
7145 cast<BinaryOperator>(Op0BO->getOperand(0))
7146 ->getOperand(0)->hasOneUse()) {
7147 Instruction *YS = BinaryOperator::CreateShl(
7148 Op0BO->getOperand(1), Op1,
7150 InsertNewInstBefore(YS, I); // (Y << C)
7152 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7153 V1->getName()+".mask");
7154 InsertNewInstBefore(XM, I); // X & (CC << C)
7156 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7164 // If the operand is an bitwise operator with a constant RHS, and the
7165 // shift is the only use, we can pull it out of the shift.
7166 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7167 bool isValid = true; // Valid only for And, Or, Xor
7168 bool highBitSet = false; // Transform if high bit of constant set?
7170 switch (Op0BO->getOpcode()) {
7171 default: isValid = false; break; // Do not perform transform!
7172 case Instruction::Add:
7173 isValid = isLeftShift;
7175 case Instruction::Or:
7176 case Instruction::Xor:
7179 case Instruction::And:
7184 // If this is a signed shift right, and the high bit is modified
7185 // by the logical operation, do not perform the transformation.
7186 // The highBitSet boolean indicates the value of the high bit of
7187 // the constant which would cause it to be modified for this
7190 if (isValid && I.getOpcode() == Instruction::AShr)
7191 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7194 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7196 Instruction *NewShift =
7197 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7198 InsertNewInstBefore(NewShift, I);
7199 NewShift->takeName(Op0BO);
7201 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7208 // Find out if this is a shift of a shift by a constant.
7209 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7210 if (ShiftOp && !ShiftOp->isShift())
7213 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7214 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7215 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7216 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7217 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7218 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7219 Value *X = ShiftOp->getOperand(0);
7221 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7222 if (AmtSum > TypeBits)
7225 const IntegerType *Ty = cast<IntegerType>(I.getType());
7227 // Check for (X << c1) << c2 and (X >> c1) >> c2
7228 if (I.getOpcode() == ShiftOp->getOpcode()) {
7229 return BinaryOperator::Create(I.getOpcode(), X,
7230 ConstantInt::get(Ty, AmtSum));
7231 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7232 I.getOpcode() == Instruction::AShr) {
7233 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7234 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7235 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7236 I.getOpcode() == Instruction::LShr) {
7237 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7238 Instruction *Shift =
7239 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7240 InsertNewInstBefore(Shift, I);
7242 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7243 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7246 // Okay, if we get here, one shift must be left, and the other shift must be
7247 // right. See if the amounts are equal.
7248 if (ShiftAmt1 == ShiftAmt2) {
7249 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7250 if (I.getOpcode() == Instruction::Shl) {
7251 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7252 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7254 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7255 if (I.getOpcode() == Instruction::LShr) {
7256 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7257 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7259 // We can simplify ((X << C) >>s C) into a trunc + sext.
7260 // NOTE: we could do this for any C, but that would make 'unusual' integer
7261 // types. For now, just stick to ones well-supported by the code
7263 const Type *SExtType = 0;
7264 switch (Ty->getBitWidth() - ShiftAmt1) {
7271 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7276 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7277 InsertNewInstBefore(NewTrunc, I);
7278 return new SExtInst(NewTrunc, Ty);
7280 // Otherwise, we can't handle it yet.
7281 } else if (ShiftAmt1 < ShiftAmt2) {
7282 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7284 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7285 if (I.getOpcode() == Instruction::Shl) {
7286 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7287 ShiftOp->getOpcode() == Instruction::AShr);
7288 Instruction *Shift =
7289 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7290 InsertNewInstBefore(Shift, I);
7292 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7293 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7296 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7297 if (I.getOpcode() == Instruction::LShr) {
7298 assert(ShiftOp->getOpcode() == Instruction::Shl);
7299 Instruction *Shift =
7300 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7301 InsertNewInstBefore(Shift, I);
7303 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7304 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7307 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7309 assert(ShiftAmt2 < ShiftAmt1);
7310 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7312 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7313 if (I.getOpcode() == Instruction::Shl) {
7314 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7315 ShiftOp->getOpcode() == Instruction::AShr);
7316 Instruction *Shift =
7317 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7318 ConstantInt::get(Ty, ShiftDiff));
7319 InsertNewInstBefore(Shift, I);
7321 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7322 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7325 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7326 if (I.getOpcode() == Instruction::LShr) {
7327 assert(ShiftOp->getOpcode() == Instruction::Shl);
7328 Instruction *Shift =
7329 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7330 InsertNewInstBefore(Shift, I);
7332 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7333 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7336 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7343 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7344 /// expression. If so, decompose it, returning some value X, such that Val is
7347 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7349 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7350 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7351 Offset = CI->getZExtValue();
7353 return ConstantInt::get(Type::Int32Ty, 0);
7354 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7355 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7356 if (I->getOpcode() == Instruction::Shl) {
7357 // This is a value scaled by '1 << the shift amt'.
7358 Scale = 1U << RHS->getZExtValue();
7360 return I->getOperand(0);
7361 } else if (I->getOpcode() == Instruction::Mul) {
7362 // This value is scaled by 'RHS'.
7363 Scale = RHS->getZExtValue();
7365 return I->getOperand(0);
7366 } else if (I->getOpcode() == Instruction::Add) {
7367 // We have X+C. Check to see if we really have (X*C2)+C1,
7368 // where C1 is divisible by C2.
7371 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7372 Offset += RHS->getZExtValue();
7379 // Otherwise, we can't look past this.
7386 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7387 /// try to eliminate the cast by moving the type information into the alloc.
7388 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7389 AllocationInst &AI) {
7390 const PointerType *PTy = cast<PointerType>(CI.getType());
7392 // Remove any uses of AI that are dead.
7393 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7395 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7396 Instruction *User = cast<Instruction>(*UI++);
7397 if (isInstructionTriviallyDead(User)) {
7398 while (UI != E && *UI == User)
7399 ++UI; // If this instruction uses AI more than once, don't break UI.
7402 DOUT << "IC: DCE: " << *User;
7403 EraseInstFromFunction(*User);
7407 // Get the type really allocated and the type casted to.
7408 const Type *AllocElTy = AI.getAllocatedType();
7409 const Type *CastElTy = PTy->getElementType();
7410 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7412 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7413 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7414 if (CastElTyAlign < AllocElTyAlign) return 0;
7416 // If the allocation has multiple uses, only promote it if we are strictly
7417 // increasing the alignment of the resultant allocation. If we keep it the
7418 // same, we open the door to infinite loops of various kinds.
7419 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7421 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7422 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
7423 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7425 // See if we can satisfy the modulus by pulling a scale out of the array
7427 unsigned ArraySizeScale;
7429 Value *NumElements = // See if the array size is a decomposable linear expr.
7430 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7432 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7434 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7435 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7437 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7442 // If the allocation size is constant, form a constant mul expression
7443 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7444 if (isa<ConstantInt>(NumElements))
7445 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7446 // otherwise multiply the amount and the number of elements
7447 else if (Scale != 1) {
7448 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7449 Amt = InsertNewInstBefore(Tmp, AI);
7453 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7454 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7455 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7456 Amt = InsertNewInstBefore(Tmp, AI);
7459 AllocationInst *New;
7460 if (isa<MallocInst>(AI))
7461 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7463 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7464 InsertNewInstBefore(New, AI);
7467 // If the allocation has multiple uses, insert a cast and change all things
7468 // that used it to use the new cast. This will also hack on CI, but it will
7470 if (!AI.hasOneUse()) {
7471 AddUsesToWorkList(AI);
7472 // New is the allocation instruction, pointer typed. AI is the original
7473 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7474 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7475 InsertNewInstBefore(NewCast, AI);
7476 AI.replaceAllUsesWith(NewCast);
7478 return ReplaceInstUsesWith(CI, New);
7481 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7482 /// and return it as type Ty without inserting any new casts and without
7483 /// changing the computed value. This is used by code that tries to decide
7484 /// whether promoting or shrinking integer operations to wider or smaller types
7485 /// will allow us to eliminate a truncate or extend.
7487 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7488 /// extension operation if Ty is larger.
7490 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7491 /// should return true if trunc(V) can be computed by computing V in the smaller
7492 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7493 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7494 /// efficiently truncated.
7496 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7497 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7498 /// the final result.
7499 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7501 int &NumCastsRemoved){
7502 // We can always evaluate constants in another type.
7503 if (isa<ConstantInt>(V))
7506 Instruction *I = dyn_cast<Instruction>(V);
7507 if (!I) return false;
7509 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7511 // If this is an extension or truncate, we can often eliminate it.
7512 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7513 // If this is a cast from the destination type, we can trivially eliminate
7514 // it, and this will remove a cast overall.
7515 if (I->getOperand(0)->getType() == Ty) {
7516 // If the first operand is itself a cast, and is eliminable, do not count
7517 // this as an eliminable cast. We would prefer to eliminate those two
7519 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7525 // We can't extend or shrink something that has multiple uses: doing so would
7526 // require duplicating the instruction in general, which isn't profitable.
7527 if (!I->hasOneUse()) return false;
7529 unsigned Opc = I->getOpcode();
7531 case Instruction::Add:
7532 case Instruction::Sub:
7533 case Instruction::Mul:
7534 case Instruction::And:
7535 case Instruction::Or:
7536 case Instruction::Xor:
7537 // These operators can all arbitrarily be extended or truncated.
7538 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7540 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7543 case Instruction::Shl:
7544 // If we are truncating the result of this SHL, and if it's a shift of a
7545 // constant amount, we can always perform a SHL in a smaller type.
7546 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7547 uint32_t BitWidth = Ty->getBitWidth();
7548 if (BitWidth < OrigTy->getBitWidth() &&
7549 CI->getLimitedValue(BitWidth) < BitWidth)
7550 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7554 case Instruction::LShr:
7555 // If this is a truncate of a logical shr, we can truncate it to a smaller
7556 // lshr iff we know that the bits we would otherwise be shifting in are
7558 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7559 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7560 uint32_t BitWidth = Ty->getBitWidth();
7561 if (BitWidth < OrigBitWidth &&
7562 MaskedValueIsZero(I->getOperand(0),
7563 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7564 CI->getLimitedValue(BitWidth) < BitWidth) {
7565 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7570 case Instruction::ZExt:
7571 case Instruction::SExt:
7572 case Instruction::Trunc:
7573 // If this is the same kind of case as our original (e.g. zext+zext), we
7574 // can safely replace it. Note that replacing it does not reduce the number
7575 // of casts in the input.
7579 // sext (zext ty1), ty2 -> zext ty2
7580 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7583 case Instruction::Select: {
7584 SelectInst *SI = cast<SelectInst>(I);
7585 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7587 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7590 case Instruction::PHI: {
7591 // We can change a phi if we can change all operands.
7592 PHINode *PN = cast<PHINode>(I);
7593 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7594 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7600 // TODO: Can handle more cases here.
7607 /// EvaluateInDifferentType - Given an expression that
7608 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7609 /// evaluate the expression.
7610 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7612 if (Constant *C = dyn_cast<Constant>(V))
7613 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7615 // Otherwise, it must be an instruction.
7616 Instruction *I = cast<Instruction>(V);
7617 Instruction *Res = 0;
7618 unsigned Opc = I->getOpcode();
7620 case Instruction::Add:
7621 case Instruction::Sub:
7622 case Instruction::Mul:
7623 case Instruction::And:
7624 case Instruction::Or:
7625 case Instruction::Xor:
7626 case Instruction::AShr:
7627 case Instruction::LShr:
7628 case Instruction::Shl: {
7629 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7630 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7631 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7634 case Instruction::Trunc:
7635 case Instruction::ZExt:
7636 case Instruction::SExt:
7637 // If the source type of the cast is the type we're trying for then we can
7638 // just return the source. There's no need to insert it because it is not
7640 if (I->getOperand(0)->getType() == Ty)
7641 return I->getOperand(0);
7643 // Otherwise, must be the same type of cast, so just reinsert a new one.
7644 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7647 case Instruction::Select: {
7648 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7649 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7650 Res = SelectInst::Create(I->getOperand(0), True, False);
7653 case Instruction::PHI: {
7654 PHINode *OPN = cast<PHINode>(I);
7655 PHINode *NPN = PHINode::Create(Ty);
7656 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7657 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7658 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7664 // TODO: Can handle more cases here.
7665 assert(0 && "Unreachable!");
7670 return InsertNewInstBefore(Res, *I);
7673 /// @brief Implement the transforms common to all CastInst visitors.
7674 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7675 Value *Src = CI.getOperand(0);
7677 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7678 // eliminate it now.
7679 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7680 if (Instruction::CastOps opc =
7681 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7682 // The first cast (CSrc) is eliminable so we need to fix up or replace
7683 // the second cast (CI). CSrc will then have a good chance of being dead.
7684 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7688 // If we are casting a select then fold the cast into the select
7689 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7690 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7693 // If we are casting a PHI then fold the cast into the PHI
7694 if (isa<PHINode>(Src))
7695 if (Instruction *NV = FoldOpIntoPhi(CI))
7701 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7702 /// or not there is a sequence of GEP indices into the type that will land us at
7703 /// the specified offset. If so, fill them into NewIndices and return true,
7704 /// otherwise return false.
7705 static bool FindElementAtOffset(const Type *Ty, int64_t Offset,
7706 SmallVectorImpl<Value*> &NewIndices,
7707 const TargetData *TD) {
7708 if (!Ty->isSized()) return false;
7710 // Start with the index over the outer type. Note that the type size
7711 // might be zero (even if the offset isn't zero) if the indexed type
7712 // is something like [0 x {int, int}]
7713 const Type *IntPtrTy = TD->getIntPtrType();
7714 int64_t FirstIdx = 0;
7715 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
7716 FirstIdx = Offset/TySize;
7717 Offset -= FirstIdx*TySize;
7719 // Handle hosts where % returns negative instead of values [0..TySize).
7723 assert(Offset >= 0);
7725 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7728 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7730 // Index into the types. If we fail, set OrigBase to null.
7732 // Indexing into tail padding between struct/array elements.
7733 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7736 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7737 const StructLayout *SL = TD->getStructLayout(STy);
7738 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7739 "Offset must stay within the indexed type");
7741 unsigned Elt = SL->getElementContainingOffset(Offset);
7742 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7744 Offset -= SL->getElementOffset(Elt);
7745 Ty = STy->getElementType(Elt);
7746 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7747 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
7748 assert(EltSize && "Cannot index into a zero-sized array");
7749 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7751 Ty = AT->getElementType();
7753 // Otherwise, we can't index into the middle of this atomic type, bail.
7761 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7762 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7763 Value *Src = CI.getOperand(0);
7765 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7766 // If casting the result of a getelementptr instruction with no offset, turn
7767 // this into a cast of the original pointer!
7768 if (GEP->hasAllZeroIndices()) {
7769 // Changing the cast operand is usually not a good idea but it is safe
7770 // here because the pointer operand is being replaced with another
7771 // pointer operand so the opcode doesn't need to change.
7773 CI.setOperand(0, GEP->getOperand(0));
7777 // If the GEP has a single use, and the base pointer is a bitcast, and the
7778 // GEP computes a constant offset, see if we can convert these three
7779 // instructions into fewer. This typically happens with unions and other
7780 // non-type-safe code.
7781 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7782 if (GEP->hasAllConstantIndices()) {
7783 // We are guaranteed to get a constant from EmitGEPOffset.
7784 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7785 int64_t Offset = OffsetV->getSExtValue();
7787 // Get the base pointer input of the bitcast, and the type it points to.
7788 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7789 const Type *GEPIdxTy =
7790 cast<PointerType>(OrigBase->getType())->getElementType();
7791 SmallVector<Value*, 8> NewIndices;
7792 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7793 // If we were able to index down into an element, create the GEP
7794 // and bitcast the result. This eliminates one bitcast, potentially
7796 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7798 NewIndices.end(), "");
7799 InsertNewInstBefore(NGEP, CI);
7800 NGEP->takeName(GEP);
7802 if (isa<BitCastInst>(CI))
7803 return new BitCastInst(NGEP, CI.getType());
7804 assert(isa<PtrToIntInst>(CI));
7805 return new PtrToIntInst(NGEP, CI.getType());
7811 return commonCastTransforms(CI);
7815 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7816 /// integer types. This function implements the common transforms for all those
7818 /// @brief Implement the transforms common to CastInst with integer operands
7819 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7820 if (Instruction *Result = commonCastTransforms(CI))
7823 Value *Src = CI.getOperand(0);
7824 const Type *SrcTy = Src->getType();
7825 const Type *DestTy = CI.getType();
7826 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7827 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7829 // See if we can simplify any instructions used by the LHS whose sole
7830 // purpose is to compute bits we don't care about.
7831 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7832 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7833 KnownZero, KnownOne))
7836 // If the source isn't an instruction or has more than one use then we
7837 // can't do anything more.
7838 Instruction *SrcI = dyn_cast<Instruction>(Src);
7839 if (!SrcI || !Src->hasOneUse())
7842 // Attempt to propagate the cast into the instruction for int->int casts.
7843 int NumCastsRemoved = 0;
7844 if (!isa<BitCastInst>(CI) &&
7845 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7846 CI.getOpcode(), NumCastsRemoved)) {
7847 // If this cast is a truncate, evaluting in a different type always
7848 // eliminates the cast, so it is always a win. If this is a zero-extension,
7849 // we need to do an AND to maintain the clear top-part of the computation,
7850 // so we require that the input have eliminated at least one cast. If this
7851 // is a sign extension, we insert two new casts (to do the extension) so we
7852 // require that two casts have been eliminated.
7853 bool DoXForm = false;
7854 bool JustReplace = false;
7855 switch (CI.getOpcode()) {
7857 // All the others use floating point so we shouldn't actually
7858 // get here because of the check above.
7859 assert(0 && "Unknown cast type");
7860 case Instruction::Trunc:
7863 case Instruction::ZExt: {
7864 DoXForm = NumCastsRemoved >= 1;
7866 // If it's unnecessary to issue an AND to clear the high bits, it's
7867 // always profitable to do this xform.
7868 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7869 CI.getOpcode() == Instruction::SExt);
7870 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7871 if (MaskedValueIsZero(TryRes, Mask))
7872 return ReplaceInstUsesWith(CI, TryRes);
7873 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7874 if (TryI->use_empty())
7875 EraseInstFromFunction(*TryI);
7879 case Instruction::SExt: {
7880 DoXForm = NumCastsRemoved >= 2;
7881 if (!DoXForm && !isa<TruncInst>(SrcI)) {
7882 // If we do not have to emit the truncate + sext pair, then it's always
7883 // profitable to do this xform.
7885 // It's not safe to eliminate the trunc + sext pair if one of the
7886 // eliminated cast is a truncate. e.g.
7887 // t2 = trunc i32 t1 to i16
7888 // t3 = sext i16 t2 to i32
7891 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7892 CI.getOpcode() == Instruction::SExt);
7893 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7894 if (NumSignBits > (DestBitSize - SrcBitSize))
7895 return ReplaceInstUsesWith(CI, TryRes);
7896 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7897 if (TryI->use_empty())
7898 EraseInstFromFunction(*TryI);
7905 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7906 CI.getOpcode() == Instruction::SExt);
7908 // Just replace this cast with the result.
7909 return ReplaceInstUsesWith(CI, Res);
7911 assert(Res->getType() == DestTy);
7912 switch (CI.getOpcode()) {
7913 default: assert(0 && "Unknown cast type!");
7914 case Instruction::Trunc:
7915 case Instruction::BitCast:
7916 // Just replace this cast with the result.
7917 return ReplaceInstUsesWith(CI, Res);
7918 case Instruction::ZExt: {
7919 assert(SrcBitSize < DestBitSize && "Not a zext?");
7921 // If the high bits are already zero, just replace this cast with the
7923 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7924 if (MaskedValueIsZero(Res, Mask))
7925 return ReplaceInstUsesWith(CI, Res);
7927 // We need to emit an AND to clear the high bits.
7928 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7930 return BinaryOperator::CreateAnd(Res, C);
7932 case Instruction::SExt: {
7933 // If the high bits are already filled with sign bit, just replace this
7934 // cast with the result.
7935 unsigned NumSignBits = ComputeNumSignBits(Res);
7936 if (NumSignBits > (DestBitSize - SrcBitSize))
7937 return ReplaceInstUsesWith(CI, Res);
7939 // We need to emit a cast to truncate, then a cast to sext.
7940 return CastInst::Create(Instruction::SExt,
7941 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7948 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7949 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7951 switch (SrcI->getOpcode()) {
7952 case Instruction::Add:
7953 case Instruction::Mul:
7954 case Instruction::And:
7955 case Instruction::Or:
7956 case Instruction::Xor:
7957 // If we are discarding information, rewrite.
7958 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7959 // Don't insert two casts if they cannot be eliminated. We allow
7960 // two casts to be inserted if the sizes are the same. This could
7961 // only be converting signedness, which is a noop.
7962 if (DestBitSize == SrcBitSize ||
7963 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7964 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7965 Instruction::CastOps opcode = CI.getOpcode();
7966 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7967 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7968 return BinaryOperator::Create(
7969 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7973 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7974 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7975 SrcI->getOpcode() == Instruction::Xor &&
7976 Op1 == ConstantInt::getTrue() &&
7977 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7978 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
7979 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7982 case Instruction::SDiv:
7983 case Instruction::UDiv:
7984 case Instruction::SRem:
7985 case Instruction::URem:
7986 // If we are just changing the sign, rewrite.
7987 if (DestBitSize == SrcBitSize) {
7988 // Don't insert two casts if they cannot be eliminated. We allow
7989 // two casts to be inserted if the sizes are the same. This could
7990 // only be converting signedness, which is a noop.
7991 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7992 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7993 Value *Op0c = InsertCastBefore(Instruction::BitCast,
7994 Op0, DestTy, *SrcI);
7995 Value *Op1c = InsertCastBefore(Instruction::BitCast,
7996 Op1, DestTy, *SrcI);
7997 return BinaryOperator::Create(
7998 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8003 case Instruction::Shl:
8004 // Allow changing the sign of the source operand. Do not allow
8005 // changing the size of the shift, UNLESS the shift amount is a
8006 // constant. We must not change variable sized shifts to a smaller
8007 // size, because it is undefined to shift more bits out than exist
8009 if (DestBitSize == SrcBitSize ||
8010 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8011 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8012 Instruction::BitCast : Instruction::Trunc);
8013 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8014 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8015 return BinaryOperator::CreateShl(Op0c, Op1c);
8018 case Instruction::AShr:
8019 // If this is a signed shr, and if all bits shifted in are about to be
8020 // truncated off, turn it into an unsigned shr to allow greater
8022 if (DestBitSize < SrcBitSize &&
8023 isa<ConstantInt>(Op1)) {
8024 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8025 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8026 // Insert the new logical shift right.
8027 return BinaryOperator::CreateLShr(Op0, Op1);
8035 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8036 if (Instruction *Result = commonIntCastTransforms(CI))
8039 Value *Src = CI.getOperand(0);
8040 const Type *Ty = CI.getType();
8041 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8042 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8044 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8045 switch (SrcI->getOpcode()) {
8047 case Instruction::LShr:
8048 // We can shrink lshr to something smaller if we know the bits shifted in
8049 // are already zeros.
8050 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
8051 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8053 // Get a mask for the bits shifting in.
8054 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8055 Value* SrcIOp0 = SrcI->getOperand(0);
8056 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
8057 if (ShAmt >= DestBitWidth) // All zeros.
8058 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8060 // Okay, we can shrink this. Truncate the input, then return a new
8062 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8063 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8065 return BinaryOperator::CreateLShr(V1, V2);
8067 } else { // This is a variable shr.
8069 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8070 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8071 // loop-invariant and CSE'd.
8072 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8073 Value *One = ConstantInt::get(SrcI->getType(), 1);
8075 Value *V = InsertNewInstBefore(
8076 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
8078 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
8079 SrcI->getOperand(0),
8081 Value *Zero = Constant::getNullValue(V->getType());
8082 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8092 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8093 /// in order to eliminate the icmp.
8094 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8096 // If we are just checking for a icmp eq of a single bit and zext'ing it
8097 // to an integer, then shift the bit to the appropriate place and then
8098 // cast to integer to avoid the comparison.
8099 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8100 const APInt &Op1CV = Op1C->getValue();
8102 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8103 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8104 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8105 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8106 if (!DoXform) return ICI;
8108 Value *In = ICI->getOperand(0);
8109 Value *Sh = ConstantInt::get(In->getType(),
8110 In->getType()->getPrimitiveSizeInBits()-1);
8111 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8112 In->getName()+".lobit"),
8114 if (In->getType() != CI.getType())
8115 In = CastInst::CreateIntegerCast(In, CI.getType(),
8116 false/*ZExt*/, "tmp", &CI);
8118 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8119 Constant *One = ConstantInt::get(In->getType(), 1);
8120 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8121 In->getName()+".not"),
8125 return ReplaceInstUsesWith(CI, In);
8130 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8131 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8132 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8133 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8134 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8135 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8136 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8137 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8138 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8139 // This only works for EQ and NE
8140 ICI->isEquality()) {
8141 // If Op1C some other power of two, convert:
8142 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8143 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8144 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8145 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8147 APInt KnownZeroMask(~KnownZero);
8148 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8149 if (!DoXform) return ICI;
8151 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8152 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8153 // (X&4) == 2 --> false
8154 // (X&4) != 2 --> true
8155 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8156 Res = ConstantExpr::getZExt(Res, CI.getType());
8157 return ReplaceInstUsesWith(CI, Res);
8160 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8161 Value *In = ICI->getOperand(0);
8163 // Perform a logical shr by shiftamt.
8164 // Insert the shift to put the result in the low bit.
8165 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8166 ConstantInt::get(In->getType(), ShiftAmt),
8167 In->getName()+".lobit"), CI);
8170 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8171 Constant *One = ConstantInt::get(In->getType(), 1);
8172 In = BinaryOperator::CreateXor(In, One, "tmp");
8173 InsertNewInstBefore(cast<Instruction>(In), CI);
8176 if (CI.getType() == In->getType())
8177 return ReplaceInstUsesWith(CI, In);
8179 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8187 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8188 // If one of the common conversion will work ..
8189 if (Instruction *Result = commonIntCastTransforms(CI))
8192 Value *Src = CI.getOperand(0);
8194 // If this is a cast of a cast
8195 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8196 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8197 // types and if the sizes are just right we can convert this into a logical
8198 // 'and' which will be much cheaper than the pair of casts.
8199 if (isa<TruncInst>(CSrc)) {
8200 // Get the sizes of the types involved
8201 Value *A = CSrc->getOperand(0);
8202 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8203 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8204 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8205 // If we're actually extending zero bits and the trunc is a no-op
8206 if (MidSize < DstSize && SrcSize == DstSize) {
8207 // Replace both of the casts with an And of the type mask.
8208 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8209 Constant *AndConst = ConstantInt::get(AndValue);
8211 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8212 // Unfortunately, if the type changed, we need to cast it back.
8213 if (And->getType() != CI.getType()) {
8214 And->setName(CSrc->getName()+".mask");
8215 InsertNewInstBefore(And, CI);
8216 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8223 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8224 return transformZExtICmp(ICI, CI);
8226 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8227 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8228 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8229 // of the (zext icmp) will be transformed.
8230 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8231 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8232 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8233 (transformZExtICmp(LHS, CI, false) ||
8234 transformZExtICmp(RHS, CI, false))) {
8235 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8236 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8237 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8244 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8245 if (Instruction *I = commonIntCastTransforms(CI))
8248 Value *Src = CI.getOperand(0);
8250 // Canonicalize sign-extend from i1 to a select.
8251 if (Src->getType() == Type::Int1Ty)
8252 return SelectInst::Create(Src,
8253 ConstantInt::getAllOnesValue(CI.getType()),
8254 Constant::getNullValue(CI.getType()));
8256 // See if the value being truncated is already sign extended. If so, just
8257 // eliminate the trunc/sext pair.
8258 if (getOpcode(Src) == Instruction::Trunc) {
8259 Value *Op = cast<User>(Src)->getOperand(0);
8260 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8261 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8262 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8263 unsigned NumSignBits = ComputeNumSignBits(Op);
8265 if (OpBits == DestBits) {
8266 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8267 // bits, it is already ready.
8268 if (NumSignBits > DestBits-MidBits)
8269 return ReplaceInstUsesWith(CI, Op);
8270 } else if (OpBits < DestBits) {
8271 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8272 // bits, just sext from i32.
8273 if (NumSignBits > OpBits-MidBits)
8274 return new SExtInst(Op, CI.getType(), "tmp");
8276 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8277 // bits, just truncate to i32.
8278 if (NumSignBits > OpBits-MidBits)
8279 return new TruncInst(Op, CI.getType(), "tmp");
8283 // If the input is a shl/ashr pair of a same constant, then this is a sign
8284 // extension from a smaller value. If we could trust arbitrary bitwidth
8285 // integers, we could turn this into a truncate to the smaller bit and then
8286 // use a sext for the whole extension. Since we don't, look deeper and check
8287 // for a truncate. If the source and dest are the same type, eliminate the
8288 // trunc and extend and just do shifts. For example, turn:
8289 // %a = trunc i32 %i to i8
8290 // %b = shl i8 %a, 6
8291 // %c = ashr i8 %b, 6
8292 // %d = sext i8 %c to i32
8294 // %a = shl i32 %i, 30
8295 // %d = ashr i32 %a, 30
8297 ConstantInt *BA = 0, *CA = 0;
8298 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8299 m_ConstantInt(CA))) &&
8300 BA == CA && isa<TruncInst>(A)) {
8301 Value *I = cast<TruncInst>(A)->getOperand(0);
8302 if (I->getType() == CI.getType()) {
8303 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8304 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8305 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8306 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8307 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8309 return BinaryOperator::CreateAShr(I, ShAmtV);
8316 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8317 /// in the specified FP type without changing its value.
8318 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8320 APFloat F = CFP->getValueAPF();
8321 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8323 return ConstantFP::get(F);
8327 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8328 /// through it until we get the source value.
8329 static Value *LookThroughFPExtensions(Value *V) {
8330 if (Instruction *I = dyn_cast<Instruction>(V))
8331 if (I->getOpcode() == Instruction::FPExt)
8332 return LookThroughFPExtensions(I->getOperand(0));
8334 // If this value is a constant, return the constant in the smallest FP type
8335 // that can accurately represent it. This allows us to turn
8336 // (float)((double)X+2.0) into x+2.0f.
8337 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8338 if (CFP->getType() == Type::PPC_FP128Ty)
8339 return V; // No constant folding of this.
8340 // See if the value can be truncated to float and then reextended.
8341 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8343 if (CFP->getType() == Type::DoubleTy)
8344 return V; // Won't shrink.
8345 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8347 // Don't try to shrink to various long double types.
8353 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8354 if (Instruction *I = commonCastTransforms(CI))
8357 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8358 // smaller than the destination type, we can eliminate the truncate by doing
8359 // the add as the smaller type. This applies to add/sub/mul/div as well as
8360 // many builtins (sqrt, etc).
8361 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8362 if (OpI && OpI->hasOneUse()) {
8363 switch (OpI->getOpcode()) {
8365 case Instruction::Add:
8366 case Instruction::Sub:
8367 case Instruction::Mul:
8368 case Instruction::FDiv:
8369 case Instruction::FRem:
8370 const Type *SrcTy = OpI->getType();
8371 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8372 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8373 if (LHSTrunc->getType() != SrcTy &&
8374 RHSTrunc->getType() != SrcTy) {
8375 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8376 // If the source types were both smaller than the destination type of
8377 // the cast, do this xform.
8378 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8379 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8380 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8382 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8384 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8393 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8394 return commonCastTransforms(CI);
8397 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8398 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8400 return commonCastTransforms(FI);
8402 // fptoui(uitofp(X)) --> X
8403 // fptoui(sitofp(X)) --> X
8404 // This is safe if the intermediate type has enough bits in its mantissa to
8405 // accurately represent all values of X. For example, do not do this with
8406 // i64->float->i64. This is also safe for sitofp case, because any negative
8407 // 'X' value would cause an undefined result for the fptoui.
8408 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8409 OpI->getOperand(0)->getType() == FI.getType() &&
8410 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8411 OpI->getType()->getFPMantissaWidth())
8412 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8414 return commonCastTransforms(FI);
8417 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8418 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8420 return commonCastTransforms(FI);
8422 // fptosi(sitofp(X)) --> X
8423 // fptosi(uitofp(X)) --> X
8424 // This is safe if the intermediate type has enough bits in its mantissa to
8425 // accurately represent all values of X. For example, do not do this with
8426 // i64->float->i64. This is also safe for sitofp case, because any negative
8427 // 'X' value would cause an undefined result for the fptoui.
8428 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8429 OpI->getOperand(0)->getType() == FI.getType() &&
8430 (int)FI.getType()->getPrimitiveSizeInBits() <=
8431 OpI->getType()->getFPMantissaWidth())
8432 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8434 return commonCastTransforms(FI);
8437 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8438 return commonCastTransforms(CI);
8441 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8442 return commonCastTransforms(CI);
8445 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8446 return commonPointerCastTransforms(CI);
8449 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8450 if (Instruction *I = commonCastTransforms(CI))
8453 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8454 if (!DestPointee->isSized()) return 0;
8456 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8459 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8460 m_ConstantInt(Cst)))) {
8461 // If the source and destination operands have the same type, see if this
8462 // is a single-index GEP.
8463 if (X->getType() == CI.getType()) {
8464 // Get the size of the pointee type.
8465 uint64_t Size = TD->getTypePaddedSize(DestPointee);
8467 // Convert the constant to intptr type.
8468 APInt Offset = Cst->getValue();
8469 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8471 // If Offset is evenly divisible by Size, we can do this xform.
8472 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8473 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8474 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8477 // TODO: Could handle other cases, e.g. where add is indexing into field of
8479 } else if (CI.getOperand(0)->hasOneUse() &&
8480 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8481 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8482 // "inttoptr+GEP" instead of "add+intptr".
8484 // Get the size of the pointee type.
8485 uint64_t Size = TD->getTypePaddedSize(DestPointee);
8487 // Convert the constant to intptr type.
8488 APInt Offset = Cst->getValue();
8489 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8491 // If Offset is evenly divisible by Size, we can do this xform.
8492 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8493 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8495 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8497 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8503 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8504 // If the operands are integer typed then apply the integer transforms,
8505 // otherwise just apply the common ones.
8506 Value *Src = CI.getOperand(0);
8507 const Type *SrcTy = Src->getType();
8508 const Type *DestTy = CI.getType();
8510 if (SrcTy->isInteger() && DestTy->isInteger()) {
8511 if (Instruction *Result = commonIntCastTransforms(CI))
8513 } else if (isa<PointerType>(SrcTy)) {
8514 if (Instruction *I = commonPointerCastTransforms(CI))
8517 if (Instruction *Result = commonCastTransforms(CI))
8522 // Get rid of casts from one type to the same type. These are useless and can
8523 // be replaced by the operand.
8524 if (DestTy == Src->getType())
8525 return ReplaceInstUsesWith(CI, Src);
8527 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8528 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8529 const Type *DstElTy = DstPTy->getElementType();
8530 const Type *SrcElTy = SrcPTy->getElementType();
8532 // If the address spaces don't match, don't eliminate the bitcast, which is
8533 // required for changing types.
8534 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8537 // If we are casting a malloc or alloca to a pointer to a type of the same
8538 // size, rewrite the allocation instruction to allocate the "right" type.
8539 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8540 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8543 // If the source and destination are pointers, and this cast is equivalent
8544 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8545 // This can enhance SROA and other transforms that want type-safe pointers.
8546 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8547 unsigned NumZeros = 0;
8548 while (SrcElTy != DstElTy &&
8549 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8550 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8551 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8555 // If we found a path from the src to dest, create the getelementptr now.
8556 if (SrcElTy == DstElTy) {
8557 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8558 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8559 ((Instruction*) NULL));
8563 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8564 if (SVI->hasOneUse()) {
8565 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8566 // a bitconvert to a vector with the same # elts.
8567 if (isa<VectorType>(DestTy) &&
8568 cast<VectorType>(DestTy)->getNumElements() ==
8569 SVI->getType()->getNumElements() &&
8570 SVI->getType()->getNumElements() ==
8571 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8573 // If either of the operands is a cast from CI.getType(), then
8574 // evaluating the shuffle in the casted destination's type will allow
8575 // us to eliminate at least one cast.
8576 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8577 Tmp->getOperand(0)->getType() == DestTy) ||
8578 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8579 Tmp->getOperand(0)->getType() == DestTy)) {
8580 Value *LHS = InsertCastBefore(Instruction::BitCast,
8581 SVI->getOperand(0), DestTy, CI);
8582 Value *RHS = InsertCastBefore(Instruction::BitCast,
8583 SVI->getOperand(1), DestTy, CI);
8584 // Return a new shuffle vector. Use the same element ID's, as we
8585 // know the vector types match #elts.
8586 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8594 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8596 /// %D = select %cond, %C, %A
8598 /// %C = select %cond, %B, 0
8601 /// Assuming that the specified instruction is an operand to the select, return
8602 /// a bitmask indicating which operands of this instruction are foldable if they
8603 /// equal the other incoming value of the select.
8605 static unsigned GetSelectFoldableOperands(Instruction *I) {
8606 switch (I->getOpcode()) {
8607 case Instruction::Add:
8608 case Instruction::Mul:
8609 case Instruction::And:
8610 case Instruction::Or:
8611 case Instruction::Xor:
8612 return 3; // Can fold through either operand.
8613 case Instruction::Sub: // Can only fold on the amount subtracted.
8614 case Instruction::Shl: // Can only fold on the shift amount.
8615 case Instruction::LShr:
8616 case Instruction::AShr:
8619 return 0; // Cannot fold
8623 /// GetSelectFoldableConstant - For the same transformation as the previous
8624 /// function, return the identity constant that goes into the select.
8625 static Constant *GetSelectFoldableConstant(Instruction *I) {
8626 switch (I->getOpcode()) {
8627 default: assert(0 && "This cannot happen!"); abort();
8628 case Instruction::Add:
8629 case Instruction::Sub:
8630 case Instruction::Or:
8631 case Instruction::Xor:
8632 case Instruction::Shl:
8633 case Instruction::LShr:
8634 case Instruction::AShr:
8635 return Constant::getNullValue(I->getType());
8636 case Instruction::And:
8637 return Constant::getAllOnesValue(I->getType());
8638 case Instruction::Mul:
8639 return ConstantInt::get(I->getType(), 1);
8643 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8644 /// have the same opcode and only one use each. Try to simplify this.
8645 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8647 if (TI->getNumOperands() == 1) {
8648 // If this is a non-volatile load or a cast from the same type,
8651 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8654 return 0; // unknown unary op.
8657 // Fold this by inserting a select from the input values.
8658 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8659 FI->getOperand(0), SI.getName()+".v");
8660 InsertNewInstBefore(NewSI, SI);
8661 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
8665 // Only handle binary operators here.
8666 if (!isa<BinaryOperator>(TI))
8669 // Figure out if the operations have any operands in common.
8670 Value *MatchOp, *OtherOpT, *OtherOpF;
8672 if (TI->getOperand(0) == FI->getOperand(0)) {
8673 MatchOp = TI->getOperand(0);
8674 OtherOpT = TI->getOperand(1);
8675 OtherOpF = FI->getOperand(1);
8676 MatchIsOpZero = true;
8677 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8678 MatchOp = TI->getOperand(1);
8679 OtherOpT = TI->getOperand(0);
8680 OtherOpF = FI->getOperand(0);
8681 MatchIsOpZero = false;
8682 } else if (!TI->isCommutative()) {
8684 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8685 MatchOp = TI->getOperand(0);
8686 OtherOpT = TI->getOperand(1);
8687 OtherOpF = FI->getOperand(0);
8688 MatchIsOpZero = true;
8689 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8690 MatchOp = TI->getOperand(1);
8691 OtherOpT = TI->getOperand(0);
8692 OtherOpF = FI->getOperand(1);
8693 MatchIsOpZero = true;
8698 // If we reach here, they do have operations in common.
8699 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8700 OtherOpF, SI.getName()+".v");
8701 InsertNewInstBefore(NewSI, SI);
8703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8705 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8707 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8709 assert(0 && "Shouldn't get here");
8713 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8714 /// ICmpInst as its first operand.
8716 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8718 bool Changed = false;
8719 ICmpInst::Predicate Pred = ICI->getPredicate();
8720 Value *CmpLHS = ICI->getOperand(0);
8721 Value *CmpRHS = ICI->getOperand(1);
8722 Value *TrueVal = SI.getTrueValue();
8723 Value *FalseVal = SI.getFalseValue();
8725 // Check cases where the comparison is with a constant that
8726 // can be adjusted to fit the min/max idiom. We may edit ICI in
8727 // place here, so make sure the select is the only user.
8728 if (ICI->hasOneUse())
8729 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8732 case ICmpInst::ICMP_ULT:
8733 case ICmpInst::ICMP_SLT: {
8734 // X < MIN ? T : F --> F
8735 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8736 return ReplaceInstUsesWith(SI, FalseVal);
8737 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8738 Constant *AdjustedRHS = SubOne(CI);
8739 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8740 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8741 Pred = ICmpInst::getSwappedPredicate(Pred);
8742 CmpRHS = AdjustedRHS;
8743 std::swap(FalseVal, TrueVal);
8744 ICI->setPredicate(Pred);
8745 ICI->setOperand(1, CmpRHS);
8746 SI.setOperand(1, TrueVal);
8747 SI.setOperand(2, FalseVal);
8752 case ICmpInst::ICMP_UGT:
8753 case ICmpInst::ICMP_SGT: {
8754 // X > MAX ? T : F --> F
8755 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8756 return ReplaceInstUsesWith(SI, FalseVal);
8757 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8758 Constant *AdjustedRHS = AddOne(CI);
8759 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8760 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8761 Pred = ICmpInst::getSwappedPredicate(Pred);
8762 CmpRHS = AdjustedRHS;
8763 std::swap(FalseVal, TrueVal);
8764 ICI->setPredicate(Pred);
8765 ICI->setOperand(1, CmpRHS);
8766 SI.setOperand(1, TrueVal);
8767 SI.setOperand(2, FalseVal);
8774 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8775 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
8776 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8777 if (match(TrueVal, m_ConstantInt<-1>()) &&
8778 match(FalseVal, m_ConstantInt<0>()))
8779 Pred = ICI->getPredicate();
8780 else if (match(TrueVal, m_ConstantInt<0>()) &&
8781 match(FalseVal, m_ConstantInt<-1>()))
8782 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8784 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8785 // If we are just checking for a icmp eq of a single bit and zext'ing it
8786 // to an integer, then shift the bit to the appropriate place and then
8787 // cast to integer to avoid the comparison.
8788 const APInt &Op1CV = CI->getValue();
8790 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8791 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8792 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8793 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8794 Value *In = ICI->getOperand(0);
8795 Value *Sh = ConstantInt::get(In->getType(),
8796 In->getType()->getPrimitiveSizeInBits()-1);
8797 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8798 In->getName()+".lobit"),
8800 if (In->getType() != SI.getType())
8801 In = CastInst::CreateIntegerCast(In, SI.getType(),
8802 true/*SExt*/, "tmp", ICI);
8804 if (Pred == ICmpInst::ICMP_SGT)
8805 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8806 In->getName()+".not"), *ICI);
8808 return ReplaceInstUsesWith(SI, In);
8813 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8814 // Transform (X == Y) ? X : Y -> Y
8815 if (Pred == ICmpInst::ICMP_EQ)
8816 return ReplaceInstUsesWith(SI, FalseVal);
8817 // Transform (X != Y) ? X : Y -> X
8818 if (Pred == ICmpInst::ICMP_NE)
8819 return ReplaceInstUsesWith(SI, TrueVal);
8820 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8822 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8823 // Transform (X == Y) ? Y : X -> X
8824 if (Pred == ICmpInst::ICMP_EQ)
8825 return ReplaceInstUsesWith(SI, FalseVal);
8826 // Transform (X != Y) ? Y : X -> Y
8827 if (Pred == ICmpInst::ICMP_NE)
8828 return ReplaceInstUsesWith(SI, TrueVal);
8829 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8832 /// NOTE: if we wanted to, this is where to detect integer ABS
8834 return Changed ? &SI : 0;
8837 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8838 Value *CondVal = SI.getCondition();
8839 Value *TrueVal = SI.getTrueValue();
8840 Value *FalseVal = SI.getFalseValue();
8842 // select true, X, Y -> X
8843 // select false, X, Y -> Y
8844 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8845 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8847 // select C, X, X -> X
8848 if (TrueVal == FalseVal)
8849 return ReplaceInstUsesWith(SI, TrueVal);
8851 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8852 return ReplaceInstUsesWith(SI, FalseVal);
8853 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8854 return ReplaceInstUsesWith(SI, TrueVal);
8855 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8856 if (isa<Constant>(TrueVal))
8857 return ReplaceInstUsesWith(SI, TrueVal);
8859 return ReplaceInstUsesWith(SI, FalseVal);
8862 if (SI.getType() == Type::Int1Ty) {
8863 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8864 if (C->getZExtValue()) {
8865 // Change: A = select B, true, C --> A = or B, C
8866 return BinaryOperator::CreateOr(CondVal, FalseVal);
8868 // Change: A = select B, false, C --> A = and !B, C
8870 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8871 "not."+CondVal->getName()), SI);
8872 return BinaryOperator::CreateAnd(NotCond, FalseVal);
8874 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8875 if (C->getZExtValue() == false) {
8876 // Change: A = select B, C, false --> A = and B, C
8877 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8879 // Change: A = select B, C, true --> A = or !B, C
8881 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8882 "not."+CondVal->getName()), SI);
8883 return BinaryOperator::CreateOr(NotCond, TrueVal);
8887 // select a, b, a -> a&b
8888 // select a, a, b -> a|b
8889 if (CondVal == TrueVal)
8890 return BinaryOperator::CreateOr(CondVal, FalseVal);
8891 else if (CondVal == FalseVal)
8892 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8895 // Selecting between two integer constants?
8896 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8897 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8898 // select C, 1, 0 -> zext C to int
8899 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8900 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8901 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8902 // select C, 0, 1 -> zext !C to int
8904 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8905 "not."+CondVal->getName()), SI);
8906 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8909 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8911 // (x <s 0) ? -1 : 0 -> ashr x, 31
8912 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8913 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8914 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8915 // The comparison constant and the result are not neccessarily the
8916 // same width. Make an all-ones value by inserting a AShr.
8917 Value *X = IC->getOperand(0);
8918 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8919 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8920 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8922 InsertNewInstBefore(SRA, SI);
8924 // Then cast to the appropriate width.
8925 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
8930 // If one of the constants is zero (we know they can't both be) and we
8931 // have an icmp instruction with zero, and we have an 'and' with the
8932 // non-constant value, eliminate this whole mess. This corresponds to
8933 // cases like this: ((X & 27) ? 27 : 0)
8934 if (TrueValC->isZero() || FalseValC->isZero())
8935 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8936 cast<Constant>(IC->getOperand(1))->isNullValue())
8937 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8938 if (ICA->getOpcode() == Instruction::And &&
8939 isa<ConstantInt>(ICA->getOperand(1)) &&
8940 (ICA->getOperand(1) == TrueValC ||
8941 ICA->getOperand(1) == FalseValC) &&
8942 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8943 // Okay, now we know that everything is set up, we just don't
8944 // know whether we have a icmp_ne or icmp_eq and whether the
8945 // true or false val is the zero.
8946 bool ShouldNotVal = !TrueValC->isZero();
8947 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8950 V = InsertNewInstBefore(BinaryOperator::Create(
8951 Instruction::Xor, V, ICA->getOperand(1)), SI);
8952 return ReplaceInstUsesWith(SI, V);
8957 // See if we are selecting two values based on a comparison of the two values.
8958 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8959 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8960 // Transform (X == Y) ? X : Y -> Y
8961 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8962 // This is not safe in general for floating point:
8963 // consider X== -0, Y== +0.
8964 // It becomes safe if either operand is a nonzero constant.
8965 ConstantFP *CFPt, *CFPf;
8966 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8967 !CFPt->getValueAPF().isZero()) ||
8968 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8969 !CFPf->getValueAPF().isZero()))
8970 return ReplaceInstUsesWith(SI, FalseVal);
8972 // Transform (X != Y) ? X : Y -> X
8973 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8974 return ReplaceInstUsesWith(SI, TrueVal);
8975 // NOTE: if we wanted to, this is where to detect MIN/MAX
8977 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8978 // Transform (X == Y) ? Y : X -> X
8979 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8980 // This is not safe in general for floating point:
8981 // consider X== -0, Y== +0.
8982 // It becomes safe if either operand is a nonzero constant.
8983 ConstantFP *CFPt, *CFPf;
8984 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8985 !CFPt->getValueAPF().isZero()) ||
8986 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8987 !CFPf->getValueAPF().isZero()))
8988 return ReplaceInstUsesWith(SI, FalseVal);
8990 // Transform (X != Y) ? Y : X -> Y
8991 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8992 return ReplaceInstUsesWith(SI, TrueVal);
8993 // NOTE: if we wanted to, this is where to detect MIN/MAX
8995 // NOTE: if we wanted to, this is where to detect ABS
8998 // See if we are selecting two values based on a comparison of the two values.
8999 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9000 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9003 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9004 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9005 if (TI->hasOneUse() && FI->hasOneUse()) {
9006 Instruction *AddOp = 0, *SubOp = 0;
9008 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9009 if (TI->getOpcode() == FI->getOpcode())
9010 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9013 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9014 // even legal for FP.
9015 if (TI->getOpcode() == Instruction::Sub &&
9016 FI->getOpcode() == Instruction::Add) {
9017 AddOp = FI; SubOp = TI;
9018 } else if (FI->getOpcode() == Instruction::Sub &&
9019 TI->getOpcode() == Instruction::Add) {
9020 AddOp = TI; SubOp = FI;
9024 Value *OtherAddOp = 0;
9025 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9026 OtherAddOp = AddOp->getOperand(1);
9027 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9028 OtherAddOp = AddOp->getOperand(0);
9032 // So at this point we know we have (Y -> OtherAddOp):
9033 // select C, (add X, Y), (sub X, Z)
9034 Value *NegVal; // Compute -Z
9035 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9036 NegVal = ConstantExpr::getNeg(C);
9038 NegVal = InsertNewInstBefore(
9039 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9042 Value *NewTrueOp = OtherAddOp;
9043 Value *NewFalseOp = NegVal;
9045 std::swap(NewTrueOp, NewFalseOp);
9046 Instruction *NewSel =
9047 SelectInst::Create(CondVal, NewTrueOp,
9048 NewFalseOp, SI.getName() + ".p");
9050 NewSel = InsertNewInstBefore(NewSel, SI);
9051 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9056 // See if we can fold the select into one of our operands.
9057 if (SI.getType()->isInteger()) {
9058 // See the comment above GetSelectFoldableOperands for a description of the
9059 // transformation we are doing here.
9060 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9061 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9062 !isa<Constant>(FalseVal))
9063 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9064 unsigned OpToFold = 0;
9065 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9067 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9072 Constant *C = GetSelectFoldableConstant(TVI);
9073 Instruction *NewSel =
9074 SelectInst::Create(SI.getCondition(),
9075 TVI->getOperand(2-OpToFold), C);
9076 InsertNewInstBefore(NewSel, SI);
9077 NewSel->takeName(TVI);
9078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9079 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9081 assert(0 && "Unknown instruction!!");
9086 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9087 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9088 !isa<Constant>(TrueVal))
9089 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9090 unsigned OpToFold = 0;
9091 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9093 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9098 Constant *C = GetSelectFoldableConstant(FVI);
9099 Instruction *NewSel =
9100 SelectInst::Create(SI.getCondition(), C,
9101 FVI->getOperand(2-OpToFold));
9102 InsertNewInstBefore(NewSel, SI);
9103 NewSel->takeName(FVI);
9104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9105 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9107 assert(0 && "Unknown instruction!!");
9112 if (BinaryOperator::isNot(CondVal)) {
9113 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9114 SI.setOperand(1, FalseVal);
9115 SI.setOperand(2, TrueVal);
9122 /// EnforceKnownAlignment - If the specified pointer points to an object that
9123 /// we control, modify the object's alignment to PrefAlign. This isn't
9124 /// often possible though. If alignment is important, a more reliable approach
9125 /// is to simply align all global variables and allocation instructions to
9126 /// their preferred alignment from the beginning.
9128 static unsigned EnforceKnownAlignment(Value *V,
9129 unsigned Align, unsigned PrefAlign) {
9131 User *U = dyn_cast<User>(V);
9132 if (!U) return Align;
9134 switch (getOpcode(U)) {
9136 case Instruction::BitCast:
9137 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9138 case Instruction::GetElementPtr: {
9139 // If all indexes are zero, it is just the alignment of the base pointer.
9140 bool AllZeroOperands = true;
9141 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9142 if (!isa<Constant>(*i) ||
9143 !cast<Constant>(*i)->isNullValue()) {
9144 AllZeroOperands = false;
9148 if (AllZeroOperands) {
9149 // Treat this like a bitcast.
9150 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9156 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9157 // If there is a large requested alignment and we can, bump up the alignment
9159 if (!GV->isDeclaration()) {
9160 GV->setAlignment(PrefAlign);
9163 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9164 // If there is a requested alignment and if this is an alloca, round up. We
9165 // don't do this for malloc, because some systems can't respect the request.
9166 if (isa<AllocaInst>(AI)) {
9167 AI->setAlignment(PrefAlign);
9175 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9176 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9177 /// and it is more than the alignment of the ultimate object, see if we can
9178 /// increase the alignment of the ultimate object, making this check succeed.
9179 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9180 unsigned PrefAlign) {
9181 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9182 sizeof(PrefAlign) * CHAR_BIT;
9183 APInt Mask = APInt::getAllOnesValue(BitWidth);
9184 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9185 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9186 unsigned TrailZ = KnownZero.countTrailingOnes();
9187 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9189 if (PrefAlign > Align)
9190 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9192 // We don't need to make any adjustment.
9196 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9197 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9198 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9199 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9200 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9202 if (CopyAlign < MinAlign) {
9203 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9207 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9209 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9210 if (MemOpLength == 0) return 0;
9212 // Source and destination pointer types are always "i8*" for intrinsic. See
9213 // if the size is something we can handle with a single primitive load/store.
9214 // A single load+store correctly handles overlapping memory in the memmove
9216 unsigned Size = MemOpLength->getZExtValue();
9217 if (Size == 0) return MI; // Delete this mem transfer.
9219 if (Size > 8 || (Size&(Size-1)))
9220 return 0; // If not 1/2/4/8 bytes, exit.
9222 // Use an integer load+store unless we can find something better.
9223 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9225 // Memcpy forces the use of i8* for the source and destination. That means
9226 // that if you're using memcpy to move one double around, you'll get a cast
9227 // from double* to i8*. We'd much rather use a double load+store rather than
9228 // an i64 load+store, here because this improves the odds that the source or
9229 // dest address will be promotable. See if we can find a better type than the
9230 // integer datatype.
9231 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9232 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9233 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9234 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9235 // down through these levels if so.
9236 while (!SrcETy->isSingleValueType()) {
9237 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9238 if (STy->getNumElements() == 1)
9239 SrcETy = STy->getElementType(0);
9242 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9243 if (ATy->getNumElements() == 1)
9244 SrcETy = ATy->getElementType();
9251 if (SrcETy->isSingleValueType())
9252 NewPtrTy = PointerType::getUnqual(SrcETy);
9257 // If the memcpy/memmove provides better alignment info than we can
9259 SrcAlign = std::max(SrcAlign, CopyAlign);
9260 DstAlign = std::max(DstAlign, CopyAlign);
9262 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9263 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9264 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9265 InsertNewInstBefore(L, *MI);
9266 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9268 // Set the size of the copy to 0, it will be deleted on the next iteration.
9269 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9273 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9274 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9275 if (MI->getAlignment()->getZExtValue() < Alignment) {
9276 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9280 // Extract the length and alignment and fill if they are constant.
9281 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9282 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9283 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9285 uint64_t Len = LenC->getZExtValue();
9286 Alignment = MI->getAlignment()->getZExtValue();
9288 // If the length is zero, this is a no-op
9289 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9291 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9292 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9293 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9295 Value *Dest = MI->getDest();
9296 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9298 // Alignment 0 is identity for alignment 1 for memset, but not store.
9299 if (Alignment == 0) Alignment = 1;
9301 // Extract the fill value and store.
9302 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9303 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9306 // Set the size of the copy to 0, it will be deleted on the next iteration.
9307 MI->setLength(Constant::getNullValue(LenC->getType()));
9315 /// visitCallInst - CallInst simplification. This mostly only handles folding
9316 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9317 /// the heavy lifting.
9319 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9320 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9321 if (!II) return visitCallSite(&CI);
9323 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9325 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9326 bool Changed = false;
9328 // memmove/cpy/set of zero bytes is a noop.
9329 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9330 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9332 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9333 if (CI->getZExtValue() == 1) {
9334 // Replace the instruction with just byte operations. We would
9335 // transform other cases to loads/stores, but we don't know if
9336 // alignment is sufficient.
9340 // If we have a memmove and the source operation is a constant global,
9341 // then the source and dest pointers can't alias, so we can change this
9342 // into a call to memcpy.
9343 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9344 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9345 if (GVSrc->isConstant()) {
9346 Module *M = CI.getParent()->getParent()->getParent();
9347 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9349 Tys[0] = CI.getOperand(3)->getType();
9351 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9355 // memmove(x,x,size) -> noop.
9356 if (MMI->getSource() == MMI->getDest())
9357 return EraseInstFromFunction(CI);
9360 // If we can determine a pointer alignment that is bigger than currently
9361 // set, update the alignment.
9362 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9363 if (Instruction *I = SimplifyMemTransfer(MI))
9365 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9366 if (Instruction *I = SimplifyMemSet(MSI))
9370 if (Changed) return II;
9373 switch (II->getIntrinsicID()) {
9375 case Intrinsic::bswap:
9376 // bswap(bswap(x)) -> x
9377 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9378 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9379 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9381 case Intrinsic::ppc_altivec_lvx:
9382 case Intrinsic::ppc_altivec_lvxl:
9383 case Intrinsic::x86_sse_loadu_ps:
9384 case Intrinsic::x86_sse2_loadu_pd:
9385 case Intrinsic::x86_sse2_loadu_dq:
9386 // Turn PPC lvx -> load if the pointer is known aligned.
9387 // Turn X86 loadups -> load if the pointer is known aligned.
9388 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9389 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9390 PointerType::getUnqual(II->getType()),
9392 return new LoadInst(Ptr);
9395 case Intrinsic::ppc_altivec_stvx:
9396 case Intrinsic::ppc_altivec_stvxl:
9397 // Turn stvx -> store if the pointer is known aligned.
9398 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9399 const Type *OpPtrTy =
9400 PointerType::getUnqual(II->getOperand(1)->getType());
9401 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9402 return new StoreInst(II->getOperand(1), Ptr);
9405 case Intrinsic::x86_sse_storeu_ps:
9406 case Intrinsic::x86_sse2_storeu_pd:
9407 case Intrinsic::x86_sse2_storeu_dq:
9408 // Turn X86 storeu -> store if the pointer is known aligned.
9409 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9410 const Type *OpPtrTy =
9411 PointerType::getUnqual(II->getOperand(2)->getType());
9412 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9413 return new StoreInst(II->getOperand(2), Ptr);
9417 case Intrinsic::x86_sse_cvttss2si: {
9418 // These intrinsics only demands the 0th element of its input vector. If
9419 // we can simplify the input based on that, do so now.
9421 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9423 II->setOperand(1, V);
9429 case Intrinsic::ppc_altivec_vperm:
9430 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9431 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9432 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9434 // Check that all of the elements are integer constants or undefs.
9435 bool AllEltsOk = true;
9436 for (unsigned i = 0; i != 16; ++i) {
9437 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9438 !isa<UndefValue>(Mask->getOperand(i))) {
9445 // Cast the input vectors to byte vectors.
9446 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9447 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9448 Value *Result = UndefValue::get(Op0->getType());
9450 // Only extract each element once.
9451 Value *ExtractedElts[32];
9452 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9454 for (unsigned i = 0; i != 16; ++i) {
9455 if (isa<UndefValue>(Mask->getOperand(i)))
9457 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9458 Idx &= 31; // Match the hardware behavior.
9460 if (ExtractedElts[Idx] == 0) {
9462 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9463 InsertNewInstBefore(Elt, CI);
9464 ExtractedElts[Idx] = Elt;
9467 // Insert this value into the result vector.
9468 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9470 InsertNewInstBefore(cast<Instruction>(Result), CI);
9472 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9477 case Intrinsic::stackrestore: {
9478 // If the save is right next to the restore, remove the restore. This can
9479 // happen when variable allocas are DCE'd.
9480 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9481 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9482 BasicBlock::iterator BI = SS;
9484 return EraseInstFromFunction(CI);
9488 // Scan down this block to see if there is another stack restore in the
9489 // same block without an intervening call/alloca.
9490 BasicBlock::iterator BI = II;
9491 TerminatorInst *TI = II->getParent()->getTerminator();
9492 bool CannotRemove = false;
9493 for (++BI; &*BI != TI; ++BI) {
9494 if (isa<AllocaInst>(BI)) {
9495 CannotRemove = true;
9498 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9499 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9500 // If there is a stackrestore below this one, remove this one.
9501 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9502 return EraseInstFromFunction(CI);
9503 // Otherwise, ignore the intrinsic.
9505 // If we found a non-intrinsic call, we can't remove the stack
9507 CannotRemove = true;
9513 // If the stack restore is in a return/unwind block and if there are no
9514 // allocas or calls between the restore and the return, nuke the restore.
9515 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9516 return EraseInstFromFunction(CI);
9521 return visitCallSite(II);
9524 // InvokeInst simplification
9526 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9527 return visitCallSite(&II);
9530 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9531 /// passed through the varargs area, we can eliminate the use of the cast.
9532 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9533 const CastInst * const CI,
9534 const TargetData * const TD,
9536 if (!CI->isLosslessCast())
9539 // The size of ByVal arguments is derived from the type, so we
9540 // can't change to a type with a different size. If the size were
9541 // passed explicitly we could avoid this check.
9542 if (!CS.paramHasAttr(ix, Attribute::ByVal))
9546 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9547 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9548 if (!SrcTy->isSized() || !DstTy->isSized())
9550 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
9555 // visitCallSite - Improvements for call and invoke instructions.
9557 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9558 bool Changed = false;
9560 // If the callee is a constexpr cast of a function, attempt to move the cast
9561 // to the arguments of the call/invoke.
9562 if (transformConstExprCastCall(CS)) return 0;
9564 Value *Callee = CS.getCalledValue();
9566 if (Function *CalleeF = dyn_cast<Function>(Callee))
9567 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9568 Instruction *OldCall = CS.getInstruction();
9569 // If the call and callee calling conventions don't match, this call must
9570 // be unreachable, as the call is undefined.
9571 new StoreInst(ConstantInt::getTrue(),
9572 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9574 if (!OldCall->use_empty())
9575 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9576 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9577 return EraseInstFromFunction(*OldCall);
9581 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9582 // This instruction is not reachable, just remove it. We insert a store to
9583 // undef so that we know that this code is not reachable, despite the fact
9584 // that we can't modify the CFG here.
9585 new StoreInst(ConstantInt::getTrue(),
9586 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9587 CS.getInstruction());
9589 if (!CS.getInstruction()->use_empty())
9590 CS.getInstruction()->
9591 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9593 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9594 // Don't break the CFG, insert a dummy cond branch.
9595 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9596 ConstantInt::getTrue(), II);
9598 return EraseInstFromFunction(*CS.getInstruction());
9601 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9602 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9603 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9604 return transformCallThroughTrampoline(CS);
9606 const PointerType *PTy = cast<PointerType>(Callee->getType());
9607 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9608 if (FTy->isVarArg()) {
9609 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9610 // See if we can optimize any arguments passed through the varargs area of
9612 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9613 E = CS.arg_end(); I != E; ++I, ++ix) {
9614 CastInst *CI = dyn_cast<CastInst>(*I);
9615 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9616 *I = CI->getOperand(0);
9622 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9623 // Inline asm calls cannot throw - mark them 'nounwind'.
9624 CS.setDoesNotThrow();
9628 return Changed ? CS.getInstruction() : 0;
9631 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9632 // attempt to move the cast to the arguments of the call/invoke.
9634 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9635 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9636 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9637 if (CE->getOpcode() != Instruction::BitCast ||
9638 !isa<Function>(CE->getOperand(0)))
9640 Function *Callee = cast<Function>(CE->getOperand(0));
9641 Instruction *Caller = CS.getInstruction();
9642 const AttrListPtr &CallerPAL = CS.getAttributes();
9644 // Okay, this is a cast from a function to a different type. Unless doing so
9645 // would cause a type conversion of one of our arguments, change this call to
9646 // be a direct call with arguments casted to the appropriate types.
9648 const FunctionType *FT = Callee->getFunctionType();
9649 const Type *OldRetTy = Caller->getType();
9650 const Type *NewRetTy = FT->getReturnType();
9652 if (isa<StructType>(NewRetTy))
9653 return false; // TODO: Handle multiple return values.
9655 // Check to see if we are changing the return type...
9656 if (OldRetTy != NewRetTy) {
9657 if (Callee->isDeclaration() &&
9658 // Conversion is ok if changing from one pointer type to another or from
9659 // a pointer to an integer of the same size.
9660 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9661 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9662 return false; // Cannot transform this return value.
9664 if (!Caller->use_empty() &&
9665 // void -> non-void is handled specially
9666 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9667 return false; // Cannot transform this return value.
9669 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9670 Attributes RAttrs = CallerPAL.getRetAttributes();
9671 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9672 return false; // Attribute not compatible with transformed value.
9675 // If the callsite is an invoke instruction, and the return value is used by
9676 // a PHI node in a successor, we cannot change the return type of the call
9677 // because there is no place to put the cast instruction (without breaking
9678 // the critical edge). Bail out in this case.
9679 if (!Caller->use_empty())
9680 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9681 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9683 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9684 if (PN->getParent() == II->getNormalDest() ||
9685 PN->getParent() == II->getUnwindDest())
9689 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9690 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9692 CallSite::arg_iterator AI = CS.arg_begin();
9693 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9694 const Type *ParamTy = FT->getParamType(i);
9695 const Type *ActTy = (*AI)->getType();
9697 if (!CastInst::isCastable(ActTy, ParamTy))
9698 return false; // Cannot transform this parameter value.
9700 if (CallerPAL.getParamAttributes(i + 1)
9701 & Attribute::typeIncompatible(ParamTy))
9702 return false; // Attribute not compatible with transformed value.
9704 // Converting from one pointer type to another or between a pointer and an
9705 // integer of the same size is safe even if we do not have a body.
9706 bool isConvertible = ActTy == ParamTy ||
9707 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9708 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9709 if (Callee->isDeclaration() && !isConvertible) return false;
9712 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9713 Callee->isDeclaration())
9714 return false; // Do not delete arguments unless we have a function body.
9716 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9717 !CallerPAL.isEmpty())
9718 // In this case we have more arguments than the new function type, but we
9719 // won't be dropping them. Check that these extra arguments have attributes
9720 // that are compatible with being a vararg call argument.
9721 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9722 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9724 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9725 if (PAttrs & Attribute::VarArgsIncompatible)
9729 // Okay, we decided that this is a safe thing to do: go ahead and start
9730 // inserting cast instructions as necessary...
9731 std::vector<Value*> Args;
9732 Args.reserve(NumActualArgs);
9733 SmallVector<AttributeWithIndex, 8> attrVec;
9734 attrVec.reserve(NumCommonArgs);
9736 // Get any return attributes.
9737 Attributes RAttrs = CallerPAL.getRetAttributes();
9739 // If the return value is not being used, the type may not be compatible
9740 // with the existing attributes. Wipe out any problematic attributes.
9741 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9743 // Add the new return attributes.
9745 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9747 AI = CS.arg_begin();
9748 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9749 const Type *ParamTy = FT->getParamType(i);
9750 if ((*AI)->getType() == ParamTy) {
9751 Args.push_back(*AI);
9753 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9754 false, ParamTy, false);
9755 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9756 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9759 // Add any parameter attributes.
9760 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9761 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9764 // If the function takes more arguments than the call was taking, add them
9766 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9767 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9769 // If we are removing arguments to the function, emit an obnoxious warning...
9770 if (FT->getNumParams() < NumActualArgs) {
9771 if (!FT->isVarArg()) {
9772 cerr << "WARNING: While resolving call to function '"
9773 << Callee->getName() << "' arguments were dropped!\n";
9775 // Add all of the arguments in their promoted form to the arg list...
9776 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9777 const Type *PTy = getPromotedType((*AI)->getType());
9778 if (PTy != (*AI)->getType()) {
9779 // Must promote to pass through va_arg area!
9780 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9782 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9783 InsertNewInstBefore(Cast, *Caller);
9784 Args.push_back(Cast);
9786 Args.push_back(*AI);
9789 // Add any parameter attributes.
9790 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9791 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9796 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9797 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9799 if (NewRetTy == Type::VoidTy)
9800 Caller->setName(""); // Void type should not have a name.
9802 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9805 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9806 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9807 Args.begin(), Args.end(),
9808 Caller->getName(), Caller);
9809 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9810 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9812 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9813 Caller->getName(), Caller);
9814 CallInst *CI = cast<CallInst>(Caller);
9815 if (CI->isTailCall())
9816 cast<CallInst>(NC)->setTailCall();
9817 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9818 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9821 // Insert a cast of the return type as necessary.
9823 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9824 if (NV->getType() != Type::VoidTy) {
9825 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
9827 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9829 // If this is an invoke instruction, we should insert it after the first
9830 // non-phi, instruction in the normal successor block.
9831 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9832 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9833 InsertNewInstBefore(NC, *I);
9835 // Otherwise, it's a call, just insert cast right after the call instr
9836 InsertNewInstBefore(NC, *Caller);
9838 AddUsersToWorkList(*Caller);
9840 NV = UndefValue::get(Caller->getType());
9844 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9845 Caller->replaceAllUsesWith(NV);
9846 Caller->eraseFromParent();
9847 RemoveFromWorkList(Caller);
9851 // transformCallThroughTrampoline - Turn a call to a function created by the
9852 // init_trampoline intrinsic into a direct call to the underlying function.
9854 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9855 Value *Callee = CS.getCalledValue();
9856 const PointerType *PTy = cast<PointerType>(Callee->getType());
9857 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9858 const AttrListPtr &Attrs = CS.getAttributes();
9860 // If the call already has the 'nest' attribute somewhere then give up -
9861 // otherwise 'nest' would occur twice after splicing in the chain.
9862 if (Attrs.hasAttrSomewhere(Attribute::Nest))
9865 IntrinsicInst *Tramp =
9866 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9868 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9869 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9870 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9872 const AttrListPtr &NestAttrs = NestF->getAttributes();
9873 if (!NestAttrs.isEmpty()) {
9874 unsigned NestIdx = 1;
9875 const Type *NestTy = 0;
9876 Attributes NestAttr = Attribute::None;
9878 // Look for a parameter marked with the 'nest' attribute.
9879 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9880 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9881 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9882 // Record the parameter type and any other attributes.
9884 NestAttr = NestAttrs.getParamAttributes(NestIdx);
9889 Instruction *Caller = CS.getInstruction();
9890 std::vector<Value*> NewArgs;
9891 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9893 SmallVector<AttributeWithIndex, 8> NewAttrs;
9894 NewAttrs.reserve(Attrs.getNumSlots() + 1);
9896 // Insert the nest argument into the call argument list, which may
9897 // mean appending it. Likewise for attributes.
9899 // Add any result attributes.
9900 if (Attributes Attr = Attrs.getRetAttributes())
9901 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9905 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9907 if (Idx == NestIdx) {
9908 // Add the chain argument and attributes.
9909 Value *NestVal = Tramp->getOperand(3);
9910 if (NestVal->getType() != NestTy)
9911 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9912 NewArgs.push_back(NestVal);
9913 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9919 // Add the original argument and attributes.
9920 NewArgs.push_back(*I);
9921 if (Attributes Attr = Attrs.getParamAttributes(Idx))
9923 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9929 // Add any function attributes.
9930 if (Attributes Attr = Attrs.getFnAttributes())
9931 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9933 // The trampoline may have been bitcast to a bogus type (FTy).
9934 // Handle this by synthesizing a new function type, equal to FTy
9935 // with the chain parameter inserted.
9937 std::vector<const Type*> NewTypes;
9938 NewTypes.reserve(FTy->getNumParams()+1);
9940 // Insert the chain's type into the list of parameter types, which may
9941 // mean appending it.
9944 FunctionType::param_iterator I = FTy->param_begin(),
9945 E = FTy->param_end();
9949 // Add the chain's type.
9950 NewTypes.push_back(NestTy);
9955 // Add the original type.
9956 NewTypes.push_back(*I);
9962 // Replace the trampoline call with a direct call. Let the generic
9963 // code sort out any function type mismatches.
9964 FunctionType *NewFTy =
9965 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9966 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9967 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9968 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9970 Instruction *NewCaller;
9971 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9972 NewCaller = InvokeInst::Create(NewCallee,
9973 II->getNormalDest(), II->getUnwindDest(),
9974 NewArgs.begin(), NewArgs.end(),
9975 Caller->getName(), Caller);
9976 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9977 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9979 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9980 Caller->getName(), Caller);
9981 if (cast<CallInst>(Caller)->isTailCall())
9982 cast<CallInst>(NewCaller)->setTailCall();
9983 cast<CallInst>(NewCaller)->
9984 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9985 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9987 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9988 Caller->replaceAllUsesWith(NewCaller);
9989 Caller->eraseFromParent();
9990 RemoveFromWorkList(Caller);
9995 // Replace the trampoline call with a direct call. Since there is no 'nest'
9996 // parameter, there is no need to adjust the argument list. Let the generic
9997 // code sort out any function type mismatches.
9998 Constant *NewCallee =
9999 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10000 CS.setCalledFunction(NewCallee);
10001 return CS.getInstruction();
10004 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10005 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10006 /// and a single binop.
10007 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10008 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10009 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10010 unsigned Opc = FirstInst->getOpcode();
10011 Value *LHSVal = FirstInst->getOperand(0);
10012 Value *RHSVal = FirstInst->getOperand(1);
10014 const Type *LHSType = LHSVal->getType();
10015 const Type *RHSType = RHSVal->getType();
10017 // Scan to see if all operands are the same opcode, all have one use, and all
10018 // kill their operands (i.e. the operands have one use).
10019 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10020 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10021 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10022 // Verify type of the LHS matches so we don't fold cmp's of different
10023 // types or GEP's with different index types.
10024 I->getOperand(0)->getType() != LHSType ||
10025 I->getOperand(1)->getType() != RHSType)
10028 // If they are CmpInst instructions, check their predicates
10029 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10030 if (cast<CmpInst>(I)->getPredicate() !=
10031 cast<CmpInst>(FirstInst)->getPredicate())
10034 // Keep track of which operand needs a phi node.
10035 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10036 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10039 // Otherwise, this is safe to transform!
10041 Value *InLHS = FirstInst->getOperand(0);
10042 Value *InRHS = FirstInst->getOperand(1);
10043 PHINode *NewLHS = 0, *NewRHS = 0;
10045 NewLHS = PHINode::Create(LHSType,
10046 FirstInst->getOperand(0)->getName() + ".pn");
10047 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10048 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10049 InsertNewInstBefore(NewLHS, PN);
10054 NewRHS = PHINode::Create(RHSType,
10055 FirstInst->getOperand(1)->getName() + ".pn");
10056 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10057 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10058 InsertNewInstBefore(NewRHS, PN);
10062 // Add all operands to the new PHIs.
10063 if (NewLHS || NewRHS) {
10064 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10065 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10067 Value *NewInLHS = InInst->getOperand(0);
10068 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10071 Value *NewInRHS = InInst->getOperand(1);
10072 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10077 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10078 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10079 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10080 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10084 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10085 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10087 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10088 FirstInst->op_end());
10090 // Scan to see if all operands are the same opcode, all have one use, and all
10091 // kill their operands (i.e. the operands have one use).
10092 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10093 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10094 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10095 GEP->getNumOperands() != FirstInst->getNumOperands())
10098 // Compare the operand lists.
10099 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10100 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10103 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10104 // if one of the PHIs has a constant for the index. The index may be
10105 // substantially cheaper to compute for the constants, so making it a
10106 // variable index could pessimize the path. This also handles the case
10107 // for struct indices, which must always be constant.
10108 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10109 isa<ConstantInt>(GEP->getOperand(op)))
10112 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10114 FixedOperands[op] = 0; // Needs a PHI.
10118 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10119 // that is variable.
10120 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10122 bool HasAnyPHIs = false;
10123 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10124 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10125 Value *FirstOp = FirstInst->getOperand(i);
10126 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10127 FirstOp->getName()+".pn");
10128 InsertNewInstBefore(NewPN, PN);
10130 NewPN->reserveOperandSpace(e);
10131 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10132 OperandPhis[i] = NewPN;
10133 FixedOperands[i] = NewPN;
10138 // Add all operands to the new PHIs.
10140 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10141 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10142 BasicBlock *InBB = PN.getIncomingBlock(i);
10144 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10145 if (PHINode *OpPhi = OperandPhis[op])
10146 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10150 Value *Base = FixedOperands[0];
10151 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10152 FixedOperands.end());
10156 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10157 /// of the block that defines it. This means that it must be obvious the value
10158 /// of the load is not changed from the point of the load to the end of the
10159 /// block it is in.
10161 /// Finally, it is safe, but not profitable, to sink a load targetting a
10162 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10164 static bool isSafeToSinkLoad(LoadInst *L) {
10165 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10167 for (++BBI; BBI != E; ++BBI)
10168 if (BBI->mayWriteToMemory())
10171 // Check for non-address taken alloca. If not address-taken already, it isn't
10172 // profitable to do this xform.
10173 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10174 bool isAddressTaken = false;
10175 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10177 if (isa<LoadInst>(UI)) continue;
10178 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10179 // If storing TO the alloca, then the address isn't taken.
10180 if (SI->getOperand(1) == AI) continue;
10182 isAddressTaken = true;
10186 if (!isAddressTaken)
10194 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10195 // operator and they all are only used by the PHI, PHI together their
10196 // inputs, and do the operation once, to the result of the PHI.
10197 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10198 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10200 // Scan the instruction, looking for input operations that can be folded away.
10201 // If all input operands to the phi are the same instruction (e.g. a cast from
10202 // the same type or "+42") we can pull the operation through the PHI, reducing
10203 // code size and simplifying code.
10204 Constant *ConstantOp = 0;
10205 const Type *CastSrcTy = 0;
10206 bool isVolatile = false;
10207 if (isa<CastInst>(FirstInst)) {
10208 CastSrcTy = FirstInst->getOperand(0)->getType();
10209 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10210 // Can fold binop, compare or shift here if the RHS is a constant,
10211 // otherwise call FoldPHIArgBinOpIntoPHI.
10212 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10213 if (ConstantOp == 0)
10214 return FoldPHIArgBinOpIntoPHI(PN);
10215 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10216 isVolatile = LI->isVolatile();
10217 // We can't sink the load if the loaded value could be modified between the
10218 // load and the PHI.
10219 if (LI->getParent() != PN.getIncomingBlock(0) ||
10220 !isSafeToSinkLoad(LI))
10223 // If the PHI is of volatile loads and the load block has multiple
10224 // successors, sinking it would remove a load of the volatile value from
10225 // the path through the other successor.
10227 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10230 } else if (isa<GetElementPtrInst>(FirstInst)) {
10231 return FoldPHIArgGEPIntoPHI(PN);
10233 return 0; // Cannot fold this operation.
10236 // Check to see if all arguments are the same operation.
10237 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10238 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10239 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10240 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10243 if (I->getOperand(0)->getType() != CastSrcTy)
10244 return 0; // Cast operation must match.
10245 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10246 // We can't sink the load if the loaded value could be modified between
10247 // the load and the PHI.
10248 if (LI->isVolatile() != isVolatile ||
10249 LI->getParent() != PN.getIncomingBlock(i) ||
10250 !isSafeToSinkLoad(LI))
10253 // If the PHI is of volatile loads and the load block has multiple
10254 // successors, sinking it would remove a load of the volatile value from
10255 // the path through the other successor.
10257 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10261 } else if (I->getOperand(1) != ConstantOp) {
10266 // Okay, they are all the same operation. Create a new PHI node of the
10267 // correct type, and PHI together all of the LHS's of the instructions.
10268 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10269 PN.getName()+".in");
10270 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10272 Value *InVal = FirstInst->getOperand(0);
10273 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10275 // Add all operands to the new PHI.
10276 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10277 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10278 if (NewInVal != InVal)
10280 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10285 // The new PHI unions all of the same values together. This is really
10286 // common, so we handle it intelligently here for compile-time speed.
10290 InsertNewInstBefore(NewPN, PN);
10294 // Insert and return the new operation.
10295 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10296 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10297 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10298 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10299 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10300 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10301 PhiVal, ConstantOp);
10302 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10304 // If this was a volatile load that we are merging, make sure to loop through
10305 // and mark all the input loads as non-volatile. If we don't do this, we will
10306 // insert a new volatile load and the old ones will not be deletable.
10308 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10309 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10311 return new LoadInst(PhiVal, "", isVolatile);
10314 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10316 static bool DeadPHICycle(PHINode *PN,
10317 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10318 if (PN->use_empty()) return true;
10319 if (!PN->hasOneUse()) return false;
10321 // Remember this node, and if we find the cycle, return.
10322 if (!PotentiallyDeadPHIs.insert(PN))
10325 // Don't scan crazily complex things.
10326 if (PotentiallyDeadPHIs.size() == 16)
10329 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10330 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10335 /// PHIsEqualValue - Return true if this phi node is always equal to
10336 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10337 /// z = some value; x = phi (y, z); y = phi (x, z)
10338 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10339 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10340 // See if we already saw this PHI node.
10341 if (!ValueEqualPHIs.insert(PN))
10344 // Don't scan crazily complex things.
10345 if (ValueEqualPHIs.size() == 16)
10348 // Scan the operands to see if they are either phi nodes or are equal to
10350 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10351 Value *Op = PN->getIncomingValue(i);
10352 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10353 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10355 } else if (Op != NonPhiInVal)
10363 // PHINode simplification
10365 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10366 // If LCSSA is around, don't mess with Phi nodes
10367 if (MustPreserveLCSSA) return 0;
10369 if (Value *V = PN.hasConstantValue())
10370 return ReplaceInstUsesWith(PN, V);
10372 // If all PHI operands are the same operation, pull them through the PHI,
10373 // reducing code size.
10374 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10375 isa<Instruction>(PN.getIncomingValue(1)) &&
10376 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10377 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10378 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10379 // than themselves more than once.
10380 PN.getIncomingValue(0)->hasOneUse())
10381 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10384 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10385 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10386 // PHI)... break the cycle.
10387 if (PN.hasOneUse()) {
10388 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10389 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10390 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10391 PotentiallyDeadPHIs.insert(&PN);
10392 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10393 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10396 // If this phi has a single use, and if that use just computes a value for
10397 // the next iteration of a loop, delete the phi. This occurs with unused
10398 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10399 // common case here is good because the only other things that catch this
10400 // are induction variable analysis (sometimes) and ADCE, which is only run
10402 if (PHIUser->hasOneUse() &&
10403 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10404 PHIUser->use_back() == &PN) {
10405 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10409 // We sometimes end up with phi cycles that non-obviously end up being the
10410 // same value, for example:
10411 // z = some value; x = phi (y, z); y = phi (x, z)
10412 // where the phi nodes don't necessarily need to be in the same block. Do a
10413 // quick check to see if the PHI node only contains a single non-phi value, if
10414 // so, scan to see if the phi cycle is actually equal to that value.
10416 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10417 // Scan for the first non-phi operand.
10418 while (InValNo != NumOperandVals &&
10419 isa<PHINode>(PN.getIncomingValue(InValNo)))
10422 if (InValNo != NumOperandVals) {
10423 Value *NonPhiInVal = PN.getOperand(InValNo);
10425 // Scan the rest of the operands to see if there are any conflicts, if so
10426 // there is no need to recursively scan other phis.
10427 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10428 Value *OpVal = PN.getIncomingValue(InValNo);
10429 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10433 // If we scanned over all operands, then we have one unique value plus
10434 // phi values. Scan PHI nodes to see if they all merge in each other or
10436 if (InValNo == NumOperandVals) {
10437 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10438 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10439 return ReplaceInstUsesWith(PN, NonPhiInVal);
10446 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10447 Instruction *InsertPoint,
10448 InstCombiner *IC) {
10449 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10450 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10451 // We must cast correctly to the pointer type. Ensure that we
10452 // sign extend the integer value if it is smaller as this is
10453 // used for address computation.
10454 Instruction::CastOps opcode =
10455 (VTySize < PtrSize ? Instruction::SExt :
10456 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10457 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10461 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10462 Value *PtrOp = GEP.getOperand(0);
10463 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10464 // If so, eliminate the noop.
10465 if (GEP.getNumOperands() == 1)
10466 return ReplaceInstUsesWith(GEP, PtrOp);
10468 if (isa<UndefValue>(GEP.getOperand(0)))
10469 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10471 bool HasZeroPointerIndex = false;
10472 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10473 HasZeroPointerIndex = C->isNullValue();
10475 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10476 return ReplaceInstUsesWith(GEP, PtrOp);
10478 // Eliminate unneeded casts for indices.
10479 bool MadeChange = false;
10481 gep_type_iterator GTI = gep_type_begin(GEP);
10482 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10483 i != e; ++i, ++GTI) {
10484 if (isa<SequentialType>(*GTI)) {
10485 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10486 if (CI->getOpcode() == Instruction::ZExt ||
10487 CI->getOpcode() == Instruction::SExt) {
10488 const Type *SrcTy = CI->getOperand(0)->getType();
10489 // We can eliminate a cast from i32 to i64 iff the target
10490 // is a 32-bit pointer target.
10491 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10493 *i = CI->getOperand(0);
10497 // If we are using a wider index than needed for this platform, shrink it
10498 // to what we need. If narrower, sign-extend it to what we need.
10499 // If the incoming value needs a cast instruction,
10500 // insert it. This explicit cast can make subsequent optimizations more
10503 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10504 if (Constant *C = dyn_cast<Constant>(Op)) {
10505 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10508 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10513 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10514 if (Constant *C = dyn_cast<Constant>(Op)) {
10515 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10518 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10526 if (MadeChange) return &GEP;
10528 // Combine Indices - If the source pointer to this getelementptr instruction
10529 // is a getelementptr instruction, combine the indices of the two
10530 // getelementptr instructions into a single instruction.
10532 SmallVector<Value*, 8> SrcGEPOperands;
10533 if (User *Src = dyn_castGetElementPtr(PtrOp))
10534 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10536 if (!SrcGEPOperands.empty()) {
10537 // Note that if our source is a gep chain itself that we wait for that
10538 // chain to be resolved before we perform this transformation. This
10539 // avoids us creating a TON of code in some cases.
10541 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10542 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10543 return 0; // Wait until our source is folded to completion.
10545 SmallVector<Value*, 8> Indices;
10547 // Find out whether the last index in the source GEP is a sequential idx.
10548 bool EndsWithSequential = false;
10549 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10550 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10551 EndsWithSequential = !isa<StructType>(*I);
10553 // Can we combine the two pointer arithmetics offsets?
10554 if (EndsWithSequential) {
10555 // Replace: gep (gep %P, long B), long A, ...
10556 // With: T = long A+B; gep %P, T, ...
10558 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10559 if (SO1 == Constant::getNullValue(SO1->getType())) {
10561 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10564 // If they aren't the same type, convert both to an integer of the
10565 // target's pointer size.
10566 if (SO1->getType() != GO1->getType()) {
10567 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10568 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10569 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10570 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10572 unsigned PS = TD->getPointerSizeInBits();
10573 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10574 // Convert GO1 to SO1's type.
10575 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10577 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10578 // Convert SO1 to GO1's type.
10579 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10581 const Type *PT = TD->getIntPtrType();
10582 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10583 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10587 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10588 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10590 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10591 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10595 // Recycle the GEP we already have if possible.
10596 if (SrcGEPOperands.size() == 2) {
10597 GEP.setOperand(0, SrcGEPOperands[0]);
10598 GEP.setOperand(1, Sum);
10601 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10602 SrcGEPOperands.end()-1);
10603 Indices.push_back(Sum);
10604 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10606 } else if (isa<Constant>(*GEP.idx_begin()) &&
10607 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10608 SrcGEPOperands.size() != 1) {
10609 // Otherwise we can do the fold if the first index of the GEP is a zero
10610 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10611 SrcGEPOperands.end());
10612 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10615 if (!Indices.empty())
10616 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10617 Indices.end(), GEP.getName());
10619 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10620 // GEP of global variable. If all of the indices for this GEP are
10621 // constants, we can promote this to a constexpr instead of an instruction.
10623 // Scan for nonconstants...
10624 SmallVector<Constant*, 8> Indices;
10625 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10626 for (; I != E && isa<Constant>(*I); ++I)
10627 Indices.push_back(cast<Constant>(*I));
10629 if (I == E) { // If they are all constants...
10630 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10631 &Indices[0],Indices.size());
10633 // Replace all uses of the GEP with the new constexpr...
10634 return ReplaceInstUsesWith(GEP, CE);
10636 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10637 if (!isa<PointerType>(X->getType())) {
10638 // Not interesting. Source pointer must be a cast from pointer.
10639 } else if (HasZeroPointerIndex) {
10640 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10641 // into : GEP [10 x i8]* X, i32 0, ...
10643 // This occurs when the program declares an array extern like "int X[];"
10645 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10646 const PointerType *XTy = cast<PointerType>(X->getType());
10647 if (const ArrayType *XATy =
10648 dyn_cast<ArrayType>(XTy->getElementType()))
10649 if (const ArrayType *CATy =
10650 dyn_cast<ArrayType>(CPTy->getElementType()))
10651 if (CATy->getElementType() == XATy->getElementType()) {
10652 // At this point, we know that the cast source type is a pointer
10653 // to an array of the same type as the destination pointer
10654 // array. Because the array type is never stepped over (there
10655 // is a leading zero) we can fold the cast into this GEP.
10656 GEP.setOperand(0, X);
10659 } else if (GEP.getNumOperands() == 2) {
10660 // Transform things like:
10661 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10662 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10663 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10664 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10665 if (isa<ArrayType>(SrcElTy) &&
10666 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10667 TD->getTypePaddedSize(ResElTy)) {
10669 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10670 Idx[1] = GEP.getOperand(1);
10671 Value *V = InsertNewInstBefore(
10672 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10673 // V and GEP are both pointer types --> BitCast
10674 return new BitCastInst(V, GEP.getType());
10677 // Transform things like:
10678 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10679 // (where tmp = 8*tmp2) into:
10680 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10682 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10683 uint64_t ArrayEltSize =
10684 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
10686 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10687 // allow either a mul, shift, or constant here.
10689 ConstantInt *Scale = 0;
10690 if (ArrayEltSize == 1) {
10691 NewIdx = GEP.getOperand(1);
10692 Scale = ConstantInt::get(NewIdx->getType(), 1);
10693 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10694 NewIdx = ConstantInt::get(CI->getType(), 1);
10696 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10697 if (Inst->getOpcode() == Instruction::Shl &&
10698 isa<ConstantInt>(Inst->getOperand(1))) {
10699 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10700 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10701 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10702 NewIdx = Inst->getOperand(0);
10703 } else if (Inst->getOpcode() == Instruction::Mul &&
10704 isa<ConstantInt>(Inst->getOperand(1))) {
10705 Scale = cast<ConstantInt>(Inst->getOperand(1));
10706 NewIdx = Inst->getOperand(0);
10710 // If the index will be to exactly the right offset with the scale taken
10711 // out, perform the transformation. Note, we don't know whether Scale is
10712 // signed or not. We'll use unsigned version of division/modulo
10713 // operation after making sure Scale doesn't have the sign bit set.
10714 if (Scale && Scale->getSExtValue() >= 0LL &&
10715 Scale->getZExtValue() % ArrayEltSize == 0) {
10716 Scale = ConstantInt::get(Scale->getType(),
10717 Scale->getZExtValue() / ArrayEltSize);
10718 if (Scale->getZExtValue() != 1) {
10719 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10721 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10722 NewIdx = InsertNewInstBefore(Sc, GEP);
10725 // Insert the new GEP instruction.
10727 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10729 Instruction *NewGEP =
10730 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10731 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10732 // The NewGEP must be pointer typed, so must the old one -> BitCast
10733 return new BitCastInst(NewGEP, GEP.getType());
10739 /// See if we can simplify:
10740 /// X = bitcast A to B*
10741 /// Y = gep X, <...constant indices...>
10742 /// into a gep of the original struct. This is important for SROA and alias
10743 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
10744 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
10745 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10746 // Determine how much the GEP moves the pointer. We are guaranteed to get
10747 // a constant back from EmitGEPOffset.
10748 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10749 int64_t Offset = OffsetV->getSExtValue();
10751 // If this GEP instruction doesn't move the pointer, just replace the GEP
10752 // with a bitcast of the real input to the dest type.
10754 // If the bitcast is of an allocation, and the allocation will be
10755 // converted to match the type of the cast, don't touch this.
10756 if (isa<AllocationInst>(BCI->getOperand(0))) {
10757 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10758 if (Instruction *I = visitBitCast(*BCI)) {
10761 BCI->getParent()->getInstList().insert(BCI, I);
10762 ReplaceInstUsesWith(*BCI, I);
10767 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10770 // Otherwise, if the offset is non-zero, we need to find out if there is a
10771 // field at Offset in 'A's type. If so, we can pull the cast through the
10773 SmallVector<Value*, 8> NewIndices;
10775 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10776 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10777 Instruction *NGEP =
10778 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10780 if (NGEP->getType() == GEP.getType()) return NGEP;
10781 InsertNewInstBefore(NGEP, GEP);
10782 NGEP->takeName(&GEP);
10783 return new BitCastInst(NGEP, GEP.getType());
10791 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10792 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10793 if (AI.isArrayAllocation()) { // Check C != 1
10794 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10795 const Type *NewTy =
10796 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10797 AllocationInst *New = 0;
10799 // Create and insert the replacement instruction...
10800 if (isa<MallocInst>(AI))
10801 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10803 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10804 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10807 InsertNewInstBefore(New, AI);
10809 // Scan to the end of the allocation instructions, to skip over a block of
10810 // allocas if possible...
10812 BasicBlock::iterator It = New;
10813 while (isa<AllocationInst>(*It)) ++It;
10815 // Now that I is pointing to the first non-allocation-inst in the block,
10816 // insert our getelementptr instruction...
10818 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10822 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10823 New->getName()+".sub", It);
10825 // Now make everything use the getelementptr instead of the original
10827 return ReplaceInstUsesWith(AI, V);
10828 } else if (isa<UndefValue>(AI.getArraySize())) {
10829 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10833 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10834 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10835 // Note that we only do this for alloca's, because malloc should allocate and
10836 // return a unique pointer, even for a zero byte allocation.
10837 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10838 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10840 // If the alignment is 0 (unspecified), assign it the preferred alignment.
10841 if (AI.getAlignment() == 0)
10842 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10848 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10849 Value *Op = FI.getOperand(0);
10851 // free undef -> unreachable.
10852 if (isa<UndefValue>(Op)) {
10853 // Insert a new store to null because we cannot modify the CFG here.
10854 new StoreInst(ConstantInt::getTrue(),
10855 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10856 return EraseInstFromFunction(FI);
10859 // If we have 'free null' delete the instruction. This can happen in stl code
10860 // when lots of inlining happens.
10861 if (isa<ConstantPointerNull>(Op))
10862 return EraseInstFromFunction(FI);
10864 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10865 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10866 FI.setOperand(0, CI->getOperand(0));
10870 // Change free (gep X, 0,0,0,0) into free(X)
10871 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10872 if (GEPI->hasAllZeroIndices()) {
10873 AddToWorkList(GEPI);
10874 FI.setOperand(0, GEPI->getOperand(0));
10879 // Change free(malloc) into nothing, if the malloc has a single use.
10880 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10881 if (MI->hasOneUse()) {
10882 EraseInstFromFunction(FI);
10883 return EraseInstFromFunction(*MI);
10890 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10891 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10892 const TargetData *TD) {
10893 User *CI = cast<User>(LI.getOperand(0));
10894 Value *CastOp = CI->getOperand(0);
10896 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10897 // Instead of loading constant c string, use corresponding integer value
10898 // directly if string length is small enough.
10900 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10901 unsigned len = Str.length();
10902 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10903 unsigned numBits = Ty->getPrimitiveSizeInBits();
10904 // Replace LI with immediate integer store.
10905 if ((numBits >> 3) == len + 1) {
10906 APInt StrVal(numBits, 0);
10907 APInt SingleChar(numBits, 0);
10908 if (TD->isLittleEndian()) {
10909 for (signed i = len-1; i >= 0; i--) {
10910 SingleChar = (uint64_t) Str[i];
10911 StrVal = (StrVal << 8) | SingleChar;
10914 for (unsigned i = 0; i < len; i++) {
10915 SingleChar = (uint64_t) Str[i];
10916 StrVal = (StrVal << 8) | SingleChar;
10918 // Append NULL at the end.
10920 StrVal = (StrVal << 8) | SingleChar;
10922 Value *NL = ConstantInt::get(StrVal);
10923 return IC.ReplaceInstUsesWith(LI, NL);
10928 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10929 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10930 const Type *SrcPTy = SrcTy->getElementType();
10932 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10933 isa<VectorType>(DestPTy)) {
10934 // If the source is an array, the code below will not succeed. Check to
10935 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10937 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10938 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10939 if (ASrcTy->getNumElements() != 0) {
10941 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10942 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10943 SrcTy = cast<PointerType>(CastOp->getType());
10944 SrcPTy = SrcTy->getElementType();
10947 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10948 isa<VectorType>(SrcPTy)) &&
10949 // Do not allow turning this into a load of an integer, which is then
10950 // casted to a pointer, this pessimizes pointer analysis a lot.
10951 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10952 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10953 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10955 // Okay, we are casting from one integer or pointer type to another of
10956 // the same size. Instead of casting the pointer before the load, cast
10957 // the result of the loaded value.
10958 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10960 LI.isVolatile()),LI);
10961 // Now cast the result of the load.
10962 return new BitCastInst(NewLoad, LI.getType());
10969 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10970 /// from this value cannot trap. If it is not obviously safe to load from the
10971 /// specified pointer, we do a quick local scan of the basic block containing
10972 /// ScanFrom, to determine if the address is already accessed.
10973 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10974 // If it is an alloca it is always safe to load from.
10975 if (isa<AllocaInst>(V)) return true;
10977 // If it is a global variable it is mostly safe to load from.
10978 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10979 // Don't try to evaluate aliases. External weak GV can be null.
10980 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10982 // Otherwise, be a little bit agressive by scanning the local block where we
10983 // want to check to see if the pointer is already being loaded or stored
10984 // from/to. If so, the previous load or store would have already trapped,
10985 // so there is no harm doing an extra load (also, CSE will later eliminate
10986 // the load entirely).
10987 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10992 // If we see a free or a call (which might do a free) the pointer could be
10994 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10997 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10998 if (LI->getOperand(0) == V) return true;
10999 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11000 if (SI->getOperand(1) == V) return true;
11007 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11008 Value *Op = LI.getOperand(0);
11010 // Attempt to improve the alignment.
11011 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
11013 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11014 LI.getAlignment()))
11015 LI.setAlignment(KnownAlign);
11017 // load (cast X) --> cast (load X) iff safe
11018 if (isa<CastInst>(Op))
11019 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11022 // None of the following transforms are legal for volatile loads.
11023 if (LI.isVolatile()) return 0;
11025 // Do really simple store-to-load forwarding and load CSE, to catch cases
11026 // where there are several consequtive memory accesses to the same location,
11027 // separated by a few arithmetic operations.
11028 BasicBlock::iterator BBI = &LI;
11029 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11030 return ReplaceInstUsesWith(LI, AvailableVal);
11032 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11033 const Value *GEPI0 = GEPI->getOperand(0);
11034 // TODO: Consider a target hook for valid address spaces for this xform.
11035 if (isa<ConstantPointerNull>(GEPI0) &&
11036 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11037 // Insert a new store to null instruction before the load to indicate
11038 // that this code is not reachable. We do this instead of inserting
11039 // an unreachable instruction directly because we cannot modify the
11041 new StoreInst(UndefValue::get(LI.getType()),
11042 Constant::getNullValue(Op->getType()), &LI);
11043 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11047 if (Constant *C = dyn_cast<Constant>(Op)) {
11048 // load null/undef -> undef
11049 // TODO: Consider a target hook for valid address spaces for this xform.
11050 if (isa<UndefValue>(C) || (C->isNullValue() &&
11051 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11052 // Insert a new store to null instruction before the load to indicate that
11053 // this code is not reachable. We do this instead of inserting an
11054 // unreachable instruction directly because we cannot modify the CFG.
11055 new StoreInst(UndefValue::get(LI.getType()),
11056 Constant::getNullValue(Op->getType()), &LI);
11057 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11060 // Instcombine load (constant global) into the value loaded.
11061 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11062 if (GV->isConstant() && !GV->isDeclaration())
11063 return ReplaceInstUsesWith(LI, GV->getInitializer());
11065 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11066 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11067 if (CE->getOpcode() == Instruction::GetElementPtr) {
11068 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11069 if (GV->isConstant() && !GV->isDeclaration())
11071 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11072 return ReplaceInstUsesWith(LI, V);
11073 if (CE->getOperand(0)->isNullValue()) {
11074 // Insert a new store to null instruction before the load to indicate
11075 // that this code is not reachable. We do this instead of inserting
11076 // an unreachable instruction directly because we cannot modify the
11078 new StoreInst(UndefValue::get(LI.getType()),
11079 Constant::getNullValue(Op->getType()), &LI);
11080 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11083 } else if (CE->isCast()) {
11084 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11090 // If this load comes from anywhere in a constant global, and if the global
11091 // is all undef or zero, we know what it loads.
11092 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11093 if (GV->isConstant() && GV->hasInitializer()) {
11094 if (GV->getInitializer()->isNullValue())
11095 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11096 else if (isa<UndefValue>(GV->getInitializer()))
11097 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11101 if (Op->hasOneUse()) {
11102 // Change select and PHI nodes to select values instead of addresses: this
11103 // helps alias analysis out a lot, allows many others simplifications, and
11104 // exposes redundancy in the code.
11106 // Note that we cannot do the transformation unless we know that the
11107 // introduced loads cannot trap! Something like this is valid as long as
11108 // the condition is always false: load (select bool %C, int* null, int* %G),
11109 // but it would not be valid if we transformed it to load from null
11110 // unconditionally.
11112 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11113 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11114 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11115 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11116 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11117 SI->getOperand(1)->getName()+".val"), LI);
11118 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11119 SI->getOperand(2)->getName()+".val"), LI);
11120 return SelectInst::Create(SI->getCondition(), V1, V2);
11123 // load (select (cond, null, P)) -> load P
11124 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11125 if (C->isNullValue()) {
11126 LI.setOperand(0, SI->getOperand(2));
11130 // load (select (cond, P, null)) -> load P
11131 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11132 if (C->isNullValue()) {
11133 LI.setOperand(0, SI->getOperand(1));
11141 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11143 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11144 User *CI = cast<User>(SI.getOperand(1));
11145 Value *CastOp = CI->getOperand(0);
11147 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11148 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11149 if (SrcTy == 0) return 0;
11151 const Type *SrcPTy = SrcTy->getElementType();
11153 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11156 // If the source is an array, the code below will not succeed. Check to
11157 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11159 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11160 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11161 if (ASrcTy->getNumElements() != 0) {
11163 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11164 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11165 SrcTy = cast<PointerType>(CastOp->getType());
11166 SrcPTy = SrcTy->getElementType();
11169 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11172 if (IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11173 IC.getTargetData().getTypeSizeInBits(DestPTy))
11176 // Okay, we are casting from one integer or pointer type to another of
11177 // the same size. Instead of casting the pointer before
11178 // the store, cast the value to be stored.
11180 Value *SIOp0 = SI.getOperand(0);
11181 Instruction::CastOps opcode = Instruction::BitCast;
11182 const Type* CastSrcTy = SIOp0->getType();
11183 const Type* CastDstTy = SrcPTy;
11184 if (isa<PointerType>(CastDstTy)) {
11185 if (CastSrcTy->isInteger())
11186 opcode = Instruction::IntToPtr;
11187 } else if (isa<IntegerType>(CastDstTy)) {
11188 if (isa<PointerType>(SIOp0->getType()))
11189 opcode = Instruction::PtrToInt;
11191 if (Constant *C = dyn_cast<Constant>(SIOp0))
11192 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11194 NewCast = IC.InsertNewInstBefore(
11195 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11197 return new StoreInst(NewCast, CastOp);
11200 /// equivalentAddressValues - Test if A and B will obviously have the same
11201 /// value. This includes recognizing that %t0 and %t1 will have the same
11202 /// value in code like this:
11203 /// %t0 = getelementptr @a, 0, 3
11204 /// store i32 0, i32* %t0
11205 /// %t1 = getelementptr @a, 0, 3
11206 /// %t2 = load i32* %t1
11208 static bool equivalentAddressValues(Value *A, Value *B) {
11209 // Test if the values are trivially equivalent.
11210 if (A == B) return true;
11212 // Test if the values come form identical arithmetic instructions.
11213 if (isa<BinaryOperator>(A) ||
11214 isa<CastInst>(A) ||
11216 isa<GetElementPtrInst>(A))
11217 if (Instruction *BI = dyn_cast<Instruction>(B))
11218 if (cast<Instruction>(A)->isIdenticalTo(BI))
11221 // Otherwise they may not be equivalent.
11225 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11226 Value *Val = SI.getOperand(0);
11227 Value *Ptr = SI.getOperand(1);
11229 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11230 EraseInstFromFunction(SI);
11235 // If the RHS is an alloca with a single use, zapify the store, making the
11237 if (Ptr->hasOneUse() && !SI.isVolatile()) {
11238 if (isa<AllocaInst>(Ptr)) {
11239 EraseInstFromFunction(SI);
11244 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11245 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11246 GEP->getOperand(0)->hasOneUse()) {
11247 EraseInstFromFunction(SI);
11253 // Attempt to improve the alignment.
11254 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11256 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11257 SI.getAlignment()))
11258 SI.setAlignment(KnownAlign);
11260 // Do really simple DSE, to catch cases where there are several consequtive
11261 // stores to the same location, separated by a few arithmetic operations. This
11262 // situation often occurs with bitfield accesses.
11263 BasicBlock::iterator BBI = &SI;
11264 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11268 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11269 // Prev store isn't volatile, and stores to the same location?
11270 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11271 SI.getOperand(1))) {
11274 EraseInstFromFunction(*PrevSI);
11280 // If this is a load, we have to stop. However, if the loaded value is from
11281 // the pointer we're loading and is producing the pointer we're storing,
11282 // then *this* store is dead (X = load P; store X -> P).
11283 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11284 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11285 !SI.isVolatile()) {
11286 EraseInstFromFunction(SI);
11290 // Otherwise, this is a load from some other location. Stores before it
11291 // may not be dead.
11295 // Don't skip over loads or things that can modify memory.
11296 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11301 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11303 // store X, null -> turns into 'unreachable' in SimplifyCFG
11304 if (isa<ConstantPointerNull>(Ptr)) {
11305 if (!isa<UndefValue>(Val)) {
11306 SI.setOperand(0, UndefValue::get(Val->getType()));
11307 if (Instruction *U = dyn_cast<Instruction>(Val))
11308 AddToWorkList(U); // Dropped a use.
11311 return 0; // Do not modify these!
11314 // store undef, Ptr -> noop
11315 if (isa<UndefValue>(Val)) {
11316 EraseInstFromFunction(SI);
11321 // If the pointer destination is a cast, see if we can fold the cast into the
11323 if (isa<CastInst>(Ptr))
11324 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11326 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11328 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11332 // If this store is the last instruction in the basic block, and if the block
11333 // ends with an unconditional branch, try to move it to the successor block.
11335 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11336 if (BI->isUnconditional())
11337 if (SimplifyStoreAtEndOfBlock(SI))
11338 return 0; // xform done!
11343 /// SimplifyStoreAtEndOfBlock - Turn things like:
11344 /// if () { *P = v1; } else { *P = v2 }
11345 /// into a phi node with a store in the successor.
11347 /// Simplify things like:
11348 /// *P = v1; if () { *P = v2; }
11349 /// into a phi node with a store in the successor.
11351 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11352 BasicBlock *StoreBB = SI.getParent();
11354 // Check to see if the successor block has exactly two incoming edges. If
11355 // so, see if the other predecessor contains a store to the same location.
11356 // if so, insert a PHI node (if needed) and move the stores down.
11357 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11359 // Determine whether Dest has exactly two predecessors and, if so, compute
11360 // the other predecessor.
11361 pred_iterator PI = pred_begin(DestBB);
11362 BasicBlock *OtherBB = 0;
11363 if (*PI != StoreBB)
11366 if (PI == pred_end(DestBB))
11369 if (*PI != StoreBB) {
11374 if (++PI != pred_end(DestBB))
11377 // Bail out if all the relevant blocks aren't distinct (this can happen,
11378 // for example, if SI is in an infinite loop)
11379 if (StoreBB == DestBB || OtherBB == DestBB)
11382 // Verify that the other block ends in a branch and is not otherwise empty.
11383 BasicBlock::iterator BBI = OtherBB->getTerminator();
11384 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11385 if (!OtherBr || BBI == OtherBB->begin())
11388 // If the other block ends in an unconditional branch, check for the 'if then
11389 // else' case. there is an instruction before the branch.
11390 StoreInst *OtherStore = 0;
11391 if (OtherBr->isUnconditional()) {
11392 // If this isn't a store, or isn't a store to the same location, bail out.
11394 OtherStore = dyn_cast<StoreInst>(BBI);
11395 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11398 // Otherwise, the other block ended with a conditional branch. If one of the
11399 // destinations is StoreBB, then we have the if/then case.
11400 if (OtherBr->getSuccessor(0) != StoreBB &&
11401 OtherBr->getSuccessor(1) != StoreBB)
11404 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11405 // if/then triangle. See if there is a store to the same ptr as SI that
11406 // lives in OtherBB.
11408 // Check to see if we find the matching store.
11409 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11410 if (OtherStore->getOperand(1) != SI.getOperand(1))
11414 // If we find something that may be using or overwriting the stored
11415 // value, or if we run out of instructions, we can't do the xform.
11416 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11417 BBI == OtherBB->begin())
11421 // In order to eliminate the store in OtherBr, we have to
11422 // make sure nothing reads or overwrites the stored value in
11424 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11425 // FIXME: This should really be AA driven.
11426 if (I->mayReadFromMemory() || I->mayWriteToMemory())
11431 // Insert a PHI node now if we need it.
11432 Value *MergedVal = OtherStore->getOperand(0);
11433 if (MergedVal != SI.getOperand(0)) {
11434 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11435 PN->reserveOperandSpace(2);
11436 PN->addIncoming(SI.getOperand(0), SI.getParent());
11437 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11438 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11441 // Advance to a place where it is safe to insert the new store and
11443 BBI = DestBB->getFirstNonPHI();
11444 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11445 OtherStore->isVolatile()), *BBI);
11447 // Nuke the old stores.
11448 EraseInstFromFunction(SI);
11449 EraseInstFromFunction(*OtherStore);
11455 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11456 // Change br (not X), label True, label False to: br X, label False, True
11458 BasicBlock *TrueDest;
11459 BasicBlock *FalseDest;
11460 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11461 !isa<Constant>(X)) {
11462 // Swap Destinations and condition...
11463 BI.setCondition(X);
11464 BI.setSuccessor(0, FalseDest);
11465 BI.setSuccessor(1, TrueDest);
11469 // Cannonicalize fcmp_one -> fcmp_oeq
11470 FCmpInst::Predicate FPred; Value *Y;
11471 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11472 TrueDest, FalseDest)))
11473 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11474 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11475 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11476 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11477 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11478 NewSCC->takeName(I);
11479 // Swap Destinations and condition...
11480 BI.setCondition(NewSCC);
11481 BI.setSuccessor(0, FalseDest);
11482 BI.setSuccessor(1, TrueDest);
11483 RemoveFromWorkList(I);
11484 I->eraseFromParent();
11485 AddToWorkList(NewSCC);
11489 // Cannonicalize icmp_ne -> icmp_eq
11490 ICmpInst::Predicate IPred;
11491 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11492 TrueDest, FalseDest)))
11493 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11494 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11495 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11496 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11497 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11498 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11499 NewSCC->takeName(I);
11500 // Swap Destinations and condition...
11501 BI.setCondition(NewSCC);
11502 BI.setSuccessor(0, FalseDest);
11503 BI.setSuccessor(1, TrueDest);
11504 RemoveFromWorkList(I);
11505 I->eraseFromParent();;
11506 AddToWorkList(NewSCC);
11513 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11514 Value *Cond = SI.getCondition();
11515 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11516 if (I->getOpcode() == Instruction::Add)
11517 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11518 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11519 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11520 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11522 SI.setOperand(0, I->getOperand(0));
11530 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11531 Value *Agg = EV.getAggregateOperand();
11533 if (!EV.hasIndices())
11534 return ReplaceInstUsesWith(EV, Agg);
11536 if (Constant *C = dyn_cast<Constant>(Agg)) {
11537 if (isa<UndefValue>(C))
11538 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11540 if (isa<ConstantAggregateZero>(C))
11541 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11543 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11544 // Extract the element indexed by the first index out of the constant
11545 Value *V = C->getOperand(*EV.idx_begin());
11546 if (EV.getNumIndices() > 1)
11547 // Extract the remaining indices out of the constant indexed by the
11549 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11551 return ReplaceInstUsesWith(EV, V);
11553 return 0; // Can't handle other constants
11555 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11556 // We're extracting from an insertvalue instruction, compare the indices
11557 const unsigned *exti, *exte, *insi, *inse;
11558 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11559 exte = EV.idx_end(), inse = IV->idx_end();
11560 exti != exte && insi != inse;
11562 if (*insi != *exti)
11563 // The insert and extract both reference distinctly different elements.
11564 // This means the extract is not influenced by the insert, and we can
11565 // replace the aggregate operand of the extract with the aggregate
11566 // operand of the insert. i.e., replace
11567 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11568 // %E = extractvalue { i32, { i32 } } %I, 0
11570 // %E = extractvalue { i32, { i32 } } %A, 0
11571 return ExtractValueInst::Create(IV->getAggregateOperand(),
11572 EV.idx_begin(), EV.idx_end());
11574 if (exti == exte && insi == inse)
11575 // Both iterators are at the end: Index lists are identical. Replace
11576 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11577 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11579 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11580 if (exti == exte) {
11581 // The extract list is a prefix of the insert list. i.e. replace
11582 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11583 // %E = extractvalue { i32, { i32 } } %I, 1
11585 // %X = extractvalue { i32, { i32 } } %A, 1
11586 // %E = insertvalue { i32 } %X, i32 42, 0
11587 // by switching the order of the insert and extract (though the
11588 // insertvalue should be left in, since it may have other uses).
11589 Value *NewEV = InsertNewInstBefore(
11590 ExtractValueInst::Create(IV->getAggregateOperand(),
11591 EV.idx_begin(), EV.idx_end()),
11593 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11597 // The insert list is a prefix of the extract list
11598 // We can simply remove the common indices from the extract and make it
11599 // operate on the inserted value instead of the insertvalue result.
11601 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11602 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11604 // %E extractvalue { i32 } { i32 42 }, 0
11605 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11608 // Can't simplify extracts from other values. Note that nested extracts are
11609 // already simplified implicitely by the above (extract ( extract (insert) )
11610 // will be translated into extract ( insert ( extract ) ) first and then just
11611 // the value inserted, if appropriate).
11615 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11616 /// is to leave as a vector operation.
11617 static bool CheapToScalarize(Value *V, bool isConstant) {
11618 if (isa<ConstantAggregateZero>(V))
11620 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11621 if (isConstant) return true;
11622 // If all elts are the same, we can extract.
11623 Constant *Op0 = C->getOperand(0);
11624 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11625 if (C->getOperand(i) != Op0)
11629 Instruction *I = dyn_cast<Instruction>(V);
11630 if (!I) return false;
11632 // Insert element gets simplified to the inserted element or is deleted if
11633 // this is constant idx extract element and its a constant idx insertelt.
11634 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11635 isa<ConstantInt>(I->getOperand(2)))
11637 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11639 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11640 if (BO->hasOneUse() &&
11641 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11642 CheapToScalarize(BO->getOperand(1), isConstant)))
11644 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11645 if (CI->hasOneUse() &&
11646 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11647 CheapToScalarize(CI->getOperand(1), isConstant)))
11653 /// Read and decode a shufflevector mask.
11655 /// It turns undef elements into values that are larger than the number of
11656 /// elements in the input.
11657 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11658 unsigned NElts = SVI->getType()->getNumElements();
11659 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11660 return std::vector<unsigned>(NElts, 0);
11661 if (isa<UndefValue>(SVI->getOperand(2)))
11662 return std::vector<unsigned>(NElts, 2*NElts);
11664 std::vector<unsigned> Result;
11665 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11666 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11667 if (isa<UndefValue>(*i))
11668 Result.push_back(NElts*2); // undef -> 8
11670 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11674 /// FindScalarElement - Given a vector and an element number, see if the scalar
11675 /// value is already around as a register, for example if it were inserted then
11676 /// extracted from the vector.
11677 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11678 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11679 const VectorType *PTy = cast<VectorType>(V->getType());
11680 unsigned Width = PTy->getNumElements();
11681 if (EltNo >= Width) // Out of range access.
11682 return UndefValue::get(PTy->getElementType());
11684 if (isa<UndefValue>(V))
11685 return UndefValue::get(PTy->getElementType());
11686 else if (isa<ConstantAggregateZero>(V))
11687 return Constant::getNullValue(PTy->getElementType());
11688 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11689 return CP->getOperand(EltNo);
11690 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11691 // If this is an insert to a variable element, we don't know what it is.
11692 if (!isa<ConstantInt>(III->getOperand(2)))
11694 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11696 // If this is an insert to the element we are looking for, return the
11698 if (EltNo == IIElt)
11699 return III->getOperand(1);
11701 // Otherwise, the insertelement doesn't modify the value, recurse on its
11703 return FindScalarElement(III->getOperand(0), EltNo);
11704 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11705 unsigned LHSWidth =
11706 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11707 unsigned InEl = getShuffleMask(SVI)[EltNo];
11708 if (InEl < LHSWidth)
11709 return FindScalarElement(SVI->getOperand(0), InEl);
11710 else if (InEl < LHSWidth*2)
11711 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11713 return UndefValue::get(PTy->getElementType());
11716 // Otherwise, we don't know.
11720 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11721 // If vector val is undef, replace extract with scalar undef.
11722 if (isa<UndefValue>(EI.getOperand(0)))
11723 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11725 // If vector val is constant 0, replace extract with scalar 0.
11726 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11727 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11729 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11730 // If vector val is constant with all elements the same, replace EI with
11731 // that element. When the elements are not identical, we cannot replace yet
11732 // (we do that below, but only when the index is constant).
11733 Constant *op0 = C->getOperand(0);
11734 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11735 if (C->getOperand(i) != op0) {
11740 return ReplaceInstUsesWith(EI, op0);
11743 // If extracting a specified index from the vector, see if we can recursively
11744 // find a previously computed scalar that was inserted into the vector.
11745 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11746 unsigned IndexVal = IdxC->getZExtValue();
11747 unsigned VectorWidth =
11748 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11750 // If this is extracting an invalid index, turn this into undef, to avoid
11751 // crashing the code below.
11752 if (IndexVal >= VectorWidth)
11753 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11755 // This instruction only demands the single element from the input vector.
11756 // If the input vector has a single use, simplify it based on this use
11758 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11759 uint64_t UndefElts;
11760 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11763 EI.setOperand(0, V);
11768 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11769 return ReplaceInstUsesWith(EI, Elt);
11771 // If the this extractelement is directly using a bitcast from a vector of
11772 // the same number of elements, see if we can find the source element from
11773 // it. In this case, we will end up needing to bitcast the scalars.
11774 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11775 if (const VectorType *VT =
11776 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11777 if (VT->getNumElements() == VectorWidth)
11778 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11779 return new BitCastInst(Elt, EI.getType());
11783 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11784 if (I->hasOneUse()) {
11785 // Push extractelement into predecessor operation if legal and
11786 // profitable to do so
11787 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11788 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11789 if (CheapToScalarize(BO, isConstantElt)) {
11790 ExtractElementInst *newEI0 =
11791 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11792 EI.getName()+".lhs");
11793 ExtractElementInst *newEI1 =
11794 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11795 EI.getName()+".rhs");
11796 InsertNewInstBefore(newEI0, EI);
11797 InsertNewInstBefore(newEI1, EI);
11798 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11800 } else if (isa<LoadInst>(I)) {
11802 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11803 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11804 PointerType::get(EI.getType(), AS),EI);
11805 GetElementPtrInst *GEP =
11806 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11807 InsertNewInstBefore(GEP, EI);
11808 return new LoadInst(GEP);
11811 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11812 // Extracting the inserted element?
11813 if (IE->getOperand(2) == EI.getOperand(1))
11814 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11815 // If the inserted and extracted elements are constants, they must not
11816 // be the same value, extract from the pre-inserted value instead.
11817 if (isa<Constant>(IE->getOperand(2)) &&
11818 isa<Constant>(EI.getOperand(1))) {
11819 AddUsesToWorkList(EI);
11820 EI.setOperand(0, IE->getOperand(0));
11823 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11824 // If this is extracting an element from a shufflevector, figure out where
11825 // it came from and extract from the appropriate input element instead.
11826 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11827 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11829 unsigned LHSWidth =
11830 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11832 if (SrcIdx < LHSWidth)
11833 Src = SVI->getOperand(0);
11834 else if (SrcIdx < LHSWidth*2) {
11835 SrcIdx -= LHSWidth;
11836 Src = SVI->getOperand(1);
11838 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11840 return new ExtractElementInst(Src, SrcIdx);
11847 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11848 /// elements from either LHS or RHS, return the shuffle mask and true.
11849 /// Otherwise, return false.
11850 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11851 std::vector<Constant*> &Mask) {
11852 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11853 "Invalid CollectSingleShuffleElements");
11854 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11856 if (isa<UndefValue>(V)) {
11857 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11859 } else if (V == LHS) {
11860 for (unsigned i = 0; i != NumElts; ++i)
11861 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11863 } else if (V == RHS) {
11864 for (unsigned i = 0; i != NumElts; ++i)
11865 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11867 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11868 // If this is an insert of an extract from some other vector, include it.
11869 Value *VecOp = IEI->getOperand(0);
11870 Value *ScalarOp = IEI->getOperand(1);
11871 Value *IdxOp = IEI->getOperand(2);
11873 if (!isa<ConstantInt>(IdxOp))
11875 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11877 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11878 // Okay, we can handle this if the vector we are insertinting into is
11879 // transitively ok.
11880 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11881 // If so, update the mask to reflect the inserted undef.
11882 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11885 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11886 if (isa<ConstantInt>(EI->getOperand(1)) &&
11887 EI->getOperand(0)->getType() == V->getType()) {
11888 unsigned ExtractedIdx =
11889 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11891 // This must be extracting from either LHS or RHS.
11892 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11893 // Okay, we can handle this if the vector we are insertinting into is
11894 // transitively ok.
11895 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11896 // If so, update the mask to reflect the inserted value.
11897 if (EI->getOperand(0) == LHS) {
11898 Mask[InsertedIdx % NumElts] =
11899 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11901 assert(EI->getOperand(0) == RHS);
11902 Mask[InsertedIdx % NumElts] =
11903 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11912 // TODO: Handle shufflevector here!
11917 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11918 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11919 /// that computes V and the LHS value of the shuffle.
11920 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11922 assert(isa<VectorType>(V->getType()) &&
11923 (RHS == 0 || V->getType() == RHS->getType()) &&
11924 "Invalid shuffle!");
11925 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11927 if (isa<UndefValue>(V)) {
11928 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11930 } else if (isa<ConstantAggregateZero>(V)) {
11931 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11933 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11934 // If this is an insert of an extract from some other vector, include it.
11935 Value *VecOp = IEI->getOperand(0);
11936 Value *ScalarOp = IEI->getOperand(1);
11937 Value *IdxOp = IEI->getOperand(2);
11939 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11940 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11941 EI->getOperand(0)->getType() == V->getType()) {
11942 unsigned ExtractedIdx =
11943 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11944 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11946 // Either the extracted from or inserted into vector must be RHSVec,
11947 // otherwise we'd end up with a shuffle of three inputs.
11948 if (EI->getOperand(0) == RHS || RHS == 0) {
11949 RHS = EI->getOperand(0);
11950 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11951 Mask[InsertedIdx % NumElts] =
11952 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11956 if (VecOp == RHS) {
11957 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11958 // Everything but the extracted element is replaced with the RHS.
11959 for (unsigned i = 0; i != NumElts; ++i) {
11960 if (i != InsertedIdx)
11961 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11966 // If this insertelement is a chain that comes from exactly these two
11967 // vectors, return the vector and the effective shuffle.
11968 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11969 return EI->getOperand(0);
11974 // TODO: Handle shufflevector here!
11976 // Otherwise, can't do anything fancy. Return an identity vector.
11977 for (unsigned i = 0; i != NumElts; ++i)
11978 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11982 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11983 Value *VecOp = IE.getOperand(0);
11984 Value *ScalarOp = IE.getOperand(1);
11985 Value *IdxOp = IE.getOperand(2);
11987 // Inserting an undef or into an undefined place, remove this.
11988 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11989 ReplaceInstUsesWith(IE, VecOp);
11991 // If the inserted element was extracted from some other vector, and if the
11992 // indexes are constant, try to turn this into a shufflevector operation.
11993 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11994 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11995 EI->getOperand(0)->getType() == IE.getType()) {
11996 unsigned NumVectorElts = IE.getType()->getNumElements();
11997 unsigned ExtractedIdx =
11998 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11999 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12001 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12002 return ReplaceInstUsesWith(IE, VecOp);
12004 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12005 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12007 // If we are extracting a value from a vector, then inserting it right
12008 // back into the same place, just use the input vector.
12009 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12010 return ReplaceInstUsesWith(IE, VecOp);
12012 // We could theoretically do this for ANY input. However, doing so could
12013 // turn chains of insertelement instructions into a chain of shufflevector
12014 // instructions, and right now we do not merge shufflevectors. As such,
12015 // only do this in a situation where it is clear that there is benefit.
12016 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12017 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12018 // the values of VecOp, except then one read from EIOp0.
12019 // Build a new shuffle mask.
12020 std::vector<Constant*> Mask;
12021 if (isa<UndefValue>(VecOp))
12022 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12024 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12025 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12028 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12029 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12030 ConstantVector::get(Mask));
12033 // If this insertelement isn't used by some other insertelement, turn it
12034 // (and any insertelements it points to), into one big shuffle.
12035 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12036 std::vector<Constant*> Mask;
12038 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12039 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12040 // We now have a shuffle of LHS, RHS, Mask.
12041 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12050 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12051 Value *LHS = SVI.getOperand(0);
12052 Value *RHS = SVI.getOperand(1);
12053 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12055 bool MadeChange = false;
12057 // Undefined shuffle mask -> undefined value.
12058 if (isa<UndefValue>(SVI.getOperand(2)))
12059 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12061 uint64_t UndefElts;
12062 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12064 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12067 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12068 if (VWidth <= 64 &&
12069 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12070 LHS = SVI.getOperand(0);
12071 RHS = SVI.getOperand(1);
12075 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12076 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12077 if (LHS == RHS || isa<UndefValue>(LHS)) {
12078 if (isa<UndefValue>(LHS) && LHS == RHS) {
12079 // shuffle(undef,undef,mask) -> undef.
12080 return ReplaceInstUsesWith(SVI, LHS);
12083 // Remap any references to RHS to use LHS.
12084 std::vector<Constant*> Elts;
12085 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12086 if (Mask[i] >= 2*e)
12087 Elts.push_back(UndefValue::get(Type::Int32Ty));
12089 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12090 (Mask[i] < e && isa<UndefValue>(LHS))) {
12091 Mask[i] = 2*e; // Turn into undef.
12092 Elts.push_back(UndefValue::get(Type::Int32Ty));
12094 Mask[i] = Mask[i] % e; // Force to LHS.
12095 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12099 SVI.setOperand(0, SVI.getOperand(1));
12100 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12101 SVI.setOperand(2, ConstantVector::get(Elts));
12102 LHS = SVI.getOperand(0);
12103 RHS = SVI.getOperand(1);
12107 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12108 bool isLHSID = true, isRHSID = true;
12110 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12111 if (Mask[i] >= e*2) continue; // Ignore undef values.
12112 // Is this an identity shuffle of the LHS value?
12113 isLHSID &= (Mask[i] == i);
12115 // Is this an identity shuffle of the RHS value?
12116 isRHSID &= (Mask[i]-e == i);
12119 // Eliminate identity shuffles.
12120 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12121 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12123 // If the LHS is a shufflevector itself, see if we can combine it with this
12124 // one without producing an unusual shuffle. Here we are really conservative:
12125 // we are absolutely afraid of producing a shuffle mask not in the input
12126 // program, because the code gen may not be smart enough to turn a merged
12127 // shuffle into two specific shuffles: it may produce worse code. As such,
12128 // we only merge two shuffles if the result is one of the two input shuffle
12129 // masks. In this case, merging the shuffles just removes one instruction,
12130 // which we know is safe. This is good for things like turning:
12131 // (splat(splat)) -> splat.
12132 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12133 if (isa<UndefValue>(RHS)) {
12134 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12136 std::vector<unsigned> NewMask;
12137 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12138 if (Mask[i] >= 2*e)
12139 NewMask.push_back(2*e);
12141 NewMask.push_back(LHSMask[Mask[i]]);
12143 // If the result mask is equal to the src shuffle or this shuffle mask, do
12144 // the replacement.
12145 if (NewMask == LHSMask || NewMask == Mask) {
12146 std::vector<Constant*> Elts;
12147 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12148 if (NewMask[i] >= e*2) {
12149 Elts.push_back(UndefValue::get(Type::Int32Ty));
12151 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12154 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12155 LHSSVI->getOperand(1),
12156 ConstantVector::get(Elts));
12161 return MadeChange ? &SVI : 0;
12167 /// TryToSinkInstruction - Try to move the specified instruction from its
12168 /// current block into the beginning of DestBlock, which can only happen if it's
12169 /// safe to move the instruction past all of the instructions between it and the
12170 /// end of its block.
12171 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12172 assert(I->hasOneUse() && "Invariants didn't hold!");
12174 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12175 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12178 // Do not sink alloca instructions out of the entry block.
12179 if (isa<AllocaInst>(I) && I->getParent() ==
12180 &DestBlock->getParent()->getEntryBlock())
12183 // We can only sink load instructions if there is nothing between the load and
12184 // the end of block that could change the value.
12185 if (I->mayReadFromMemory()) {
12186 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12188 if (Scan->mayWriteToMemory())
12192 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12194 I->moveBefore(InsertPos);
12200 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12201 /// all reachable code to the worklist.
12203 /// This has a couple of tricks to make the code faster and more powerful. In
12204 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12205 /// them to the worklist (this significantly speeds up instcombine on code where
12206 /// many instructions are dead or constant). Additionally, if we find a branch
12207 /// whose condition is a known constant, we only visit the reachable successors.
12209 static void AddReachableCodeToWorklist(BasicBlock *BB,
12210 SmallPtrSet<BasicBlock*, 64> &Visited,
12212 const TargetData *TD) {
12213 SmallVector<BasicBlock*, 256> Worklist;
12214 Worklist.push_back(BB);
12216 while (!Worklist.empty()) {
12217 BB = Worklist.back();
12218 Worklist.pop_back();
12220 // We have now visited this block! If we've already been here, ignore it.
12221 if (!Visited.insert(BB)) continue;
12223 DbgInfoIntrinsic *DBI_Prev = NULL;
12224 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12225 Instruction *Inst = BBI++;
12227 // DCE instruction if trivially dead.
12228 if (isInstructionTriviallyDead(Inst)) {
12230 DOUT << "IC: DCE: " << *Inst;
12231 Inst->eraseFromParent();
12235 // ConstantProp instruction if trivially constant.
12236 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12237 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12238 Inst->replaceAllUsesWith(C);
12240 Inst->eraseFromParent();
12244 // If there are two consecutive llvm.dbg.stoppoint calls then
12245 // it is likely that the optimizer deleted code in between these
12247 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12250 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12251 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12252 IC.RemoveFromWorkList(DBI_Prev);
12253 DBI_Prev->eraseFromParent();
12255 DBI_Prev = DBI_Next;
12258 IC.AddToWorkList(Inst);
12261 // Recursively visit successors. If this is a branch or switch on a
12262 // constant, only visit the reachable successor.
12263 TerminatorInst *TI = BB->getTerminator();
12264 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12265 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12266 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12267 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12268 Worklist.push_back(ReachableBB);
12271 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12272 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12273 // See if this is an explicit destination.
12274 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12275 if (SI->getCaseValue(i) == Cond) {
12276 BasicBlock *ReachableBB = SI->getSuccessor(i);
12277 Worklist.push_back(ReachableBB);
12281 // Otherwise it is the default destination.
12282 Worklist.push_back(SI->getSuccessor(0));
12287 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12288 Worklist.push_back(TI->getSuccessor(i));
12292 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12293 bool Changed = false;
12294 TD = &getAnalysis<TargetData>();
12296 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12297 << F.getNameStr() << "\n");
12300 // Do a depth-first traversal of the function, populate the worklist with
12301 // the reachable instructions. Ignore blocks that are not reachable. Keep
12302 // track of which blocks we visit.
12303 SmallPtrSet<BasicBlock*, 64> Visited;
12304 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12306 // Do a quick scan over the function. If we find any blocks that are
12307 // unreachable, remove any instructions inside of them. This prevents
12308 // the instcombine code from having to deal with some bad special cases.
12309 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12310 if (!Visited.count(BB)) {
12311 Instruction *Term = BB->getTerminator();
12312 while (Term != BB->begin()) { // Remove instrs bottom-up
12313 BasicBlock::iterator I = Term; --I;
12315 DOUT << "IC: DCE: " << *I;
12318 if (!I->use_empty())
12319 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12320 I->eraseFromParent();
12325 while (!Worklist.empty()) {
12326 Instruction *I = RemoveOneFromWorkList();
12327 if (I == 0) continue; // skip null values.
12329 // Check to see if we can DCE the instruction.
12330 if (isInstructionTriviallyDead(I)) {
12331 // Add operands to the worklist.
12332 if (I->getNumOperands() < 4)
12333 AddUsesToWorkList(*I);
12336 DOUT << "IC: DCE: " << *I;
12338 I->eraseFromParent();
12339 RemoveFromWorkList(I);
12343 // Instruction isn't dead, see if we can constant propagate it.
12344 if (Constant *C = ConstantFoldInstruction(I, TD)) {
12345 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12347 // Add operands to the worklist.
12348 AddUsesToWorkList(*I);
12349 ReplaceInstUsesWith(*I, C);
12352 I->eraseFromParent();
12353 RemoveFromWorkList(I);
12357 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12358 // See if we can constant fold its operands.
12359 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12360 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12361 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12367 // See if we can trivially sink this instruction to a successor basic block.
12368 if (I->hasOneUse()) {
12369 BasicBlock *BB = I->getParent();
12370 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12371 if (UserParent != BB) {
12372 bool UserIsSuccessor = false;
12373 // See if the user is one of our successors.
12374 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12375 if (*SI == UserParent) {
12376 UserIsSuccessor = true;
12380 // If the user is one of our immediate successors, and if that successor
12381 // only has us as a predecessors (we'd have to split the critical edge
12382 // otherwise), we can keep going.
12383 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12384 next(pred_begin(UserParent)) == pred_end(UserParent))
12385 // Okay, the CFG is simple enough, try to sink this instruction.
12386 Changed |= TryToSinkInstruction(I, UserParent);
12390 // Now that we have an instruction, try combining it to simplify it...
12394 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12395 if (Instruction *Result = visit(*I)) {
12397 // Should we replace the old instruction with a new one?
12399 DOUT << "IC: Old = " << *I
12400 << " New = " << *Result;
12402 // Everything uses the new instruction now.
12403 I->replaceAllUsesWith(Result);
12405 // Push the new instruction and any users onto the worklist.
12406 AddToWorkList(Result);
12407 AddUsersToWorkList(*Result);
12409 // Move the name to the new instruction first.
12410 Result->takeName(I);
12412 // Insert the new instruction into the basic block...
12413 BasicBlock *InstParent = I->getParent();
12414 BasicBlock::iterator InsertPos = I;
12416 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12417 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12420 InstParent->getInstList().insert(InsertPos, Result);
12422 // Make sure that we reprocess all operands now that we reduced their
12424 AddUsesToWorkList(*I);
12426 // Instructions can end up on the worklist more than once. Make sure
12427 // we do not process an instruction that has been deleted.
12428 RemoveFromWorkList(I);
12430 // Erase the old instruction.
12431 InstParent->getInstList().erase(I);
12434 DOUT << "IC: Mod = " << OrigI
12435 << " New = " << *I;
12438 // If the instruction was modified, it's possible that it is now dead.
12439 // if so, remove it.
12440 if (isInstructionTriviallyDead(I)) {
12441 // Make sure we process all operands now that we are reducing their
12443 AddUsesToWorkList(*I);
12445 // Instructions may end up in the worklist more than once. Erase all
12446 // occurrences of this instruction.
12447 RemoveFromWorkList(I);
12448 I->eraseFromParent();
12451 AddUsersToWorkList(*I);
12458 assert(WorklistMap.empty() && "Worklist empty, but map not?");
12460 // Do an explicit clear, this shrinks the map if needed.
12461 WorklistMap.clear();
12466 bool InstCombiner::runOnFunction(Function &F) {
12467 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12469 bool EverMadeChange = false;
12471 // Iterate while there is work to do.
12472 unsigned Iteration = 0;
12473 while (DoOneIteration(F, Iteration++))
12474 EverMadeChange = true;
12475 return EverMadeChange;
12478 FunctionPass *llvm::createInstructionCombiningPass() {
12479 return new InstCombiner();