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/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/PatternMatch.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/ADT/DenseMap.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/SmallPtrSet.h"
62 #include "llvm/ADT/Statistic.h"
63 #include "llvm/ADT/STLExtras.h"
68 using namespace llvm::PatternMatch;
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
77 /// InstCombineWorklist - This is the worklist management logic for
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86 InstCombineWorklist() {}
88 bool isEmpty() const { return Worklist.empty(); }
90 /// Add - Add the specified instruction to the worklist if it isn't already
92 void Add(Instruction *I) {
93 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94 Worklist.push_back(I);
97 void AddValue(Value *V) {
98 if (Instruction *I = dyn_cast<Instruction>(V))
102 // Remove - remove I from the worklist if it exists.
103 void Remove(Instruction *I) {
104 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
105 if (It == WorklistMap.end()) return; // Not in worklist.
107 // Don't bother moving everything down, just null out the slot.
108 Worklist[It->second] = 0;
110 WorklistMap.erase(It);
113 Instruction *RemoveOne() {
114 Instruction *I = Worklist.back();
116 WorklistMap.erase(I);
120 /// AddUsersToWorkList - When an instruction is simplified, add all users of
121 /// the instruction to the work lists because they might get more simplified
124 void AddUsersToWorkList(Instruction &I) {
125 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
127 Add(cast<Instruction>(*UI));
131 /// Zap - check that the worklist is empty and nuke the backing store for
132 /// the map if it is large.
134 assert(WorklistMap.empty() && "Worklist empty, but map not?");
136 // Do an explicit clear, this shrinks the map if needed.
140 } // end anonymous namespace.
144 class VISIBILITY_HIDDEN InstCombiner
145 : public FunctionPass,
146 public InstVisitor<InstCombiner, Instruction*> {
148 bool MustPreserveLCSSA;
150 // Worklist of all of the instructions that need to be simplified.
151 InstCombineWorklist Worklist;
153 static char ID; // Pass identification, replacement for typeid
154 InstCombiner() : FunctionPass(&ID) {}
156 LLVMContext *Context;
157 LLVMContext *getContext() const { return Context; }
160 virtual bool runOnFunction(Function &F);
162 bool DoOneIteration(Function &F, unsigned ItNum);
164 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
165 AU.addPreservedID(LCSSAID);
166 AU.setPreservesCFG();
169 TargetData *getTargetData() const { return TD; }
171 // Visitation implementation - Implement instruction combining for different
172 // instruction types. The semantics are as follows:
174 // null - No change was made
175 // I - Change was made, I is still valid, I may be dead though
176 // otherwise - Change was made, replace I with returned instruction
178 Instruction *visitAdd(BinaryOperator &I);
179 Instruction *visitFAdd(BinaryOperator &I);
180 Instruction *visitSub(BinaryOperator &I);
181 Instruction *visitFSub(BinaryOperator &I);
182 Instruction *visitMul(BinaryOperator &I);
183 Instruction *visitFMul(BinaryOperator &I);
184 Instruction *visitURem(BinaryOperator &I);
185 Instruction *visitSRem(BinaryOperator &I);
186 Instruction *visitFRem(BinaryOperator &I);
187 bool SimplifyDivRemOfSelect(BinaryOperator &I);
188 Instruction *commonRemTransforms(BinaryOperator &I);
189 Instruction *commonIRemTransforms(BinaryOperator &I);
190 Instruction *commonDivTransforms(BinaryOperator &I);
191 Instruction *commonIDivTransforms(BinaryOperator &I);
192 Instruction *visitUDiv(BinaryOperator &I);
193 Instruction *visitSDiv(BinaryOperator &I);
194 Instruction *visitFDiv(BinaryOperator &I);
195 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
196 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
197 Instruction *visitAnd(BinaryOperator &I);
198 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
199 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
200 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
201 Value *A, Value *B, Value *C);
202 Instruction *visitOr (BinaryOperator &I);
203 Instruction *visitXor(BinaryOperator &I);
204 Instruction *visitShl(BinaryOperator &I);
205 Instruction *visitAShr(BinaryOperator &I);
206 Instruction *visitLShr(BinaryOperator &I);
207 Instruction *commonShiftTransforms(BinaryOperator &I);
208 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
210 Instruction *visitFCmpInst(FCmpInst &I);
211 Instruction *visitICmpInst(ICmpInst &I);
212 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
213 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
216 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
217 ConstantInt *DivRHS);
219 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
220 ICmpInst::Predicate Cond, Instruction &I);
221 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
223 Instruction *commonCastTransforms(CastInst &CI);
224 Instruction *commonIntCastTransforms(CastInst &CI);
225 Instruction *commonPointerCastTransforms(CastInst &CI);
226 Instruction *visitTrunc(TruncInst &CI);
227 Instruction *visitZExt(ZExtInst &CI);
228 Instruction *visitSExt(SExtInst &CI);
229 Instruction *visitFPTrunc(FPTruncInst &CI);
230 Instruction *visitFPExt(CastInst &CI);
231 Instruction *visitFPToUI(FPToUIInst &FI);
232 Instruction *visitFPToSI(FPToSIInst &FI);
233 Instruction *visitUIToFP(CastInst &CI);
234 Instruction *visitSIToFP(CastInst &CI);
235 Instruction *visitPtrToInt(PtrToIntInst &CI);
236 Instruction *visitIntToPtr(IntToPtrInst &CI);
237 Instruction *visitBitCast(BitCastInst &CI);
238 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
240 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
241 Instruction *visitSelectInst(SelectInst &SI);
242 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
243 Instruction *visitCallInst(CallInst &CI);
244 Instruction *visitInvokeInst(InvokeInst &II);
245 Instruction *visitPHINode(PHINode &PN);
246 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
247 Instruction *visitAllocationInst(AllocationInst &AI);
248 Instruction *visitFreeInst(FreeInst &FI);
249 Instruction *visitLoadInst(LoadInst &LI);
250 Instruction *visitStoreInst(StoreInst &SI);
251 Instruction *visitBranchInst(BranchInst &BI);
252 Instruction *visitSwitchInst(SwitchInst &SI);
253 Instruction *visitInsertElementInst(InsertElementInst &IE);
254 Instruction *visitExtractElementInst(ExtractElementInst &EI);
255 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
256 Instruction *visitExtractValueInst(ExtractValueInst &EV);
258 // visitInstruction - Specify what to return for unhandled instructions...
259 Instruction *visitInstruction(Instruction &I) { return 0; }
262 Instruction *visitCallSite(CallSite CS);
263 bool transformConstExprCastCall(CallSite CS);
264 Instruction *transformCallThroughTrampoline(CallSite CS);
265 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
266 bool DoXform = true);
267 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
268 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
272 // InsertNewInstBefore - insert an instruction New before instruction Old
273 // in the program. Add the new instruction to the worklist.
275 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
276 assert(New && New->getParent() == 0 &&
277 "New instruction already inserted into a basic block!");
278 BasicBlock *BB = Old.getParent();
279 BB->getInstList().insert(&Old, New); // Insert inst
284 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
285 /// This also adds the cast to the worklist. Finally, this returns the
287 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
289 if (V->getType() == Ty) return V;
291 if (Constant *CV = dyn_cast<Constant>(V))
292 return ConstantExpr::getCast(opc, CV, Ty);
294 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
299 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
300 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
304 // ReplaceInstUsesWith - This method is to be used when an instruction is
305 // found to be dead, replacable with another preexisting expression. Here
306 // we add all uses of I to the worklist, replace all uses of I with the new
307 // value, then return I, so that the inst combiner will know that I was
310 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
311 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
313 // If we are replacing the instruction with itself, this must be in a
314 // segment of unreachable code, so just clobber the instruction.
316 V = UndefValue::get(I.getType());
318 I.replaceAllUsesWith(V);
322 // EraseInstFromFunction - When dealing with an instruction that has side
323 // effects or produces a void value, we can't rely on DCE to delete the
324 // instruction. Instead, visit methods should return the value returned by
326 Instruction *EraseInstFromFunction(Instruction &I) {
327 assert(I.use_empty() && "Cannot erase instruction that is used!");
328 // Make sure that we reprocess all operands now that we reduced their
330 if (I.getNumOperands() < 8) {
331 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
332 if (Instruction *Op = dyn_cast<Instruction>(*i))
337 return 0; // Don't do anything with FI
340 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
341 APInt &KnownOne, unsigned Depth = 0) const {
342 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
345 bool MaskedValueIsZero(Value *V, const APInt &Mask,
346 unsigned Depth = 0) const {
347 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
349 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
350 return llvm::ComputeNumSignBits(Op, TD, Depth);
355 /// SimplifyCommutative - This performs a few simplifications for
356 /// commutative operators.
357 bool SimplifyCommutative(BinaryOperator &I);
359 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
360 /// most-complex to least-complex order.
361 bool SimplifyCompare(CmpInst &I);
363 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
364 /// based on the demanded bits.
365 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
366 APInt& KnownZero, APInt& KnownOne,
368 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
369 APInt& KnownZero, APInt& KnownOne,
372 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
373 /// SimplifyDemandedBits knows about. See if the instruction has any
374 /// properties that allow us to simplify its operands.
375 bool SimplifyDemandedInstructionBits(Instruction &Inst);
377 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
378 APInt& UndefElts, unsigned Depth = 0);
380 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
381 // PHI node as operand #0, see if we can fold the instruction into the PHI
382 // (which is only possible if all operands to the PHI are constants).
383 Instruction *FoldOpIntoPhi(Instruction &I);
385 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
386 // operator and they all are only used by the PHI, PHI together their
387 // inputs, and do the operation once, to the result of the PHI.
388 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
389 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
390 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
393 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
394 ConstantInt *AndRHS, BinaryOperator &TheAnd);
396 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
397 bool isSub, Instruction &I);
398 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
399 bool isSigned, bool Inside, Instruction &IB);
400 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
401 Instruction *MatchBSwap(BinaryOperator &I);
402 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
403 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
404 Instruction *SimplifyMemSet(MemSetInst *MI);
407 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
409 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
410 unsigned CastOpc, int &NumCastsRemoved);
411 unsigned GetOrEnforceKnownAlignment(Value *V,
412 unsigned PrefAlign = 0);
415 } // end anonymous namespace
417 char InstCombiner::ID = 0;
418 static RegisterPass<InstCombiner>
419 X("instcombine", "Combine redundant instructions");
421 // getComplexity: Assign a complexity or rank value to LLVM Values...
422 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
423 static unsigned getComplexity(Value *V) {
424 if (isa<Instruction>(V)) {
425 if (BinaryOperator::isNeg(V) ||
426 BinaryOperator::isFNeg(V) ||
427 BinaryOperator::isNot(V))
431 if (isa<Argument>(V)) return 3;
432 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
435 // isOnlyUse - Return true if this instruction will be deleted if we stop using
437 static bool isOnlyUse(Value *V) {
438 return V->hasOneUse() || isa<Constant>(V);
441 // getPromotedType - Return the specified type promoted as it would be to pass
442 // though a va_arg area...
443 static const Type *getPromotedType(const Type *Ty) {
444 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
445 if (ITy->getBitWidth() < 32)
446 return Type::getInt32Ty(Ty->getContext());
451 /// getBitCastOperand - If the specified operand is a CastInst, a constant
452 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
453 /// operand value, otherwise return null.
454 static Value *getBitCastOperand(Value *V) {
455 if (Operator *O = dyn_cast<Operator>(V)) {
456 if (O->getOpcode() == Instruction::BitCast)
457 return O->getOperand(0);
458 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
459 if (GEP->hasAllZeroIndices())
460 return GEP->getPointerOperand();
465 /// This function is a wrapper around CastInst::isEliminableCastPair. It
466 /// simply extracts arguments and returns what that function returns.
467 static Instruction::CastOps
468 isEliminableCastPair(
469 const CastInst *CI, ///< The first cast instruction
470 unsigned opcode, ///< The opcode of the second cast instruction
471 const Type *DstTy, ///< The target type for the second cast instruction
472 TargetData *TD ///< The target data for pointer size
475 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
476 const Type *MidTy = CI->getType(); // B from above
478 // Get the opcodes of the two Cast instructions
479 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
482 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
484 TD ? TD->getIntPtrType(CI->getContext()) : 0);
486 // We don't want to form an inttoptr or ptrtoint that converts to an integer
487 // type that differs from the pointer size.
488 if ((Res == Instruction::IntToPtr &&
489 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
490 (Res == Instruction::PtrToInt &&
491 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
494 return Instruction::CastOps(Res);
497 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
498 /// in any code being generated. It does not require codegen if V is simple
499 /// enough or if the cast can be folded into other casts.
500 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
501 const Type *Ty, TargetData *TD) {
502 if (V->getType() == Ty || isa<Constant>(V)) return false;
504 // If this is another cast that can be eliminated, it isn't codegen either.
505 if (const CastInst *CI = dyn_cast<CastInst>(V))
506 if (isEliminableCastPair(CI, opcode, Ty, TD))
511 // SimplifyCommutative - This performs a few simplifications for commutative
514 // 1. Order operands such that they are listed from right (least complex) to
515 // left (most complex). This puts constants before unary operators before
518 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
519 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
521 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
522 bool Changed = false;
523 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
524 Changed = !I.swapOperands();
526 if (!I.isAssociative()) return Changed;
527 Instruction::BinaryOps Opcode = I.getOpcode();
528 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
529 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
530 if (isa<Constant>(I.getOperand(1))) {
531 Constant *Folded = ConstantExpr::get(I.getOpcode(),
532 cast<Constant>(I.getOperand(1)),
533 cast<Constant>(Op->getOperand(1)));
534 I.setOperand(0, Op->getOperand(0));
535 I.setOperand(1, Folded);
537 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
538 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
539 isOnlyUse(Op) && isOnlyUse(Op1)) {
540 Constant *C1 = cast<Constant>(Op->getOperand(1));
541 Constant *C2 = cast<Constant>(Op1->getOperand(1));
543 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
544 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
545 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
549 I.setOperand(0, New);
550 I.setOperand(1, Folded);
557 /// SimplifyCompare - For a CmpInst this function just orders the operands
558 /// so that theyare listed from right (least complex) to left (most complex).
559 /// This puts constants before unary operators before binary operators.
560 bool InstCombiner::SimplifyCompare(CmpInst &I) {
561 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
564 // Compare instructions are not associative so there's nothing else we can do.
568 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
569 // if the LHS is a constant zero (which is the 'negate' form).
571 static inline Value *dyn_castNegVal(Value *V) {
572 if (BinaryOperator::isNeg(V))
573 return BinaryOperator::getNegArgument(V);
575 // Constants can be considered to be negated values if they can be folded.
576 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
577 return ConstantExpr::getNeg(C);
579 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
580 if (C->getType()->getElementType()->isInteger())
581 return ConstantExpr::getNeg(C);
586 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
587 // instruction if the LHS is a constant negative zero (which is the 'negate'
590 static inline Value *dyn_castFNegVal(Value *V) {
591 if (BinaryOperator::isFNeg(V))
592 return BinaryOperator::getFNegArgument(V);
594 // Constants can be considered to be negated values if they can be folded.
595 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
596 return ConstantExpr::getFNeg(C);
598 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
599 if (C->getType()->getElementType()->isFloatingPoint())
600 return ConstantExpr::getFNeg(C);
605 static inline Value *dyn_castNotVal(Value *V) {
606 if (BinaryOperator::isNot(V))
607 return BinaryOperator::getNotArgument(V);
609 // Constants can be considered to be not'ed values...
610 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
611 return ConstantInt::get(C->getType(), ~C->getValue());
615 // dyn_castFoldableMul - If this value is a multiply that can be folded into
616 // other computations (because it has a constant operand), return the
617 // non-constant operand of the multiply, and set CST to point to the multiplier.
618 // Otherwise, return null.
620 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
621 if (V->hasOneUse() && V->getType()->isInteger())
622 if (Instruction *I = dyn_cast<Instruction>(V)) {
623 if (I->getOpcode() == Instruction::Mul)
624 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
625 return I->getOperand(0);
626 if (I->getOpcode() == Instruction::Shl)
627 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
628 // The multiplier is really 1 << CST.
629 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
630 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
631 CST = ConstantInt::get(V->getType()->getContext(),
632 APInt(BitWidth, 1).shl(CSTVal));
633 return I->getOperand(0);
639 /// AddOne - Add one to a ConstantInt
640 static Constant *AddOne(Constant *C) {
641 return ConstantExpr::getAdd(C,
642 ConstantInt::get(C->getType(), 1));
644 /// SubOne - Subtract one from a ConstantInt
645 static Constant *SubOne(ConstantInt *C) {
646 return ConstantExpr::getSub(C,
647 ConstantInt::get(C->getType(), 1));
649 /// MultiplyOverflows - True if the multiply can not be expressed in an int
651 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652 uint32_t W = C1->getBitWidth();
653 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
662 APInt MulExt = LHSExt * RHSExt;
665 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667 return MulExt.slt(Min) || MulExt.sgt(Max);
669 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
673 /// ShrinkDemandedConstant - Check to see if the specified operand of the
674 /// specified instruction is a constant integer. If so, check to see if there
675 /// are any bits set in the constant that are not demanded. If so, shrink the
676 /// constant and return true.
677 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
679 assert(I && "No instruction?");
680 assert(OpNo < I->getNumOperands() && "Operand index too large");
682 // If the operand is not a constant integer, nothing to do.
683 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684 if (!OpC) return false;
686 // If there are no bits set that aren't demanded, nothing to do.
687 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688 if ((~Demanded & OpC->getValue()) == 0)
691 // This instruction is producing bits that are not demanded. Shrink the RHS.
692 Demanded &= OpC->getValue();
693 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
697 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
698 // set of known zero and one bits, compute the maximum and minimum values that
699 // could have the specified known zero and known one bits, returning them in
701 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
702 const APInt& KnownOne,
703 APInt& Min, APInt& Max) {
704 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
705 KnownZero.getBitWidth() == Min.getBitWidth() &&
706 KnownZero.getBitWidth() == Max.getBitWidth() &&
707 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
708 APInt UnknownBits = ~(KnownZero|KnownOne);
710 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
711 // bit if it is unknown.
713 Max = KnownOne|UnknownBits;
715 if (UnknownBits.isNegative()) { // Sign bit is unknown
716 Min.set(Min.getBitWidth()-1);
717 Max.clear(Max.getBitWidth()-1);
721 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
722 // a set of known zero and one bits, compute the maximum and minimum values that
723 // could have the specified known zero and known one bits, returning them in
725 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
726 const APInt &KnownOne,
727 APInt &Min, APInt &Max) {
728 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
729 KnownZero.getBitWidth() == Min.getBitWidth() &&
730 KnownZero.getBitWidth() == Max.getBitWidth() &&
731 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
732 APInt UnknownBits = ~(KnownZero|KnownOne);
734 // The minimum value is when the unknown bits are all zeros.
736 // The maximum value is when the unknown bits are all ones.
737 Max = KnownOne|UnknownBits;
740 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
741 /// SimplifyDemandedBits knows about. See if the instruction has any
742 /// properties that allow us to simplify its operands.
743 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
744 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
745 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
746 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
748 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
749 KnownZero, KnownOne, 0);
750 if (V == 0) return false;
751 if (V == &Inst) return true;
752 ReplaceInstUsesWith(Inst, V);
756 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
757 /// specified instruction operand if possible, updating it in place. It returns
758 /// true if it made any change and false otherwise.
759 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
760 APInt &KnownZero, APInt &KnownOne,
762 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
763 KnownZero, KnownOne, Depth);
764 if (NewVal == 0) return false;
770 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
771 /// value based on the demanded bits. When this function is called, it is known
772 /// that only the bits set in DemandedMask of the result of V are ever used
773 /// downstream. Consequently, depending on the mask and V, it may be possible
774 /// to replace V with a constant or one of its operands. In such cases, this
775 /// function does the replacement and returns true. In all other cases, it
776 /// returns false after analyzing the expression and setting KnownOne and known
777 /// to be one in the expression. KnownZero contains all the bits that are known
778 /// to be zero in the expression. These are provided to potentially allow the
779 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
780 /// the expression. KnownOne and KnownZero always follow the invariant that
781 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
782 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
783 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
784 /// and KnownOne must all be the same.
786 /// This returns null if it did not change anything and it permits no
787 /// simplification. This returns V itself if it did some simplification of V's
788 /// operands based on the information about what bits are demanded. This returns
789 /// some other non-null value if it found out that V is equal to another value
790 /// in the context where the specified bits are demanded, but not for all users.
791 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
792 APInt &KnownZero, APInt &KnownOne,
794 assert(V != 0 && "Null pointer of Value???");
795 assert(Depth <= 6 && "Limit Search Depth");
796 uint32_t BitWidth = DemandedMask.getBitWidth();
797 const Type *VTy = V->getType();
798 assert((TD || !isa<PointerType>(VTy)) &&
799 "SimplifyDemandedBits needs to know bit widths!");
800 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
801 (!VTy->isIntOrIntVector() ||
802 VTy->getScalarSizeInBits() == BitWidth) &&
803 KnownZero.getBitWidth() == BitWidth &&
804 KnownOne.getBitWidth() == BitWidth &&
805 "Value *V, DemandedMask, KnownZero and KnownOne "
806 "must have same BitWidth");
807 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808 // We know all of the bits for a constant!
809 KnownOne = CI->getValue() & DemandedMask;
810 KnownZero = ~KnownOne & DemandedMask;
813 if (isa<ConstantPointerNull>(V)) {
814 // We know all of the bits for a constant!
816 KnownZero = DemandedMask;
822 if (DemandedMask == 0) { // Not demanding any bits from V.
823 if (isa<UndefValue>(V))
825 return UndefValue::get(VTy);
828 if (Depth == 6) // Limit search depth.
831 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
832 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
834 Instruction *I = dyn_cast<Instruction>(V);
836 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
837 return 0; // Only analyze instructions.
840 // If there are multiple uses of this value and we aren't at the root, then
841 // we can't do any simplifications of the operands, because DemandedMask
842 // only reflects the bits demanded by *one* of the users.
843 if (Depth != 0 && !I->hasOneUse()) {
844 // Despite the fact that we can't simplify this instruction in all User's
845 // context, we can at least compute the knownzero/knownone bits, and we can
846 // do simplifications that apply to *just* the one user if we know that
847 // this instruction has a simpler value in that context.
848 if (I->getOpcode() == Instruction::And) {
849 // If either the LHS or the RHS are Zero, the result is zero.
850 ComputeMaskedBits(I->getOperand(1), DemandedMask,
851 RHSKnownZero, RHSKnownOne, Depth+1);
852 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
853 LHSKnownZero, LHSKnownOne, Depth+1);
855 // If all of the demanded bits are known 1 on one side, return the other.
856 // These bits cannot contribute to the result of the 'and' in this
858 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
859 (DemandedMask & ~LHSKnownZero))
860 return I->getOperand(0);
861 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
862 (DemandedMask & ~RHSKnownZero))
863 return I->getOperand(1);
865 // If all of the demanded bits in the inputs are known zeros, return zero.
866 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
867 return Constant::getNullValue(VTy);
869 } else if (I->getOpcode() == Instruction::Or) {
870 // We can simplify (X|Y) -> X or Y in the user's context if we know that
871 // only bits from X or Y are demanded.
873 // If either the LHS or the RHS are One, the result is One.
874 ComputeMaskedBits(I->getOperand(1), DemandedMask,
875 RHSKnownZero, RHSKnownOne, Depth+1);
876 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
877 LHSKnownZero, LHSKnownOne, Depth+1);
879 // If all of the demanded bits are known zero on one side, return the
880 // other. These bits cannot contribute to the result of the 'or' in this
882 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
883 (DemandedMask & ~LHSKnownOne))
884 return I->getOperand(0);
885 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
886 (DemandedMask & ~RHSKnownOne))
887 return I->getOperand(1);
889 // If all of the potentially set bits on one side are known to be set on
890 // the other side, just use the 'other' side.
891 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
892 (DemandedMask & (~RHSKnownZero)))
893 return I->getOperand(0);
894 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
895 (DemandedMask & (~LHSKnownZero)))
896 return I->getOperand(1);
899 // Compute the KnownZero/KnownOne bits to simplify things downstream.
900 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
904 // If this is the root being simplified, allow it to have multiple uses,
905 // just set the DemandedMask to all bits so that we can try to simplify the
906 // operands. This allows visitTruncInst (for example) to simplify the
907 // operand of a trunc without duplicating all the logic below.
908 if (Depth == 0 && !V->hasOneUse())
909 DemandedMask = APInt::getAllOnesValue(BitWidth);
911 switch (I->getOpcode()) {
913 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
915 case Instruction::And:
916 // If either the LHS or the RHS are Zero, the result is zero.
917 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
918 RHSKnownZero, RHSKnownOne, Depth+1) ||
919 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
920 LHSKnownZero, LHSKnownOne, Depth+1))
922 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
923 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
925 // If all of the demanded bits are known 1 on one side, return the other.
926 // These bits cannot contribute to the result of the 'and'.
927 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
928 (DemandedMask & ~LHSKnownZero))
929 return I->getOperand(0);
930 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
931 (DemandedMask & ~RHSKnownZero))
932 return I->getOperand(1);
934 // If all of the demanded bits in the inputs are known zeros, return zero.
935 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
936 return Constant::getNullValue(VTy);
938 // If the RHS is a constant, see if we can simplify it.
939 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
942 // Output known-1 bits are only known if set in both the LHS & RHS.
943 RHSKnownOne &= LHSKnownOne;
944 // Output known-0 are known to be clear if zero in either the LHS | RHS.
945 RHSKnownZero |= LHSKnownZero;
947 case Instruction::Or:
948 // If either the LHS or the RHS are One, the result is One.
949 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
950 RHSKnownZero, RHSKnownOne, Depth+1) ||
951 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
952 LHSKnownZero, LHSKnownOne, Depth+1))
954 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
955 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
957 // If all of the demanded bits are known zero on one side, return the other.
958 // These bits cannot contribute to the result of the 'or'.
959 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
960 (DemandedMask & ~LHSKnownOne))
961 return I->getOperand(0);
962 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
963 (DemandedMask & ~RHSKnownOne))
964 return I->getOperand(1);
966 // If all of the potentially set bits on one side are known to be set on
967 // the other side, just use the 'other' side.
968 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
969 (DemandedMask & (~RHSKnownZero)))
970 return I->getOperand(0);
971 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
972 (DemandedMask & (~LHSKnownZero)))
973 return I->getOperand(1);
975 // If the RHS is a constant, see if we can simplify it.
976 if (ShrinkDemandedConstant(I, 1, DemandedMask))
979 // Output known-0 bits are only known if clear in both the LHS & RHS.
980 RHSKnownZero &= LHSKnownZero;
981 // Output known-1 are known to be set if set in either the LHS | RHS.
982 RHSKnownOne |= LHSKnownOne;
984 case Instruction::Xor: {
985 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
986 RHSKnownZero, RHSKnownOne, Depth+1) ||
987 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
988 LHSKnownZero, LHSKnownOne, Depth+1))
990 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
991 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
993 // If all of the demanded bits are known zero on one side, return the other.
994 // These bits cannot contribute to the result of the 'xor'.
995 if ((DemandedMask & RHSKnownZero) == DemandedMask)
996 return I->getOperand(0);
997 if ((DemandedMask & LHSKnownZero) == DemandedMask)
998 return I->getOperand(1);
1000 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1001 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1002 (RHSKnownOne & LHSKnownOne);
1003 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1004 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1005 (RHSKnownOne & LHSKnownZero);
1007 // If all of the demanded bits are known to be zero on one side or the
1008 // other, turn this into an *inclusive* or.
1009 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1010 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1012 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1014 return InsertNewInstBefore(Or, *I);
1017 // If all of the demanded bits on one side are known, and all of the set
1018 // bits on that side are also known to be set on the other side, turn this
1019 // into an AND, as we know the bits will be cleared.
1020 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1021 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1023 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1024 Constant *AndC = Constant::getIntegerValue(VTy,
1025 ~RHSKnownOne & DemandedMask);
1027 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1028 return InsertNewInstBefore(And, *I);
1032 // If the RHS is a constant, see if we can simplify it.
1033 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1034 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1037 RHSKnownZero = KnownZeroOut;
1038 RHSKnownOne = KnownOneOut;
1041 case Instruction::Select:
1042 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1043 RHSKnownZero, RHSKnownOne, Depth+1) ||
1044 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1045 LHSKnownZero, LHSKnownOne, Depth+1))
1047 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1048 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1050 // If the operands are constants, see if we can simplify them.
1051 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1052 ShrinkDemandedConstant(I, 2, DemandedMask))
1055 // Only known if known in both the LHS and RHS.
1056 RHSKnownOne &= LHSKnownOne;
1057 RHSKnownZero &= LHSKnownZero;
1059 case Instruction::Trunc: {
1060 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1061 DemandedMask.zext(truncBf);
1062 RHSKnownZero.zext(truncBf);
1063 RHSKnownOne.zext(truncBf);
1064 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1065 RHSKnownZero, RHSKnownOne, Depth+1))
1067 DemandedMask.trunc(BitWidth);
1068 RHSKnownZero.trunc(BitWidth);
1069 RHSKnownOne.trunc(BitWidth);
1070 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1073 case Instruction::BitCast:
1074 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1075 return false; // vector->int or fp->int?
1077 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1078 if (const VectorType *SrcVTy =
1079 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1080 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1081 // Don't touch a bitcast between vectors of different element counts.
1084 // Don't touch a scalar-to-vector bitcast.
1086 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1087 // Don't touch a vector-to-scalar bitcast.
1090 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1091 RHSKnownZero, RHSKnownOne, Depth+1))
1093 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1095 case Instruction::ZExt: {
1096 // Compute the bits in the result that are not present in the input.
1097 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1099 DemandedMask.trunc(SrcBitWidth);
1100 RHSKnownZero.trunc(SrcBitWidth);
1101 RHSKnownOne.trunc(SrcBitWidth);
1102 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1103 RHSKnownZero, RHSKnownOne, Depth+1))
1105 DemandedMask.zext(BitWidth);
1106 RHSKnownZero.zext(BitWidth);
1107 RHSKnownOne.zext(BitWidth);
1108 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1109 // The top bits are known to be zero.
1110 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1113 case Instruction::SExt: {
1114 // Compute the bits in the result that are not present in the input.
1115 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1117 APInt InputDemandedBits = DemandedMask &
1118 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1120 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1121 // If any of the sign extended bits are demanded, we know that the sign
1123 if ((NewBits & DemandedMask) != 0)
1124 InputDemandedBits.set(SrcBitWidth-1);
1126 InputDemandedBits.trunc(SrcBitWidth);
1127 RHSKnownZero.trunc(SrcBitWidth);
1128 RHSKnownOne.trunc(SrcBitWidth);
1129 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1130 RHSKnownZero, RHSKnownOne, Depth+1))
1132 InputDemandedBits.zext(BitWidth);
1133 RHSKnownZero.zext(BitWidth);
1134 RHSKnownOne.zext(BitWidth);
1135 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1137 // If the sign bit of the input is known set or clear, then we know the
1138 // top bits of the result.
1140 // If the input sign bit is known zero, or if the NewBits are not demanded
1141 // convert this into a zero extension.
1142 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1143 // Convert to ZExt cast
1144 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1145 return InsertNewInstBefore(NewCast, *I);
1146 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1147 RHSKnownOne |= NewBits;
1151 case Instruction::Add: {
1152 // Figure out what the input bits are. If the top bits of the and result
1153 // are not demanded, then the add doesn't demand them from its input
1155 unsigned NLZ = DemandedMask.countLeadingZeros();
1157 // If there is a constant on the RHS, there are a variety of xformations
1159 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1160 // If null, this should be simplified elsewhere. Some of the xforms here
1161 // won't work if the RHS is zero.
1165 // If the top bit of the output is demanded, demand everything from the
1166 // input. Otherwise, we demand all the input bits except NLZ top bits.
1167 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1169 // Find information about known zero/one bits in the input.
1170 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1171 LHSKnownZero, LHSKnownOne, Depth+1))
1174 // If the RHS of the add has bits set that can't affect the input, reduce
1176 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1179 // Avoid excess work.
1180 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1183 // Turn it into OR if input bits are zero.
1184 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1186 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1188 return InsertNewInstBefore(Or, *I);
1191 // We can say something about the output known-zero and known-one bits,
1192 // depending on potential carries from the input constant and the
1193 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1194 // bits set and the RHS constant is 0x01001, then we know we have a known
1195 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1197 // To compute this, we first compute the potential carry bits. These are
1198 // the bits which may be modified. I'm not aware of a better way to do
1200 const APInt &RHSVal = RHS->getValue();
1201 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1203 // Now that we know which bits have carries, compute the known-1/0 sets.
1205 // Bits are known one if they are known zero in one operand and one in the
1206 // other, and there is no input carry.
1207 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1208 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1210 // Bits are known zero if they are known zero in both operands and there
1211 // is no input carry.
1212 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1214 // If the high-bits of this ADD are not demanded, then it does not demand
1215 // the high bits of its LHS or RHS.
1216 if (DemandedMask[BitWidth-1] == 0) {
1217 // Right fill the mask of bits for this ADD to demand the most
1218 // significant bit and all those below it.
1219 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1220 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1221 LHSKnownZero, LHSKnownOne, Depth+1) ||
1222 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1223 LHSKnownZero, LHSKnownOne, Depth+1))
1229 case Instruction::Sub:
1230 // If the high-bits of this SUB are not demanded, then it does not demand
1231 // the high bits of its LHS or RHS.
1232 if (DemandedMask[BitWidth-1] == 0) {
1233 // Right fill the mask of bits for this SUB to demand the most
1234 // significant bit and all those below it.
1235 uint32_t NLZ = DemandedMask.countLeadingZeros();
1236 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1237 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1238 LHSKnownZero, LHSKnownOne, Depth+1) ||
1239 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1240 LHSKnownZero, LHSKnownOne, Depth+1))
1243 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1244 // the known zeros and ones.
1245 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1247 case Instruction::Shl:
1248 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1249 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1250 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1251 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1252 RHSKnownZero, RHSKnownOne, Depth+1))
1254 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1255 RHSKnownZero <<= ShiftAmt;
1256 RHSKnownOne <<= ShiftAmt;
1257 // low bits known zero.
1259 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1262 case Instruction::LShr:
1263 // For a logical shift right
1264 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1265 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1267 // Unsigned shift right.
1268 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1269 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1270 RHSKnownZero, RHSKnownOne, Depth+1))
1272 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1273 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1274 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1276 // Compute the new bits that are at the top now.
1277 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1278 RHSKnownZero |= HighBits; // high bits known zero.
1282 case Instruction::AShr:
1283 // If this is an arithmetic shift right and only the low-bit is set, we can
1284 // always convert this into a logical shr, even if the shift amount is
1285 // variable. The low bit of the shift cannot be an input sign bit unless
1286 // the shift amount is >= the size of the datatype, which is undefined.
1287 if (DemandedMask == 1) {
1288 // Perform the logical shift right.
1289 Instruction *NewVal = BinaryOperator::CreateLShr(
1290 I->getOperand(0), I->getOperand(1), I->getName());
1291 return InsertNewInstBefore(NewVal, *I);
1294 // If the sign bit is the only bit demanded by this ashr, then there is no
1295 // need to do it, the shift doesn't change the high bit.
1296 if (DemandedMask.isSignBit())
1297 return I->getOperand(0);
1299 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1300 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1302 // Signed shift right.
1303 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1304 // If any of the "high bits" are demanded, we should set the sign bit as
1306 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1307 DemandedMaskIn.set(BitWidth-1);
1308 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1309 RHSKnownZero, RHSKnownOne, Depth+1))
1311 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1312 // Compute the new bits that are at the top now.
1313 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1314 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1315 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1317 // Handle the sign bits.
1318 APInt SignBit(APInt::getSignBit(BitWidth));
1319 // Adjust to where it is now in the mask.
1320 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1322 // If the input sign bit is known to be zero, or if none of the top bits
1323 // are demanded, turn this into an unsigned shift right.
1324 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1325 (HighBits & ~DemandedMask) == HighBits) {
1326 // Perform the logical shift right.
1327 Instruction *NewVal = BinaryOperator::CreateLShr(
1328 I->getOperand(0), SA, I->getName());
1329 return InsertNewInstBefore(NewVal, *I);
1330 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1331 RHSKnownOne |= HighBits;
1335 case Instruction::SRem:
1336 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1337 APInt RA = Rem->getValue().abs();
1338 if (RA.isPowerOf2()) {
1339 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1340 return I->getOperand(0);
1342 APInt LowBits = RA - 1;
1343 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1344 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1345 LHSKnownZero, LHSKnownOne, Depth+1))
1348 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1349 LHSKnownZero |= ~LowBits;
1351 KnownZero |= LHSKnownZero & DemandedMask;
1353 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1357 case Instruction::URem: {
1358 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1359 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1360 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1361 KnownZero2, KnownOne2, Depth+1) ||
1362 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1363 KnownZero2, KnownOne2, Depth+1))
1366 unsigned Leaders = KnownZero2.countLeadingOnes();
1367 Leaders = std::max(Leaders,
1368 KnownZero2.countLeadingOnes());
1369 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1372 case Instruction::Call:
1373 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1374 switch (II->getIntrinsicID()) {
1376 case Intrinsic::bswap: {
1377 // If the only bits demanded come from one byte of the bswap result,
1378 // just shift the input byte into position to eliminate the bswap.
1379 unsigned NLZ = DemandedMask.countLeadingZeros();
1380 unsigned NTZ = DemandedMask.countTrailingZeros();
1382 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1383 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1384 // have 14 leading zeros, round to 8.
1387 // If we need exactly one byte, we can do this transformation.
1388 if (BitWidth-NLZ-NTZ == 8) {
1389 unsigned ResultBit = NTZ;
1390 unsigned InputBit = BitWidth-NTZ-8;
1392 // Replace this with either a left or right shift to get the byte into
1394 Instruction *NewVal;
1395 if (InputBit > ResultBit)
1396 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1397 ConstantInt::get(I->getType(), InputBit-ResultBit));
1399 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1400 ConstantInt::get(I->getType(), ResultBit-InputBit));
1401 NewVal->takeName(I);
1402 return InsertNewInstBefore(NewVal, *I);
1405 // TODO: Could compute known zero/one bits based on the input.
1410 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1414 // If the client is only demanding bits that we know, return the known
1416 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1417 return Constant::getIntegerValue(VTy, RHSKnownOne);
1422 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1423 /// any number of elements. DemandedElts contains the set of elements that are
1424 /// actually used by the caller. This method analyzes which elements of the
1425 /// operand are undef and returns that information in UndefElts.
1427 /// If the information about demanded elements can be used to simplify the
1428 /// operation, the operation is simplified, then the resultant value is
1429 /// returned. This returns null if no change was made.
1430 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1433 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1434 APInt EltMask(APInt::getAllOnesValue(VWidth));
1435 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1437 if (isa<UndefValue>(V)) {
1438 // If the entire vector is undefined, just return this info.
1439 UndefElts = EltMask;
1441 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1442 UndefElts = EltMask;
1443 return UndefValue::get(V->getType());
1447 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1448 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1449 Constant *Undef = UndefValue::get(EltTy);
1451 std::vector<Constant*> Elts;
1452 for (unsigned i = 0; i != VWidth; ++i)
1453 if (!DemandedElts[i]) { // If not demanded, set to undef.
1454 Elts.push_back(Undef);
1456 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1457 Elts.push_back(Undef);
1459 } else { // Otherwise, defined.
1460 Elts.push_back(CP->getOperand(i));
1463 // If we changed the constant, return it.
1464 Constant *NewCP = ConstantVector::get(Elts);
1465 return NewCP != CP ? NewCP : 0;
1466 } else if (isa<ConstantAggregateZero>(V)) {
1467 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1470 // Check if this is identity. If so, return 0 since we are not simplifying
1472 if (DemandedElts == ((1ULL << VWidth) -1))
1475 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1476 Constant *Zero = Constant::getNullValue(EltTy);
1477 Constant *Undef = UndefValue::get(EltTy);
1478 std::vector<Constant*> Elts;
1479 for (unsigned i = 0; i != VWidth; ++i) {
1480 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1481 Elts.push_back(Elt);
1483 UndefElts = DemandedElts ^ EltMask;
1484 return ConstantVector::get(Elts);
1487 // Limit search depth.
1491 // If multiple users are using the root value, procede with
1492 // simplification conservatively assuming that all elements
1494 if (!V->hasOneUse()) {
1495 // Quit if we find multiple users of a non-root value though.
1496 // They'll be handled when it's their turn to be visited by
1497 // the main instcombine process.
1499 // TODO: Just compute the UndefElts information recursively.
1502 // Conservatively assume that all elements are needed.
1503 DemandedElts = EltMask;
1506 Instruction *I = dyn_cast<Instruction>(V);
1507 if (!I) return 0; // Only analyze instructions.
1509 bool MadeChange = false;
1510 APInt UndefElts2(VWidth, 0);
1512 switch (I->getOpcode()) {
1515 case Instruction::InsertElement: {
1516 // If this is a variable index, we don't know which element it overwrites.
1517 // demand exactly the same input as we produce.
1518 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1520 // Note that we can't propagate undef elt info, because we don't know
1521 // which elt is getting updated.
1522 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1523 UndefElts2, Depth+1);
1524 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1528 // If this is inserting an element that isn't demanded, remove this
1530 unsigned IdxNo = Idx->getZExtValue();
1531 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1533 return I->getOperand(0);
1536 // Otherwise, the element inserted overwrites whatever was there, so the
1537 // input demanded set is simpler than the output set.
1538 APInt DemandedElts2 = DemandedElts;
1539 DemandedElts2.clear(IdxNo);
1540 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1541 UndefElts, Depth+1);
1542 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1544 // The inserted element is defined.
1545 UndefElts.clear(IdxNo);
1548 case Instruction::ShuffleVector: {
1549 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1550 uint64_t LHSVWidth =
1551 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1552 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1553 for (unsigned i = 0; i < VWidth; i++) {
1554 if (DemandedElts[i]) {
1555 unsigned MaskVal = Shuffle->getMaskValue(i);
1556 if (MaskVal != -1u) {
1557 assert(MaskVal < LHSVWidth * 2 &&
1558 "shufflevector mask index out of range!");
1559 if (MaskVal < LHSVWidth)
1560 LeftDemanded.set(MaskVal);
1562 RightDemanded.set(MaskVal - LHSVWidth);
1567 APInt UndefElts4(LHSVWidth, 0);
1568 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1569 UndefElts4, Depth+1);
1570 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1572 APInt UndefElts3(LHSVWidth, 0);
1573 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1574 UndefElts3, Depth+1);
1575 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1577 bool NewUndefElts = false;
1578 for (unsigned i = 0; i < VWidth; i++) {
1579 unsigned MaskVal = Shuffle->getMaskValue(i);
1580 if (MaskVal == -1u) {
1582 } else if (MaskVal < LHSVWidth) {
1583 if (UndefElts4[MaskVal]) {
1584 NewUndefElts = true;
1588 if (UndefElts3[MaskVal - LHSVWidth]) {
1589 NewUndefElts = true;
1596 // Add additional discovered undefs.
1597 std::vector<Constant*> Elts;
1598 for (unsigned i = 0; i < VWidth; ++i) {
1600 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1602 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1603 Shuffle->getMaskValue(i)));
1605 I->setOperand(2, ConstantVector::get(Elts));
1610 case Instruction::BitCast: {
1611 // Vector->vector casts only.
1612 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1614 unsigned InVWidth = VTy->getNumElements();
1615 APInt InputDemandedElts(InVWidth, 0);
1618 if (VWidth == InVWidth) {
1619 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1620 // elements as are demanded of us.
1622 InputDemandedElts = DemandedElts;
1623 } else if (VWidth > InVWidth) {
1627 // If there are more elements in the result than there are in the source,
1628 // then an input element is live if any of the corresponding output
1629 // elements are live.
1630 Ratio = VWidth/InVWidth;
1631 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1632 if (DemandedElts[OutIdx])
1633 InputDemandedElts.set(OutIdx/Ratio);
1639 // If there are more elements in the source than there are in the result,
1640 // then an input element is live if the corresponding output element is
1642 Ratio = InVWidth/VWidth;
1643 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1644 if (DemandedElts[InIdx/Ratio])
1645 InputDemandedElts.set(InIdx);
1648 // div/rem demand all inputs, because they don't want divide by zero.
1649 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1650 UndefElts2, Depth+1);
1652 I->setOperand(0, TmpV);
1656 UndefElts = UndefElts2;
1657 if (VWidth > InVWidth) {
1658 llvm_unreachable("Unimp");
1659 // If there are more elements in the result than there are in the source,
1660 // then an output element is undef if the corresponding input element is
1662 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1663 if (UndefElts2[OutIdx/Ratio])
1664 UndefElts.set(OutIdx);
1665 } else if (VWidth < InVWidth) {
1666 llvm_unreachable("Unimp");
1667 // If there are more elements in the source than there are in the result,
1668 // then a result element is undef if all of the corresponding input
1669 // elements are undef.
1670 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1671 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1672 if (!UndefElts2[InIdx]) // Not undef?
1673 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1677 case Instruction::And:
1678 case Instruction::Or:
1679 case Instruction::Xor:
1680 case Instruction::Add:
1681 case Instruction::Sub:
1682 case Instruction::Mul:
1683 // div/rem demand all inputs, because they don't want divide by zero.
1684 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1685 UndefElts, Depth+1);
1686 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1687 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1688 UndefElts2, Depth+1);
1689 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1691 // Output elements are undefined if both are undefined. Consider things
1692 // like undef&0. The result is known zero, not undef.
1693 UndefElts &= UndefElts2;
1696 case Instruction::Call: {
1697 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1699 switch (II->getIntrinsicID()) {
1702 // Binary vector operations that work column-wise. A dest element is a
1703 // function of the corresponding input elements from the two inputs.
1704 case Intrinsic::x86_sse_sub_ss:
1705 case Intrinsic::x86_sse_mul_ss:
1706 case Intrinsic::x86_sse_min_ss:
1707 case Intrinsic::x86_sse_max_ss:
1708 case Intrinsic::x86_sse2_sub_sd:
1709 case Intrinsic::x86_sse2_mul_sd:
1710 case Intrinsic::x86_sse2_min_sd:
1711 case Intrinsic::x86_sse2_max_sd:
1712 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1713 UndefElts, Depth+1);
1714 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1715 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1716 UndefElts2, Depth+1);
1717 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1719 // If only the low elt is demanded and this is a scalarizable intrinsic,
1720 // scalarize it now.
1721 if (DemandedElts == 1) {
1722 switch (II->getIntrinsicID()) {
1724 case Intrinsic::x86_sse_sub_ss:
1725 case Intrinsic::x86_sse_mul_ss:
1726 case Intrinsic::x86_sse2_sub_sd:
1727 case Intrinsic::x86_sse2_mul_sd:
1728 // TODO: Lower MIN/MAX/ABS/etc
1729 Value *LHS = II->getOperand(1);
1730 Value *RHS = II->getOperand(2);
1731 // Extract the element as scalars.
1732 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
1733 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1734 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1735 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1737 switch (II->getIntrinsicID()) {
1738 default: llvm_unreachable("Case stmts out of sync!");
1739 case Intrinsic::x86_sse_sub_ss:
1740 case Intrinsic::x86_sse2_sub_sd:
1741 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1742 II->getName()), *II);
1744 case Intrinsic::x86_sse_mul_ss:
1745 case Intrinsic::x86_sse2_mul_sd:
1746 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1747 II->getName()), *II);
1752 InsertElementInst::Create(
1753 UndefValue::get(II->getType()), TmpV,
1754 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1755 InsertNewInstBefore(New, *II);
1760 // Output elements are undefined if both are undefined. Consider things
1761 // like undef&0. The result is known zero, not undef.
1762 UndefElts &= UndefElts2;
1768 return MadeChange ? I : 0;
1772 /// AssociativeOpt - Perform an optimization on an associative operator. This
1773 /// function is designed to check a chain of associative operators for a
1774 /// potential to apply a certain optimization. Since the optimization may be
1775 /// applicable if the expression was reassociated, this checks the chain, then
1776 /// reassociates the expression as necessary to expose the optimization
1777 /// opportunity. This makes use of a special Functor, which must define
1778 /// 'shouldApply' and 'apply' methods.
1780 template<typename Functor>
1781 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1782 unsigned Opcode = Root.getOpcode();
1783 Value *LHS = Root.getOperand(0);
1785 // Quick check, see if the immediate LHS matches...
1786 if (F.shouldApply(LHS))
1787 return F.apply(Root);
1789 // Otherwise, if the LHS is not of the same opcode as the root, return.
1790 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1791 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1792 // Should we apply this transform to the RHS?
1793 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1795 // If not to the RHS, check to see if we should apply to the LHS...
1796 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1797 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1801 // If the functor wants to apply the optimization to the RHS of LHSI,
1802 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1804 // Now all of the instructions are in the current basic block, go ahead
1805 // and perform the reassociation.
1806 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1808 // First move the selected RHS to the LHS of the root...
1809 Root.setOperand(0, LHSI->getOperand(1));
1811 // Make what used to be the LHS of the root be the user of the root...
1812 Value *ExtraOperand = TmpLHSI->getOperand(1);
1813 if (&Root == TmpLHSI) {
1814 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1817 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1818 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1819 BasicBlock::iterator ARI = &Root; ++ARI;
1820 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1823 // Now propagate the ExtraOperand down the chain of instructions until we
1825 while (TmpLHSI != LHSI) {
1826 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1827 // Move the instruction to immediately before the chain we are
1828 // constructing to avoid breaking dominance properties.
1829 NextLHSI->moveBefore(ARI);
1832 Value *NextOp = NextLHSI->getOperand(1);
1833 NextLHSI->setOperand(1, ExtraOperand);
1835 ExtraOperand = NextOp;
1838 // Now that the instructions are reassociated, have the functor perform
1839 // the transformation...
1840 return F.apply(Root);
1843 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1850 // AddRHS - Implements: X + X --> X << 1
1853 explicit AddRHS(Value *rhs) : RHS(rhs) {}
1854 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1855 Instruction *apply(BinaryOperator &Add) const {
1856 return BinaryOperator::CreateShl(Add.getOperand(0),
1857 ConstantInt::get(Add.getType(), 1));
1861 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1863 struct AddMaskingAnd {
1865 explicit AddMaskingAnd(Constant *c) : C2(c) {}
1866 bool shouldApply(Value *LHS) const {
1868 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1869 ConstantExpr::getAnd(C1, C2)->isNullValue();
1871 Instruction *apply(BinaryOperator &Add) const {
1872 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1878 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1880 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1881 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1884 // Figure out if the constant is the left or the right argument.
1885 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1886 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1888 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1890 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1891 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1894 Value *Op0 = SO, *Op1 = ConstOperand;
1896 std::swap(Op0, Op1);
1898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1899 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1900 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1901 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1902 Op0, Op1, SO->getName()+".cmp");
1904 llvm_unreachable("Unknown binary instruction type!");
1906 return IC->InsertNewInstBefore(New, I);
1909 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1910 // constant as the other operand, try to fold the binary operator into the
1911 // select arguments. This also works for Cast instructions, which obviously do
1912 // not have a second operand.
1913 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1915 // Don't modify shared select instructions
1916 if (!SI->hasOneUse()) return 0;
1917 Value *TV = SI->getOperand(1);
1918 Value *FV = SI->getOperand(2);
1920 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1921 // Bool selects with constant operands can be folded to logical ops.
1922 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1924 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1925 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1927 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1934 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1935 /// node as operand #0, see if we can fold the instruction into the PHI (which
1936 /// is only possible if all operands to the PHI are constants).
1937 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1938 PHINode *PN = cast<PHINode>(I.getOperand(0));
1939 unsigned NumPHIValues = PN->getNumIncomingValues();
1940 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1942 // Check to see if all of the operands of the PHI are constants. If there is
1943 // one non-constant value, remember the BB it is. If there is more than one
1944 // or if *it* is a PHI, bail out.
1945 BasicBlock *NonConstBB = 0;
1946 for (unsigned i = 0; i != NumPHIValues; ++i)
1947 if (!isa<Constant>(PN->getIncomingValue(i))) {
1948 if (NonConstBB) return 0; // More than one non-const value.
1949 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1950 NonConstBB = PN->getIncomingBlock(i);
1952 // If the incoming non-constant value is in I's block, we have an infinite
1954 if (NonConstBB == I.getParent())
1958 // If there is exactly one non-constant value, we can insert a copy of the
1959 // operation in that block. However, if this is a critical edge, we would be
1960 // inserting the computation one some other paths (e.g. inside a loop). Only
1961 // do this if the pred block is unconditionally branching into the phi block.
1963 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1964 if (!BI || !BI->isUnconditional()) return 0;
1967 // Okay, we can do the transformation: create the new PHI node.
1968 PHINode *NewPN = PHINode::Create(I.getType(), "");
1969 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1970 InsertNewInstBefore(NewPN, *PN);
1971 NewPN->takeName(PN);
1973 // Next, add all of the operands to the PHI.
1974 if (I.getNumOperands() == 2) {
1975 Constant *C = cast<Constant>(I.getOperand(1));
1976 for (unsigned i = 0; i != NumPHIValues; ++i) {
1978 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1979 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1980 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1982 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1984 assert(PN->getIncomingBlock(i) == NonConstBB);
1985 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1986 InV = BinaryOperator::Create(BO->getOpcode(),
1987 PN->getIncomingValue(i), C, "phitmp",
1988 NonConstBB->getTerminator());
1989 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1990 InV = CmpInst::Create(CI->getOpcode(),
1992 PN->getIncomingValue(i), C, "phitmp",
1993 NonConstBB->getTerminator());
1995 llvm_unreachable("Unknown binop!");
1997 Worklist.Add(cast<Instruction>(InV));
1999 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2002 CastInst *CI = cast<CastInst>(&I);
2003 const Type *RetTy = CI->getType();
2004 for (unsigned i = 0; i != NumPHIValues; ++i) {
2006 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2007 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2009 assert(PN->getIncomingBlock(i) == NonConstBB);
2010 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2011 I.getType(), "phitmp",
2012 NonConstBB->getTerminator());
2013 Worklist.Add(cast<Instruction>(InV));
2015 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2018 return ReplaceInstUsesWith(I, NewPN);
2022 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2023 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2024 /// This basically requires proving that the add in the original type would not
2025 /// overflow to change the sign bit or have a carry out.
2026 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2027 // There are different heuristics we can use for this. Here are some simple
2030 // Add has the property that adding any two 2's complement numbers can only
2031 // have one carry bit which can change a sign. As such, if LHS and RHS each
2032 // have at least two sign bits, we know that the addition of the two values will
2033 // sign extend fine.
2034 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2038 // If one of the operands only has one non-zero bit, and if the other operand
2039 // has a known-zero bit in a more significant place than it (not including the
2040 // sign bit) the ripple may go up to and fill the zero, but won't change the
2041 // sign. For example, (X & ~4) + 1.
2049 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2050 bool Changed = SimplifyCommutative(I);
2051 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2053 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2054 // X + undef -> undef
2055 if (isa<UndefValue>(RHS))
2056 return ReplaceInstUsesWith(I, RHS);
2059 if (RHSC->isNullValue())
2060 return ReplaceInstUsesWith(I, LHS);
2062 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2063 // X + (signbit) --> X ^ signbit
2064 const APInt& Val = CI->getValue();
2065 uint32_t BitWidth = Val.getBitWidth();
2066 if (Val == APInt::getSignBit(BitWidth))
2067 return BinaryOperator::CreateXor(LHS, RHS);
2069 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2070 // (X & 254)+1 -> (X&254)|1
2071 if (SimplifyDemandedInstructionBits(I))
2074 // zext(bool) + C -> bool ? C + 1 : C
2075 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2076 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2077 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2080 if (isa<PHINode>(LHS))
2081 if (Instruction *NV = FoldOpIntoPhi(I))
2084 ConstantInt *XorRHS = 0;
2086 if (isa<ConstantInt>(RHSC) &&
2087 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2088 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2089 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2091 uint32_t Size = TySizeBits / 2;
2092 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2093 APInt CFF80Val(-C0080Val);
2095 if (TySizeBits > Size) {
2096 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2097 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2098 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2099 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2100 // This is a sign extend if the top bits are known zero.
2101 if (!MaskedValueIsZero(XorLHS,
2102 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2103 Size = 0; // Not a sign ext, but can't be any others either.
2108 C0080Val = APIntOps::lshr(C0080Val, Size);
2109 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2110 } while (Size >= 1);
2112 // FIXME: This shouldn't be necessary. When the backends can handle types
2113 // with funny bit widths then this switch statement should be removed. It
2114 // is just here to get the size of the "middle" type back up to something
2115 // that the back ends can handle.
2116 const Type *MiddleType = 0;
2119 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2120 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2121 case 8: MiddleType = Type::getInt8Ty(*Context); break;
2124 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2125 InsertNewInstBefore(NewTrunc, I);
2126 return new SExtInst(NewTrunc, I.getType(), I.getName());
2131 if (I.getType() == Type::getInt1Ty(*Context))
2132 return BinaryOperator::CreateXor(LHS, RHS);
2135 if (I.getType()->isInteger()) {
2136 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2139 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2140 if (RHSI->getOpcode() == Instruction::Sub)
2141 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2142 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2144 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2145 if (LHSI->getOpcode() == Instruction::Sub)
2146 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2147 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2152 // -A + -B --> -(A + B)
2153 if (Value *LHSV = dyn_castNegVal(LHS)) {
2154 if (LHS->getType()->isIntOrIntVector()) {
2155 if (Value *RHSV = dyn_castNegVal(RHS)) {
2156 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2157 InsertNewInstBefore(NewAdd, I);
2158 return BinaryOperator::CreateNeg(NewAdd);
2162 return BinaryOperator::CreateSub(RHS, LHSV);
2166 if (!isa<Constant>(RHS))
2167 if (Value *V = dyn_castNegVal(RHS))
2168 return BinaryOperator::CreateSub(LHS, V);
2172 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2173 if (X == RHS) // X*C + X --> X * (C+1)
2174 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2176 // X*C1 + X*C2 --> X * (C1+C2)
2178 if (X == dyn_castFoldableMul(RHS, C1))
2179 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2182 // X + X*C --> X * (C+1)
2183 if (dyn_castFoldableMul(RHS, C2) == LHS)
2184 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2186 // X + ~X --> -1 since ~X = -X-1
2187 if (dyn_castNotVal(LHS) == RHS ||
2188 dyn_castNotVal(RHS) == LHS)
2189 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2192 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2193 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2194 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2197 // A+B --> A|B iff A and B have no bits set in common.
2198 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2199 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2200 APInt LHSKnownOne(IT->getBitWidth(), 0);
2201 APInt LHSKnownZero(IT->getBitWidth(), 0);
2202 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2203 if (LHSKnownZero != 0) {
2204 APInt RHSKnownOne(IT->getBitWidth(), 0);
2205 APInt RHSKnownZero(IT->getBitWidth(), 0);
2206 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2208 // No bits in common -> bitwise or.
2209 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2210 return BinaryOperator::CreateOr(LHS, RHS);
2214 // W*X + Y*Z --> W * (X+Z) iff W == Y
2215 if (I.getType()->isIntOrIntVector()) {
2216 Value *W, *X, *Y, *Z;
2217 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2218 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2222 } else if (Y == X) {
2224 } else if (X == Z) {
2231 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2232 LHS->getName()), I);
2233 return BinaryOperator::CreateMul(W, NewAdd);
2238 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2240 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2241 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2243 // (X & FF00) + xx00 -> (X+xx00) & FF00
2244 if (LHS->hasOneUse() &&
2245 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2246 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2247 if (Anded == CRHS) {
2248 // See if all bits from the first bit set in the Add RHS up are included
2249 // in the mask. First, get the rightmost bit.
2250 const APInt& AddRHSV = CRHS->getValue();
2252 // Form a mask of all bits from the lowest bit added through the top.
2253 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2255 // See if the and mask includes all of these bits.
2256 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2258 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2259 // Okay, the xform is safe. Insert the new add pronto.
2260 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2261 LHS->getName()), I);
2262 return BinaryOperator::CreateAnd(NewAdd, C2);
2267 // Try to fold constant add into select arguments.
2268 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2269 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2273 // add (select X 0 (sub n A)) A --> select X A n
2275 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2278 SI = dyn_cast<SelectInst>(RHS);
2281 if (SI && SI->hasOneUse()) {
2282 Value *TV = SI->getTrueValue();
2283 Value *FV = SI->getFalseValue();
2286 // Can we fold the add into the argument of the select?
2287 // We check both true and false select arguments for a matching subtract.
2288 if (match(FV, m_Zero()) &&
2289 match(TV, m_Sub(m_Value(N), m_Specific(A))))
2290 // Fold the add into the true select value.
2291 return SelectInst::Create(SI->getCondition(), N, A);
2292 if (match(TV, m_Zero()) &&
2293 match(FV, m_Sub(m_Value(N), m_Specific(A))))
2294 // Fold the add into the false select value.
2295 return SelectInst::Create(SI->getCondition(), A, N);
2299 // Check for (add (sext x), y), see if we can merge this into an
2300 // integer add followed by a sext.
2301 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2302 // (add (sext x), cst) --> (sext (add x, cst'))
2303 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2305 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2306 if (LHSConv->hasOneUse() &&
2307 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2308 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2309 // Insert the new, smaller add.
2310 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2312 InsertNewInstBefore(NewAdd, I);
2313 return new SExtInst(NewAdd, I.getType());
2317 // (add (sext x), (sext y)) --> (sext (add int x, y))
2318 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2319 // Only do this if x/y have the same type, if at last one of them has a
2320 // single use (so we don't increase the number of sexts), and if the
2321 // integer add will not overflow.
2322 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2323 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2324 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2325 RHSConv->getOperand(0))) {
2326 // Insert the new integer add.
2327 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2328 RHSConv->getOperand(0),
2330 InsertNewInstBefore(NewAdd, I);
2331 return new SExtInst(NewAdd, I.getType());
2336 return Changed ? &I : 0;
2339 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2340 bool Changed = SimplifyCommutative(I);
2341 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2343 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2345 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2346 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2347 (I.getType())->getValueAPF()))
2348 return ReplaceInstUsesWith(I, LHS);
2351 if (isa<PHINode>(LHS))
2352 if (Instruction *NV = FoldOpIntoPhi(I))
2357 // -A + -B --> -(A + B)
2358 if (Value *LHSV = dyn_castFNegVal(LHS))
2359 return BinaryOperator::CreateFSub(RHS, LHSV);
2362 if (!isa<Constant>(RHS))
2363 if (Value *V = dyn_castFNegVal(RHS))
2364 return BinaryOperator::CreateFSub(LHS, V);
2366 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2367 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2368 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2369 return ReplaceInstUsesWith(I, LHS);
2371 // Check for (add double (sitofp x), y), see if we can merge this into an
2372 // integer add followed by a promotion.
2373 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2374 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2375 // ... if the constant fits in the integer value. This is useful for things
2376 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2377 // requires a constant pool load, and generally allows the add to be better
2379 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2381 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2382 if (LHSConv->hasOneUse() &&
2383 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2384 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2385 // Insert the new integer add.
2386 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2388 InsertNewInstBefore(NewAdd, I);
2389 return new SIToFPInst(NewAdd, I.getType());
2393 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2394 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2395 // Only do this if x/y have the same type, if at last one of them has a
2396 // single use (so we don't increase the number of int->fp conversions),
2397 // and if the integer add will not overflow.
2398 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2399 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2400 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2401 RHSConv->getOperand(0))) {
2402 // Insert the new integer add.
2403 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2404 RHSConv->getOperand(0),
2406 InsertNewInstBefore(NewAdd, I);
2407 return new SIToFPInst(NewAdd, I.getType());
2412 return Changed ? &I : 0;
2415 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2416 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2418 if (Op0 == Op1) // sub X, X -> 0
2419 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2421 // If this is a 'B = x-(-A)', change to B = x+A...
2422 if (Value *V = dyn_castNegVal(Op1))
2423 return BinaryOperator::CreateAdd(Op0, V);
2425 if (isa<UndefValue>(Op0))
2426 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2427 if (isa<UndefValue>(Op1))
2428 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2430 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2431 // Replace (-1 - A) with (~A)...
2432 if (C->isAllOnesValue())
2433 return BinaryOperator::CreateNot(Op1);
2435 // C - ~X == X + (1+C)
2437 if (match(Op1, m_Not(m_Value(X))))
2438 return BinaryOperator::CreateAdd(X, AddOne(C));
2440 // -(X >>u 31) -> (X >>s 31)
2441 // -(X >>s 31) -> (X >>u 31)
2443 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2444 if (SI->getOpcode() == Instruction::LShr) {
2445 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2446 // Check to see if we are shifting out everything but the sign bit.
2447 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2448 SI->getType()->getPrimitiveSizeInBits()-1) {
2449 // Ok, the transformation is safe. Insert AShr.
2450 return BinaryOperator::Create(Instruction::AShr,
2451 SI->getOperand(0), CU, SI->getName());
2455 else if (SI->getOpcode() == Instruction::AShr) {
2456 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2457 // Check to see if we are shifting out everything but the sign bit.
2458 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2459 SI->getType()->getPrimitiveSizeInBits()-1) {
2460 // Ok, the transformation is safe. Insert LShr.
2461 return BinaryOperator::CreateLShr(
2462 SI->getOperand(0), CU, SI->getName());
2469 // Try to fold constant sub into select arguments.
2470 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2471 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2474 // C - zext(bool) -> bool ? C - 1 : C
2475 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2476 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2477 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2480 if (I.getType() == Type::getInt1Ty(*Context))
2481 return BinaryOperator::CreateXor(Op0, Op1);
2483 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2484 if (Op1I->getOpcode() == Instruction::Add) {
2485 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2486 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2488 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2489 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2491 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2492 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2493 // C1-(X+C2) --> (C1-C2)-X
2494 return BinaryOperator::CreateSub(
2495 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2499 if (Op1I->hasOneUse()) {
2500 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2501 // is not used by anyone else...
2503 if (Op1I->getOpcode() == Instruction::Sub) {
2504 // Swap the two operands of the subexpr...
2505 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2506 Op1I->setOperand(0, IIOp1);
2507 Op1I->setOperand(1, IIOp0);
2509 // Create the new top level add instruction...
2510 return BinaryOperator::CreateAdd(Op0, Op1);
2513 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2515 if (Op1I->getOpcode() == Instruction::And &&
2516 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2517 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2520 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2521 return BinaryOperator::CreateAnd(Op0, NewNot);
2524 // 0 - (X sdiv C) -> (X sdiv -C)
2525 if (Op1I->getOpcode() == Instruction::SDiv)
2526 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2528 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2529 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2530 ConstantExpr::getNeg(DivRHS));
2532 // X - X*C --> X * (1-C)
2533 ConstantInt *C2 = 0;
2534 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2536 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2538 return BinaryOperator::CreateMul(Op0, CP1);
2543 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2544 if (Op0I->getOpcode() == Instruction::Add) {
2545 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2546 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2547 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2548 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2549 } else if (Op0I->getOpcode() == Instruction::Sub) {
2550 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2551 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2557 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2558 if (X == Op1) // X*C - X --> X * (C-1)
2559 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2561 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2562 if (X == dyn_castFoldableMul(Op1, C2))
2563 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2568 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2569 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2571 // If this is a 'B = x-(-A)', change to B = x+A...
2572 if (Value *V = dyn_castFNegVal(Op1))
2573 return BinaryOperator::CreateFAdd(Op0, V);
2575 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2576 if (Op1I->getOpcode() == Instruction::FAdd) {
2577 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2578 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2580 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2581 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2589 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2590 /// comparison only checks the sign bit. If it only checks the sign bit, set
2591 /// TrueIfSigned if the result of the comparison is true when the input value is
2593 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2594 bool &TrueIfSigned) {
2596 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2597 TrueIfSigned = true;
2598 return RHS->isZero();
2599 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2600 TrueIfSigned = true;
2601 return RHS->isAllOnesValue();
2602 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2603 TrueIfSigned = false;
2604 return RHS->isAllOnesValue();
2605 case ICmpInst::ICMP_UGT:
2606 // True if LHS u> RHS and RHS == high-bit-mask - 1
2607 TrueIfSigned = true;
2608 return RHS->getValue() ==
2609 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2610 case ICmpInst::ICMP_UGE:
2611 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2612 TrueIfSigned = true;
2613 return RHS->getValue().isSignBit();
2619 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2620 bool Changed = SimplifyCommutative(I);
2621 Value *Op0 = I.getOperand(0);
2623 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2624 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2626 // Simplify mul instructions with a constant RHS...
2627 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2628 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2630 // ((X << C1)*C2) == (X * (C2 << C1))
2631 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2632 if (SI->getOpcode() == Instruction::Shl)
2633 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2634 return BinaryOperator::CreateMul(SI->getOperand(0),
2635 ConstantExpr::getShl(CI, ShOp));
2638 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2639 if (CI->equalsInt(1)) // X * 1 == X
2640 return ReplaceInstUsesWith(I, Op0);
2641 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2642 return BinaryOperator::CreateNeg(Op0, I.getName());
2644 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2645 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2646 return BinaryOperator::CreateShl(Op0,
2647 ConstantInt::get(Op0->getType(), Val.logBase2()));
2649 } else if (isa<VectorType>(Op1->getType())) {
2650 if (Op1->isNullValue())
2651 return ReplaceInstUsesWith(I, Op1);
2653 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2654 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2655 return BinaryOperator::CreateNeg(Op0, I.getName());
2657 // As above, vector X*splat(1.0) -> X in all defined cases.
2658 if (Constant *Splat = Op1V->getSplatValue()) {
2659 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2660 if (CI->equalsInt(1))
2661 return ReplaceInstUsesWith(I, Op0);
2666 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2667 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2668 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2669 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2670 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2672 InsertNewInstBefore(Add, I);
2673 Value *C1C2 = ConstantExpr::getMul(Op1,
2674 cast<Constant>(Op0I->getOperand(1)));
2675 return BinaryOperator::CreateAdd(Add, C1C2);
2679 // Try to fold constant mul into select arguments.
2680 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2681 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2684 if (isa<PHINode>(Op0))
2685 if (Instruction *NV = FoldOpIntoPhi(I))
2689 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2690 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2691 return BinaryOperator::CreateMul(Op0v, Op1v);
2693 // (X / Y) * Y = X - (X % Y)
2694 // (X / Y) * -Y = (X % Y) - X
2696 Value *Op1 = I.getOperand(1);
2697 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2699 (BO->getOpcode() != Instruction::UDiv &&
2700 BO->getOpcode() != Instruction::SDiv)) {
2702 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2704 Value *Neg = dyn_castNegVal(Op1);
2705 if (BO && BO->hasOneUse() &&
2706 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2707 (BO->getOpcode() == Instruction::UDiv ||
2708 BO->getOpcode() == Instruction::SDiv)) {
2709 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2711 // If the division is exact, X % Y is zero.
2712 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2713 if (SDiv->isExact()) {
2715 return ReplaceInstUsesWith(I, Op0BO);
2717 return BinaryOperator::CreateNeg(Op0BO);
2721 if (BO->getOpcode() == Instruction::UDiv)
2722 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2724 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2726 InsertNewInstBefore(Rem, I);
2730 return BinaryOperator::CreateSub(Op0BO, Rem);
2732 return BinaryOperator::CreateSub(Rem, Op0BO);
2736 if (I.getType() == Type::getInt1Ty(*Context))
2737 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2739 // If one of the operands of the multiply is a cast from a boolean value, then
2740 // we know the bool is either zero or one, so this is a 'masking' multiply.
2741 // See if we can simplify things based on how the boolean was originally
2743 CastInst *BoolCast = 0;
2744 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2745 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2748 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2749 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2752 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2753 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2754 const Type *SCOpTy = SCIOp0->getType();
2757 // If the icmp is true iff the sign bit of X is set, then convert this
2758 // multiply into a shift/and combination.
2759 if (isa<ConstantInt>(SCIOp1) &&
2760 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2762 // Shift the X value right to turn it into "all signbits".
2763 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2764 SCOpTy->getPrimitiveSizeInBits()-1);
2766 InsertNewInstBefore(
2767 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2768 BoolCast->getOperand(0)->getName()+
2771 // If the multiply type is not the same as the source type, sign extend
2772 // or truncate to the multiply type.
2773 if (I.getType() != V->getType()) {
2774 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2775 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2776 Instruction::CastOps opcode =
2777 (SrcBits == DstBits ? Instruction::BitCast :
2778 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2779 V = InsertCastBefore(opcode, V, I.getType(), I);
2782 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2783 return BinaryOperator::CreateAnd(V, OtherOp);
2788 return Changed ? &I : 0;
2791 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2792 bool Changed = SimplifyCommutative(I);
2793 Value *Op0 = I.getOperand(0);
2795 // Simplify mul instructions with a constant RHS...
2796 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2797 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2798 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2799 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2800 if (Op1F->isExactlyValue(1.0))
2801 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2802 } else if (isa<VectorType>(Op1->getType())) {
2803 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2804 // As above, vector X*splat(1.0) -> X in all defined cases.
2805 if (Constant *Splat = Op1V->getSplatValue()) {
2806 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2807 if (F->isExactlyValue(1.0))
2808 return ReplaceInstUsesWith(I, Op0);
2813 // Try to fold constant mul into select arguments.
2814 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2815 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2818 if (isa<PHINode>(Op0))
2819 if (Instruction *NV = FoldOpIntoPhi(I))
2823 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2824 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2825 return BinaryOperator::CreateFMul(Op0v, Op1v);
2827 return Changed ? &I : 0;
2830 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2832 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2833 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2835 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2836 int NonNullOperand = -1;
2837 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2838 if (ST->isNullValue())
2840 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2841 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2842 if (ST->isNullValue())
2845 if (NonNullOperand == -1)
2848 Value *SelectCond = SI->getOperand(0);
2850 // Change the div/rem to use 'Y' instead of the select.
2851 I.setOperand(1, SI->getOperand(NonNullOperand));
2853 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2854 // problem. However, the select, or the condition of the select may have
2855 // multiple uses. Based on our knowledge that the operand must be non-zero,
2856 // propagate the known value for the select into other uses of it, and
2857 // propagate a known value of the condition into its other users.
2859 // If the select and condition only have a single use, don't bother with this,
2861 if (SI->use_empty() && SelectCond->hasOneUse())
2864 // Scan the current block backward, looking for other uses of SI.
2865 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2867 while (BBI != BBFront) {
2869 // If we found a call to a function, we can't assume it will return, so
2870 // information from below it cannot be propagated above it.
2871 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2874 // Replace uses of the select or its condition with the known values.
2875 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2878 *I = SI->getOperand(NonNullOperand);
2880 } else if (*I == SelectCond) {
2881 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2882 ConstantInt::getFalse(*Context);
2887 // If we past the instruction, quit looking for it.
2890 if (&*BBI == SelectCond)
2893 // If we ran out of things to eliminate, break out of the loop.
2894 if (SelectCond == 0 && SI == 0)
2902 /// This function implements the transforms on div instructions that work
2903 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2904 /// used by the visitors to those instructions.
2905 /// @brief Transforms common to all three div instructions
2906 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2907 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2909 // undef / X -> 0 for integer.
2910 // undef / X -> undef for FP (the undef could be a snan).
2911 if (isa<UndefValue>(Op0)) {
2912 if (Op0->getType()->isFPOrFPVector())
2913 return ReplaceInstUsesWith(I, Op0);
2914 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2917 // X / undef -> undef
2918 if (isa<UndefValue>(Op1))
2919 return ReplaceInstUsesWith(I, Op1);
2924 /// This function implements the transforms common to both integer division
2925 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2926 /// division instructions.
2927 /// @brief Common integer divide transforms
2928 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2929 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2931 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2933 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2934 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2935 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2936 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2939 Constant *CI = ConstantInt::get(I.getType(), 1);
2940 return ReplaceInstUsesWith(I, CI);
2943 if (Instruction *Common = commonDivTransforms(I))
2946 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2947 // This does not apply for fdiv.
2948 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2951 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2953 if (RHS->equalsInt(1))
2954 return ReplaceInstUsesWith(I, Op0);
2956 // (X / C1) / C2 -> X / (C1*C2)
2957 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2958 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2959 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2960 if (MultiplyOverflows(RHS, LHSRHS,
2961 I.getOpcode()==Instruction::SDiv))
2962 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2964 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2965 ConstantExpr::getMul(RHS, LHSRHS));
2968 if (!RHS->isZero()) { // avoid X udiv 0
2969 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2970 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2972 if (isa<PHINode>(Op0))
2973 if (Instruction *NV = FoldOpIntoPhi(I))
2978 // 0 / X == 0, we don't need to preserve faults!
2979 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2980 if (LHS->equalsInt(0))
2981 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2983 // It can't be division by zero, hence it must be division by one.
2984 if (I.getType() == Type::getInt1Ty(*Context))
2985 return ReplaceInstUsesWith(I, Op0);
2987 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2988 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2991 return ReplaceInstUsesWith(I, Op0);
2997 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2998 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3000 // Handle the integer div common cases
3001 if (Instruction *Common = commonIDivTransforms(I))
3004 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3005 // X udiv C^2 -> X >> C
3006 // Check to see if this is an unsigned division with an exact power of 2,
3007 // if so, convert to a right shift.
3008 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3009 return BinaryOperator::CreateLShr(Op0,
3010 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3012 // X udiv C, where C >= signbit
3013 if (C->getValue().isNegative()) {
3014 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3016 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3017 ConstantInt::get(I.getType(), 1));
3021 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3022 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3023 if (RHSI->getOpcode() == Instruction::Shl &&
3024 isa<ConstantInt>(RHSI->getOperand(0))) {
3025 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3026 if (C1.isPowerOf2()) {
3027 Value *N = RHSI->getOperand(1);
3028 const Type *NTy = N->getType();
3029 if (uint32_t C2 = C1.logBase2()) {
3030 Constant *C2V = ConstantInt::get(NTy, C2);
3031 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3033 return BinaryOperator::CreateLShr(Op0, N);
3038 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3039 // where C1&C2 are powers of two.
3040 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3041 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3042 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3043 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3044 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3045 // Compute the shift amounts
3046 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3047 // Construct the "on true" case of the select
3048 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3049 Instruction *TSI = BinaryOperator::CreateLShr(
3050 Op0, TC, SI->getName()+".t");
3051 TSI = InsertNewInstBefore(TSI, I);
3053 // Construct the "on false" case of the select
3054 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3055 Instruction *FSI = BinaryOperator::CreateLShr(
3056 Op0, FC, SI->getName()+".f");
3057 FSI = InsertNewInstBefore(FSI, I);
3059 // construct the select instruction and return it.
3060 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3066 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3067 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3069 // Handle the integer div common cases
3070 if (Instruction *Common = commonIDivTransforms(I))
3073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3075 if (RHS->isAllOnesValue())
3076 return BinaryOperator::CreateNeg(Op0);
3078 // sdiv X, C --> ashr X, log2(C)
3079 if (cast<SDivOperator>(&I)->isExact() &&
3080 RHS->getValue().isNonNegative() &&
3081 RHS->getValue().isPowerOf2()) {
3082 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3083 RHS->getValue().exactLogBase2());
3084 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3087 // -X/C --> X/-C provided the negation doesn't overflow.
3088 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3089 if (isa<Constant>(Sub->getOperand(0)) &&
3090 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3091 Sub->hasNoSignedWrap())
3092 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3093 ConstantExpr::getNeg(RHS));
3096 // If the sign bits of both operands are zero (i.e. we can prove they are
3097 // unsigned inputs), turn this into a udiv.
3098 if (I.getType()->isInteger()) {
3099 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3100 if (MaskedValueIsZero(Op0, Mask)) {
3101 if (MaskedValueIsZero(Op1, Mask)) {
3102 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3103 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3105 ConstantInt *ShiftedInt;
3106 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3107 ShiftedInt->getValue().isPowerOf2()) {
3108 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3109 // Safe because the only negative value (1 << Y) can take on is
3110 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3111 // the sign bit set.
3112 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3120 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3121 return commonDivTransforms(I);
3124 /// This function implements the transforms on rem instructions that work
3125 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3126 /// is used by the visitors to those instructions.
3127 /// @brief Transforms common to all three rem instructions
3128 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3129 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3131 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3132 if (I.getType()->isFPOrFPVector())
3133 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3134 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3136 if (isa<UndefValue>(Op1))
3137 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3139 // Handle cases involving: rem X, (select Cond, Y, Z)
3140 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3146 /// This function implements the transforms common to both integer remainder
3147 /// instructions (urem and srem). It is called by the visitors to those integer
3148 /// remainder instructions.
3149 /// @brief Common integer remainder transforms
3150 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3151 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3153 if (Instruction *common = commonRemTransforms(I))
3156 // 0 % X == 0 for integer, we don't need to preserve faults!
3157 if (Constant *LHS = dyn_cast<Constant>(Op0))
3158 if (LHS->isNullValue())
3159 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3161 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3162 // X % 0 == undef, we don't need to preserve faults!
3163 if (RHS->equalsInt(0))
3164 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3166 if (RHS->equalsInt(1)) // X % 1 == 0
3167 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3169 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3170 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3171 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3173 } else if (isa<PHINode>(Op0I)) {
3174 if (Instruction *NV = FoldOpIntoPhi(I))
3178 // See if we can fold away this rem instruction.
3179 if (SimplifyDemandedInstructionBits(I))
3187 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3188 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3190 if (Instruction *common = commonIRemTransforms(I))
3193 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3194 // X urem C^2 -> X and C
3195 // Check to see if this is an unsigned remainder with an exact power of 2,
3196 // if so, convert to a bitwise and.
3197 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3198 if (C->getValue().isPowerOf2())
3199 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3202 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3203 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3204 if (RHSI->getOpcode() == Instruction::Shl &&
3205 isa<ConstantInt>(RHSI->getOperand(0))) {
3206 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3207 Constant *N1 = Constant::getAllOnesValue(I.getType());
3208 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3210 return BinaryOperator::CreateAnd(Op0, Add);
3215 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3216 // where C1&C2 are powers of two.
3217 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3218 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3219 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3220 // STO == 0 and SFO == 0 handled above.
3221 if ((STO->getValue().isPowerOf2()) &&
3222 (SFO->getValue().isPowerOf2())) {
3223 Value *TrueAnd = InsertNewInstBefore(
3224 BinaryOperator::CreateAnd(Op0, SubOne(STO),
3225 SI->getName()+".t"), I);
3226 Value *FalseAnd = InsertNewInstBefore(
3227 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
3228 SI->getName()+".f"), I);
3229 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3237 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3238 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3240 // Handle the integer rem common cases
3241 if (Instruction *Common = commonIRemTransforms(I))
3244 if (Value *RHSNeg = dyn_castNegVal(Op1))
3245 if (!isa<Constant>(RHSNeg) ||
3246 (isa<ConstantInt>(RHSNeg) &&
3247 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3249 Worklist.AddValue(I.getOperand(1));
3250 I.setOperand(1, RHSNeg);
3254 // If the sign bits of both operands are zero (i.e. we can prove they are
3255 // unsigned inputs), turn this into a urem.
3256 if (I.getType()->isInteger()) {
3257 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3258 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3259 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3260 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3264 // If it's a constant vector, flip any negative values positive.
3265 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3266 unsigned VWidth = RHSV->getNumOperands();
3268 bool hasNegative = false;
3269 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3270 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3271 if (RHS->getValue().isNegative())
3275 std::vector<Constant *> Elts(VWidth);
3276 for (unsigned i = 0; i != VWidth; ++i) {
3277 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3278 if (RHS->getValue().isNegative())
3279 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3285 Constant *NewRHSV = ConstantVector::get(Elts);
3286 if (NewRHSV != RHSV) {
3287 Worklist.AddValue(I.getOperand(1));
3288 I.setOperand(1, NewRHSV);
3297 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3298 return commonRemTransforms(I);
3301 // isOneBitSet - Return true if there is exactly one bit set in the specified
3303 static bool isOneBitSet(const ConstantInt *CI) {
3304 return CI->getValue().isPowerOf2();
3307 // isHighOnes - Return true if the constant is of the form 1+0+.
3308 // This is the same as lowones(~X).
3309 static bool isHighOnes(const ConstantInt *CI) {
3310 return (~CI->getValue() + 1).isPowerOf2();
3313 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3314 /// are carefully arranged to allow folding of expressions such as:
3316 /// (A < B) | (A > B) --> (A != B)
3318 /// Note that this is only valid if the first and second predicates have the
3319 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3321 /// Three bits are used to represent the condition, as follows:
3326 /// <=> Value Definition
3327 /// 000 0 Always false
3334 /// 111 7 Always true
3336 static unsigned getICmpCode(const ICmpInst *ICI) {
3337 switch (ICI->getPredicate()) {
3339 case ICmpInst::ICMP_UGT: return 1; // 001
3340 case ICmpInst::ICMP_SGT: return 1; // 001
3341 case ICmpInst::ICMP_EQ: return 2; // 010
3342 case ICmpInst::ICMP_UGE: return 3; // 011
3343 case ICmpInst::ICMP_SGE: return 3; // 011
3344 case ICmpInst::ICMP_ULT: return 4; // 100
3345 case ICmpInst::ICMP_SLT: return 4; // 100
3346 case ICmpInst::ICMP_NE: return 5; // 101
3347 case ICmpInst::ICMP_ULE: return 6; // 110
3348 case ICmpInst::ICMP_SLE: return 6; // 110
3351 llvm_unreachable("Invalid ICmp predicate!");
3356 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3357 /// predicate into a three bit mask. It also returns whether it is an ordered
3358 /// predicate by reference.
3359 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3362 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3363 case FCmpInst::FCMP_UNO: return 0; // 000
3364 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3365 case FCmpInst::FCMP_UGT: return 1; // 001
3366 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3367 case FCmpInst::FCMP_UEQ: return 2; // 010
3368 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3369 case FCmpInst::FCMP_UGE: return 3; // 011
3370 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3371 case FCmpInst::FCMP_ULT: return 4; // 100
3372 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3373 case FCmpInst::FCMP_UNE: return 5; // 101
3374 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3375 case FCmpInst::FCMP_ULE: return 6; // 110
3378 // Not expecting FCMP_FALSE and FCMP_TRUE;
3379 llvm_unreachable("Unexpected FCmp predicate!");
3384 /// getICmpValue - This is the complement of getICmpCode, which turns an
3385 /// opcode and two operands into either a constant true or false, or a brand
3386 /// new ICmp instruction. The sign is passed in to determine which kind
3387 /// of predicate to use in the new icmp instruction.
3388 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3389 LLVMContext *Context) {
3391 default: llvm_unreachable("Illegal ICmp code!");
3392 case 0: return ConstantInt::getFalse(*Context);
3395 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3397 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3398 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3401 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3403 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3406 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3408 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3409 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3412 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3414 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3415 case 7: return ConstantInt::getTrue(*Context);
3419 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3420 /// opcode and two operands into either a FCmp instruction. isordered is passed
3421 /// in to determine which kind of predicate to use in the new fcmp instruction.
3422 static Value *getFCmpValue(bool isordered, unsigned code,
3423 Value *LHS, Value *RHS, LLVMContext *Context) {
3425 default: llvm_unreachable("Illegal FCmp code!");
3428 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3430 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3433 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3435 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3438 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3440 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3443 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3445 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3448 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3450 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3453 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3455 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3458 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3460 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3461 case 7: return ConstantInt::getTrue(*Context);
3465 /// PredicatesFoldable - Return true if both predicates match sign or if at
3466 /// least one of them is an equality comparison (which is signless).
3467 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3468 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3469 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3470 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3474 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3475 struct FoldICmpLogical {
3478 ICmpInst::Predicate pred;
3479 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3480 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3481 pred(ICI->getPredicate()) {}
3482 bool shouldApply(Value *V) const {
3483 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3484 if (PredicatesFoldable(pred, ICI->getPredicate()))
3485 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3486 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3489 Instruction *apply(Instruction &Log) const {
3490 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3491 if (ICI->getOperand(0) != LHS) {
3492 assert(ICI->getOperand(1) == LHS);
3493 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3496 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3497 unsigned LHSCode = getICmpCode(ICI);
3498 unsigned RHSCode = getICmpCode(RHSICI);
3500 switch (Log.getOpcode()) {
3501 case Instruction::And: Code = LHSCode & RHSCode; break;
3502 case Instruction::Or: Code = LHSCode | RHSCode; break;
3503 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3504 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3507 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3508 ICmpInst::isSignedPredicate(ICI->getPredicate());
3510 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3511 if (Instruction *I = dyn_cast<Instruction>(RV))
3513 // Otherwise, it's a constant boolean value...
3514 return IC.ReplaceInstUsesWith(Log, RV);
3517 } // end anonymous namespace
3519 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3520 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3521 // guaranteed to be a binary operator.
3522 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3524 ConstantInt *AndRHS,
3525 BinaryOperator &TheAnd) {
3526 Value *X = Op->getOperand(0);
3527 Constant *Together = 0;
3529 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3531 switch (Op->getOpcode()) {
3532 case Instruction::Xor:
3533 if (Op->hasOneUse()) {
3534 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3535 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3536 InsertNewInstBefore(And, TheAnd);
3538 return BinaryOperator::CreateXor(And, Together);
3541 case Instruction::Or:
3542 if (Together == AndRHS) // (X | C) & C --> C
3543 return ReplaceInstUsesWith(TheAnd, AndRHS);
3545 if (Op->hasOneUse() && Together != OpRHS) {
3546 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3547 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3548 InsertNewInstBefore(Or, TheAnd);
3550 return BinaryOperator::CreateAnd(Or, AndRHS);
3553 case Instruction::Add:
3554 if (Op->hasOneUse()) {
3555 // Adding a one to a single bit bit-field should be turned into an XOR
3556 // of the bit. First thing to check is to see if this AND is with a
3557 // single bit constant.
3558 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3560 // If there is only one bit set...
3561 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3562 // Ok, at this point, we know that we are masking the result of the
3563 // ADD down to exactly one bit. If the constant we are adding has
3564 // no bits set below this bit, then we can eliminate the ADD.
3565 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3567 // Check to see if any bits below the one bit set in AndRHSV are set.
3568 if ((AddRHS & (AndRHSV-1)) == 0) {
3569 // If not, the only thing that can effect the output of the AND is
3570 // the bit specified by AndRHSV. If that bit is set, the effect of
3571 // the XOR is to toggle the bit. If it is clear, then the ADD has
3573 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3574 TheAnd.setOperand(0, X);
3577 // Pull the XOR out of the AND.
3578 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3579 InsertNewInstBefore(NewAnd, TheAnd);
3580 NewAnd->takeName(Op);
3581 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3588 case Instruction::Shl: {
3589 // We know that the AND will not produce any of the bits shifted in, so if
3590 // the anded constant includes them, clear them now!
3592 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3593 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3594 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3595 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3597 if (CI->getValue() == ShlMask) {
3598 // Masking out bits that the shift already masks
3599 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3600 } else if (CI != AndRHS) { // Reducing bits set in and.
3601 TheAnd.setOperand(1, CI);
3606 case Instruction::LShr:
3608 // We know that the AND will not produce any of the bits shifted in, so if
3609 // the anded constant includes them, clear them now! This only applies to
3610 // unsigned shifts, because a signed shr may bring in set bits!
3612 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3613 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3614 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3615 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3617 if (CI->getValue() == ShrMask) {
3618 // Masking out bits that the shift already masks.
3619 return ReplaceInstUsesWith(TheAnd, Op);
3620 } else if (CI != AndRHS) {
3621 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3626 case Instruction::AShr:
3628 // See if this is shifting in some sign extension, then masking it out
3630 if (Op->hasOneUse()) {
3631 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3632 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3633 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3634 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3635 if (C == AndRHS) { // Masking out bits shifted in.
3636 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3637 // Make the argument unsigned.
3638 Value *ShVal = Op->getOperand(0);
3639 ShVal = InsertNewInstBefore(
3640 BinaryOperator::CreateLShr(ShVal, OpRHS,
3641 Op->getName()), TheAnd);
3642 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3651 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3652 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3653 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3654 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3655 /// insert new instructions.
3656 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3657 bool isSigned, bool Inside,
3659 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3660 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3661 "Lo is not <= Hi in range emission code!");
3664 if (Lo == Hi) // Trivially false.
3665 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3667 // V >= Min && V < Hi --> V < Hi
3668 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3669 ICmpInst::Predicate pred = (isSigned ?
3670 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3671 return new ICmpInst(pred, V, Hi);
3674 // Emit V-Lo <u Hi-Lo
3675 Constant *NegLo = ConstantExpr::getNeg(Lo);
3676 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3677 InsertNewInstBefore(Add, IB);
3678 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3679 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3682 if (Lo == Hi) // Trivially true.
3683 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3685 // V < Min || V >= Hi -> V > Hi-1
3686 Hi = SubOne(cast<ConstantInt>(Hi));
3687 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3688 ICmpInst::Predicate pred = (isSigned ?
3689 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3690 return new ICmpInst(pred, V, Hi);
3693 // Emit V-Lo >u Hi-1-Lo
3694 // Note that Hi has already had one subtracted from it, above.
3695 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3696 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3697 InsertNewInstBefore(Add, IB);
3698 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3699 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3702 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3703 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3704 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3705 // not, since all 1s are not contiguous.
3706 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3707 const APInt& V = Val->getValue();
3708 uint32_t BitWidth = Val->getType()->getBitWidth();
3709 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3711 // look for the first zero bit after the run of ones
3712 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3713 // look for the first non-zero bit
3714 ME = V.getActiveBits();
3718 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3719 /// where isSub determines whether the operator is a sub. If we can fold one of
3720 /// the following xforms:
3722 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3723 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3724 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3726 /// return (A +/- B).
3728 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3729 ConstantInt *Mask, bool isSub,
3731 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3732 if (!LHSI || LHSI->getNumOperands() != 2 ||
3733 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3735 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3737 switch (LHSI->getOpcode()) {
3739 case Instruction::And:
3740 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3741 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3742 if ((Mask->getValue().countLeadingZeros() +
3743 Mask->getValue().countPopulation()) ==
3744 Mask->getValue().getBitWidth())
3747 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3748 // part, we don't need any explicit masks to take them out of A. If that
3749 // is all N is, ignore it.
3750 uint32_t MB = 0, ME = 0;
3751 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3752 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3753 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3754 if (MaskedValueIsZero(RHS, Mask))
3759 case Instruction::Or:
3760 case Instruction::Xor:
3761 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3762 if ((Mask->getValue().countLeadingZeros() +
3763 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3764 && ConstantExpr::getAnd(N, Mask)->isNullValue())
3771 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3773 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3774 return InsertNewInstBefore(New, I);
3777 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3778 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3779 ICmpInst *LHS, ICmpInst *RHS) {
3781 ConstantInt *LHSCst, *RHSCst;
3782 ICmpInst::Predicate LHSCC, RHSCC;
3784 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3785 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3786 m_ConstantInt(LHSCst))) ||
3787 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3788 m_ConstantInt(RHSCst))))
3791 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3792 // where C is a power of 2
3793 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3794 LHSCst->getValue().isPowerOf2()) {
3795 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3796 InsertNewInstBefore(NewOr, I);
3797 return new ICmpInst(LHSCC, NewOr, LHSCst);
3800 // From here on, we only handle:
3801 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3802 if (Val != Val2) return 0;
3804 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3805 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3806 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3807 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3808 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3811 // We can't fold (ugt x, C) & (sgt x, C2).
3812 if (!PredicatesFoldable(LHSCC, RHSCC))
3815 // Ensure that the larger constant is on the RHS.
3817 if (ICmpInst::isSignedPredicate(LHSCC) ||
3818 (ICmpInst::isEquality(LHSCC) &&
3819 ICmpInst::isSignedPredicate(RHSCC)))
3820 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3822 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3825 std::swap(LHS, RHS);
3826 std::swap(LHSCst, RHSCst);
3827 std::swap(LHSCC, RHSCC);
3830 // At this point, we know we have have two icmp instructions
3831 // comparing a value against two constants and and'ing the result
3832 // together. Because of the above check, we know that we only have
3833 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3834 // (from the FoldICmpLogical check above), that the two constants
3835 // are not equal and that the larger constant is on the RHS
3836 assert(LHSCst != RHSCst && "Compares not folded above?");
3839 default: llvm_unreachable("Unknown integer condition code!");
3840 case ICmpInst::ICMP_EQ:
3842 default: llvm_unreachable("Unknown integer condition code!");
3843 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3844 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3845 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3846 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3847 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3848 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3849 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3850 return ReplaceInstUsesWith(I, LHS);
3852 case ICmpInst::ICMP_NE:
3854 default: llvm_unreachable("Unknown integer condition code!");
3855 case ICmpInst::ICMP_ULT:
3856 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3857 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3858 break; // (X != 13 & X u< 15) -> no change
3859 case ICmpInst::ICMP_SLT:
3860 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3861 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3862 break; // (X != 13 & X s< 15) -> no change
3863 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3864 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3865 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3866 return ReplaceInstUsesWith(I, RHS);
3867 case ICmpInst::ICMP_NE:
3868 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3869 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3870 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3871 Val->getName()+".off");
3872 InsertNewInstBefore(Add, I);
3873 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3874 ConstantInt::get(Add->getType(), 1));
3876 break; // (X != 13 & X != 15) -> no change
3879 case ICmpInst::ICMP_ULT:
3881 default: llvm_unreachable("Unknown integer condition code!");
3882 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3883 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3884 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3885 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3887 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3888 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3889 return ReplaceInstUsesWith(I, LHS);
3890 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3894 case ICmpInst::ICMP_SLT:
3896 default: llvm_unreachable("Unknown integer condition code!");
3897 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3898 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3899 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3900 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3902 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3903 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3904 return ReplaceInstUsesWith(I, LHS);
3905 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3909 case ICmpInst::ICMP_UGT:
3911 default: llvm_unreachable("Unknown integer condition code!");
3912 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3913 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3914 return ReplaceInstUsesWith(I, RHS);
3915 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3917 case ICmpInst::ICMP_NE:
3918 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3919 return new ICmpInst(LHSCC, Val, RHSCst);
3920 break; // (X u> 13 & X != 15) -> no change
3921 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3922 return InsertRangeTest(Val, AddOne(LHSCst),
3923 RHSCst, false, true, I);
3924 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3928 case ICmpInst::ICMP_SGT:
3930 default: llvm_unreachable("Unknown integer condition code!");
3931 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3932 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3933 return ReplaceInstUsesWith(I, RHS);
3934 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3936 case ICmpInst::ICMP_NE:
3937 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3938 return new ICmpInst(LHSCC, Val, RHSCst);
3939 break; // (X s> 13 & X != 15) -> no change
3940 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3941 return InsertRangeTest(Val, AddOne(LHSCst),
3942 RHSCst, true, true, I);
3943 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3952 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3955 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3956 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3957 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3958 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3959 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3960 // If either of the constants are nans, then the whole thing returns
3962 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3963 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3964 return new FCmpInst(FCmpInst::FCMP_ORD,
3965 LHS->getOperand(0), RHS->getOperand(0));
3968 // Handle vector zeros. This occurs because the canonical form of
3969 // "fcmp ord x,x" is "fcmp ord x, 0".
3970 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3971 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3972 return new FCmpInst(FCmpInst::FCMP_ORD,
3973 LHS->getOperand(0), RHS->getOperand(0));
3977 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3978 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3979 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3982 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3983 // Swap RHS operands to match LHS.
3984 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3985 std::swap(Op1LHS, Op1RHS);
3988 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3989 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3991 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3993 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3994 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3995 if (Op0CC == FCmpInst::FCMP_TRUE)
3996 return ReplaceInstUsesWith(I, RHS);
3997 if (Op1CC == FCmpInst::FCMP_TRUE)
3998 return ReplaceInstUsesWith(I, LHS);
4002 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4003 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4005 std::swap(LHS, RHS);
4006 std::swap(Op0Pred, Op1Pred);
4007 std::swap(Op0Ordered, Op1Ordered);
4010 // uno && ueq -> uno && (uno || eq) -> ueq
4011 // ord && olt -> ord && (ord && lt) -> olt
4012 if (Op0Ordered == Op1Ordered)
4013 return ReplaceInstUsesWith(I, RHS);
4015 // uno && oeq -> uno && (ord && eq) -> false
4016 // uno && ord -> false
4018 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4019 // ord && ueq -> ord && (uno || eq) -> oeq
4020 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4021 Op0LHS, Op0RHS, Context));
4029 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4030 bool Changed = SimplifyCommutative(I);
4031 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4033 if (isa<UndefValue>(Op1)) // X & undef -> 0
4034 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4038 return ReplaceInstUsesWith(I, Op1);
4040 // See if we can simplify any instructions used by the instruction whose sole
4041 // purpose is to compute bits we don't care about.
4042 if (SimplifyDemandedInstructionBits(I))
4044 if (isa<VectorType>(I.getType())) {
4045 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4046 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4047 return ReplaceInstUsesWith(I, I.getOperand(0));
4048 } else if (isa<ConstantAggregateZero>(Op1)) {
4049 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4053 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4054 const APInt& AndRHSMask = AndRHS->getValue();
4055 APInt NotAndRHS(~AndRHSMask);
4057 // Optimize a variety of ((val OP C1) & C2) combinations...
4058 if (isa<BinaryOperator>(Op0)) {
4059 Instruction *Op0I = cast<Instruction>(Op0);
4060 Value *Op0LHS = Op0I->getOperand(0);
4061 Value *Op0RHS = Op0I->getOperand(1);
4062 switch (Op0I->getOpcode()) {
4063 case Instruction::Xor:
4064 case Instruction::Or:
4065 // If the mask is only needed on one incoming arm, push it up.
4066 if (Op0I->hasOneUse()) {
4067 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4068 // Not masking anything out for the LHS, move to RHS.
4069 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4070 Op0RHS->getName()+".masked");
4071 InsertNewInstBefore(NewRHS, I);
4072 return BinaryOperator::Create(
4073 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4075 if (!isa<Constant>(Op0RHS) &&
4076 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4077 // Not masking anything out for the RHS, move to LHS.
4078 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4079 Op0LHS->getName()+".masked");
4080 InsertNewInstBefore(NewLHS, I);
4081 return BinaryOperator::Create(
4082 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4087 case Instruction::Add:
4088 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4089 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4090 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4091 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4092 return BinaryOperator::CreateAnd(V, AndRHS);
4093 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4094 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4097 case Instruction::Sub:
4098 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4099 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4100 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4101 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4102 return BinaryOperator::CreateAnd(V, AndRHS);
4104 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4105 // has 1's for all bits that the subtraction with A might affect.
4106 if (Op0I->hasOneUse()) {
4107 uint32_t BitWidth = AndRHSMask.getBitWidth();
4108 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4109 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4111 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4112 if (!(A && A->isZero()) && // avoid infinite recursion.
4113 MaskedValueIsZero(Op0LHS, Mask)) {
4114 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4115 InsertNewInstBefore(NewNeg, I);
4116 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4121 case Instruction::Shl:
4122 case Instruction::LShr:
4123 // (1 << x) & 1 --> zext(x == 0)
4124 // (1 >> x) & 1 --> zext(x == 0)
4125 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4126 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ,
4127 Op0RHS, Constant::getNullValue(I.getType()));
4128 InsertNewInstBefore(NewICmp, I);
4129 return new ZExtInst(NewICmp, I.getType());
4134 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4135 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4137 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4138 // If this is an integer truncation or change from signed-to-unsigned, and
4139 // if the source is an and/or with immediate, transform it. This
4140 // frequently occurs for bitfield accesses.
4141 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4142 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4143 CastOp->getNumOperands() == 2)
4144 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4145 if (CastOp->getOpcode() == Instruction::And) {
4146 // Change: and (cast (and X, C1) to T), C2
4147 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4148 // This will fold the two constants together, which may allow
4149 // other simplifications.
4150 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4151 CastOp->getOperand(0), I.getType(),
4152 CastOp->getName()+".shrunk");
4153 NewCast = InsertNewInstBefore(NewCast, I);
4154 // trunc_or_bitcast(C1)&C2
4156 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4157 C3 = ConstantExpr::getAnd(C3, AndRHS);
4158 return BinaryOperator::CreateAnd(NewCast, C3);
4159 } else if (CastOp->getOpcode() == Instruction::Or) {
4160 // Change: and (cast (or X, C1) to T), C2
4161 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4163 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4164 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4166 return ReplaceInstUsesWith(I, AndRHS);
4172 // Try to fold constant and into select arguments.
4173 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4174 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4176 if (isa<PHINode>(Op0))
4177 if (Instruction *NV = FoldOpIntoPhi(I))
4181 Value *Op0NotVal = dyn_castNotVal(Op0);
4182 Value *Op1NotVal = dyn_castNotVal(Op1);
4184 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4185 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4187 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4188 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4189 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4190 I.getName()+".demorgan");
4191 InsertNewInstBefore(Or, I);
4192 return BinaryOperator::CreateNot(Or);
4196 Value *A = 0, *B = 0, *C = 0, *D = 0;
4197 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4198 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4199 return ReplaceInstUsesWith(I, Op1);
4201 // (A|B) & ~(A&B) -> A^B
4202 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4203 if ((A == C && B == D) || (A == D && B == C))
4204 return BinaryOperator::CreateXor(A, B);
4208 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4209 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4210 return ReplaceInstUsesWith(I, Op0);
4212 // ~(A&B) & (A|B) -> A^B
4213 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4214 if ((A == C && B == D) || (A == D && B == C))
4215 return BinaryOperator::CreateXor(A, B);
4219 if (Op0->hasOneUse() &&
4220 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4221 if (A == Op1) { // (A^B)&A -> A&(A^B)
4222 I.swapOperands(); // Simplify below
4223 std::swap(Op0, Op1);
4224 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4225 cast<BinaryOperator>(Op0)->swapOperands();
4226 I.swapOperands(); // Simplify below
4227 std::swap(Op0, Op1);
4231 if (Op1->hasOneUse() &&
4232 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4233 if (B == Op0) { // B&(A^B) -> B&(B^A)
4234 cast<BinaryOperator>(Op1)->swapOperands();
4237 if (A == Op0) { // A&(A^B) -> A & ~B
4238 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4239 InsertNewInstBefore(NotB, I);
4240 return BinaryOperator::CreateAnd(A, NotB);
4244 // (A&((~A)|B)) -> A&B
4245 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4246 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4247 return BinaryOperator::CreateAnd(A, Op1);
4248 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4249 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4250 return BinaryOperator::CreateAnd(A, Op0);
4253 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4254 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4255 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4258 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4259 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4263 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4264 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4265 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4266 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4267 const Type *SrcTy = Op0C->getOperand(0)->getType();
4268 if (SrcTy == Op1C->getOperand(0)->getType() &&
4269 SrcTy->isIntOrIntVector() &&
4270 // Only do this if the casts both really cause code to be generated.
4271 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4273 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4275 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4276 Op1C->getOperand(0),
4278 InsertNewInstBefore(NewOp, I);
4279 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4283 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4284 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4285 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4286 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4287 SI0->getOperand(1) == SI1->getOperand(1) &&
4288 (SI0->hasOneUse() || SI1->hasOneUse())) {
4289 Instruction *NewOp =
4290 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4292 SI0->getName()), I);
4293 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4294 SI1->getOperand(1));
4298 // If and'ing two fcmp, try combine them into one.
4299 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4300 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4301 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4305 return Changed ? &I : 0;
4308 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4309 /// capable of providing pieces of a bswap. The subexpression provides pieces
4310 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4311 /// the expression came from the corresponding "byte swapped" byte in some other
4312 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4313 /// we know that the expression deposits the low byte of %X into the high byte
4314 /// of the bswap result and that all other bytes are zero. This expression is
4315 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4318 /// This function returns true if the match was unsuccessful and false if so.
4319 /// On entry to the function the "OverallLeftShift" is a signed integer value
4320 /// indicating the number of bytes that the subexpression is later shifted. For
4321 /// example, if the expression is later right shifted by 16 bits, the
4322 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4323 /// byte of ByteValues is actually being set.
4325 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4326 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4327 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4328 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4329 /// always in the local (OverallLeftShift) coordinate space.
4331 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4332 SmallVector<Value*, 8> &ByteValues) {
4333 if (Instruction *I = dyn_cast<Instruction>(V)) {
4334 // If this is an or instruction, it may be an inner node of the bswap.
4335 if (I->getOpcode() == Instruction::Or) {
4336 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4338 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4342 // If this is a logical shift by a constant multiple of 8, recurse with
4343 // OverallLeftShift and ByteMask adjusted.
4344 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4346 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4347 // Ensure the shift amount is defined and of a byte value.
4348 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4351 unsigned ByteShift = ShAmt >> 3;
4352 if (I->getOpcode() == Instruction::Shl) {
4353 // X << 2 -> collect(X, +2)
4354 OverallLeftShift += ByteShift;
4355 ByteMask >>= ByteShift;
4357 // X >>u 2 -> collect(X, -2)
4358 OverallLeftShift -= ByteShift;
4359 ByteMask <<= ByteShift;
4360 ByteMask &= (~0U >> (32-ByteValues.size()));
4363 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4364 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4366 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4370 // If this is a logical 'and' with a mask that clears bytes, clear the
4371 // corresponding bytes in ByteMask.
4372 if (I->getOpcode() == Instruction::And &&
4373 isa<ConstantInt>(I->getOperand(1))) {
4374 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4375 unsigned NumBytes = ByteValues.size();
4376 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4377 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4379 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4380 // If this byte is masked out by a later operation, we don't care what
4382 if ((ByteMask & (1 << i)) == 0)
4385 // If the AndMask is all zeros for this byte, clear the bit.
4386 APInt MaskB = AndMask & Byte;
4388 ByteMask &= ~(1U << i);
4392 // If the AndMask is not all ones for this byte, it's not a bytezap.
4396 // Otherwise, this byte is kept.
4399 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4404 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4405 // the input value to the bswap. Some observations: 1) if more than one byte
4406 // is demanded from this input, then it could not be successfully assembled
4407 // into a byteswap. At least one of the two bytes would not be aligned with
4408 // their ultimate destination.
4409 if (!isPowerOf2_32(ByteMask)) return true;
4410 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4412 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4413 // is demanded, it needs to go into byte 0 of the result. This means that the
4414 // byte needs to be shifted until it lands in the right byte bucket. The
4415 // shift amount depends on the position: if the byte is coming from the high
4416 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4417 // low part, it must be shifted left.
4418 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4419 if (InputByteNo < ByteValues.size()/2) {
4420 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4423 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4427 // If the destination byte value is already defined, the values are or'd
4428 // together, which isn't a bswap (unless it's an or of the same bits).
4429 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4431 ByteValues[DestByteNo] = V;
4435 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4436 /// If so, insert the new bswap intrinsic and return it.
4437 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4438 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4439 if (!ITy || ITy->getBitWidth() % 16 ||
4440 // ByteMask only allows up to 32-byte values.
4441 ITy->getBitWidth() > 32*8)
4442 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4444 /// ByteValues - For each byte of the result, we keep track of which value
4445 /// defines each byte.
4446 SmallVector<Value*, 8> ByteValues;
4447 ByteValues.resize(ITy->getBitWidth()/8);
4449 // Try to find all the pieces corresponding to the bswap.
4450 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4451 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4454 // Check to see if all of the bytes come from the same value.
4455 Value *V = ByteValues[0];
4456 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4458 // Check to make sure that all of the bytes come from the same value.
4459 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4460 if (ByteValues[i] != V)
4462 const Type *Tys[] = { ITy };
4463 Module *M = I.getParent()->getParent()->getParent();
4464 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4465 return CallInst::Create(F, V);
4468 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4469 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4470 /// we can simplify this expression to "cond ? C : D or B".
4471 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4473 LLVMContext *Context) {
4474 // If A is not a select of -1/0, this cannot match.
4476 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4479 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4480 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4481 return SelectInst::Create(Cond, C, B);
4482 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4483 return SelectInst::Create(Cond, C, B);
4484 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4485 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4486 return SelectInst::Create(Cond, C, D);
4487 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4488 return SelectInst::Create(Cond, C, D);
4492 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4493 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4494 ICmpInst *LHS, ICmpInst *RHS) {
4496 ConstantInt *LHSCst, *RHSCst;
4497 ICmpInst::Predicate LHSCC, RHSCC;
4499 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4500 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4501 m_ConstantInt(LHSCst))) ||
4502 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4503 m_ConstantInt(RHSCst))))
4506 // From here on, we only handle:
4507 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4508 if (Val != Val2) return 0;
4510 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4511 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4512 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4513 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4514 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4517 // We can't fold (ugt x, C) | (sgt x, C2).
4518 if (!PredicatesFoldable(LHSCC, RHSCC))
4521 // Ensure that the larger constant is on the RHS.
4523 if (ICmpInst::isSignedPredicate(LHSCC) ||
4524 (ICmpInst::isEquality(LHSCC) &&
4525 ICmpInst::isSignedPredicate(RHSCC)))
4526 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4528 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4531 std::swap(LHS, RHS);
4532 std::swap(LHSCst, RHSCst);
4533 std::swap(LHSCC, RHSCC);
4536 // At this point, we know we have have two icmp instructions
4537 // comparing a value against two constants and or'ing the result
4538 // together. Because of the above check, we know that we only have
4539 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4540 // FoldICmpLogical check above), that the two constants are not
4542 assert(LHSCst != RHSCst && "Compares not folded above?");
4545 default: llvm_unreachable("Unknown integer condition code!");
4546 case ICmpInst::ICMP_EQ:
4548 default: llvm_unreachable("Unknown integer condition code!");
4549 case ICmpInst::ICMP_EQ:
4550 if (LHSCst == SubOne(RHSCst)) {
4551 // (X == 13 | X == 14) -> X-13 <u 2
4552 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4553 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4554 Val->getName()+".off");
4555 InsertNewInstBefore(Add, I);
4556 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4557 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4559 break; // (X == 13 | X == 15) -> no change
4560 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4561 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4563 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4564 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4565 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4566 return ReplaceInstUsesWith(I, RHS);
4569 case ICmpInst::ICMP_NE:
4571 default: llvm_unreachable("Unknown integer condition code!");
4572 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4573 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4574 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4575 return ReplaceInstUsesWith(I, LHS);
4576 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4577 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4578 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4579 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4582 case ICmpInst::ICMP_ULT:
4584 default: llvm_unreachable("Unknown integer condition code!");
4585 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4587 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4588 // If RHSCst is [us]MAXINT, it is always false. Not handling
4589 // this can cause overflow.
4590 if (RHSCst->isMaxValue(false))
4591 return ReplaceInstUsesWith(I, LHS);
4592 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4594 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4596 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4597 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4598 return ReplaceInstUsesWith(I, RHS);
4599 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4603 case ICmpInst::ICMP_SLT:
4605 default: llvm_unreachable("Unknown integer condition code!");
4606 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4608 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4609 // If RHSCst is [us]MAXINT, it is always false. Not handling
4610 // this can cause overflow.
4611 if (RHSCst->isMaxValue(true))
4612 return ReplaceInstUsesWith(I, LHS);
4613 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4615 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4617 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4618 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4619 return ReplaceInstUsesWith(I, RHS);
4620 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4624 case ICmpInst::ICMP_UGT:
4626 default: llvm_unreachable("Unknown integer condition code!");
4627 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4628 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4629 return ReplaceInstUsesWith(I, LHS);
4630 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4632 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4633 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4634 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4635 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4639 case ICmpInst::ICMP_SGT:
4641 default: llvm_unreachable("Unknown integer condition code!");
4642 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4643 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4644 return ReplaceInstUsesWith(I, LHS);
4645 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4647 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4648 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4649 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4650 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4658 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4660 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4661 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4662 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4663 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4664 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4665 // If either of the constants are nans, then the whole thing returns
4667 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4668 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4670 // Otherwise, no need to compare the two constants, compare the
4672 return new FCmpInst(FCmpInst::FCMP_UNO,
4673 LHS->getOperand(0), RHS->getOperand(0));
4676 // Handle vector zeros. This occurs because the canonical form of
4677 // "fcmp uno x,x" is "fcmp uno x, 0".
4678 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4679 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4680 return new FCmpInst(FCmpInst::FCMP_UNO,
4681 LHS->getOperand(0), RHS->getOperand(0));
4686 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4687 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4688 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4690 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4691 // Swap RHS operands to match LHS.
4692 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4693 std::swap(Op1LHS, Op1RHS);
4695 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4696 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4698 return new FCmpInst((FCmpInst::Predicate)Op0CC,
4700 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4701 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4702 if (Op0CC == FCmpInst::FCMP_FALSE)
4703 return ReplaceInstUsesWith(I, RHS);
4704 if (Op1CC == FCmpInst::FCMP_FALSE)
4705 return ReplaceInstUsesWith(I, LHS);
4708 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4709 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4710 if (Op0Ordered == Op1Ordered) {
4711 // If both are ordered or unordered, return a new fcmp with
4712 // or'ed predicates.
4713 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4714 Op0LHS, Op0RHS, Context);
4715 if (Instruction *I = dyn_cast<Instruction>(RV))
4717 // Otherwise, it's a constant boolean value...
4718 return ReplaceInstUsesWith(I, RV);
4724 /// FoldOrWithConstants - This helper function folds:
4726 /// ((A | B) & C1) | (B & C2)
4732 /// when the XOR of the two constants is "all ones" (-1).
4733 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4734 Value *A, Value *B, Value *C) {
4735 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4739 ConstantInt *CI2 = 0;
4740 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4742 APInt Xor = CI1->getValue() ^ CI2->getValue();
4743 if (!Xor.isAllOnesValue()) return 0;
4745 if (V1 == A || V1 == B) {
4746 Instruction *NewOp =
4747 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4748 return BinaryOperator::CreateOr(NewOp, V1);
4754 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4755 bool Changed = SimplifyCommutative(I);
4756 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4758 if (isa<UndefValue>(Op1)) // X | undef -> -1
4759 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4763 return ReplaceInstUsesWith(I, Op0);
4765 // See if we can simplify any instructions used by the instruction whose sole
4766 // purpose is to compute bits we don't care about.
4767 if (SimplifyDemandedInstructionBits(I))
4769 if (isa<VectorType>(I.getType())) {
4770 if (isa<ConstantAggregateZero>(Op1)) {
4771 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4772 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4773 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4774 return ReplaceInstUsesWith(I, I.getOperand(1));
4779 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4780 ConstantInt *C1 = 0; Value *X = 0;
4781 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4782 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4784 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4785 InsertNewInstBefore(Or, I);
4787 return BinaryOperator::CreateAnd(Or,
4788 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4791 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4792 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4794 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4795 InsertNewInstBefore(Or, I);
4797 return BinaryOperator::CreateXor(Or,
4798 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4801 // Try to fold constant and into select arguments.
4802 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4803 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4805 if (isa<PHINode>(Op0))
4806 if (Instruction *NV = FoldOpIntoPhi(I))
4810 Value *A = 0, *B = 0;
4811 ConstantInt *C1 = 0, *C2 = 0;
4813 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4814 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4815 return ReplaceInstUsesWith(I, Op1);
4816 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4817 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4818 return ReplaceInstUsesWith(I, Op0);
4820 // (A | B) | C and A | (B | C) -> bswap if possible.
4821 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4822 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4823 match(Op1, m_Or(m_Value(), m_Value())) ||
4824 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4825 match(Op1, m_Shift(m_Value(), m_Value())))) {
4826 if (Instruction *BSwap = MatchBSwap(I))
4830 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4831 if (Op0->hasOneUse() &&
4832 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4833 MaskedValueIsZero(Op1, C1->getValue())) {
4834 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4835 InsertNewInstBefore(NOr, I);
4837 return BinaryOperator::CreateXor(NOr, C1);
4840 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4841 if (Op1->hasOneUse() &&
4842 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4843 MaskedValueIsZero(Op0, C1->getValue())) {
4844 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4845 InsertNewInstBefore(NOr, I);
4847 return BinaryOperator::CreateXor(NOr, C1);
4851 Value *C = 0, *D = 0;
4852 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4853 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4854 Value *V1 = 0, *V2 = 0, *V3 = 0;
4855 C1 = dyn_cast<ConstantInt>(C);
4856 C2 = dyn_cast<ConstantInt>(D);
4857 if (C1 && C2) { // (A & C1)|(B & C2)
4858 // If we have: ((V + N) & C1) | (V & C2)
4859 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4860 // replace with V+N.
4861 if (C1->getValue() == ~C2->getValue()) {
4862 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4863 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4864 // Add commutes, try both ways.
4865 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4866 return ReplaceInstUsesWith(I, A);
4867 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4868 return ReplaceInstUsesWith(I, A);
4870 // Or commutes, try both ways.
4871 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4872 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4873 // Add commutes, try both ways.
4874 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4875 return ReplaceInstUsesWith(I, B);
4876 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4877 return ReplaceInstUsesWith(I, B);
4880 V1 = 0; V2 = 0; V3 = 0;
4883 // Check to see if we have any common things being and'ed. If so, find the
4884 // terms for V1 & (V2|V3).
4885 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4886 if (A == B) // (A & C)|(A & D) == A & (C|D)
4887 V1 = A, V2 = C, V3 = D;
4888 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4889 V1 = A, V2 = B, V3 = C;
4890 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4891 V1 = C, V2 = A, V3 = D;
4892 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4893 V1 = C, V2 = A, V3 = B;
4897 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4898 return BinaryOperator::CreateAnd(V1, Or);
4902 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4903 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4905 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4907 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4909 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4912 // ((A&~B)|(~A&B)) -> A^B
4913 if ((match(C, m_Not(m_Specific(D))) &&
4914 match(B, m_Not(m_Specific(A)))))
4915 return BinaryOperator::CreateXor(A, D);
4916 // ((~B&A)|(~A&B)) -> A^B
4917 if ((match(A, m_Not(m_Specific(D))) &&
4918 match(B, m_Not(m_Specific(C)))))
4919 return BinaryOperator::CreateXor(C, D);
4920 // ((A&~B)|(B&~A)) -> A^B
4921 if ((match(C, m_Not(m_Specific(B))) &&
4922 match(D, m_Not(m_Specific(A)))))
4923 return BinaryOperator::CreateXor(A, B);
4924 // ((~B&A)|(B&~A)) -> A^B
4925 if ((match(A, m_Not(m_Specific(B))) &&
4926 match(D, m_Not(m_Specific(C)))))
4927 return BinaryOperator::CreateXor(C, B);
4930 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4931 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4932 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4933 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4934 SI0->getOperand(1) == SI1->getOperand(1) &&
4935 (SI0->hasOneUse() || SI1->hasOneUse())) {
4936 Instruction *NewOp =
4937 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4939 SI0->getName()), I);
4940 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4941 SI1->getOperand(1));
4945 // ((A|B)&1)|(B&-2) -> (A&1) | B
4946 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4947 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4948 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4949 if (Ret) return Ret;
4951 // (B&-2)|((A|B)&1) -> (A&1) | B
4952 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4953 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4954 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4955 if (Ret) return Ret;
4958 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4959 if (A == Op1) // ~A | A == -1
4960 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4964 // Note, A is still live here!
4965 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4967 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4969 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4970 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4971 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4972 I.getName()+".demorgan"), I);
4973 return BinaryOperator::CreateNot(And);
4977 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4978 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4979 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4982 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4983 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4987 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4988 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4989 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4990 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4991 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4992 !isa<ICmpInst>(Op1C->getOperand(0))) {
4993 const Type *SrcTy = Op0C->getOperand(0)->getType();
4994 if (SrcTy == Op1C->getOperand(0)->getType() &&
4995 SrcTy->isIntOrIntVector() &&
4996 // Only do this if the casts both really cause code to be
4998 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5000 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5002 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
5003 Op1C->getOperand(0),
5005 InsertNewInstBefore(NewOp, I);
5006 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5013 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5014 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5015 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5016 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5020 return Changed ? &I : 0;
5025 // XorSelf - Implements: X ^ X --> 0
5028 XorSelf(Value *rhs) : RHS(rhs) {}
5029 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5030 Instruction *apply(BinaryOperator &Xor) const {
5037 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5038 bool Changed = SimplifyCommutative(I);
5039 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5041 if (isa<UndefValue>(Op1)) {
5042 if (isa<UndefValue>(Op0))
5043 // Handle undef ^ undef -> 0 special case. This is a common
5045 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5046 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
5049 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5050 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5051 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5052 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5055 // See if we can simplify any instructions used by the instruction whose sole
5056 // purpose is to compute bits we don't care about.
5057 if (SimplifyDemandedInstructionBits(I))
5059 if (isa<VectorType>(I.getType()))
5060 if (isa<ConstantAggregateZero>(Op1))
5061 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
5063 // Is this a ~ operation?
5064 if (Value *NotOp = dyn_castNotVal(&I)) {
5065 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5066 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5067 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5068 if (Op0I->getOpcode() == Instruction::And ||
5069 Op0I->getOpcode() == Instruction::Or) {
5070 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5071 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5073 BinaryOperator::CreateNot(Op0I->getOperand(1),
5074 Op0I->getOperand(1)->getName()+".not");
5075 InsertNewInstBefore(NotY, I);
5076 if (Op0I->getOpcode() == Instruction::And)
5077 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5079 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5086 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5087 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5088 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5089 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5090 return new ICmpInst(ICI->getInversePredicate(),
5091 ICI->getOperand(0), ICI->getOperand(1));
5093 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5094 return new FCmpInst(FCI->getInversePredicate(),
5095 FCI->getOperand(0), FCI->getOperand(1));
5098 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5099 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5100 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5101 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5102 Instruction::CastOps Opcode = Op0C->getOpcode();
5103 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5104 if (RHS == ConstantExpr::getCast(Opcode,
5105 ConstantInt::getTrue(*Context),
5106 Op0C->getDestTy())) {
5107 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5108 CI->getOpcode(), CI->getInversePredicate(),
5109 CI->getOperand(0), CI->getOperand(1)), I);
5110 NewCI->takeName(CI);
5111 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5118 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5119 // ~(c-X) == X-c-1 == X+(-c-1)
5120 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5121 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5122 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5123 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5124 ConstantInt::get(I.getType(), 1));
5125 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5128 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5129 if (Op0I->getOpcode() == Instruction::Add) {
5130 // ~(X-c) --> (-c-1)-X
5131 if (RHS->isAllOnesValue()) {
5132 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5133 return BinaryOperator::CreateSub(
5134 ConstantExpr::getSub(NegOp0CI,
5135 ConstantInt::get(I.getType(), 1)),
5136 Op0I->getOperand(0));
5137 } else if (RHS->getValue().isSignBit()) {
5138 // (X + C) ^ signbit -> (X + C + signbit)
5139 Constant *C = ConstantInt::get(*Context,
5140 RHS->getValue() + Op0CI->getValue());
5141 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5144 } else if (Op0I->getOpcode() == Instruction::Or) {
5145 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5146 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5147 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5148 // Anything in both C1 and C2 is known to be zero, remove it from
5150 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5151 NewRHS = ConstantExpr::getAnd(NewRHS,
5152 ConstantExpr::getNot(CommonBits));
5154 I.setOperand(0, Op0I->getOperand(0));
5155 I.setOperand(1, NewRHS);
5162 // Try to fold constant and into select arguments.
5163 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5164 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5166 if (isa<PHINode>(Op0))
5167 if (Instruction *NV = FoldOpIntoPhi(I))
5171 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5173 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5175 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5177 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5180 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5183 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5184 if (A == Op0) { // B^(B|A) == (A|B)^B
5185 Op1I->swapOperands();
5187 std::swap(Op0, Op1);
5188 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5189 I.swapOperands(); // Simplified below.
5190 std::swap(Op0, Op1);
5192 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5193 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5194 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5195 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5196 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
5198 if (A == Op0) { // A^(A&B) -> A^(B&A)
5199 Op1I->swapOperands();
5202 if (B == Op0) { // A^(B&A) -> (B&A)^A
5203 I.swapOperands(); // Simplified below.
5204 std::swap(Op0, Op1);
5209 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5212 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5213 Op0I->hasOneUse()) {
5214 if (A == Op1) // (B|A)^B == (A|B)^B
5216 if (B == Op1) { // (A|B)^B == A & ~B
5218 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5219 return BinaryOperator::CreateAnd(A, NotB);
5221 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5222 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5223 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5224 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5225 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5227 if (A == Op1) // (A&B)^A -> (B&A)^A
5229 if (B == Op1 && // (B&A)^A == ~B & A
5230 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5232 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5233 return BinaryOperator::CreateAnd(N, Op1);
5238 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5239 if (Op0I && Op1I && Op0I->isShift() &&
5240 Op0I->getOpcode() == Op1I->getOpcode() &&
5241 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5242 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5243 Instruction *NewOp =
5244 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5245 Op1I->getOperand(0),
5246 Op0I->getName()), I);
5247 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5248 Op1I->getOperand(1));
5252 Value *A, *B, *C, *D;
5253 // (A & B)^(A | B) -> A ^ B
5254 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5255 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5256 if ((A == C && B == D) || (A == D && B == C))
5257 return BinaryOperator::CreateXor(A, B);
5259 // (A | B)^(A & B) -> A ^ B
5260 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5261 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5262 if ((A == C && B == D) || (A == D && B == C))
5263 return BinaryOperator::CreateXor(A, B);
5267 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5268 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5269 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5270 // (X & Y)^(X & Y) -> (Y^Z) & X
5271 Value *X = 0, *Y = 0, *Z = 0;
5273 X = A, Y = B, Z = D;
5275 X = A, Y = B, Z = C;
5277 X = B, Y = A, Z = D;
5279 X = B, Y = A, Z = C;
5282 Instruction *NewOp =
5283 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5284 return BinaryOperator::CreateAnd(NewOp, X);
5289 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5290 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5291 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5294 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5295 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5296 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5297 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5298 const Type *SrcTy = Op0C->getOperand(0)->getType();
5299 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5300 // Only do this if the casts both really cause code to be generated.
5301 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5303 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5305 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5306 Op1C->getOperand(0),
5308 InsertNewInstBefore(NewOp, I);
5309 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5314 return Changed ? &I : 0;
5317 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5318 LLVMContext *Context) {
5319 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5322 static bool HasAddOverflow(ConstantInt *Result,
5323 ConstantInt *In1, ConstantInt *In2,
5326 if (In2->getValue().isNegative())
5327 return Result->getValue().sgt(In1->getValue());
5329 return Result->getValue().slt(In1->getValue());
5331 return Result->getValue().ult(In1->getValue());
5334 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5335 /// overflowed for this type.
5336 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5337 Constant *In2, LLVMContext *Context,
5338 bool IsSigned = false) {
5339 Result = ConstantExpr::getAdd(In1, In2);
5341 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5342 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5343 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5344 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5345 ExtractElement(In1, Idx, Context),
5346 ExtractElement(In2, Idx, Context),
5353 return HasAddOverflow(cast<ConstantInt>(Result),
5354 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5358 static bool HasSubOverflow(ConstantInt *Result,
5359 ConstantInt *In1, ConstantInt *In2,
5362 if (In2->getValue().isNegative())
5363 return Result->getValue().slt(In1->getValue());
5365 return Result->getValue().sgt(In1->getValue());
5367 return Result->getValue().ugt(In1->getValue());
5370 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5371 /// overflowed for this type.
5372 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5373 Constant *In2, LLVMContext *Context,
5374 bool IsSigned = false) {
5375 Result = ConstantExpr::getSub(In1, In2);
5377 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5378 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5379 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5380 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5381 ExtractElement(In1, Idx, Context),
5382 ExtractElement(In2, Idx, Context),
5389 return HasSubOverflow(cast<ConstantInt>(Result),
5390 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5394 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5395 /// code necessary to compute the offset from the base pointer (without adding
5396 /// in the base pointer). Return the result as a signed integer of intptr size.
5397 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5398 TargetData &TD = *IC.getTargetData();
5399 gep_type_iterator GTI = gep_type_begin(GEP);
5400 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5401 LLVMContext *Context = IC.getContext();
5402 Value *Result = Constant::getNullValue(IntPtrTy);
5404 // Build a mask for high order bits.
5405 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5406 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5408 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5411 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5412 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5413 if (OpC->isZero()) continue;
5415 // Handle a struct index, which adds its field offset to the pointer.
5416 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5417 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5419 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5421 ConstantInt::get(*Context,
5422 RC->getValue() + APInt(IntPtrWidth, Size));
5424 Result = IC.InsertNewInstBefore(
5425 BinaryOperator::CreateAdd(Result,
5426 ConstantInt::get(IntPtrTy, Size),
5427 GEP->getName()+".offs"), I);
5431 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5433 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5434 Scale = ConstantExpr::getMul(OC, Scale);
5435 if (Constant *RC = dyn_cast<Constant>(Result))
5436 Result = ConstantExpr::getAdd(RC, Scale);
5438 // Emit an add instruction.
5439 Result = IC.InsertNewInstBefore(
5440 BinaryOperator::CreateAdd(Result, Scale,
5441 GEP->getName()+".offs"), I);
5445 // Convert to correct type.
5446 if (Op->getType() != IntPtrTy) {
5447 if (Constant *OpC = dyn_cast<Constant>(Op))
5448 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5450 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5452 Op->getName()+".c"), I);
5455 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5456 if (Constant *OpC = dyn_cast<Constant>(Op))
5457 Op = ConstantExpr::getMul(OpC, Scale);
5458 else // We'll let instcombine(mul) convert this to a shl if possible.
5459 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5460 GEP->getName()+".idx"), I);
5463 // Emit an add instruction.
5464 if (isa<Constant>(Op) && isa<Constant>(Result))
5465 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5466 cast<Constant>(Result));
5468 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5469 GEP->getName()+".offs"), I);
5475 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5476 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5477 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5478 /// be complex, and scales are involved. The above expression would also be
5479 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5480 /// This later form is less amenable to optimization though, and we are allowed
5481 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5483 /// If we can't emit an optimized form for this expression, this returns null.
5485 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5487 TargetData &TD = *IC.getTargetData();
5488 gep_type_iterator GTI = gep_type_begin(GEP);
5490 // Check to see if this gep only has a single variable index. If so, and if
5491 // any constant indices are a multiple of its scale, then we can compute this
5492 // in terms of the scale of the variable index. For example, if the GEP
5493 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5494 // because the expression will cross zero at the same point.
5495 unsigned i, e = GEP->getNumOperands();
5497 for (i = 1; i != e; ++i, ++GTI) {
5498 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5499 // Compute the aggregate offset of constant indices.
5500 if (CI->isZero()) continue;
5502 // Handle a struct index, which adds its field offset to the pointer.
5503 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5504 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5506 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5507 Offset += Size*CI->getSExtValue();
5510 // Found our variable index.
5515 // If there are no variable indices, we must have a constant offset, just
5516 // evaluate it the general way.
5517 if (i == e) return 0;
5519 Value *VariableIdx = GEP->getOperand(i);
5520 // Determine the scale factor of the variable element. For example, this is
5521 // 4 if the variable index is into an array of i32.
5522 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5524 // Verify that there are no other variable indices. If so, emit the hard way.
5525 for (++i, ++GTI; i != e; ++i, ++GTI) {
5526 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5529 // Compute the aggregate offset of constant indices.
5530 if (CI->isZero()) continue;
5532 // Handle a struct index, which adds its field offset to the pointer.
5533 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5534 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5536 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5537 Offset += Size*CI->getSExtValue();
5541 // Okay, we know we have a single variable index, which must be a
5542 // pointer/array/vector index. If there is no offset, life is simple, return
5544 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5546 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5547 // we don't need to bother extending: the extension won't affect where the
5548 // computation crosses zero.
5549 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5550 VariableIdx = new TruncInst(VariableIdx,
5551 TD.getIntPtrType(VariableIdx->getContext()),
5552 VariableIdx->getName(), &I);
5556 // Otherwise, there is an index. The computation we will do will be modulo
5557 // the pointer size, so get it.
5558 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5560 Offset &= PtrSizeMask;
5561 VariableScale &= PtrSizeMask;
5563 // To do this transformation, any constant index must be a multiple of the
5564 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5565 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5566 // multiple of the variable scale.
5567 int64_t NewOffs = Offset / (int64_t)VariableScale;
5568 if (Offset != NewOffs*(int64_t)VariableScale)
5571 // Okay, we can do this evaluation. Start by converting the index to intptr.
5572 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5573 if (VariableIdx->getType() != IntPtrTy)
5574 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5576 VariableIdx->getName(), &I);
5577 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5578 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5582 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5583 /// else. At this point we know that the GEP is on the LHS of the comparison.
5584 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5585 ICmpInst::Predicate Cond,
5587 // Look through bitcasts.
5588 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5589 RHS = BCI->getOperand(0);
5591 Value *PtrBase = GEPLHS->getOperand(0);
5592 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5593 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5594 // This transformation (ignoring the base and scales) is valid because we
5595 // know pointers can't overflow since the gep is inbounds. See if we can
5596 // output an optimized form.
5597 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5599 // If not, synthesize the offset the hard way.
5601 Offset = EmitGEPOffset(GEPLHS, I, *this);
5602 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5603 Constant::getNullValue(Offset->getType()));
5604 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5605 // If the base pointers are different, but the indices are the same, just
5606 // compare the base pointer.
5607 if (PtrBase != GEPRHS->getOperand(0)) {
5608 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5609 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5610 GEPRHS->getOperand(0)->getType();
5612 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5613 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5614 IndicesTheSame = false;
5618 // If all indices are the same, just compare the base pointers.
5620 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5621 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5623 // Otherwise, the base pointers are different and the indices are
5624 // different, bail out.
5628 // If one of the GEPs has all zero indices, recurse.
5629 bool AllZeros = true;
5630 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5631 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5632 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5637 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5638 ICmpInst::getSwappedPredicate(Cond), I);
5640 // If the other GEP has all zero indices, recurse.
5642 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5643 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5644 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5649 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5651 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5652 // If the GEPs only differ by one index, compare it.
5653 unsigned NumDifferences = 0; // Keep track of # differences.
5654 unsigned DiffOperand = 0; // The operand that differs.
5655 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5656 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5657 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5658 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5659 // Irreconcilable differences.
5663 if (NumDifferences++) break;
5668 if (NumDifferences == 0) // SAME GEP?
5669 return ReplaceInstUsesWith(I, // No comparison is needed here.
5670 ConstantInt::get(Type::getInt1Ty(*Context),
5671 ICmpInst::isTrueWhenEqual(Cond)));
5673 else if (NumDifferences == 1) {
5674 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5675 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5676 // Make sure we do a signed comparison here.
5677 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5681 // Only lower this if the icmp is the only user of the GEP or if we expect
5682 // the result to fold to a constant!
5684 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5685 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5686 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5687 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5688 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5689 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5695 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5697 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5700 if (!isa<ConstantFP>(RHSC)) return 0;
5701 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5703 // Get the width of the mantissa. We don't want to hack on conversions that
5704 // might lose information from the integer, e.g. "i64 -> float"
5705 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5706 if (MantissaWidth == -1) return 0; // Unknown.
5708 // Check to see that the input is converted from an integer type that is small
5709 // enough that preserves all bits. TODO: check here for "known" sign bits.
5710 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5711 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5713 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5714 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5718 // If the conversion would lose info, don't hack on this.
5719 if ((int)InputSize > MantissaWidth)
5722 // Otherwise, we can potentially simplify the comparison. We know that it
5723 // will always come through as an integer value and we know the constant is
5724 // not a NAN (it would have been previously simplified).
5725 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5727 ICmpInst::Predicate Pred;
5728 switch (I.getPredicate()) {
5729 default: llvm_unreachable("Unexpected predicate!");
5730 case FCmpInst::FCMP_UEQ:
5731 case FCmpInst::FCMP_OEQ:
5732 Pred = ICmpInst::ICMP_EQ;
5734 case FCmpInst::FCMP_UGT:
5735 case FCmpInst::FCMP_OGT:
5736 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5738 case FCmpInst::FCMP_UGE:
5739 case FCmpInst::FCMP_OGE:
5740 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5742 case FCmpInst::FCMP_ULT:
5743 case FCmpInst::FCMP_OLT:
5744 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5746 case FCmpInst::FCMP_ULE:
5747 case FCmpInst::FCMP_OLE:
5748 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5750 case FCmpInst::FCMP_UNE:
5751 case FCmpInst::FCMP_ONE:
5752 Pred = ICmpInst::ICMP_NE;
5754 case FCmpInst::FCMP_ORD:
5755 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5756 case FCmpInst::FCMP_UNO:
5757 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5760 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5762 // Now we know that the APFloat is a normal number, zero or inf.
5764 // See if the FP constant is too large for the integer. For example,
5765 // comparing an i8 to 300.0.
5766 unsigned IntWidth = IntTy->getScalarSizeInBits();
5769 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5770 // and large values.
5771 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5772 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5773 APFloat::rmNearestTiesToEven);
5774 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5775 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5776 Pred == ICmpInst::ICMP_SLE)
5777 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5778 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5781 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5782 // +INF and large values.
5783 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5784 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5785 APFloat::rmNearestTiesToEven);
5786 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5787 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5788 Pred == ICmpInst::ICMP_ULE)
5789 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5790 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5795 // See if the RHS value is < SignedMin.
5796 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5797 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5798 APFloat::rmNearestTiesToEven);
5799 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5800 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5801 Pred == ICmpInst::ICMP_SGE)
5802 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5803 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5807 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5808 // [0, UMAX], but it may still be fractional. See if it is fractional by
5809 // casting the FP value to the integer value and back, checking for equality.
5810 // Don't do this for zero, because -0.0 is not fractional.
5811 Constant *RHSInt = LHSUnsigned
5812 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5813 : ConstantExpr::getFPToSI(RHSC, IntTy);
5814 if (!RHS.isZero()) {
5815 bool Equal = LHSUnsigned
5816 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5817 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5819 // If we had a comparison against a fractional value, we have to adjust
5820 // the compare predicate and sometimes the value. RHSC is rounded towards
5821 // zero at this point.
5823 default: llvm_unreachable("Unexpected integer comparison!");
5824 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5825 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5826 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5827 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5828 case ICmpInst::ICMP_ULE:
5829 // (float)int <= 4.4 --> int <= 4
5830 // (float)int <= -4.4 --> false
5831 if (RHS.isNegative())
5832 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5834 case ICmpInst::ICMP_SLE:
5835 // (float)int <= 4.4 --> int <= 4
5836 // (float)int <= -4.4 --> int < -4
5837 if (RHS.isNegative())
5838 Pred = ICmpInst::ICMP_SLT;
5840 case ICmpInst::ICMP_ULT:
5841 // (float)int < -4.4 --> false
5842 // (float)int < 4.4 --> int <= 4
5843 if (RHS.isNegative())
5844 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5845 Pred = ICmpInst::ICMP_ULE;
5847 case ICmpInst::ICMP_SLT:
5848 // (float)int < -4.4 --> int < -4
5849 // (float)int < 4.4 --> int <= 4
5850 if (!RHS.isNegative())
5851 Pred = ICmpInst::ICMP_SLE;
5853 case ICmpInst::ICMP_UGT:
5854 // (float)int > 4.4 --> int > 4
5855 // (float)int > -4.4 --> true
5856 if (RHS.isNegative())
5857 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5859 case ICmpInst::ICMP_SGT:
5860 // (float)int > 4.4 --> int > 4
5861 // (float)int > -4.4 --> int >= -4
5862 if (RHS.isNegative())
5863 Pred = ICmpInst::ICMP_SGE;
5865 case ICmpInst::ICMP_UGE:
5866 // (float)int >= -4.4 --> true
5867 // (float)int >= 4.4 --> int > 4
5868 if (!RHS.isNegative())
5869 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5870 Pred = ICmpInst::ICMP_UGT;
5872 case ICmpInst::ICMP_SGE:
5873 // (float)int >= -4.4 --> int >= -4
5874 // (float)int >= 4.4 --> int > 4
5875 if (!RHS.isNegative())
5876 Pred = ICmpInst::ICMP_SGT;
5882 // Lower this FP comparison into an appropriate integer version of the
5884 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5887 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5888 bool Changed = SimplifyCompare(I);
5889 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5891 // Fold trivial predicates.
5892 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5893 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5894 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5895 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5897 // Simplify 'fcmp pred X, X'
5899 switch (I.getPredicate()) {
5900 default: llvm_unreachable("Unknown predicate!");
5901 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5902 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5903 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5904 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5905 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5906 case FCmpInst::FCMP_OLT: // True if ordered and less than
5907 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5908 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5910 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5911 case FCmpInst::FCMP_ULT: // True if unordered or less than
5912 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5913 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5914 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5915 I.setPredicate(FCmpInst::FCMP_UNO);
5916 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5919 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5920 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5921 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5922 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5923 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5924 I.setPredicate(FCmpInst::FCMP_ORD);
5925 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5930 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5931 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5933 // Handle fcmp with constant RHS
5934 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5935 // If the constant is a nan, see if we can fold the comparison based on it.
5936 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5937 if (CFP->getValueAPF().isNaN()) {
5938 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5939 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5940 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5941 "Comparison must be either ordered or unordered!");
5942 // True if unordered.
5943 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5947 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5948 switch (LHSI->getOpcode()) {
5949 case Instruction::PHI:
5950 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5951 // block. If in the same block, we're encouraging jump threading. If
5952 // not, we are just pessimizing the code by making an i1 phi.
5953 if (LHSI->getParent() == I.getParent())
5954 if (Instruction *NV = FoldOpIntoPhi(I))
5957 case Instruction::SIToFP:
5958 case Instruction::UIToFP:
5959 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5962 case Instruction::Select:
5963 // If either operand of the select is a constant, we can fold the
5964 // comparison into the select arms, which will cause one to be
5965 // constant folded and the select turned into a bitwise or.
5966 Value *Op1 = 0, *Op2 = 0;
5967 if (LHSI->hasOneUse()) {
5968 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5969 // Fold the known value into the constant operand.
5970 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5971 // Insert a new FCmp of the other select operand.
5972 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5973 LHSI->getOperand(2), RHSC,
5975 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5976 // Fold the known value into the constant operand.
5977 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5978 // Insert a new FCmp of the other select operand.
5979 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5980 LHSI->getOperand(1), RHSC,
5986 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5991 return Changed ? &I : 0;
5994 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5995 bool Changed = SimplifyCompare(I);
5996 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5997 const Type *Ty = Op0->getType();
6001 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6002 I.isTrueWhenEqual()));
6004 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
6005 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
6007 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6008 // addresses never equal each other! We already know that Op0 != Op1.
6009 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6010 isa<ConstantPointerNull>(Op0)) &&
6011 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6012 isa<ConstantPointerNull>(Op1)))
6013 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6014 !I.isTrueWhenEqual()));
6016 // icmp's with boolean values can always be turned into bitwise operations
6017 if (Ty == Type::getInt1Ty(*Context)) {
6018 switch (I.getPredicate()) {
6019 default: llvm_unreachable("Invalid icmp instruction!");
6020 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
6021 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6022 InsertNewInstBefore(Xor, I);
6023 return BinaryOperator::CreateNot(Xor);
6025 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
6026 return BinaryOperator::CreateXor(Op0, Op1);
6028 case ICmpInst::ICMP_UGT:
6029 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
6031 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
6032 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6033 InsertNewInstBefore(Not, I);
6034 return BinaryOperator::CreateAnd(Not, Op1);
6036 case ICmpInst::ICMP_SGT:
6037 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
6039 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
6040 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6041 InsertNewInstBefore(Not, I);
6042 return BinaryOperator::CreateAnd(Not, Op0);
6044 case ICmpInst::ICMP_UGE:
6045 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6047 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
6048 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6049 InsertNewInstBefore(Not, I);
6050 return BinaryOperator::CreateOr(Not, Op1);
6052 case ICmpInst::ICMP_SGE:
6053 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6055 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6056 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6057 InsertNewInstBefore(Not, I);
6058 return BinaryOperator::CreateOr(Not, Op0);
6063 unsigned BitWidth = 0;
6065 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6066 else if (Ty->isIntOrIntVector())
6067 BitWidth = Ty->getScalarSizeInBits();
6069 bool isSignBit = false;
6071 // See if we are doing a comparison with a constant.
6072 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6073 Value *A = 0, *B = 0;
6075 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6076 if (I.isEquality() && CI->isNullValue() &&
6077 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6078 // (icmp cond A B) if cond is equality
6079 return new ICmpInst(I.getPredicate(), A, B);
6082 // If we have an icmp le or icmp ge instruction, turn it into the
6083 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6084 // them being folded in the code below.
6085 switch (I.getPredicate()) {
6087 case ICmpInst::ICMP_ULE:
6088 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6089 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6090 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6092 case ICmpInst::ICMP_SLE:
6093 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6094 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6095 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6097 case ICmpInst::ICMP_UGE:
6098 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6099 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6100 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6102 case ICmpInst::ICMP_SGE:
6103 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6104 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6105 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6109 // If this comparison is a normal comparison, it demands all
6110 // bits, if it is a sign bit comparison, it only demands the sign bit.
6112 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6115 // See if we can fold the comparison based on range information we can get
6116 // by checking whether bits are known to be zero or one in the input.
6117 if (BitWidth != 0) {
6118 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6119 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6121 if (SimplifyDemandedBits(I.getOperandUse(0),
6122 isSignBit ? APInt::getSignBit(BitWidth)
6123 : APInt::getAllOnesValue(BitWidth),
6124 Op0KnownZero, Op0KnownOne, 0))
6126 if (SimplifyDemandedBits(I.getOperandUse(1),
6127 APInt::getAllOnesValue(BitWidth),
6128 Op1KnownZero, Op1KnownOne, 0))
6131 // Given the known and unknown bits, compute a range that the LHS could be
6132 // in. Compute the Min, Max and RHS values based on the known bits. For the
6133 // EQ and NE we use unsigned values.
6134 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6135 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6136 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6137 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6139 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6142 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6144 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6148 // If Min and Max are known to be the same, then SimplifyDemandedBits
6149 // figured out that the LHS is a constant. Just constant fold this now so
6150 // that code below can assume that Min != Max.
6151 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6152 return new ICmpInst(I.getPredicate(),
6153 ConstantInt::get(*Context, Op0Min), Op1);
6154 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6155 return new ICmpInst(I.getPredicate(), Op0,
6156 ConstantInt::get(*Context, Op1Min));
6158 // Based on the range information we know about the LHS, see if we can
6159 // simplify this comparison. For example, (x&4) < 8 is always true.
6160 switch (I.getPredicate()) {
6161 default: llvm_unreachable("Unknown icmp opcode!");
6162 case ICmpInst::ICMP_EQ:
6163 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6164 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6166 case ICmpInst::ICMP_NE:
6167 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6168 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6170 case ICmpInst::ICMP_ULT:
6171 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6172 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6173 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6174 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6175 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6176 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6177 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6178 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6179 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6182 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6183 if (CI->isMinValue(true))
6184 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6185 Constant::getAllOnesValue(Op0->getType()));
6188 case ICmpInst::ICMP_UGT:
6189 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6190 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6191 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6192 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6194 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6195 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6196 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6197 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6198 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6201 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6202 if (CI->isMaxValue(true))
6203 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6204 Constant::getNullValue(Op0->getType()));
6207 case ICmpInst::ICMP_SLT:
6208 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6209 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6210 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6211 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6212 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6213 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6214 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6215 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6216 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6220 case ICmpInst::ICMP_SGT:
6221 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6222 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6223 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6224 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6226 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6227 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6228 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6229 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6230 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6234 case ICmpInst::ICMP_SGE:
6235 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6236 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6237 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6238 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6239 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6241 case ICmpInst::ICMP_SLE:
6242 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6243 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6244 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6245 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6246 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6248 case ICmpInst::ICMP_UGE:
6249 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6250 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6251 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6252 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6253 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6255 case ICmpInst::ICMP_ULE:
6256 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6257 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6258 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6259 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6260 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6264 // Turn a signed comparison into an unsigned one if both operands
6265 // are known to have the same sign.
6266 if (I.isSignedPredicate() &&
6267 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6268 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6269 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6272 // Test if the ICmpInst instruction is used exclusively by a select as
6273 // part of a minimum or maximum operation. If so, refrain from doing
6274 // any other folding. This helps out other analyses which understand
6275 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6276 // and CodeGen. And in this case, at least one of the comparison
6277 // operands has at least one user besides the compare (the select),
6278 // which would often largely negate the benefit of folding anyway.
6280 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6281 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6282 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6285 // See if we are doing a comparison between a constant and an instruction that
6286 // can be folded into the comparison.
6287 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6288 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6289 // instruction, see if that instruction also has constants so that the
6290 // instruction can be folded into the icmp
6291 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6292 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6296 // Handle icmp with constant (but not simple integer constant) RHS
6297 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6298 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6299 switch (LHSI->getOpcode()) {
6300 case Instruction::GetElementPtr:
6301 if (RHSC->isNullValue()) {
6302 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6303 bool isAllZeros = true;
6304 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6305 if (!isa<Constant>(LHSI->getOperand(i)) ||
6306 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6311 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6312 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6316 case Instruction::PHI:
6317 // Only fold icmp into the PHI if the phi and fcmp are in the same
6318 // block. If in the same block, we're encouraging jump threading. If
6319 // not, we are just pessimizing the code by making an i1 phi.
6320 if (LHSI->getParent() == I.getParent())
6321 if (Instruction *NV = FoldOpIntoPhi(I))
6324 case Instruction::Select: {
6325 // If either operand of the select is a constant, we can fold the
6326 // comparison into the select arms, which will cause one to be
6327 // constant folded and the select turned into a bitwise or.
6328 Value *Op1 = 0, *Op2 = 0;
6329 if (LHSI->hasOneUse()) {
6330 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6331 // Fold the known value into the constant operand.
6332 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6333 // Insert a new ICmp of the other select operand.
6334 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6335 LHSI->getOperand(2), RHSC,
6337 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6338 // Fold the known value into the constant operand.
6339 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6340 // Insert a new ICmp of the other select operand.
6341 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6342 LHSI->getOperand(1), RHSC,
6348 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6351 case Instruction::Malloc:
6352 // If we have (malloc != null), and if the malloc has a single use, we
6353 // can assume it is successful and remove the malloc.
6354 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6356 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6357 !I.isTrueWhenEqual()));
6363 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6364 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6365 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6367 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6368 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6369 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6372 // Test to see if the operands of the icmp are casted versions of other
6373 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6375 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6376 if (isa<PointerType>(Op0->getType()) &&
6377 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6378 // We keep moving the cast from the left operand over to the right
6379 // operand, where it can often be eliminated completely.
6380 Op0 = CI->getOperand(0);
6382 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6383 // so eliminate it as well.
6384 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6385 Op1 = CI2->getOperand(0);
6387 // If Op1 is a constant, we can fold the cast into the constant.
6388 if (Op0->getType() != Op1->getType()) {
6389 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6390 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6392 // Otherwise, cast the RHS right before the icmp
6393 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6396 return new ICmpInst(I.getPredicate(), Op0, Op1);
6400 if (isa<CastInst>(Op0)) {
6401 // Handle the special case of: icmp (cast bool to X), <cst>
6402 // This comes up when you have code like
6405 // For generality, we handle any zero-extension of any operand comparison
6406 // with a constant or another cast from the same type.
6407 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6408 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6412 // See if it's the same type of instruction on the left and right.
6413 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6414 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6415 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6416 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6417 switch (Op0I->getOpcode()) {
6419 case Instruction::Add:
6420 case Instruction::Sub:
6421 case Instruction::Xor:
6422 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6423 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6424 Op1I->getOperand(0));
6425 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6426 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6427 if (CI->getValue().isSignBit()) {
6428 ICmpInst::Predicate Pred = I.isSignedPredicate()
6429 ? I.getUnsignedPredicate()
6430 : I.getSignedPredicate();
6431 return new ICmpInst(Pred, Op0I->getOperand(0),
6432 Op1I->getOperand(0));
6435 if (CI->getValue().isMaxSignedValue()) {
6436 ICmpInst::Predicate Pred = I.isSignedPredicate()
6437 ? I.getUnsignedPredicate()
6438 : I.getSignedPredicate();
6439 Pred = I.getSwappedPredicate(Pred);
6440 return new ICmpInst(Pred, Op0I->getOperand(0),
6441 Op1I->getOperand(0));
6445 case Instruction::Mul:
6446 if (!I.isEquality())
6449 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6450 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6451 // Mask = -1 >> count-trailing-zeros(Cst).
6452 if (!CI->isZero() && !CI->isOne()) {
6453 const APInt &AP = CI->getValue();
6454 ConstantInt *Mask = ConstantInt::get(*Context,
6455 APInt::getLowBitsSet(AP.getBitWidth(),
6457 AP.countTrailingZeros()));
6458 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6460 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6462 InsertNewInstBefore(And1, I);
6463 InsertNewInstBefore(And2, I);
6464 return new ICmpInst(I.getPredicate(), And1, And2);
6473 // ~x < ~y --> y < x
6475 if (match(Op0, m_Not(m_Value(A))) &&
6476 match(Op1, m_Not(m_Value(B))))
6477 return new ICmpInst(I.getPredicate(), B, A);
6480 if (I.isEquality()) {
6481 Value *A, *B, *C, *D;
6483 // -x == -y --> x == y
6484 if (match(Op0, m_Neg(m_Value(A))) &&
6485 match(Op1, m_Neg(m_Value(B))))
6486 return new ICmpInst(I.getPredicate(), A, B);
6488 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6489 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6490 Value *OtherVal = A == Op1 ? B : A;
6491 return new ICmpInst(I.getPredicate(), OtherVal,
6492 Constant::getNullValue(A->getType()));
6495 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6496 // A^c1 == C^c2 --> A == C^(c1^c2)
6497 ConstantInt *C1, *C2;
6498 if (match(B, m_ConstantInt(C1)) &&
6499 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6501 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6502 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6503 return new ICmpInst(I.getPredicate(), A,
6504 InsertNewInstBefore(Xor, I));
6507 // A^B == A^D -> B == D
6508 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6509 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6510 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6511 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6515 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6516 (A == Op0 || B == Op0)) {
6517 // A == (A^B) -> B == 0
6518 Value *OtherVal = A == Op0 ? B : A;
6519 return new ICmpInst(I.getPredicate(), OtherVal,
6520 Constant::getNullValue(A->getType()));
6523 // (A-B) == A -> B == 0
6524 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6525 return new ICmpInst(I.getPredicate(), B,
6526 Constant::getNullValue(B->getType()));
6528 // A == (A-B) -> B == 0
6529 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6530 return new ICmpInst(I.getPredicate(), B,
6531 Constant::getNullValue(B->getType()));
6533 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6534 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6535 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6536 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6537 Value *X = 0, *Y = 0, *Z = 0;
6540 X = B; Y = D; Z = A;
6541 } else if (A == D) {
6542 X = B; Y = C; Z = A;
6543 } else if (B == C) {
6544 X = A; Y = D; Z = B;
6545 } else if (B == D) {
6546 X = A; Y = C; Z = B;
6549 if (X) { // Build (X^Y) & Z
6550 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6551 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6552 I.setOperand(0, Op1);
6553 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6558 return Changed ? &I : 0;
6562 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6563 /// and CmpRHS are both known to be integer constants.
6564 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6565 ConstantInt *DivRHS) {
6566 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6567 const APInt &CmpRHSV = CmpRHS->getValue();
6569 // FIXME: If the operand types don't match the type of the divide
6570 // then don't attempt this transform. The code below doesn't have the
6571 // logic to deal with a signed divide and an unsigned compare (and
6572 // vice versa). This is because (x /s C1) <s C2 produces different
6573 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6574 // (x /u C1) <u C2. Simply casting the operands and result won't
6575 // work. :( The if statement below tests that condition and bails
6577 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6578 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6580 if (DivRHS->isZero())
6581 return 0; // The ProdOV computation fails on divide by zero.
6582 if (DivIsSigned && DivRHS->isAllOnesValue())
6583 return 0; // The overflow computation also screws up here
6584 if (DivRHS->isOne())
6585 return 0; // Not worth bothering, and eliminates some funny cases
6588 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6589 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6590 // C2 (CI). By solving for X we can turn this into a range check
6591 // instead of computing a divide.
6592 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6594 // Determine if the product overflows by seeing if the product is
6595 // not equal to the divide. Make sure we do the same kind of divide
6596 // as in the LHS instruction that we're folding.
6597 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6598 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6600 // Get the ICmp opcode
6601 ICmpInst::Predicate Pred = ICI.getPredicate();
6603 // Figure out the interval that is being checked. For example, a comparison
6604 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6605 // Compute this interval based on the constants involved and the signedness of
6606 // the compare/divide. This computes a half-open interval, keeping track of
6607 // whether either value in the interval overflows. After analysis each
6608 // overflow variable is set to 0 if it's corresponding bound variable is valid
6609 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6610 int LoOverflow = 0, HiOverflow = 0;
6611 Constant *LoBound = 0, *HiBound = 0;
6613 if (!DivIsSigned) { // udiv
6614 // e.g. X/5 op 3 --> [15, 20)
6616 HiOverflow = LoOverflow = ProdOV;
6618 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6619 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6620 if (CmpRHSV == 0) { // (X / pos) op 0
6621 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6622 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6624 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6625 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6626 HiOverflow = LoOverflow = ProdOV;
6628 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6629 } else { // (X / pos) op neg
6630 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6631 HiBound = AddOne(Prod);
6632 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6634 ConstantInt* DivNeg =
6635 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6636 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6640 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6641 if (CmpRHSV == 0) { // (X / neg) op 0
6642 // e.g. X/-5 op 0 --> [-4, 5)
6643 LoBound = AddOne(DivRHS);
6644 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6645 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6646 HiOverflow = 1; // [INTMIN+1, overflow)
6647 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6649 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6650 // e.g. X/-5 op 3 --> [-19, -14)
6651 HiBound = AddOne(Prod);
6652 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6654 LoOverflow = AddWithOverflow(LoBound, HiBound,
6655 DivRHS, Context, true) ? -1 : 0;
6656 } else { // (X / neg) op neg
6657 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6658 LoOverflow = HiOverflow = ProdOV;
6660 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6663 // Dividing by a negative swaps the condition. LT <-> GT
6664 Pred = ICmpInst::getSwappedPredicate(Pred);
6667 Value *X = DivI->getOperand(0);
6669 default: llvm_unreachable("Unhandled icmp opcode!");
6670 case ICmpInst::ICMP_EQ:
6671 if (LoOverflow && HiOverflow)
6672 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6673 else if (HiOverflow)
6674 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6675 ICmpInst::ICMP_UGE, X, LoBound);
6676 else if (LoOverflow)
6677 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6678 ICmpInst::ICMP_ULT, X, HiBound);
6680 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6681 case ICmpInst::ICMP_NE:
6682 if (LoOverflow && HiOverflow)
6683 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6684 else if (HiOverflow)
6685 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6686 ICmpInst::ICMP_ULT, X, LoBound);
6687 else if (LoOverflow)
6688 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6689 ICmpInst::ICMP_UGE, X, HiBound);
6691 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6692 case ICmpInst::ICMP_ULT:
6693 case ICmpInst::ICMP_SLT:
6694 if (LoOverflow == +1) // Low bound is greater than input range.
6695 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6696 if (LoOverflow == -1) // Low bound is less than input range.
6697 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6698 return new ICmpInst(Pred, X, LoBound);
6699 case ICmpInst::ICMP_UGT:
6700 case ICmpInst::ICMP_SGT:
6701 if (HiOverflow == +1) // High bound greater than input range.
6702 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6703 else if (HiOverflow == -1) // High bound less than input range.
6704 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6705 if (Pred == ICmpInst::ICMP_UGT)
6706 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6708 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6713 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6715 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6718 const APInt &RHSV = RHS->getValue();
6720 switch (LHSI->getOpcode()) {
6721 case Instruction::Trunc:
6722 if (ICI.isEquality() && LHSI->hasOneUse()) {
6723 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6724 // of the high bits truncated out of x are known.
6725 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6726 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6727 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6728 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6729 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6731 // If all the high bits are known, we can do this xform.
6732 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6733 // Pull in the high bits from known-ones set.
6734 APInt NewRHS(RHS->getValue());
6735 NewRHS.zext(SrcBits);
6737 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6738 ConstantInt::get(*Context, NewRHS));
6743 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6744 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6745 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6747 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6748 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6749 Value *CompareVal = LHSI->getOperand(0);
6751 // If the sign bit of the XorCST is not set, there is no change to
6752 // the operation, just stop using the Xor.
6753 if (!XorCST->getValue().isNegative()) {
6754 ICI.setOperand(0, CompareVal);
6759 // Was the old condition true if the operand is positive?
6760 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6762 // If so, the new one isn't.
6763 isTrueIfPositive ^= true;
6765 if (isTrueIfPositive)
6766 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6769 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6773 if (LHSI->hasOneUse()) {
6774 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6775 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6776 const APInt &SignBit = XorCST->getValue();
6777 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6778 ? ICI.getUnsignedPredicate()
6779 : ICI.getSignedPredicate();
6780 return new ICmpInst(Pred, LHSI->getOperand(0),
6781 ConstantInt::get(*Context, RHSV ^ SignBit));
6784 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6785 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6786 const APInt &NotSignBit = XorCST->getValue();
6787 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6788 ? ICI.getUnsignedPredicate()
6789 : ICI.getSignedPredicate();
6790 Pred = ICI.getSwappedPredicate(Pred);
6791 return new ICmpInst(Pred, LHSI->getOperand(0),
6792 ConstantInt::get(*Context, RHSV ^ NotSignBit));
6797 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6798 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6799 LHSI->getOperand(0)->hasOneUse()) {
6800 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6802 // If the LHS is an AND of a truncating cast, we can widen the
6803 // and/compare to be the input width without changing the value
6804 // produced, eliminating a cast.
6805 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6806 // We can do this transformation if either the AND constant does not
6807 // have its sign bit set or if it is an equality comparison.
6808 // Extending a relational comparison when we're checking the sign
6809 // bit would not work.
6810 if (Cast->hasOneUse() &&
6811 (ICI.isEquality() ||
6812 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6814 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6815 APInt NewCST = AndCST->getValue();
6816 NewCST.zext(BitWidth);
6818 NewCI.zext(BitWidth);
6819 Instruction *NewAnd =
6820 BinaryOperator::CreateAnd(Cast->getOperand(0),
6821 ConstantInt::get(*Context, NewCST), LHSI->getName());
6822 InsertNewInstBefore(NewAnd, ICI);
6823 return new ICmpInst(ICI.getPredicate(), NewAnd,
6824 ConstantInt::get(*Context, NewCI));
6828 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6829 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6830 // happens a LOT in code produced by the C front-end, for bitfield
6832 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6833 if (Shift && !Shift->isShift())
6837 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6838 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6839 const Type *AndTy = AndCST->getType(); // Type of the and.
6841 // We can fold this as long as we can't shift unknown bits
6842 // into the mask. This can only happen with signed shift
6843 // rights, as they sign-extend.
6845 bool CanFold = Shift->isLogicalShift();
6847 // To test for the bad case of the signed shr, see if any
6848 // of the bits shifted in could be tested after the mask.
6849 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6850 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6852 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6853 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6854 AndCST->getValue()) == 0)
6860 if (Shift->getOpcode() == Instruction::Shl)
6861 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6863 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6865 // Check to see if we are shifting out any of the bits being
6867 if (ConstantExpr::get(Shift->getOpcode(),
6868 NewCst, ShAmt) != RHS) {
6869 // If we shifted bits out, the fold is not going to work out.
6870 // As a special case, check to see if this means that the
6871 // result is always true or false now.
6872 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6873 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6874 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6875 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6877 ICI.setOperand(1, NewCst);
6878 Constant *NewAndCST;
6879 if (Shift->getOpcode() == Instruction::Shl)
6880 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6882 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6883 LHSI->setOperand(1, NewAndCST);
6884 LHSI->setOperand(0, Shift->getOperand(0));
6885 Worklist.Add(Shift); // Shift is dead.
6891 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6892 // preferable because it allows the C<<Y expression to be hoisted out
6893 // of a loop if Y is invariant and X is not.
6894 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6895 ICI.isEquality() && !Shift->isArithmeticShift() &&
6896 !isa<Constant>(Shift->getOperand(0))) {
6899 if (Shift->getOpcode() == Instruction::LShr) {
6900 NS = BinaryOperator::CreateShl(AndCST,
6901 Shift->getOperand(1), "tmp");
6903 // Insert a logical shift.
6904 NS = BinaryOperator::CreateLShr(AndCST,
6905 Shift->getOperand(1), "tmp");
6907 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6909 // Compute X & (C << Y).
6910 Instruction *NewAnd =
6911 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6912 InsertNewInstBefore(NewAnd, ICI);
6914 ICI.setOperand(0, NewAnd);
6920 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6921 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6924 uint32_t TypeBits = RHSV.getBitWidth();
6926 // Check that the shift amount is in range. If not, don't perform
6927 // undefined shifts. When the shift is visited it will be
6929 if (ShAmt->uge(TypeBits))
6932 if (ICI.isEquality()) {
6933 // If we are comparing against bits always shifted out, the
6934 // comparison cannot succeed.
6936 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6938 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6939 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6940 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6941 return ReplaceInstUsesWith(ICI, Cst);
6944 if (LHSI->hasOneUse()) {
6945 // Otherwise strength reduce the shift into an and.
6946 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6948 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
6949 TypeBits-ShAmtVal));
6952 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6953 Mask, LHSI->getName()+".mask");
6954 Value *And = InsertNewInstBefore(AndI, ICI);
6955 return new ICmpInst(ICI.getPredicate(), And,
6956 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6960 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6961 bool TrueIfSigned = false;
6962 if (LHSI->hasOneUse() &&
6963 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6964 // (X << 31) <s 0 --> (X&1) != 0
6965 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6966 (TypeBits-ShAmt->getZExtValue()-1));
6968 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6969 Mask, LHSI->getName()+".mask");
6970 Value *And = InsertNewInstBefore(AndI, ICI);
6972 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6973 And, Constant::getNullValue(And->getType()));
6978 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6979 case Instruction::AShr: {
6980 // Only handle equality comparisons of shift-by-constant.
6981 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6982 if (!ShAmt || !ICI.isEquality()) break;
6984 // Check that the shift amount is in range. If not, don't perform
6985 // undefined shifts. When the shift is visited it will be
6987 uint32_t TypeBits = RHSV.getBitWidth();
6988 if (ShAmt->uge(TypeBits))
6991 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6993 // If we are comparing against bits always shifted out, the
6994 // comparison cannot succeed.
6995 APInt Comp = RHSV << ShAmtVal;
6996 if (LHSI->getOpcode() == Instruction::LShr)
6997 Comp = Comp.lshr(ShAmtVal);
6999 Comp = Comp.ashr(ShAmtVal);
7001 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7002 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7003 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7004 return ReplaceInstUsesWith(ICI, Cst);
7007 // Otherwise, check to see if the bits shifted out are known to be zero.
7008 // If so, we can compare against the unshifted value:
7009 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
7010 if (LHSI->hasOneUse() &&
7011 MaskedValueIsZero(LHSI->getOperand(0),
7012 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7013 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7014 ConstantExpr::getShl(RHS, ShAmt));
7017 if (LHSI->hasOneUse()) {
7018 // Otherwise strength reduce the shift into an and.
7019 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7020 Constant *Mask = ConstantInt::get(*Context, Val);
7023 BinaryOperator::CreateAnd(LHSI->getOperand(0),
7024 Mask, LHSI->getName()+".mask");
7025 Value *And = InsertNewInstBefore(AndI, ICI);
7026 return new ICmpInst(ICI.getPredicate(), And,
7027 ConstantExpr::getShl(RHS, ShAmt));
7032 case Instruction::SDiv:
7033 case Instruction::UDiv:
7034 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7035 // Fold this div into the comparison, producing a range check.
7036 // Determine, based on the divide type, what the range is being
7037 // checked. If there is an overflow on the low or high side, remember
7038 // it, otherwise compute the range [low, hi) bounding the new value.
7039 // See: InsertRangeTest above for the kinds of replacements possible.
7040 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7041 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7046 case Instruction::Add:
7047 // Fold: icmp pred (add, X, C1), C2
7049 if (!ICI.isEquality()) {
7050 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7052 const APInt &LHSV = LHSC->getValue();
7054 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7057 if (ICI.isSignedPredicate()) {
7058 if (CR.getLower().isSignBit()) {
7059 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7060 ConstantInt::get(*Context, CR.getUpper()));
7061 } else if (CR.getUpper().isSignBit()) {
7062 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7063 ConstantInt::get(*Context, CR.getLower()));
7066 if (CR.getLower().isMinValue()) {
7067 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7068 ConstantInt::get(*Context, CR.getUpper()));
7069 } else if (CR.getUpper().isMinValue()) {
7070 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7071 ConstantInt::get(*Context, CR.getLower()));
7078 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7079 if (ICI.isEquality()) {
7080 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7082 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7083 // the second operand is a constant, simplify a bit.
7084 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7085 switch (BO->getOpcode()) {
7086 case Instruction::SRem:
7087 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7088 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7089 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7090 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7091 Instruction *NewRem =
7092 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7094 InsertNewInstBefore(NewRem, ICI);
7095 return new ICmpInst(ICI.getPredicate(), NewRem,
7096 Constant::getNullValue(BO->getType()));
7100 case Instruction::Add:
7101 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7102 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7103 if (BO->hasOneUse())
7104 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7105 ConstantExpr::getSub(RHS, BOp1C));
7106 } else if (RHSV == 0) {
7107 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7108 // efficiently invertible, or if the add has just this one use.
7109 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7111 if (Value *NegVal = dyn_castNegVal(BOp1))
7112 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7113 else if (Value *NegVal = dyn_castNegVal(BOp0))
7114 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7115 else if (BO->hasOneUse()) {
7116 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7117 InsertNewInstBefore(Neg, ICI);
7119 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7123 case Instruction::Xor:
7124 // For the xor case, we can xor two constants together, eliminating
7125 // the explicit xor.
7126 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7127 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7128 ConstantExpr::getXor(RHS, BOC));
7131 case Instruction::Sub:
7132 // Replace (([sub|xor] A, B) != 0) with (A != B)
7134 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7138 case Instruction::Or:
7139 // If bits are being or'd in that are not present in the constant we
7140 // are comparing against, then the comparison could never succeed!
7141 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7142 Constant *NotCI = ConstantExpr::getNot(RHS);
7143 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7144 return ReplaceInstUsesWith(ICI,
7145 ConstantInt::get(Type::getInt1Ty(*Context),
7150 case Instruction::And:
7151 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7152 // If bits are being compared against that are and'd out, then the
7153 // comparison can never succeed!
7154 if ((RHSV & ~BOC->getValue()) != 0)
7155 return ReplaceInstUsesWith(ICI,
7156 ConstantInt::get(Type::getInt1Ty(*Context),
7159 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7160 if (RHS == BOC && RHSV.isPowerOf2())
7161 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7162 ICmpInst::ICMP_NE, LHSI,
7163 Constant::getNullValue(RHS->getType()));
7165 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7166 if (BOC->getValue().isSignBit()) {
7167 Value *X = BO->getOperand(0);
7168 Constant *Zero = Constant::getNullValue(X->getType());
7169 ICmpInst::Predicate pred = isICMP_NE ?
7170 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7171 return new ICmpInst(pred, X, Zero);
7174 // ((X & ~7) == 0) --> X < 8
7175 if (RHSV == 0 && isHighOnes(BOC)) {
7176 Value *X = BO->getOperand(0);
7177 Constant *NegX = ConstantExpr::getNeg(BOC);
7178 ICmpInst::Predicate pred = isICMP_NE ?
7179 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7180 return new ICmpInst(pred, X, NegX);
7185 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7186 // Handle icmp {eq|ne} <intrinsic>, intcst.
7187 if (II->getIntrinsicID() == Intrinsic::bswap) {
7189 ICI.setOperand(0, II->getOperand(1));
7190 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7198 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7199 /// We only handle extending casts so far.
7201 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7202 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7203 Value *LHSCIOp = LHSCI->getOperand(0);
7204 const Type *SrcTy = LHSCIOp->getType();
7205 const Type *DestTy = LHSCI->getType();
7208 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7209 // integer type is the same size as the pointer type.
7210 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7211 TD->getPointerSizeInBits() ==
7212 cast<IntegerType>(DestTy)->getBitWidth()) {
7214 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7215 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7216 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7217 RHSOp = RHSC->getOperand(0);
7218 // If the pointer types don't match, insert a bitcast.
7219 if (LHSCIOp->getType() != RHSOp->getType())
7220 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7224 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7227 // The code below only handles extension cast instructions, so far.
7229 if (LHSCI->getOpcode() != Instruction::ZExt &&
7230 LHSCI->getOpcode() != Instruction::SExt)
7233 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7234 bool isSignedCmp = ICI.isSignedPredicate();
7236 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7237 // Not an extension from the same type?
7238 RHSCIOp = CI->getOperand(0);
7239 if (RHSCIOp->getType() != LHSCIOp->getType())
7242 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7243 // and the other is a zext), then we can't handle this.
7244 if (CI->getOpcode() != LHSCI->getOpcode())
7247 // Deal with equality cases early.
7248 if (ICI.isEquality())
7249 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7251 // A signed comparison of sign extended values simplifies into a
7252 // signed comparison.
7253 if (isSignedCmp && isSignedExt)
7254 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7256 // The other three cases all fold into an unsigned comparison.
7257 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7260 // If we aren't dealing with a constant on the RHS, exit early
7261 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7265 // Compute the constant that would happen if we truncated to SrcTy then
7266 // reextended to DestTy.
7267 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7268 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7271 // If the re-extended constant didn't change...
7273 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7274 // For example, we might have:
7275 // %A = sext i16 %X to i32
7276 // %B = icmp ugt i32 %A, 1330
7277 // It is incorrect to transform this into
7278 // %B = icmp ugt i16 %X, 1330
7279 // because %A may have negative value.
7281 // However, we allow this when the compare is EQ/NE, because they are
7283 if (isSignedExt == isSignedCmp || ICI.isEquality())
7284 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7288 // The re-extended constant changed so the constant cannot be represented
7289 // in the shorter type. Consequently, we cannot emit a simple comparison.
7291 // First, handle some easy cases. We know the result cannot be equal at this
7292 // point so handle the ICI.isEquality() cases
7293 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7294 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7295 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7296 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7298 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7299 // should have been folded away previously and not enter in here.
7302 // We're performing a signed comparison.
7303 if (cast<ConstantInt>(CI)->getValue().isNegative())
7304 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
7306 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
7308 // We're performing an unsigned comparison.
7310 // We're performing an unsigned comp with a sign extended value.
7311 // This is true if the input is >= 0. [aka >s -1]
7312 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7313 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT,
7314 LHSCIOp, NegOne, ICI.getName()), ICI);
7316 // Unsigned extend & unsigned compare -> always true.
7317 Result = ConstantInt::getTrue(*Context);
7321 // Finally, return the value computed.
7322 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7323 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7324 return ReplaceInstUsesWith(ICI, Result);
7326 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7327 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7328 "ICmp should be folded!");
7329 if (Constant *CI = dyn_cast<Constant>(Result))
7330 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7331 return BinaryOperator::CreateNot(Result);
7334 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7335 return commonShiftTransforms(I);
7338 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7339 return commonShiftTransforms(I);
7342 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7343 if (Instruction *R = commonShiftTransforms(I))
7346 Value *Op0 = I.getOperand(0);
7348 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7349 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7350 if (CSI->isAllOnesValue())
7351 return ReplaceInstUsesWith(I, CSI);
7353 // See if we can turn a signed shr into an unsigned shr.
7354 if (MaskedValueIsZero(Op0,
7355 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7356 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7358 // Arithmetic shifting an all-sign-bit value is a no-op.
7359 unsigned NumSignBits = ComputeNumSignBits(Op0);
7360 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7361 return ReplaceInstUsesWith(I, Op0);
7366 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7367 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7368 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7370 // shl X, 0 == X and shr X, 0 == X
7371 // shl 0, X == 0 and shr 0, X == 0
7372 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7373 Op0 == Constant::getNullValue(Op0->getType()))
7374 return ReplaceInstUsesWith(I, Op0);
7376 if (isa<UndefValue>(Op0)) {
7377 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7378 return ReplaceInstUsesWith(I, Op0);
7379 else // undef << X -> 0, undef >>u X -> 0
7380 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7382 if (isa<UndefValue>(Op1)) {
7383 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7384 return ReplaceInstUsesWith(I, Op0);
7385 else // X << undef, X >>u undef -> 0
7386 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7389 // See if we can fold away this shift.
7390 if (SimplifyDemandedInstructionBits(I))
7393 // Try to fold constant and into select arguments.
7394 if (isa<Constant>(Op0))
7395 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7399 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7400 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7405 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7406 BinaryOperator &I) {
7407 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7409 // See if we can simplify any instructions used by the instruction whose sole
7410 // purpose is to compute bits we don't care about.
7411 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7413 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7416 if (Op1->uge(TypeBits)) {
7417 if (I.getOpcode() != Instruction::AShr)
7418 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7420 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7425 // ((X*C1) << C2) == (X * (C1 << C2))
7426 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7427 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7428 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7429 return BinaryOperator::CreateMul(BO->getOperand(0),
7430 ConstantExpr::getShl(BOOp, Op1));
7432 // Try to fold constant and into select arguments.
7433 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7434 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7436 if (isa<PHINode>(Op0))
7437 if (Instruction *NV = FoldOpIntoPhi(I))
7440 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7441 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7442 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7443 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7444 // place. Don't try to do this transformation in this case. Also, we
7445 // require that the input operand is a shift-by-constant so that we have
7446 // confidence that the shifts will get folded together. We could do this
7447 // xform in more cases, but it is unlikely to be profitable.
7448 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7449 isa<ConstantInt>(TrOp->getOperand(1))) {
7450 // Okay, we'll do this xform. Make the shift of shift.
7451 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7452 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7454 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7456 // For logical shifts, the truncation has the effect of making the high
7457 // part of the register be zeros. Emulate this by inserting an AND to
7458 // clear the top bits as needed. This 'and' will usually be zapped by
7459 // other xforms later if dead.
7460 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7461 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7462 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7464 // The mask we constructed says what the trunc would do if occurring
7465 // between the shifts. We want to know the effect *after* the second
7466 // shift. We know that it is a logical shift by a constant, so adjust the
7467 // mask as appropriate.
7468 if (I.getOpcode() == Instruction::Shl)
7469 MaskV <<= Op1->getZExtValue();
7471 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7472 MaskV = MaskV.lshr(Op1->getZExtValue());
7476 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7478 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7480 // Return the value truncated to the interesting size.
7481 return new TruncInst(And, I.getType());
7485 if (Op0->hasOneUse()) {
7486 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7487 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7490 switch (Op0BO->getOpcode()) {
7492 case Instruction::Add:
7493 case Instruction::And:
7494 case Instruction::Or:
7495 case Instruction::Xor: {
7496 // These operators commute.
7497 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7498 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7499 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7501 Instruction *YS = BinaryOperator::CreateShl(
7502 Op0BO->getOperand(0), Op1,
7504 InsertNewInstBefore(YS, I); // (Y << C)
7506 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7507 Op0BO->getOperand(1)->getName());
7508 InsertNewInstBefore(X, I); // (X + (Y << C))
7509 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7510 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7511 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7514 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7515 Value *Op0BOOp1 = Op0BO->getOperand(1);
7516 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7518 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7519 m_ConstantInt(CC))) &&
7520 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7521 Instruction *YS = BinaryOperator::CreateShl(
7522 Op0BO->getOperand(0), Op1,
7524 InsertNewInstBefore(YS, I); // (Y << C)
7526 BinaryOperator::CreateAnd(V1,
7527 ConstantExpr::getShl(CC, Op1),
7528 V1->getName()+".mask");
7529 InsertNewInstBefore(XM, I); // X & (CC << C)
7531 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7536 case Instruction::Sub: {
7537 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7538 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7539 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7540 m_Specific(Op1)))) {
7541 Instruction *YS = BinaryOperator::CreateShl(
7542 Op0BO->getOperand(1), Op1,
7544 InsertNewInstBefore(YS, I); // (Y << C)
7546 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7547 Op0BO->getOperand(0)->getName());
7548 InsertNewInstBefore(X, I); // (X + (Y << C))
7549 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7550 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7551 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7554 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7555 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7556 match(Op0BO->getOperand(0),
7557 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7558 m_ConstantInt(CC))) && V2 == Op1 &&
7559 cast<BinaryOperator>(Op0BO->getOperand(0))
7560 ->getOperand(0)->hasOneUse()) {
7561 Instruction *YS = BinaryOperator::CreateShl(
7562 Op0BO->getOperand(1), Op1,
7564 InsertNewInstBefore(YS, I); // (Y << C)
7566 BinaryOperator::CreateAnd(V1,
7567 ConstantExpr::getShl(CC, Op1),
7568 V1->getName()+".mask");
7569 InsertNewInstBefore(XM, I); // X & (CC << C)
7571 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7579 // If the operand is an bitwise operator with a constant RHS, and the
7580 // shift is the only use, we can pull it out of the shift.
7581 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7582 bool isValid = true; // Valid only for And, Or, Xor
7583 bool highBitSet = false; // Transform if high bit of constant set?
7585 switch (Op0BO->getOpcode()) {
7586 default: isValid = false; break; // Do not perform transform!
7587 case Instruction::Add:
7588 isValid = isLeftShift;
7590 case Instruction::Or:
7591 case Instruction::Xor:
7594 case Instruction::And:
7599 // If this is a signed shift right, and the high bit is modified
7600 // by the logical operation, do not perform the transformation.
7601 // The highBitSet boolean indicates the value of the high bit of
7602 // the constant which would cause it to be modified for this
7605 if (isValid && I.getOpcode() == Instruction::AShr)
7606 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7609 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7611 Instruction *NewShift =
7612 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7613 InsertNewInstBefore(NewShift, I);
7614 NewShift->takeName(Op0BO);
7616 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7623 // Find out if this is a shift of a shift by a constant.
7624 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7625 if (ShiftOp && !ShiftOp->isShift())
7628 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7629 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7630 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7631 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7632 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7633 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7634 Value *X = ShiftOp->getOperand(0);
7636 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7638 const IntegerType *Ty = cast<IntegerType>(I.getType());
7640 // Check for (X << c1) << c2 and (X >> c1) >> c2
7641 if (I.getOpcode() == ShiftOp->getOpcode()) {
7642 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7644 if (AmtSum >= TypeBits) {
7645 if (I.getOpcode() != Instruction::AShr)
7646 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7647 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7650 return BinaryOperator::Create(I.getOpcode(), X,
7651 ConstantInt::get(Ty, AmtSum));
7652 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7653 I.getOpcode() == Instruction::AShr) {
7654 if (AmtSum >= TypeBits)
7655 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7657 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7658 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7659 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7660 I.getOpcode() == Instruction::LShr) {
7661 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7662 if (AmtSum >= TypeBits)
7663 AmtSum = TypeBits-1;
7665 Instruction *Shift =
7666 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7667 InsertNewInstBefore(Shift, I);
7669 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7670 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7673 // Okay, if we get here, one shift must be left, and the other shift must be
7674 // right. See if the amounts are equal.
7675 if (ShiftAmt1 == ShiftAmt2) {
7676 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7677 if (I.getOpcode() == Instruction::Shl) {
7678 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7679 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7681 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7682 if (I.getOpcode() == Instruction::LShr) {
7683 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7684 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7686 // We can simplify ((X << C) >>s C) into a trunc + sext.
7687 // NOTE: we could do this for any C, but that would make 'unusual' integer
7688 // types. For now, just stick to ones well-supported by the code
7690 const Type *SExtType = 0;
7691 switch (Ty->getBitWidth() - ShiftAmt1) {
7698 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7703 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7704 InsertNewInstBefore(NewTrunc, I);
7705 return new SExtInst(NewTrunc, Ty);
7707 // Otherwise, we can't handle it yet.
7708 } else if (ShiftAmt1 < ShiftAmt2) {
7709 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7711 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7712 if (I.getOpcode() == Instruction::Shl) {
7713 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7714 ShiftOp->getOpcode() == Instruction::AShr);
7715 Instruction *Shift =
7716 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7717 InsertNewInstBefore(Shift, I);
7719 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7720 return BinaryOperator::CreateAnd(Shift,
7721 ConstantInt::get(*Context, Mask));
7724 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7725 if (I.getOpcode() == Instruction::LShr) {
7726 assert(ShiftOp->getOpcode() == Instruction::Shl);
7727 Instruction *Shift =
7728 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7729 InsertNewInstBefore(Shift, I);
7731 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7732 return BinaryOperator::CreateAnd(Shift,
7733 ConstantInt::get(*Context, Mask));
7736 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7738 assert(ShiftAmt2 < ShiftAmt1);
7739 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7741 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7742 if (I.getOpcode() == Instruction::Shl) {
7743 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7744 ShiftOp->getOpcode() == Instruction::AShr);
7745 Instruction *Shift =
7746 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7747 ConstantInt::get(Ty, ShiftDiff));
7748 InsertNewInstBefore(Shift, I);
7750 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7751 return BinaryOperator::CreateAnd(Shift,
7752 ConstantInt::get(*Context, Mask));
7755 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7756 if (I.getOpcode() == Instruction::LShr) {
7757 assert(ShiftOp->getOpcode() == Instruction::Shl);
7758 Instruction *Shift =
7759 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7760 InsertNewInstBefore(Shift, I);
7762 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7763 return BinaryOperator::CreateAnd(Shift,
7764 ConstantInt::get(*Context, Mask));
7767 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7774 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7775 /// expression. If so, decompose it, returning some value X, such that Val is
7778 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7779 int &Offset, LLVMContext *Context) {
7780 assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
7781 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7782 Offset = CI->getZExtValue();
7784 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7785 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7786 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7787 if (I->getOpcode() == Instruction::Shl) {
7788 // This is a value scaled by '1 << the shift amt'.
7789 Scale = 1U << RHS->getZExtValue();
7791 return I->getOperand(0);
7792 } else if (I->getOpcode() == Instruction::Mul) {
7793 // This value is scaled by 'RHS'.
7794 Scale = RHS->getZExtValue();
7796 return I->getOperand(0);
7797 } else if (I->getOpcode() == Instruction::Add) {
7798 // We have X+C. Check to see if we really have (X*C2)+C1,
7799 // where C1 is divisible by C2.
7802 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7804 Offset += RHS->getZExtValue();
7811 // Otherwise, we can't look past this.
7818 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7819 /// try to eliminate the cast by moving the type information into the alloc.
7820 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7821 AllocationInst &AI) {
7822 const PointerType *PTy = cast<PointerType>(CI.getType());
7824 // Remove any uses of AI that are dead.
7825 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7827 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7828 Instruction *User = cast<Instruction>(*UI++);
7829 if (isInstructionTriviallyDead(User)) {
7830 while (UI != E && *UI == User)
7831 ++UI; // If this instruction uses AI more than once, don't break UI.
7834 DEBUG(errs() << "IC: DCE: " << *User << '\n');
7835 EraseInstFromFunction(*User);
7839 // This requires TargetData to get the alloca alignment and size information.
7842 // Get the type really allocated and the type casted to.
7843 const Type *AllocElTy = AI.getAllocatedType();
7844 const Type *CastElTy = PTy->getElementType();
7845 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7847 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7848 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7849 if (CastElTyAlign < AllocElTyAlign) return 0;
7851 // If the allocation has multiple uses, only promote it if we are strictly
7852 // increasing the alignment of the resultant allocation. If we keep it the
7853 // same, we open the door to infinite loops of various kinds. (A reference
7854 // from a dbg.declare doesn't count as a use for this purpose.)
7855 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7856 CastElTyAlign == AllocElTyAlign) return 0;
7858 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7859 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7860 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7862 // See if we can satisfy the modulus by pulling a scale out of the array
7864 unsigned ArraySizeScale;
7866 Value *NumElements = // See if the array size is a decomposable linear expr.
7867 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7868 ArrayOffset, Context);
7870 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7872 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7873 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7875 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7880 // If the allocation size is constant, form a constant mul expression
7881 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7882 if (isa<ConstantInt>(NumElements))
7883 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7884 cast<ConstantInt>(Amt));
7885 // otherwise multiply the amount and the number of elements
7887 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7888 Amt = InsertNewInstBefore(Tmp, AI);
7892 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7893 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7894 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7895 Amt = InsertNewInstBefore(Tmp, AI);
7898 AllocationInst *New;
7899 if (isa<MallocInst>(AI))
7900 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7902 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7903 InsertNewInstBefore(New, AI);
7906 // If the allocation has one real use plus a dbg.declare, just remove the
7908 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7909 EraseInstFromFunction(*DI);
7911 // If the allocation has multiple real uses, insert a cast and change all
7912 // things that used it to use the new cast. This will also hack on CI, but it
7914 else if (!AI.hasOneUse()) {
7915 // New is the allocation instruction, pointer typed. AI is the original
7916 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7917 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7918 InsertNewInstBefore(NewCast, AI);
7919 AI.replaceAllUsesWith(NewCast);
7921 return ReplaceInstUsesWith(CI, New);
7924 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7925 /// and return it as type Ty without inserting any new casts and without
7926 /// changing the computed value. This is used by code that tries to decide
7927 /// whether promoting or shrinking integer operations to wider or smaller types
7928 /// will allow us to eliminate a truncate or extend.
7930 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7931 /// extension operation if Ty is larger.
7933 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7934 /// should return true if trunc(V) can be computed by computing V in the smaller
7935 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7936 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7937 /// efficiently truncated.
7939 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7940 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7941 /// the final result.
7942 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7944 int &NumCastsRemoved){
7945 // We can always evaluate constants in another type.
7946 if (isa<Constant>(V))
7949 Instruction *I = dyn_cast<Instruction>(V);
7950 if (!I) return false;
7952 const Type *OrigTy = V->getType();
7954 // If this is an extension or truncate, we can often eliminate it.
7955 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7956 // If this is a cast from the destination type, we can trivially eliminate
7957 // it, and this will remove a cast overall.
7958 if (I->getOperand(0)->getType() == Ty) {
7959 // If the first operand is itself a cast, and is eliminable, do not count
7960 // this as an eliminable cast. We would prefer to eliminate those two
7962 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7968 // We can't extend or shrink something that has multiple uses: doing so would
7969 // require duplicating the instruction in general, which isn't profitable.
7970 if (!I->hasOneUse()) return false;
7972 unsigned Opc = I->getOpcode();
7974 case Instruction::Add:
7975 case Instruction::Sub:
7976 case Instruction::Mul:
7977 case Instruction::And:
7978 case Instruction::Or:
7979 case Instruction::Xor:
7980 // These operators can all arbitrarily be extended or truncated.
7981 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7983 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7986 case Instruction::UDiv:
7987 case Instruction::URem: {
7988 // UDiv and URem can be truncated if all the truncated bits are zero.
7989 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7990 uint32_t BitWidth = Ty->getScalarSizeInBits();
7991 if (BitWidth < OrigBitWidth) {
7992 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7993 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7994 MaskedValueIsZero(I->getOperand(1), Mask)) {
7995 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7997 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8003 case Instruction::Shl:
8004 // If we are truncating the result of this SHL, and if it's a shift of a
8005 // constant amount, we can always perform a SHL in a smaller type.
8006 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8007 uint32_t BitWidth = Ty->getScalarSizeInBits();
8008 if (BitWidth < OrigTy->getScalarSizeInBits() &&
8009 CI->getLimitedValue(BitWidth) < BitWidth)
8010 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8014 case Instruction::LShr:
8015 // If this is a truncate of a logical shr, we can truncate it to a smaller
8016 // lshr iff we know that the bits we would otherwise be shifting in are
8018 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8019 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8020 uint32_t BitWidth = Ty->getScalarSizeInBits();
8021 if (BitWidth < OrigBitWidth &&
8022 MaskedValueIsZero(I->getOperand(0),
8023 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8024 CI->getLimitedValue(BitWidth) < BitWidth) {
8025 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8030 case Instruction::ZExt:
8031 case Instruction::SExt:
8032 case Instruction::Trunc:
8033 // If this is the same kind of case as our original (e.g. zext+zext), we
8034 // can safely replace it. Note that replacing it does not reduce the number
8035 // of casts in the input.
8039 // sext (zext ty1), ty2 -> zext ty2
8040 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8043 case Instruction::Select: {
8044 SelectInst *SI = cast<SelectInst>(I);
8045 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8047 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8050 case Instruction::PHI: {
8051 // We can change a phi if we can change all operands.
8052 PHINode *PN = cast<PHINode>(I);
8053 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8054 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8060 // TODO: Can handle more cases here.
8067 /// EvaluateInDifferentType - Given an expression that
8068 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8069 /// evaluate the expression.
8070 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8072 if (Constant *C = dyn_cast<Constant>(V))
8073 return ConstantExpr::getIntegerCast(C, Ty,
8074 isSigned /*Sext or ZExt*/);
8076 // Otherwise, it must be an instruction.
8077 Instruction *I = cast<Instruction>(V);
8078 Instruction *Res = 0;
8079 unsigned Opc = I->getOpcode();
8081 case Instruction::Add:
8082 case Instruction::Sub:
8083 case Instruction::Mul:
8084 case Instruction::And:
8085 case Instruction::Or:
8086 case Instruction::Xor:
8087 case Instruction::AShr:
8088 case Instruction::LShr:
8089 case Instruction::Shl:
8090 case Instruction::UDiv:
8091 case Instruction::URem: {
8092 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8093 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8094 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8097 case Instruction::Trunc:
8098 case Instruction::ZExt:
8099 case Instruction::SExt:
8100 // If the source type of the cast is the type we're trying for then we can
8101 // just return the source. There's no need to insert it because it is not
8103 if (I->getOperand(0)->getType() == Ty)
8104 return I->getOperand(0);
8106 // Otherwise, must be the same type of cast, so just reinsert a new one.
8107 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8110 case Instruction::Select: {
8111 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8112 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8113 Res = SelectInst::Create(I->getOperand(0), True, False);
8116 case Instruction::PHI: {
8117 PHINode *OPN = cast<PHINode>(I);
8118 PHINode *NPN = PHINode::Create(Ty);
8119 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8120 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8121 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8127 // TODO: Can handle more cases here.
8128 llvm_unreachable("Unreachable!");
8133 return InsertNewInstBefore(Res, *I);
8136 /// @brief Implement the transforms common to all CastInst visitors.
8137 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8138 Value *Src = CI.getOperand(0);
8140 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8141 // eliminate it now.
8142 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8143 if (Instruction::CastOps opc =
8144 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8145 // The first cast (CSrc) is eliminable so we need to fix up or replace
8146 // the second cast (CI). CSrc will then have a good chance of being dead.
8147 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8151 // If we are casting a select then fold the cast into the select
8152 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8153 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8156 // If we are casting a PHI then fold the cast into the PHI
8157 if (isa<PHINode>(Src))
8158 if (Instruction *NV = FoldOpIntoPhi(CI))
8164 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8165 /// or not there is a sequence of GEP indices into the type that will land us at
8166 /// the specified offset. If so, fill them into NewIndices and return the
8167 /// resultant element type, otherwise return null.
8168 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8169 SmallVectorImpl<Value*> &NewIndices,
8170 const TargetData *TD,
8171 LLVMContext *Context) {
8173 if (!Ty->isSized()) return 0;
8175 // Start with the index over the outer type. Note that the type size
8176 // might be zero (even if the offset isn't zero) if the indexed type
8177 // is something like [0 x {int, int}]
8178 const Type *IntPtrTy = TD->getIntPtrType(*Context);
8179 int64_t FirstIdx = 0;
8180 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8181 FirstIdx = Offset/TySize;
8182 Offset -= FirstIdx*TySize;
8184 // Handle hosts where % returns negative instead of values [0..TySize).
8188 assert(Offset >= 0);
8190 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8193 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8195 // Index into the types. If we fail, set OrigBase to null.
8197 // Indexing into tail padding between struct/array elements.
8198 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8201 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8202 const StructLayout *SL = TD->getStructLayout(STy);
8203 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8204 "Offset must stay within the indexed type");
8206 unsigned Elt = SL->getElementContainingOffset(Offset);
8207 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8209 Offset -= SL->getElementOffset(Elt);
8210 Ty = STy->getElementType(Elt);
8211 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8212 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8213 assert(EltSize && "Cannot index into a zero-sized array");
8214 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8216 Ty = AT->getElementType();
8218 // Otherwise, we can't index into the middle of this atomic type, bail.
8226 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8227 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8228 Value *Src = CI.getOperand(0);
8230 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8231 // If casting the result of a getelementptr instruction with no offset, turn
8232 // this into a cast of the original pointer!
8233 if (GEP->hasAllZeroIndices()) {
8234 // Changing the cast operand is usually not a good idea but it is safe
8235 // here because the pointer operand is being replaced with another
8236 // pointer operand so the opcode doesn't need to change.
8238 CI.setOperand(0, GEP->getOperand(0));
8242 // If the GEP has a single use, and the base pointer is a bitcast, and the
8243 // GEP computes a constant offset, see if we can convert these three
8244 // instructions into fewer. This typically happens with unions and other
8245 // non-type-safe code.
8246 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8247 if (GEP->hasAllConstantIndices()) {
8248 // We are guaranteed to get a constant from EmitGEPOffset.
8249 ConstantInt *OffsetV =
8250 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8251 int64_t Offset = OffsetV->getSExtValue();
8253 // Get the base pointer input of the bitcast, and the type it points to.
8254 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8255 const Type *GEPIdxTy =
8256 cast<PointerType>(OrigBase->getType())->getElementType();
8257 SmallVector<Value*, 8> NewIndices;
8258 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8259 // If we were able to index down into an element, create the GEP
8260 // and bitcast the result. This eliminates one bitcast, potentially
8262 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8264 NewIndices.end(), "");
8265 InsertNewInstBefore(NGEP, CI);
8266 NGEP->takeName(GEP);
8267 if (cast<GEPOperator>(GEP)->isInBounds())
8268 cast<GEPOperator>(NGEP)->setIsInBounds(true);
8270 if (isa<BitCastInst>(CI))
8271 return new BitCastInst(NGEP, CI.getType());
8272 assert(isa<PtrToIntInst>(CI));
8273 return new PtrToIntInst(NGEP, CI.getType());
8279 return commonCastTransforms(CI);
8282 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8283 /// type like i42. We don't want to introduce operations on random non-legal
8284 /// integer types where they don't already exist in the code. In the future,
8285 /// we should consider making this based off target-data, so that 32-bit targets
8286 /// won't get i64 operations etc.
8287 static bool isSafeIntegerType(const Type *Ty) {
8288 switch (Ty->getPrimitiveSizeInBits()) {
8299 /// commonIntCastTransforms - This function implements the common transforms
8300 /// for trunc, zext, and sext.
8301 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8302 if (Instruction *Result = commonCastTransforms(CI))
8305 Value *Src = CI.getOperand(0);
8306 const Type *SrcTy = Src->getType();
8307 const Type *DestTy = CI.getType();
8308 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8309 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8311 // See if we can simplify any instructions used by the LHS whose sole
8312 // purpose is to compute bits we don't care about.
8313 if (SimplifyDemandedInstructionBits(CI))
8316 // If the source isn't an instruction or has more than one use then we
8317 // can't do anything more.
8318 Instruction *SrcI = dyn_cast<Instruction>(Src);
8319 if (!SrcI || !Src->hasOneUse())
8322 // Attempt to propagate the cast into the instruction for int->int casts.
8323 int NumCastsRemoved = 0;
8324 // Only do this if the dest type is a simple type, don't convert the
8325 // expression tree to something weird like i93 unless the source is also
8327 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8328 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8329 CanEvaluateInDifferentType(SrcI, DestTy,
8330 CI.getOpcode(), NumCastsRemoved)) {
8331 // If this cast is a truncate, evaluting in a different type always
8332 // eliminates the cast, so it is always a win. If this is a zero-extension,
8333 // we need to do an AND to maintain the clear top-part of the computation,
8334 // so we require that the input have eliminated at least one cast. If this
8335 // is a sign extension, we insert two new casts (to do the extension) so we
8336 // require that two casts have been eliminated.
8337 bool DoXForm = false;
8338 bool JustReplace = false;
8339 switch (CI.getOpcode()) {
8341 // All the others use floating point so we shouldn't actually
8342 // get here because of the check above.
8343 llvm_unreachable("Unknown cast type");
8344 case Instruction::Trunc:
8347 case Instruction::ZExt: {
8348 DoXForm = NumCastsRemoved >= 1;
8349 if (!DoXForm && 0) {
8350 // If it's unnecessary to issue an AND to clear the high bits, it's
8351 // always profitable to do this xform.
8352 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8353 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8354 if (MaskedValueIsZero(TryRes, Mask))
8355 return ReplaceInstUsesWith(CI, TryRes);
8357 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8358 if (TryI->use_empty())
8359 EraseInstFromFunction(*TryI);
8363 case Instruction::SExt: {
8364 DoXForm = NumCastsRemoved >= 2;
8365 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8366 // If we do not have to emit the truncate + sext pair, then it's always
8367 // profitable to do this xform.
8369 // It's not safe to eliminate the trunc + sext pair if one of the
8370 // eliminated cast is a truncate. e.g.
8371 // t2 = trunc i32 t1 to i16
8372 // t3 = sext i16 t2 to i32
8375 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8376 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8377 if (NumSignBits > (DestBitSize - SrcBitSize))
8378 return ReplaceInstUsesWith(CI, TryRes);
8380 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8381 if (TryI->use_empty())
8382 EraseInstFromFunction(*TryI);
8389 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8390 " to avoid cast: " << CI);
8391 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8392 CI.getOpcode() == Instruction::SExt);
8394 // Just replace this cast with the result.
8395 return ReplaceInstUsesWith(CI, Res);
8397 assert(Res->getType() == DestTy);
8398 switch (CI.getOpcode()) {
8399 default: llvm_unreachable("Unknown cast type!");
8400 case Instruction::Trunc:
8401 // Just replace this cast with the result.
8402 return ReplaceInstUsesWith(CI, Res);
8403 case Instruction::ZExt: {
8404 assert(SrcBitSize < DestBitSize && "Not a zext?");
8406 // If the high bits are already zero, just replace this cast with the
8408 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8409 if (MaskedValueIsZero(Res, Mask))
8410 return ReplaceInstUsesWith(CI, Res);
8412 // We need to emit an AND to clear the high bits.
8413 Constant *C = ConstantInt::get(*Context,
8414 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8415 return BinaryOperator::CreateAnd(Res, C);
8417 case Instruction::SExt: {
8418 // If the high bits are already filled with sign bit, just replace this
8419 // cast with the result.
8420 unsigned NumSignBits = ComputeNumSignBits(Res);
8421 if (NumSignBits > (DestBitSize - SrcBitSize))
8422 return ReplaceInstUsesWith(CI, Res);
8424 // We need to emit a cast to truncate, then a cast to sext.
8425 return CastInst::Create(Instruction::SExt,
8426 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8433 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8434 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8436 switch (SrcI->getOpcode()) {
8437 case Instruction::Add:
8438 case Instruction::Mul:
8439 case Instruction::And:
8440 case Instruction::Or:
8441 case Instruction::Xor:
8442 // If we are discarding information, rewrite.
8443 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8444 // Don't insert two casts unless at least one can be eliminated.
8445 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8446 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8447 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8448 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8449 return BinaryOperator::Create(
8450 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8454 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8455 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8456 SrcI->getOpcode() == Instruction::Xor &&
8457 Op1 == ConstantInt::getTrue(*Context) &&
8458 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8459 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8460 return BinaryOperator::CreateXor(New,
8461 ConstantInt::get(CI.getType(), 1));
8465 case Instruction::Shl: {
8466 // Canonicalize trunc inside shl, if we can.
8467 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8468 if (CI && DestBitSize < SrcBitSize &&
8469 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8470 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8471 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8472 return BinaryOperator::CreateShl(Op0c, Op1c);
8480 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8481 if (Instruction *Result = commonIntCastTransforms(CI))
8484 Value *Src = CI.getOperand(0);
8485 const Type *Ty = CI.getType();
8486 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8487 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8489 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8490 if (DestBitWidth == 1) {
8491 Constant *One = ConstantInt::get(Src->getType(), 1);
8492 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8493 Value *Zero = Constant::getNullValue(Src->getType());
8494 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8497 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8498 ConstantInt *ShAmtV = 0;
8500 if (Src->hasOneUse() &&
8501 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8502 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8504 // Get a mask for the bits shifting in.
8505 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8506 if (MaskedValueIsZero(ShiftOp, Mask)) {
8507 if (ShAmt >= DestBitWidth) // All zeros.
8508 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8510 // Okay, we can shrink this. Truncate the input, then return a new
8512 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8513 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8514 return BinaryOperator::CreateLShr(V1, V2);
8521 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8522 /// in order to eliminate the icmp.
8523 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8525 // If we are just checking for a icmp eq of a single bit and zext'ing it
8526 // to an integer, then shift the bit to the appropriate place and then
8527 // cast to integer to avoid the comparison.
8528 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8529 const APInt &Op1CV = Op1C->getValue();
8531 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8532 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8533 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8534 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8535 if (!DoXform) return ICI;
8537 Value *In = ICI->getOperand(0);
8538 Value *Sh = ConstantInt::get(In->getType(),
8539 In->getType()->getScalarSizeInBits()-1);
8540 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8541 In->getName()+".lobit"),
8543 if (In->getType() != CI.getType())
8544 In = CastInst::CreateIntegerCast(In, CI.getType(),
8545 false/*ZExt*/, "tmp", &CI);
8547 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8548 Constant *One = ConstantInt::get(In->getType(), 1);
8549 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8550 In->getName()+".not"),
8554 return ReplaceInstUsesWith(CI, In);
8559 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8560 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8561 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8562 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8563 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8564 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8565 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8566 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8567 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8568 // This only works for EQ and NE
8569 ICI->isEquality()) {
8570 // If Op1C some other power of two, convert:
8571 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8572 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8573 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8574 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8576 APInt KnownZeroMask(~KnownZero);
8577 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8578 if (!DoXform) return ICI;
8580 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8581 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8582 // (X&4) == 2 --> false
8583 // (X&4) != 2 --> true
8584 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8585 Res = ConstantExpr::getZExt(Res, CI.getType());
8586 return ReplaceInstUsesWith(CI, Res);
8589 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8590 Value *In = ICI->getOperand(0);
8592 // Perform a logical shr by shiftamt.
8593 // Insert the shift to put the result in the low bit.
8594 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8595 ConstantInt::get(In->getType(), ShiftAmt),
8596 In->getName()+".lobit"), CI);
8599 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8600 Constant *One = ConstantInt::get(In->getType(), 1);
8601 In = BinaryOperator::CreateXor(In, One, "tmp");
8602 InsertNewInstBefore(cast<Instruction>(In), CI);
8605 if (CI.getType() == In->getType())
8606 return ReplaceInstUsesWith(CI, In);
8608 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8616 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8617 // If one of the common conversion will work ..
8618 if (Instruction *Result = commonIntCastTransforms(CI))
8621 Value *Src = CI.getOperand(0);
8623 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8624 // types and if the sizes are just right we can convert this into a logical
8625 // 'and' which will be much cheaper than the pair of casts.
8626 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8627 // Get the sizes of the types involved. We know that the intermediate type
8628 // will be smaller than A or C, but don't know the relation between A and C.
8629 Value *A = CSrc->getOperand(0);
8630 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8631 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8632 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8633 // If we're actually extending zero bits, then if
8634 // SrcSize < DstSize: zext(a & mask)
8635 // SrcSize == DstSize: a & mask
8636 // SrcSize > DstSize: trunc(a) & mask
8637 if (SrcSize < DstSize) {
8638 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8639 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8641 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8642 InsertNewInstBefore(And, CI);
8643 return new ZExtInst(And, CI.getType());
8644 } else if (SrcSize == DstSize) {
8645 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8646 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8648 } else if (SrcSize > DstSize) {
8649 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8650 InsertNewInstBefore(Trunc, CI);
8651 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8652 return BinaryOperator::CreateAnd(Trunc,
8653 ConstantInt::get(Trunc->getType(),
8658 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8659 return transformZExtICmp(ICI, CI);
8661 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8662 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8663 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8664 // of the (zext icmp) will be transformed.
8665 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8666 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8667 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8668 (transformZExtICmp(LHS, CI, false) ||
8669 transformZExtICmp(RHS, CI, false))) {
8670 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8671 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8672 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8676 // zext(trunc(t) & C) -> (t & zext(C)).
8677 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8678 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8679 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8680 Value *TI0 = TI->getOperand(0);
8681 if (TI0->getType() == CI.getType())
8683 BinaryOperator::CreateAnd(TI0,
8684 ConstantExpr::getZExt(C, CI.getType()));
8687 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8688 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8689 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8690 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8691 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8692 And->getOperand(1) == C)
8693 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8694 Value *TI0 = TI->getOperand(0);
8695 if (TI0->getType() == CI.getType()) {
8696 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8697 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8698 InsertNewInstBefore(NewAnd, *And);
8699 return BinaryOperator::CreateXor(NewAnd, ZC);
8706 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8707 if (Instruction *I = commonIntCastTransforms(CI))
8710 Value *Src = CI.getOperand(0);
8712 // Canonicalize sign-extend from i1 to a select.
8713 if (Src->getType() == Type::getInt1Ty(*Context))
8714 return SelectInst::Create(Src,
8715 Constant::getAllOnesValue(CI.getType()),
8716 Constant::getNullValue(CI.getType()));
8718 // See if the value being truncated is already sign extended. If so, just
8719 // eliminate the trunc/sext pair.
8720 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8721 Value *Op = cast<User>(Src)->getOperand(0);
8722 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8723 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8724 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8725 unsigned NumSignBits = ComputeNumSignBits(Op);
8727 if (OpBits == DestBits) {
8728 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8729 // bits, it is already ready.
8730 if (NumSignBits > DestBits-MidBits)
8731 return ReplaceInstUsesWith(CI, Op);
8732 } else if (OpBits < DestBits) {
8733 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8734 // bits, just sext from i32.
8735 if (NumSignBits > OpBits-MidBits)
8736 return new SExtInst(Op, CI.getType(), "tmp");
8738 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8739 // bits, just truncate to i32.
8740 if (NumSignBits > OpBits-MidBits)
8741 return new TruncInst(Op, CI.getType(), "tmp");
8745 // If the input is a shl/ashr pair of a same constant, then this is a sign
8746 // extension from a smaller value. If we could trust arbitrary bitwidth
8747 // integers, we could turn this into a truncate to the smaller bit and then
8748 // use a sext for the whole extension. Since we don't, look deeper and check
8749 // for a truncate. If the source and dest are the same type, eliminate the
8750 // trunc and extend and just do shifts. For example, turn:
8751 // %a = trunc i32 %i to i8
8752 // %b = shl i8 %a, 6
8753 // %c = ashr i8 %b, 6
8754 // %d = sext i8 %c to i32
8756 // %a = shl i32 %i, 30
8757 // %d = ashr i32 %a, 30
8759 ConstantInt *BA = 0, *CA = 0;
8760 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8761 m_ConstantInt(CA))) &&
8762 BA == CA && isa<TruncInst>(A)) {
8763 Value *I = cast<TruncInst>(A)->getOperand(0);
8764 if (I->getType() == CI.getType()) {
8765 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8766 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8767 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8768 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8769 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8771 return BinaryOperator::CreateAShr(I, ShAmtV);
8778 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8779 /// in the specified FP type without changing its value.
8780 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8781 LLVMContext *Context) {
8783 APFloat F = CFP->getValueAPF();
8784 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8786 return ConstantFP::get(*Context, F);
8790 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8791 /// through it until we get the source value.
8792 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8793 if (Instruction *I = dyn_cast<Instruction>(V))
8794 if (I->getOpcode() == Instruction::FPExt)
8795 return LookThroughFPExtensions(I->getOperand(0), Context);
8797 // If this value is a constant, return the constant in the smallest FP type
8798 // that can accurately represent it. This allows us to turn
8799 // (float)((double)X+2.0) into x+2.0f.
8800 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8801 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8802 return V; // No constant folding of this.
8803 // See if the value can be truncated to float and then reextended.
8804 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8806 if (CFP->getType() == Type::getDoubleTy(*Context))
8807 return V; // Won't shrink.
8808 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8810 // Don't try to shrink to various long double types.
8816 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8817 if (Instruction *I = commonCastTransforms(CI))
8820 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8821 // smaller than the destination type, we can eliminate the truncate by doing
8822 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8823 // many builtins (sqrt, etc).
8824 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8825 if (OpI && OpI->hasOneUse()) {
8826 switch (OpI->getOpcode()) {
8828 case Instruction::FAdd:
8829 case Instruction::FSub:
8830 case Instruction::FMul:
8831 case Instruction::FDiv:
8832 case Instruction::FRem:
8833 const Type *SrcTy = OpI->getType();
8834 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8835 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8836 if (LHSTrunc->getType() != SrcTy &&
8837 RHSTrunc->getType() != SrcTy) {
8838 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8839 // If the source types were both smaller than the destination type of
8840 // the cast, do this xform.
8841 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8842 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8843 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8845 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8847 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8856 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8857 return commonCastTransforms(CI);
8860 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8861 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8863 return commonCastTransforms(FI);
8865 // fptoui(uitofp(X)) --> X
8866 // fptoui(sitofp(X)) --> X
8867 // This is safe if the intermediate type has enough bits in its mantissa to
8868 // accurately represent all values of X. For example, do not do this with
8869 // i64->float->i64. This is also safe for sitofp case, because any negative
8870 // 'X' value would cause an undefined result for the fptoui.
8871 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8872 OpI->getOperand(0)->getType() == FI.getType() &&
8873 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8874 OpI->getType()->getFPMantissaWidth())
8875 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8877 return commonCastTransforms(FI);
8880 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8881 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8883 return commonCastTransforms(FI);
8885 // fptosi(sitofp(X)) --> X
8886 // fptosi(uitofp(X)) --> X
8887 // This is safe if the intermediate type has enough bits in its mantissa to
8888 // accurately represent all values of X. For example, do not do this with
8889 // i64->float->i64. This is also safe for sitofp case, because any negative
8890 // 'X' value would cause an undefined result for the fptoui.
8891 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8892 OpI->getOperand(0)->getType() == FI.getType() &&
8893 (int)FI.getType()->getScalarSizeInBits() <=
8894 OpI->getType()->getFPMantissaWidth())
8895 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8897 return commonCastTransforms(FI);
8900 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8901 return commonCastTransforms(CI);
8904 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8905 return commonCastTransforms(CI);
8908 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8909 // If the destination integer type is smaller than the intptr_t type for
8910 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8911 // trunc to be exposed to other transforms. Don't do this for extending
8912 // ptrtoint's, because we don't know if the target sign or zero extends its
8915 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8916 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8917 TD->getIntPtrType(CI.getContext()),
8919 return new TruncInst(P, CI.getType());
8922 return commonPointerCastTransforms(CI);
8925 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8926 // If the source integer type is larger than the intptr_t type for
8927 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8928 // allows the trunc to be exposed to other transforms. Don't do this for
8929 // extending inttoptr's, because we don't know if the target sign or zero
8930 // extends to pointers.
8932 CI.getOperand(0)->getType()->getScalarSizeInBits() >
8933 TD->getPointerSizeInBits()) {
8934 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8935 TD->getIntPtrType(CI.getContext()),
8937 return new IntToPtrInst(P, CI.getType());
8940 if (Instruction *I = commonCastTransforms(CI))
8946 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8947 // If the operands are integer typed then apply the integer transforms,
8948 // otherwise just apply the common ones.
8949 Value *Src = CI.getOperand(0);
8950 const Type *SrcTy = Src->getType();
8951 const Type *DestTy = CI.getType();
8953 if (isa<PointerType>(SrcTy)) {
8954 if (Instruction *I = commonPointerCastTransforms(CI))
8957 if (Instruction *Result = commonCastTransforms(CI))
8962 // Get rid of casts from one type to the same type. These are useless and can
8963 // be replaced by the operand.
8964 if (DestTy == Src->getType())
8965 return ReplaceInstUsesWith(CI, Src);
8967 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8968 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8969 const Type *DstElTy = DstPTy->getElementType();
8970 const Type *SrcElTy = SrcPTy->getElementType();
8972 // If the address spaces don't match, don't eliminate the bitcast, which is
8973 // required for changing types.
8974 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8977 // If we are casting a malloc or alloca to a pointer to a type of the same
8978 // size, rewrite the allocation instruction to allocate the "right" type.
8979 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8980 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8983 // If the source and destination are pointers, and this cast is equivalent
8984 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8985 // This can enhance SROA and other transforms that want type-safe pointers.
8986 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8987 unsigned NumZeros = 0;
8988 while (SrcElTy != DstElTy &&
8989 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8990 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8991 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8995 // If we found a path from the src to dest, create the getelementptr now.
8996 if (SrcElTy == DstElTy) {
8997 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8998 Instruction *GEP = GetElementPtrInst::Create(Src,
8999 Idxs.begin(), Idxs.end(), "",
9000 ((Instruction*) NULL));
9001 cast<GEPOperator>(GEP)->setIsInBounds(true);
9006 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9007 if (DestVTy->getNumElements() == 1) {
9008 if (!isa<VectorType>(SrcTy)) {
9009 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9010 DestVTy->getElementType(), CI);
9011 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9012 Constant::getNullValue(Type::getInt32Ty(*Context)));
9014 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9018 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9019 if (SrcVTy->getNumElements() == 1) {
9020 if (!isa<VectorType>(DestTy)) {
9022 ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
9023 InsertNewInstBefore(Elem, CI);
9024 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9029 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9030 if (SVI->hasOneUse()) {
9031 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9032 // a bitconvert to a vector with the same # elts.
9033 if (isa<VectorType>(DestTy) &&
9034 cast<VectorType>(DestTy)->getNumElements() ==
9035 SVI->getType()->getNumElements() &&
9036 SVI->getType()->getNumElements() ==
9037 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9039 // If either of the operands is a cast from CI.getType(), then
9040 // evaluating the shuffle in the casted destination's type will allow
9041 // us to eliminate at least one cast.
9042 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9043 Tmp->getOperand(0)->getType() == DestTy) ||
9044 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9045 Tmp->getOperand(0)->getType() == DestTy)) {
9046 Value *LHS = InsertCastBefore(Instruction::BitCast,
9047 SVI->getOperand(0), DestTy, CI);
9048 Value *RHS = InsertCastBefore(Instruction::BitCast,
9049 SVI->getOperand(1), DestTy, CI);
9050 // Return a new shuffle vector. Use the same element ID's, as we
9051 // know the vector types match #elts.
9052 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9060 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9062 /// %D = select %cond, %C, %A
9064 /// %C = select %cond, %B, 0
9067 /// Assuming that the specified instruction is an operand to the select, return
9068 /// a bitmask indicating which operands of this instruction are foldable if they
9069 /// equal the other incoming value of the select.
9071 static unsigned GetSelectFoldableOperands(Instruction *I) {
9072 switch (I->getOpcode()) {
9073 case Instruction::Add:
9074 case Instruction::Mul:
9075 case Instruction::And:
9076 case Instruction::Or:
9077 case Instruction::Xor:
9078 return 3; // Can fold through either operand.
9079 case Instruction::Sub: // Can only fold on the amount subtracted.
9080 case Instruction::Shl: // Can only fold on the shift amount.
9081 case Instruction::LShr:
9082 case Instruction::AShr:
9085 return 0; // Cannot fold
9089 /// GetSelectFoldableConstant - For the same transformation as the previous
9090 /// function, return the identity constant that goes into the select.
9091 static Constant *GetSelectFoldableConstant(Instruction *I,
9092 LLVMContext *Context) {
9093 switch (I->getOpcode()) {
9094 default: llvm_unreachable("This cannot happen!");
9095 case Instruction::Add:
9096 case Instruction::Sub:
9097 case Instruction::Or:
9098 case Instruction::Xor:
9099 case Instruction::Shl:
9100 case Instruction::LShr:
9101 case Instruction::AShr:
9102 return Constant::getNullValue(I->getType());
9103 case Instruction::And:
9104 return Constant::getAllOnesValue(I->getType());
9105 case Instruction::Mul:
9106 return ConstantInt::get(I->getType(), 1);
9110 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9111 /// have the same opcode and only one use each. Try to simplify this.
9112 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9114 if (TI->getNumOperands() == 1) {
9115 // If this is a non-volatile load or a cast from the same type,
9118 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9121 return 0; // unknown unary op.
9124 // Fold this by inserting a select from the input values.
9125 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9126 FI->getOperand(0), SI.getName()+".v");
9127 InsertNewInstBefore(NewSI, SI);
9128 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
9132 // Only handle binary operators here.
9133 if (!isa<BinaryOperator>(TI))
9136 // Figure out if the operations have any operands in common.
9137 Value *MatchOp, *OtherOpT, *OtherOpF;
9139 if (TI->getOperand(0) == FI->getOperand(0)) {
9140 MatchOp = TI->getOperand(0);
9141 OtherOpT = TI->getOperand(1);
9142 OtherOpF = FI->getOperand(1);
9143 MatchIsOpZero = true;
9144 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9145 MatchOp = TI->getOperand(1);
9146 OtherOpT = TI->getOperand(0);
9147 OtherOpF = FI->getOperand(0);
9148 MatchIsOpZero = false;
9149 } else if (!TI->isCommutative()) {
9151 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9152 MatchOp = TI->getOperand(0);
9153 OtherOpT = TI->getOperand(1);
9154 OtherOpF = FI->getOperand(0);
9155 MatchIsOpZero = true;
9156 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9157 MatchOp = TI->getOperand(1);
9158 OtherOpT = TI->getOperand(0);
9159 OtherOpF = FI->getOperand(1);
9160 MatchIsOpZero = true;
9165 // If we reach here, they do have operations in common.
9166 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9167 OtherOpF, SI.getName()+".v");
9168 InsertNewInstBefore(NewSI, SI);
9170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9172 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9174 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9176 llvm_unreachable("Shouldn't get here");
9180 static bool isSelect01(Constant *C1, Constant *C2) {
9181 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9184 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9187 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9190 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9191 /// facilitate further optimization.
9192 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9194 // See the comment above GetSelectFoldableOperands for a description of the
9195 // transformation we are doing here.
9196 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9197 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9198 !isa<Constant>(FalseVal)) {
9199 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9200 unsigned OpToFold = 0;
9201 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9203 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9208 Constant *C = GetSelectFoldableConstant(TVI, Context);
9209 Value *OOp = TVI->getOperand(2-OpToFold);
9210 // Avoid creating select between 2 constants unless it's selecting
9212 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9213 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9214 InsertNewInstBefore(NewSel, SI);
9215 NewSel->takeName(TVI);
9216 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9217 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9218 llvm_unreachable("Unknown instruction!!");
9225 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9226 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9227 !isa<Constant>(TrueVal)) {
9228 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9229 unsigned OpToFold = 0;
9230 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9232 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9237 Constant *C = GetSelectFoldableConstant(FVI, Context);
9238 Value *OOp = FVI->getOperand(2-OpToFold);
9239 // Avoid creating select between 2 constants unless it's selecting
9241 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9242 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9243 InsertNewInstBefore(NewSel, SI);
9244 NewSel->takeName(FVI);
9245 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9246 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9247 llvm_unreachable("Unknown instruction!!");
9257 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9258 /// ICmpInst as its first operand.
9260 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9262 bool Changed = false;
9263 ICmpInst::Predicate Pred = ICI->getPredicate();
9264 Value *CmpLHS = ICI->getOperand(0);
9265 Value *CmpRHS = ICI->getOperand(1);
9266 Value *TrueVal = SI.getTrueValue();
9267 Value *FalseVal = SI.getFalseValue();
9269 // Check cases where the comparison is with a constant that
9270 // can be adjusted to fit the min/max idiom. We may edit ICI in
9271 // place here, so make sure the select is the only user.
9272 if (ICI->hasOneUse())
9273 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9276 case ICmpInst::ICMP_ULT:
9277 case ICmpInst::ICMP_SLT: {
9278 // X < MIN ? T : F --> F
9279 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9280 return ReplaceInstUsesWith(SI, FalseVal);
9281 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9282 Constant *AdjustedRHS = SubOne(CI);
9283 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9284 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9285 Pred = ICmpInst::getSwappedPredicate(Pred);
9286 CmpRHS = AdjustedRHS;
9287 std::swap(FalseVal, TrueVal);
9288 ICI->setPredicate(Pred);
9289 ICI->setOperand(1, CmpRHS);
9290 SI.setOperand(1, TrueVal);
9291 SI.setOperand(2, FalseVal);
9296 case ICmpInst::ICMP_UGT:
9297 case ICmpInst::ICMP_SGT: {
9298 // X > MAX ? T : F --> F
9299 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9300 return ReplaceInstUsesWith(SI, FalseVal);
9301 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9302 Constant *AdjustedRHS = AddOne(CI);
9303 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9304 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9305 Pred = ICmpInst::getSwappedPredicate(Pred);
9306 CmpRHS = AdjustedRHS;
9307 std::swap(FalseVal, TrueVal);
9308 ICI->setPredicate(Pred);
9309 ICI->setOperand(1, CmpRHS);
9310 SI.setOperand(1, TrueVal);
9311 SI.setOperand(2, FalseVal);
9318 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9319 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9320 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9321 if (match(TrueVal, m_ConstantInt<-1>()) &&
9322 match(FalseVal, m_ConstantInt<0>()))
9323 Pred = ICI->getPredicate();
9324 else if (match(TrueVal, m_ConstantInt<0>()) &&
9325 match(FalseVal, m_ConstantInt<-1>()))
9326 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9328 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9329 // If we are just checking for a icmp eq of a single bit and zext'ing it
9330 // to an integer, then shift the bit to the appropriate place and then
9331 // cast to integer to avoid the comparison.
9332 const APInt &Op1CV = CI->getValue();
9334 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9335 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9336 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9337 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9338 Value *In = ICI->getOperand(0);
9339 Value *Sh = ConstantInt::get(In->getType(),
9340 In->getType()->getScalarSizeInBits()-1);
9341 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9342 In->getName()+".lobit"),
9344 if (In->getType() != SI.getType())
9345 In = CastInst::CreateIntegerCast(In, SI.getType(),
9346 true/*SExt*/, "tmp", ICI);
9348 if (Pred == ICmpInst::ICMP_SGT)
9349 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9350 In->getName()+".not"), *ICI);
9352 return ReplaceInstUsesWith(SI, In);
9357 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9358 // Transform (X == Y) ? X : Y -> Y
9359 if (Pred == ICmpInst::ICMP_EQ)
9360 return ReplaceInstUsesWith(SI, FalseVal);
9361 // Transform (X != Y) ? X : Y -> X
9362 if (Pred == ICmpInst::ICMP_NE)
9363 return ReplaceInstUsesWith(SI, TrueVal);
9364 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9366 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9367 // Transform (X == Y) ? Y : X -> X
9368 if (Pred == ICmpInst::ICMP_EQ)
9369 return ReplaceInstUsesWith(SI, FalseVal);
9370 // Transform (X != Y) ? Y : X -> Y
9371 if (Pred == ICmpInst::ICMP_NE)
9372 return ReplaceInstUsesWith(SI, TrueVal);
9373 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9376 /// NOTE: if we wanted to, this is where to detect integer ABS
9378 return Changed ? &SI : 0;
9381 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9382 Value *CondVal = SI.getCondition();
9383 Value *TrueVal = SI.getTrueValue();
9384 Value *FalseVal = SI.getFalseValue();
9386 // select true, X, Y -> X
9387 // select false, X, Y -> Y
9388 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9389 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9391 // select C, X, X -> X
9392 if (TrueVal == FalseVal)
9393 return ReplaceInstUsesWith(SI, TrueVal);
9395 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9396 return ReplaceInstUsesWith(SI, FalseVal);
9397 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9398 return ReplaceInstUsesWith(SI, TrueVal);
9399 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9400 if (isa<Constant>(TrueVal))
9401 return ReplaceInstUsesWith(SI, TrueVal);
9403 return ReplaceInstUsesWith(SI, FalseVal);
9406 if (SI.getType() == Type::getInt1Ty(*Context)) {
9407 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9408 if (C->getZExtValue()) {
9409 // Change: A = select B, true, C --> A = or B, C
9410 return BinaryOperator::CreateOr(CondVal, FalseVal);
9412 // Change: A = select B, false, C --> A = and !B, C
9414 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9415 "not."+CondVal->getName()), SI);
9416 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9418 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9419 if (C->getZExtValue() == false) {
9420 // Change: A = select B, C, false --> A = and B, C
9421 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9423 // Change: A = select B, C, true --> A = or !B, C
9425 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9426 "not."+CondVal->getName()), SI);
9427 return BinaryOperator::CreateOr(NotCond, TrueVal);
9431 // select a, b, a -> a&b
9432 // select a, a, b -> a|b
9433 if (CondVal == TrueVal)
9434 return BinaryOperator::CreateOr(CondVal, FalseVal);
9435 else if (CondVal == FalseVal)
9436 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9439 // Selecting between two integer constants?
9440 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9441 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9442 // select C, 1, 0 -> zext C to int
9443 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9444 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9445 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9446 // select C, 0, 1 -> zext !C to int
9448 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9449 "not."+CondVal->getName()), SI);
9450 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9453 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9454 // If one of the constants is zero (we know they can't both be) and we
9455 // have an icmp instruction with zero, and we have an 'and' with the
9456 // non-constant value, eliminate this whole mess. This corresponds to
9457 // cases like this: ((X & 27) ? 27 : 0)
9458 if (TrueValC->isZero() || FalseValC->isZero())
9459 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9460 cast<Constant>(IC->getOperand(1))->isNullValue())
9461 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9462 if (ICA->getOpcode() == Instruction::And &&
9463 isa<ConstantInt>(ICA->getOperand(1)) &&
9464 (ICA->getOperand(1) == TrueValC ||
9465 ICA->getOperand(1) == FalseValC) &&
9466 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9467 // Okay, now we know that everything is set up, we just don't
9468 // know whether we have a icmp_ne or icmp_eq and whether the
9469 // true or false val is the zero.
9470 bool ShouldNotVal = !TrueValC->isZero();
9471 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9474 V = InsertNewInstBefore(BinaryOperator::Create(
9475 Instruction::Xor, V, ICA->getOperand(1)), SI);
9476 return ReplaceInstUsesWith(SI, V);
9481 // See if we are selecting two values based on a comparison of the two values.
9482 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9483 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9484 // Transform (X == Y) ? X : Y -> Y
9485 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9486 // This is not safe in general for floating point:
9487 // consider X== -0, Y== +0.
9488 // It becomes safe if either operand is a nonzero constant.
9489 ConstantFP *CFPt, *CFPf;
9490 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9491 !CFPt->getValueAPF().isZero()) ||
9492 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9493 !CFPf->getValueAPF().isZero()))
9494 return ReplaceInstUsesWith(SI, FalseVal);
9496 // Transform (X != Y) ? X : Y -> X
9497 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9498 return ReplaceInstUsesWith(SI, TrueVal);
9499 // NOTE: if we wanted to, this is where to detect MIN/MAX
9501 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9502 // Transform (X == Y) ? Y : X -> X
9503 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9504 // This is not safe in general for floating point:
9505 // consider X== -0, Y== +0.
9506 // It becomes safe if either operand is a nonzero constant.
9507 ConstantFP *CFPt, *CFPf;
9508 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9509 !CFPt->getValueAPF().isZero()) ||
9510 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9511 !CFPf->getValueAPF().isZero()))
9512 return ReplaceInstUsesWith(SI, FalseVal);
9514 // Transform (X != Y) ? Y : X -> Y
9515 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9516 return ReplaceInstUsesWith(SI, TrueVal);
9517 // NOTE: if we wanted to, this is where to detect MIN/MAX
9519 // NOTE: if we wanted to, this is where to detect ABS
9522 // See if we are selecting two values based on a comparison of the two values.
9523 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9524 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9527 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9528 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9529 if (TI->hasOneUse() && FI->hasOneUse()) {
9530 Instruction *AddOp = 0, *SubOp = 0;
9532 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9533 if (TI->getOpcode() == FI->getOpcode())
9534 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9537 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9538 // even legal for FP.
9539 if ((TI->getOpcode() == Instruction::Sub &&
9540 FI->getOpcode() == Instruction::Add) ||
9541 (TI->getOpcode() == Instruction::FSub &&
9542 FI->getOpcode() == Instruction::FAdd)) {
9543 AddOp = FI; SubOp = TI;
9544 } else if ((FI->getOpcode() == Instruction::Sub &&
9545 TI->getOpcode() == Instruction::Add) ||
9546 (FI->getOpcode() == Instruction::FSub &&
9547 TI->getOpcode() == Instruction::FAdd)) {
9548 AddOp = TI; SubOp = FI;
9552 Value *OtherAddOp = 0;
9553 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9554 OtherAddOp = AddOp->getOperand(1);
9555 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9556 OtherAddOp = AddOp->getOperand(0);
9560 // So at this point we know we have (Y -> OtherAddOp):
9561 // select C, (add X, Y), (sub X, Z)
9562 Value *NegVal; // Compute -Z
9563 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9564 NegVal = ConstantExpr::getNeg(C);
9566 NegVal = InsertNewInstBefore(
9567 BinaryOperator::CreateNeg(SubOp->getOperand(1),
9571 Value *NewTrueOp = OtherAddOp;
9572 Value *NewFalseOp = NegVal;
9574 std::swap(NewTrueOp, NewFalseOp);
9575 Instruction *NewSel =
9576 SelectInst::Create(CondVal, NewTrueOp,
9577 NewFalseOp, SI.getName() + ".p");
9579 NewSel = InsertNewInstBefore(NewSel, SI);
9580 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9585 // See if we can fold the select into one of our operands.
9586 if (SI.getType()->isInteger()) {
9587 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9592 if (BinaryOperator::isNot(CondVal)) {
9593 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9594 SI.setOperand(1, FalseVal);
9595 SI.setOperand(2, TrueVal);
9602 /// EnforceKnownAlignment - If the specified pointer points to an object that
9603 /// we control, modify the object's alignment to PrefAlign. This isn't
9604 /// often possible though. If alignment is important, a more reliable approach
9605 /// is to simply align all global variables and allocation instructions to
9606 /// their preferred alignment from the beginning.
9608 static unsigned EnforceKnownAlignment(Value *V,
9609 unsigned Align, unsigned PrefAlign) {
9611 User *U = dyn_cast<User>(V);
9612 if (!U) return Align;
9614 switch (Operator::getOpcode(U)) {
9616 case Instruction::BitCast:
9617 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9618 case Instruction::GetElementPtr: {
9619 // If all indexes are zero, it is just the alignment of the base pointer.
9620 bool AllZeroOperands = true;
9621 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9622 if (!isa<Constant>(*i) ||
9623 !cast<Constant>(*i)->isNullValue()) {
9624 AllZeroOperands = false;
9628 if (AllZeroOperands) {
9629 // Treat this like a bitcast.
9630 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9636 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9637 // If there is a large requested alignment and we can, bump up the alignment
9639 if (!GV->isDeclaration()) {
9640 if (GV->getAlignment() >= PrefAlign)
9641 Align = GV->getAlignment();
9643 GV->setAlignment(PrefAlign);
9647 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9648 // If there is a requested alignment and if this is an alloca, round up. We
9649 // don't do this for malloc, because some systems can't respect the request.
9650 if (isa<AllocaInst>(AI)) {
9651 if (AI->getAlignment() >= PrefAlign)
9652 Align = AI->getAlignment();
9654 AI->setAlignment(PrefAlign);
9663 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9664 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9665 /// and it is more than the alignment of the ultimate object, see if we can
9666 /// increase the alignment of the ultimate object, making this check succeed.
9667 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9668 unsigned PrefAlign) {
9669 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9670 sizeof(PrefAlign) * CHAR_BIT;
9671 APInt Mask = APInt::getAllOnesValue(BitWidth);
9672 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9673 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9674 unsigned TrailZ = KnownZero.countTrailingOnes();
9675 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9677 if (PrefAlign > Align)
9678 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9680 // We don't need to make any adjustment.
9684 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9685 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9686 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9687 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9688 unsigned CopyAlign = MI->getAlignment();
9690 if (CopyAlign < MinAlign) {
9691 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9696 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9698 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9699 if (MemOpLength == 0) return 0;
9701 // Source and destination pointer types are always "i8*" for intrinsic. See
9702 // if the size is something we can handle with a single primitive load/store.
9703 // A single load+store correctly handles overlapping memory in the memmove
9705 unsigned Size = MemOpLength->getZExtValue();
9706 if (Size == 0) return MI; // Delete this mem transfer.
9708 if (Size > 8 || (Size&(Size-1)))
9709 return 0; // If not 1/2/4/8 bytes, exit.
9711 // Use an integer load+store unless we can find something better.
9713 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9715 // Memcpy forces the use of i8* for the source and destination. That means
9716 // that if you're using memcpy to move one double around, you'll get a cast
9717 // from double* to i8*. We'd much rather use a double load+store rather than
9718 // an i64 load+store, here because this improves the odds that the source or
9719 // dest address will be promotable. See if we can find a better type than the
9720 // integer datatype.
9721 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9722 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9723 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9724 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9725 // down through these levels if so.
9726 while (!SrcETy->isSingleValueType()) {
9727 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9728 if (STy->getNumElements() == 1)
9729 SrcETy = STy->getElementType(0);
9732 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9733 if (ATy->getNumElements() == 1)
9734 SrcETy = ATy->getElementType();
9741 if (SrcETy->isSingleValueType())
9742 NewPtrTy = PointerType::getUnqual(SrcETy);
9747 // If the memcpy/memmove provides better alignment info than we can
9749 SrcAlign = std::max(SrcAlign, CopyAlign);
9750 DstAlign = std::max(DstAlign, CopyAlign);
9752 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9753 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9754 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9755 InsertNewInstBefore(L, *MI);
9756 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9758 // Set the size of the copy to 0, it will be deleted on the next iteration.
9759 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9763 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9764 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9765 if (MI->getAlignment() < Alignment) {
9766 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9771 // Extract the length and alignment and fill if they are constant.
9772 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9773 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9774 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9776 uint64_t Len = LenC->getZExtValue();
9777 Alignment = MI->getAlignment();
9779 // If the length is zero, this is a no-op
9780 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9782 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9783 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9784 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
9786 Value *Dest = MI->getDest();
9787 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9789 // Alignment 0 is identity for alignment 1 for memset, but not store.
9790 if (Alignment == 0) Alignment = 1;
9792 // Extract the fill value and store.
9793 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9794 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9795 Dest, false, Alignment), *MI);
9797 // Set the size of the copy to 0, it will be deleted on the next iteration.
9798 MI->setLength(Constant::getNullValue(LenC->getType()));
9806 /// visitCallInst - CallInst simplification. This mostly only handles folding
9807 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9808 /// the heavy lifting.
9810 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9811 // If the caller function is nounwind, mark the call as nounwind, even if the
9813 if (CI.getParent()->getParent()->doesNotThrow() &&
9814 !CI.doesNotThrow()) {
9815 CI.setDoesNotThrow();
9821 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9822 if (!II) return visitCallSite(&CI);
9824 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9826 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9827 bool Changed = false;
9829 // memmove/cpy/set of zero bytes is a noop.
9830 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9831 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9833 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9834 if (CI->getZExtValue() == 1) {
9835 // Replace the instruction with just byte operations. We would
9836 // transform other cases to loads/stores, but we don't know if
9837 // alignment is sufficient.
9841 // If we have a memmove and the source operation is a constant global,
9842 // then the source and dest pointers can't alias, so we can change this
9843 // into a call to memcpy.
9844 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9845 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9846 if (GVSrc->isConstant()) {
9847 Module *M = CI.getParent()->getParent()->getParent();
9848 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9850 Tys[0] = CI.getOperand(3)->getType();
9852 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9856 // memmove(x,x,size) -> noop.
9857 if (MMI->getSource() == MMI->getDest())
9858 return EraseInstFromFunction(CI);
9861 // If we can determine a pointer alignment that is bigger than currently
9862 // set, update the alignment.
9863 if (isa<MemTransferInst>(MI)) {
9864 if (Instruction *I = SimplifyMemTransfer(MI))
9866 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9867 if (Instruction *I = SimplifyMemSet(MSI))
9871 if (Changed) return II;
9874 switch (II->getIntrinsicID()) {
9876 case Intrinsic::bswap:
9877 // bswap(bswap(x)) -> x
9878 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9879 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9880 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9882 case Intrinsic::ppc_altivec_lvx:
9883 case Intrinsic::ppc_altivec_lvxl:
9884 case Intrinsic::x86_sse_loadu_ps:
9885 case Intrinsic::x86_sse2_loadu_pd:
9886 case Intrinsic::x86_sse2_loadu_dq:
9887 // Turn PPC lvx -> load if the pointer is known aligned.
9888 // Turn X86 loadups -> load if the pointer is known aligned.
9889 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9890 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9891 PointerType::getUnqual(II->getType()),
9893 return new LoadInst(Ptr);
9896 case Intrinsic::ppc_altivec_stvx:
9897 case Intrinsic::ppc_altivec_stvxl:
9898 // Turn stvx -> store if the pointer is known aligned.
9899 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9900 const Type *OpPtrTy =
9901 PointerType::getUnqual(II->getOperand(1)->getType());
9902 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9903 return new StoreInst(II->getOperand(1), Ptr);
9906 case Intrinsic::x86_sse_storeu_ps:
9907 case Intrinsic::x86_sse2_storeu_pd:
9908 case Intrinsic::x86_sse2_storeu_dq:
9909 // Turn X86 storeu -> store if the pointer is known aligned.
9910 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9911 const Type *OpPtrTy =
9912 PointerType::getUnqual(II->getOperand(2)->getType());
9913 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9914 return new StoreInst(II->getOperand(2), Ptr);
9918 case Intrinsic::x86_sse_cvttss2si: {
9919 // These intrinsics only demands the 0th element of its input vector. If
9920 // we can simplify the input based on that, do so now.
9922 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9923 APInt DemandedElts(VWidth, 1);
9924 APInt UndefElts(VWidth, 0);
9925 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9927 II->setOperand(1, V);
9933 case Intrinsic::ppc_altivec_vperm:
9934 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9935 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9936 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9938 // Check that all of the elements are integer constants or undefs.
9939 bool AllEltsOk = true;
9940 for (unsigned i = 0; i != 16; ++i) {
9941 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9942 !isa<UndefValue>(Mask->getOperand(i))) {
9949 // Cast the input vectors to byte vectors.
9950 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9951 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9952 Value *Result = UndefValue::get(Op0->getType());
9954 // Only extract each element once.
9955 Value *ExtractedElts[32];
9956 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9958 for (unsigned i = 0; i != 16; ++i) {
9959 if (isa<UndefValue>(Mask->getOperand(i)))
9961 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9962 Idx &= 31; // Match the hardware behavior.
9964 if (ExtractedElts[Idx] == 0) {
9966 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
9967 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
9968 InsertNewInstBefore(Elt, CI);
9969 ExtractedElts[Idx] = Elt;
9972 // Insert this value into the result vector.
9973 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9974 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9976 InsertNewInstBefore(cast<Instruction>(Result), CI);
9978 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9983 case Intrinsic::stackrestore: {
9984 // If the save is right next to the restore, remove the restore. This can
9985 // happen when variable allocas are DCE'd.
9986 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9987 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9988 BasicBlock::iterator BI = SS;
9990 return EraseInstFromFunction(CI);
9994 // Scan down this block to see if there is another stack restore in the
9995 // same block without an intervening call/alloca.
9996 BasicBlock::iterator BI = II;
9997 TerminatorInst *TI = II->getParent()->getTerminator();
9998 bool CannotRemove = false;
9999 for (++BI; &*BI != TI; ++BI) {
10000 if (isa<AllocaInst>(BI)) {
10001 CannotRemove = true;
10004 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10005 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10006 // If there is a stackrestore below this one, remove this one.
10007 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10008 return EraseInstFromFunction(CI);
10009 // Otherwise, ignore the intrinsic.
10011 // If we found a non-intrinsic call, we can't remove the stack
10013 CannotRemove = true;
10019 // If the stack restore is in a return/unwind block and if there are no
10020 // allocas or calls between the restore and the return, nuke the restore.
10021 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10022 return EraseInstFromFunction(CI);
10027 return visitCallSite(II);
10030 // InvokeInst simplification
10032 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10033 return visitCallSite(&II);
10036 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
10037 /// passed through the varargs area, we can eliminate the use of the cast.
10038 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10039 const CastInst * const CI,
10040 const TargetData * const TD,
10042 if (!CI->isLosslessCast())
10045 // The size of ByVal arguments is derived from the type, so we
10046 // can't change to a type with a different size. If the size were
10047 // passed explicitly we could avoid this check.
10048 if (!CS.paramHasAttr(ix, Attribute::ByVal))
10051 const Type* SrcTy =
10052 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10053 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10054 if (!SrcTy->isSized() || !DstTy->isSized())
10056 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10061 // visitCallSite - Improvements for call and invoke instructions.
10063 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10064 bool Changed = false;
10066 // If the callee is a constexpr cast of a function, attempt to move the cast
10067 // to the arguments of the call/invoke.
10068 if (transformConstExprCastCall(CS)) return 0;
10070 Value *Callee = CS.getCalledValue();
10072 if (Function *CalleeF = dyn_cast<Function>(Callee))
10073 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10074 Instruction *OldCall = CS.getInstruction();
10075 // If the call and callee calling conventions don't match, this call must
10076 // be unreachable, as the call is undefined.
10077 new StoreInst(ConstantInt::getTrue(*Context),
10078 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
10080 if (!OldCall->use_empty())
10081 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10082 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10083 return EraseInstFromFunction(*OldCall);
10087 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10088 // This instruction is not reachable, just remove it. We insert a store to
10089 // undef so that we know that this code is not reachable, despite the fact
10090 // that we can't modify the CFG here.
10091 new StoreInst(ConstantInt::getTrue(*Context),
10092 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
10093 CS.getInstruction());
10095 if (!CS.getInstruction()->use_empty())
10096 CS.getInstruction()->
10097 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10099 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10100 // Don't break the CFG, insert a dummy cond branch.
10101 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10102 ConstantInt::getTrue(*Context), II);
10104 return EraseInstFromFunction(*CS.getInstruction());
10107 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10108 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10109 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10110 return transformCallThroughTrampoline(CS);
10112 const PointerType *PTy = cast<PointerType>(Callee->getType());
10113 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10114 if (FTy->isVarArg()) {
10115 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10116 // See if we can optimize any arguments passed through the varargs area of
10118 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10119 E = CS.arg_end(); I != E; ++I, ++ix) {
10120 CastInst *CI = dyn_cast<CastInst>(*I);
10121 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10122 *I = CI->getOperand(0);
10128 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10129 // Inline asm calls cannot throw - mark them 'nounwind'.
10130 CS.setDoesNotThrow();
10134 return Changed ? CS.getInstruction() : 0;
10137 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10138 // attempt to move the cast to the arguments of the call/invoke.
10140 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10141 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10142 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10143 if (CE->getOpcode() != Instruction::BitCast ||
10144 !isa<Function>(CE->getOperand(0)))
10146 Function *Callee = cast<Function>(CE->getOperand(0));
10147 Instruction *Caller = CS.getInstruction();
10148 const AttrListPtr &CallerPAL = CS.getAttributes();
10150 // Okay, this is a cast from a function to a different type. Unless doing so
10151 // would cause a type conversion of one of our arguments, change this call to
10152 // be a direct call with arguments casted to the appropriate types.
10154 const FunctionType *FT = Callee->getFunctionType();
10155 const Type *OldRetTy = Caller->getType();
10156 const Type *NewRetTy = FT->getReturnType();
10158 if (isa<StructType>(NewRetTy))
10159 return false; // TODO: Handle multiple return values.
10161 // Check to see if we are changing the return type...
10162 if (OldRetTy != NewRetTy) {
10163 if (Callee->isDeclaration() &&
10164 // Conversion is ok if changing from one pointer type to another or from
10165 // a pointer to an integer of the same size.
10166 !((isa<PointerType>(OldRetTy) || !TD ||
10167 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10168 (isa<PointerType>(NewRetTy) || !TD ||
10169 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10170 return false; // Cannot transform this return value.
10172 if (!Caller->use_empty() &&
10173 // void -> non-void is handled specially
10174 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10175 return false; // Cannot transform this return value.
10177 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10178 Attributes RAttrs = CallerPAL.getRetAttributes();
10179 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10180 return false; // Attribute not compatible with transformed value.
10183 // If the callsite is an invoke instruction, and the return value is used by
10184 // a PHI node in a successor, we cannot change the return type of the call
10185 // because there is no place to put the cast instruction (without breaking
10186 // the critical edge). Bail out in this case.
10187 if (!Caller->use_empty())
10188 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10189 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10191 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10192 if (PN->getParent() == II->getNormalDest() ||
10193 PN->getParent() == II->getUnwindDest())
10197 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10198 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10200 CallSite::arg_iterator AI = CS.arg_begin();
10201 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10202 const Type *ParamTy = FT->getParamType(i);
10203 const Type *ActTy = (*AI)->getType();
10205 if (!CastInst::isCastable(ActTy, ParamTy))
10206 return false; // Cannot transform this parameter value.
10208 if (CallerPAL.getParamAttributes(i + 1)
10209 & Attribute::typeIncompatible(ParamTy))
10210 return false; // Attribute not compatible with transformed value.
10212 // Converting from one pointer type to another or between a pointer and an
10213 // integer of the same size is safe even if we do not have a body.
10214 bool isConvertible = ActTy == ParamTy ||
10215 (TD && ((isa<PointerType>(ParamTy) ||
10216 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10217 (isa<PointerType>(ActTy) ||
10218 ActTy == TD->getIntPtrType(Caller->getContext()))));
10219 if (Callee->isDeclaration() && !isConvertible) return false;
10222 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10223 Callee->isDeclaration())
10224 return false; // Do not delete arguments unless we have a function body.
10226 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10227 !CallerPAL.isEmpty())
10228 // In this case we have more arguments than the new function type, but we
10229 // won't be dropping them. Check that these extra arguments have attributes
10230 // that are compatible with being a vararg call argument.
10231 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10232 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10234 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10235 if (PAttrs & Attribute::VarArgsIncompatible)
10239 // Okay, we decided that this is a safe thing to do: go ahead and start
10240 // inserting cast instructions as necessary...
10241 std::vector<Value*> Args;
10242 Args.reserve(NumActualArgs);
10243 SmallVector<AttributeWithIndex, 8> attrVec;
10244 attrVec.reserve(NumCommonArgs);
10246 // Get any return attributes.
10247 Attributes RAttrs = CallerPAL.getRetAttributes();
10249 // If the return value is not being used, the type may not be compatible
10250 // with the existing attributes. Wipe out any problematic attributes.
10251 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10253 // Add the new return attributes.
10255 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10257 AI = CS.arg_begin();
10258 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10259 const Type *ParamTy = FT->getParamType(i);
10260 if ((*AI)->getType() == ParamTy) {
10261 Args.push_back(*AI);
10263 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10264 false, ParamTy, false);
10265 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10266 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10269 // Add any parameter attributes.
10270 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10271 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10274 // If the function takes more arguments than the call was taking, add them
10276 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10277 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10279 // If we are removing arguments to the function, emit an obnoxious warning...
10280 if (FT->getNumParams() < NumActualArgs) {
10281 if (!FT->isVarArg()) {
10282 errs() << "WARNING: While resolving call to function '"
10283 << Callee->getName() << "' arguments were dropped!\n";
10285 // Add all of the arguments in their promoted form to the arg list...
10286 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10287 const Type *PTy = getPromotedType((*AI)->getType());
10288 if (PTy != (*AI)->getType()) {
10289 // Must promote to pass through va_arg area!
10290 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10292 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10293 InsertNewInstBefore(Cast, *Caller);
10294 Args.push_back(Cast);
10296 Args.push_back(*AI);
10299 // Add any parameter attributes.
10300 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10301 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10306 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10307 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10309 if (NewRetTy == Type::getVoidTy(*Context))
10310 Caller->setName(""); // Void type should not have a name.
10312 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10316 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10317 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10318 Args.begin(), Args.end(),
10319 Caller->getName(), Caller);
10320 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10321 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10323 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10324 Caller->getName(), Caller);
10325 CallInst *CI = cast<CallInst>(Caller);
10326 if (CI->isTailCall())
10327 cast<CallInst>(NC)->setTailCall();
10328 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10329 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10332 // Insert a cast of the return type as necessary.
10334 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10335 if (NV->getType() != Type::getVoidTy(*Context)) {
10336 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10338 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10340 // If this is an invoke instruction, we should insert it after the first
10341 // non-phi, instruction in the normal successor block.
10342 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10343 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10344 InsertNewInstBefore(NC, *I);
10346 // Otherwise, it's a call, just insert cast right after the call instr
10347 InsertNewInstBefore(NC, *Caller);
10349 Worklist.AddUsersToWorkList(*Caller);
10351 NV = UndefValue::get(Caller->getType());
10355 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10356 Caller->replaceAllUsesWith(NV);
10357 Caller->eraseFromParent();
10358 Worklist.Remove(Caller);
10362 // transformCallThroughTrampoline - Turn a call to a function created by the
10363 // init_trampoline intrinsic into a direct call to the underlying function.
10365 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10366 Value *Callee = CS.getCalledValue();
10367 const PointerType *PTy = cast<PointerType>(Callee->getType());
10368 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10369 const AttrListPtr &Attrs = CS.getAttributes();
10371 // If the call already has the 'nest' attribute somewhere then give up -
10372 // otherwise 'nest' would occur twice after splicing in the chain.
10373 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10376 IntrinsicInst *Tramp =
10377 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10379 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10380 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10381 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10383 const AttrListPtr &NestAttrs = NestF->getAttributes();
10384 if (!NestAttrs.isEmpty()) {
10385 unsigned NestIdx = 1;
10386 const Type *NestTy = 0;
10387 Attributes NestAttr = Attribute::None;
10389 // Look for a parameter marked with the 'nest' attribute.
10390 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10391 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10392 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10393 // Record the parameter type and any other attributes.
10395 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10400 Instruction *Caller = CS.getInstruction();
10401 std::vector<Value*> NewArgs;
10402 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10404 SmallVector<AttributeWithIndex, 8> NewAttrs;
10405 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10407 // Insert the nest argument into the call argument list, which may
10408 // mean appending it. Likewise for attributes.
10410 // Add any result attributes.
10411 if (Attributes Attr = Attrs.getRetAttributes())
10412 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10416 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10418 if (Idx == NestIdx) {
10419 // Add the chain argument and attributes.
10420 Value *NestVal = Tramp->getOperand(3);
10421 if (NestVal->getType() != NestTy)
10422 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10423 NewArgs.push_back(NestVal);
10424 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10430 // Add the original argument and attributes.
10431 NewArgs.push_back(*I);
10432 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10434 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10440 // Add any function attributes.
10441 if (Attributes Attr = Attrs.getFnAttributes())
10442 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10444 // The trampoline may have been bitcast to a bogus type (FTy).
10445 // Handle this by synthesizing a new function type, equal to FTy
10446 // with the chain parameter inserted.
10448 std::vector<const Type*> NewTypes;
10449 NewTypes.reserve(FTy->getNumParams()+1);
10451 // Insert the chain's type into the list of parameter types, which may
10452 // mean appending it.
10455 FunctionType::param_iterator I = FTy->param_begin(),
10456 E = FTy->param_end();
10459 if (Idx == NestIdx)
10460 // Add the chain's type.
10461 NewTypes.push_back(NestTy);
10466 // Add the original type.
10467 NewTypes.push_back(*I);
10473 // Replace the trampoline call with a direct call. Let the generic
10474 // code sort out any function type mismatches.
10475 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
10477 Constant *NewCallee =
10478 NestF->getType() == PointerType::getUnqual(NewFTy) ?
10479 NestF : ConstantExpr::getBitCast(NestF,
10480 PointerType::getUnqual(NewFTy));
10481 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10484 Instruction *NewCaller;
10485 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10486 NewCaller = InvokeInst::Create(NewCallee,
10487 II->getNormalDest(), II->getUnwindDest(),
10488 NewArgs.begin(), NewArgs.end(),
10489 Caller->getName(), Caller);
10490 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10491 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10493 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10494 Caller->getName(), Caller);
10495 if (cast<CallInst>(Caller)->isTailCall())
10496 cast<CallInst>(NewCaller)->setTailCall();
10497 cast<CallInst>(NewCaller)->
10498 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10499 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10501 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10502 Caller->replaceAllUsesWith(NewCaller);
10503 Caller->eraseFromParent();
10504 Worklist.Remove(Caller);
10509 // Replace the trampoline call with a direct call. Since there is no 'nest'
10510 // parameter, there is no need to adjust the argument list. Let the generic
10511 // code sort out any function type mismatches.
10512 Constant *NewCallee =
10513 NestF->getType() == PTy ? NestF :
10514 ConstantExpr::getBitCast(NestF, PTy);
10515 CS.setCalledFunction(NewCallee);
10516 return CS.getInstruction();
10519 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10520 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10521 /// and a single binop.
10522 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10523 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10524 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10525 unsigned Opc = FirstInst->getOpcode();
10526 Value *LHSVal = FirstInst->getOperand(0);
10527 Value *RHSVal = FirstInst->getOperand(1);
10529 const Type *LHSType = LHSVal->getType();
10530 const Type *RHSType = RHSVal->getType();
10532 // Scan to see if all operands are the same opcode, all have one use, and all
10533 // kill their operands (i.e. the operands have one use).
10534 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10535 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10536 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10537 // Verify type of the LHS matches so we don't fold cmp's of different
10538 // types or GEP's with different index types.
10539 I->getOperand(0)->getType() != LHSType ||
10540 I->getOperand(1)->getType() != RHSType)
10543 // If they are CmpInst instructions, check their predicates
10544 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10545 if (cast<CmpInst>(I)->getPredicate() !=
10546 cast<CmpInst>(FirstInst)->getPredicate())
10549 // Keep track of which operand needs a phi node.
10550 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10551 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10554 // Otherwise, this is safe to transform!
10556 Value *InLHS = FirstInst->getOperand(0);
10557 Value *InRHS = FirstInst->getOperand(1);
10558 PHINode *NewLHS = 0, *NewRHS = 0;
10560 NewLHS = PHINode::Create(LHSType,
10561 FirstInst->getOperand(0)->getName() + ".pn");
10562 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10563 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10564 InsertNewInstBefore(NewLHS, PN);
10569 NewRHS = PHINode::Create(RHSType,
10570 FirstInst->getOperand(1)->getName() + ".pn");
10571 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10572 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10573 InsertNewInstBefore(NewRHS, PN);
10577 // Add all operands to the new PHIs.
10578 if (NewLHS || NewRHS) {
10579 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10580 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10582 Value *NewInLHS = InInst->getOperand(0);
10583 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10586 Value *NewInRHS = InInst->getOperand(1);
10587 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10592 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10593 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10594 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10595 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10599 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10600 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10602 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10603 FirstInst->op_end());
10604 // This is true if all GEP bases are allocas and if all indices into them are
10606 bool AllBasePointersAreAllocas = true;
10608 // Scan to see if all operands are the same opcode, all have one use, and all
10609 // kill their operands (i.e. the operands have one use).
10610 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10611 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10612 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10613 GEP->getNumOperands() != FirstInst->getNumOperands())
10616 // Keep track of whether or not all GEPs are of alloca pointers.
10617 if (AllBasePointersAreAllocas &&
10618 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10619 !GEP->hasAllConstantIndices()))
10620 AllBasePointersAreAllocas = false;
10622 // Compare the operand lists.
10623 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10624 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10627 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10628 // if one of the PHIs has a constant for the index. The index may be
10629 // substantially cheaper to compute for the constants, so making it a
10630 // variable index could pessimize the path. This also handles the case
10631 // for struct indices, which must always be constant.
10632 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10633 isa<ConstantInt>(GEP->getOperand(op)))
10636 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10638 FixedOperands[op] = 0; // Needs a PHI.
10642 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10643 // bother doing this transformation. At best, this will just save a bit of
10644 // offset calculation, but all the predecessors will have to materialize the
10645 // stack address into a register anyway. We'd actually rather *clone* the
10646 // load up into the predecessors so that we have a load of a gep of an alloca,
10647 // which can usually all be folded into the load.
10648 if (AllBasePointersAreAllocas)
10651 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10652 // that is variable.
10653 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10655 bool HasAnyPHIs = false;
10656 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10657 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10658 Value *FirstOp = FirstInst->getOperand(i);
10659 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10660 FirstOp->getName()+".pn");
10661 InsertNewInstBefore(NewPN, PN);
10663 NewPN->reserveOperandSpace(e);
10664 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10665 OperandPhis[i] = NewPN;
10666 FixedOperands[i] = NewPN;
10671 // Add all operands to the new PHIs.
10673 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10674 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10675 BasicBlock *InBB = PN.getIncomingBlock(i);
10677 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10678 if (PHINode *OpPhi = OperandPhis[op])
10679 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10683 Value *Base = FixedOperands[0];
10684 GetElementPtrInst *GEP =
10685 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10686 FixedOperands.end());
10687 if (cast<GEPOperator>(FirstInst)->isInBounds())
10688 cast<GEPOperator>(GEP)->setIsInBounds(true);
10693 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10694 /// sink the load out of the block that defines it. This means that it must be
10695 /// obvious the value of the load is not changed from the point of the load to
10696 /// the end of the block it is in.
10698 /// Finally, it is safe, but not profitable, to sink a load targetting a
10699 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10701 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10702 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10704 for (++BBI; BBI != E; ++BBI)
10705 if (BBI->mayWriteToMemory())
10708 // Check for non-address taken alloca. If not address-taken already, it isn't
10709 // profitable to do this xform.
10710 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10711 bool isAddressTaken = false;
10712 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10714 if (isa<LoadInst>(UI)) continue;
10715 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10716 // If storing TO the alloca, then the address isn't taken.
10717 if (SI->getOperand(1) == AI) continue;
10719 isAddressTaken = true;
10723 if (!isAddressTaken && AI->isStaticAlloca())
10727 // If this load is a load from a GEP with a constant offset from an alloca,
10728 // then we don't want to sink it. In its present form, it will be
10729 // load [constant stack offset]. Sinking it will cause us to have to
10730 // materialize the stack addresses in each predecessor in a register only to
10731 // do a shared load from register in the successor.
10732 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10733 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10734 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10741 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10742 // operator and they all are only used by the PHI, PHI together their
10743 // inputs, and do the operation once, to the result of the PHI.
10744 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10745 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10747 // Scan the instruction, looking for input operations that can be folded away.
10748 // If all input operands to the phi are the same instruction (e.g. a cast from
10749 // the same type or "+42") we can pull the operation through the PHI, reducing
10750 // code size and simplifying code.
10751 Constant *ConstantOp = 0;
10752 const Type *CastSrcTy = 0;
10753 bool isVolatile = false;
10754 if (isa<CastInst>(FirstInst)) {
10755 CastSrcTy = FirstInst->getOperand(0)->getType();
10756 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10757 // Can fold binop, compare or shift here if the RHS is a constant,
10758 // otherwise call FoldPHIArgBinOpIntoPHI.
10759 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10760 if (ConstantOp == 0)
10761 return FoldPHIArgBinOpIntoPHI(PN);
10762 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10763 isVolatile = LI->isVolatile();
10764 // We can't sink the load if the loaded value could be modified between the
10765 // load and the PHI.
10766 if (LI->getParent() != PN.getIncomingBlock(0) ||
10767 !isSafeAndProfitableToSinkLoad(LI))
10770 // If the PHI is of volatile loads and the load block has multiple
10771 // successors, sinking it would remove a load of the volatile value from
10772 // the path through the other successor.
10774 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10777 } else if (isa<GetElementPtrInst>(FirstInst)) {
10778 return FoldPHIArgGEPIntoPHI(PN);
10780 return 0; // Cannot fold this operation.
10783 // Check to see if all arguments are the same operation.
10784 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10785 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10786 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10787 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10790 if (I->getOperand(0)->getType() != CastSrcTy)
10791 return 0; // Cast operation must match.
10792 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10793 // We can't sink the load if the loaded value could be modified between
10794 // the load and the PHI.
10795 if (LI->isVolatile() != isVolatile ||
10796 LI->getParent() != PN.getIncomingBlock(i) ||
10797 !isSafeAndProfitableToSinkLoad(LI))
10800 // If the PHI is of volatile loads and the load block has multiple
10801 // successors, sinking it would remove a load of the volatile value from
10802 // the path through the other successor.
10804 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10807 } else if (I->getOperand(1) != ConstantOp) {
10812 // Okay, they are all the same operation. Create a new PHI node of the
10813 // correct type, and PHI together all of the LHS's of the instructions.
10814 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10815 PN.getName()+".in");
10816 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10818 Value *InVal = FirstInst->getOperand(0);
10819 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10821 // Add all operands to the new PHI.
10822 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10823 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10824 if (NewInVal != InVal)
10826 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10831 // The new PHI unions all of the same values together. This is really
10832 // common, so we handle it intelligently here for compile-time speed.
10836 InsertNewInstBefore(NewPN, PN);
10840 // Insert and return the new operation.
10841 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10842 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10843 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10844 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10845 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10846 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10847 PhiVal, ConstantOp);
10848 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10850 // If this was a volatile load that we are merging, make sure to loop through
10851 // and mark all the input loads as non-volatile. If we don't do this, we will
10852 // insert a new volatile load and the old ones will not be deletable.
10854 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10855 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10857 return new LoadInst(PhiVal, "", isVolatile);
10860 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10862 static bool DeadPHICycle(PHINode *PN,
10863 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10864 if (PN->use_empty()) return true;
10865 if (!PN->hasOneUse()) return false;
10867 // Remember this node, and if we find the cycle, return.
10868 if (!PotentiallyDeadPHIs.insert(PN))
10871 // Don't scan crazily complex things.
10872 if (PotentiallyDeadPHIs.size() == 16)
10875 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10876 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10881 /// PHIsEqualValue - Return true if this phi node is always equal to
10882 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10883 /// z = some value; x = phi (y, z); y = phi (x, z)
10884 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10885 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10886 // See if we already saw this PHI node.
10887 if (!ValueEqualPHIs.insert(PN))
10890 // Don't scan crazily complex things.
10891 if (ValueEqualPHIs.size() == 16)
10894 // Scan the operands to see if they are either phi nodes or are equal to
10896 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10897 Value *Op = PN->getIncomingValue(i);
10898 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10899 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10901 } else if (Op != NonPhiInVal)
10909 // PHINode simplification
10911 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10912 // If LCSSA is around, don't mess with Phi nodes
10913 if (MustPreserveLCSSA) return 0;
10915 if (Value *V = PN.hasConstantValue())
10916 return ReplaceInstUsesWith(PN, V);
10918 // If all PHI operands are the same operation, pull them through the PHI,
10919 // reducing code size.
10920 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10921 isa<Instruction>(PN.getIncomingValue(1)) &&
10922 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10923 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10924 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10925 // than themselves more than once.
10926 PN.getIncomingValue(0)->hasOneUse())
10927 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10930 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10931 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10932 // PHI)... break the cycle.
10933 if (PN.hasOneUse()) {
10934 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10935 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10936 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10937 PotentiallyDeadPHIs.insert(&PN);
10938 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10939 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10942 // If this phi has a single use, and if that use just computes a value for
10943 // the next iteration of a loop, delete the phi. This occurs with unused
10944 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10945 // common case here is good because the only other things that catch this
10946 // are induction variable analysis (sometimes) and ADCE, which is only run
10948 if (PHIUser->hasOneUse() &&
10949 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10950 PHIUser->use_back() == &PN) {
10951 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10955 // We sometimes end up with phi cycles that non-obviously end up being the
10956 // same value, for example:
10957 // z = some value; x = phi (y, z); y = phi (x, z)
10958 // where the phi nodes don't necessarily need to be in the same block. Do a
10959 // quick check to see if the PHI node only contains a single non-phi value, if
10960 // so, scan to see if the phi cycle is actually equal to that value.
10962 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10963 // Scan for the first non-phi operand.
10964 while (InValNo != NumOperandVals &&
10965 isa<PHINode>(PN.getIncomingValue(InValNo)))
10968 if (InValNo != NumOperandVals) {
10969 Value *NonPhiInVal = PN.getOperand(InValNo);
10971 // Scan the rest of the operands to see if there are any conflicts, if so
10972 // there is no need to recursively scan other phis.
10973 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10974 Value *OpVal = PN.getIncomingValue(InValNo);
10975 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10979 // If we scanned over all operands, then we have one unique value plus
10980 // phi values. Scan PHI nodes to see if they all merge in each other or
10982 if (InValNo == NumOperandVals) {
10983 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10984 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10985 return ReplaceInstUsesWith(PN, NonPhiInVal);
10992 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10993 Value *PtrOp = GEP.getOperand(0);
10994 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10995 // If so, eliminate the noop.
10996 if (GEP.getNumOperands() == 1)
10997 return ReplaceInstUsesWith(GEP, PtrOp);
10999 if (isa<UndefValue>(GEP.getOperand(0)))
11000 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11002 bool HasZeroPointerIndex = false;
11003 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11004 HasZeroPointerIndex = C->isNullValue();
11006 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11007 return ReplaceInstUsesWith(GEP, PtrOp);
11009 // Eliminate unneeded casts for indices.
11011 bool MadeChange = false;
11012 unsigned PtrSize = TD->getPointerSizeInBits();
11014 gep_type_iterator GTI = gep_type_begin(GEP);
11015 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11016 I != E; ++I, ++GTI) {
11017 if (!isa<SequentialType>(*GTI)) continue;
11019 // If we are using a wider index than needed for this platform, shrink it
11020 // to what we need. If narrower, sign-extend it to what we need. This
11021 // explicit cast can make subsequent optimizations more obvious.
11022 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11024 if (OpBits == PtrSize)
11027 Instruction::CastOps Opc =
11028 OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
11029 *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
11032 if (MadeChange) return &GEP;
11035 // Combine Indices - If the source pointer to this getelementptr instruction
11036 // is a getelementptr instruction, combine the indices of the two
11037 // getelementptr instructions into a single instruction.
11039 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11040 // Note that if our source is a gep chain itself that we wait for that
11041 // chain to be resolved before we perform this transformation. This
11042 // avoids us creating a TON of code in some cases.
11044 if (GetElementPtrInst *SrcGEP =
11045 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11046 if (SrcGEP->getNumOperands() == 2)
11047 return 0; // Wait until our source is folded to completion.
11049 SmallVector<Value*, 8> Indices;
11051 // Find out whether the last index in the source GEP is a sequential idx.
11052 bool EndsWithSequential = false;
11053 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11055 EndsWithSequential = !isa<StructType>(*I);
11057 // Can we combine the two pointer arithmetics offsets?
11058 if (EndsWithSequential) {
11059 // Replace: gep (gep %P, long B), long A, ...
11060 // With: T = long A+B; gep %P, T, ...
11063 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11064 Value *GO1 = GEP.getOperand(1);
11065 if (SO1 == Constant::getNullValue(SO1->getType())) {
11067 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11070 // If they aren't the same type, then the input hasn't been processed
11071 // by the loop above yet (which canonicalizes sequential index types to
11072 // intptr_t). Just avoid transforming this until the input has been
11074 if (SO1->getType() != GO1->getType())
11076 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11077 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11079 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11080 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11084 // Update the GEP in place if possible.
11085 if (Src->getNumOperands() == 2) {
11086 GEP.setOperand(0, Src->getOperand(0));
11087 GEP.setOperand(1, Sum);
11090 Indices.append(Src->op_begin()+1, Src->op_end()-1);
11091 Indices.push_back(Sum);
11092 Indices.append(GEP.op_begin()+2, GEP.op_end());
11093 } else if (isa<Constant>(*GEP.idx_begin()) &&
11094 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11095 Src->getNumOperands() != 1) {
11096 // Otherwise we can do the fold if the first index of the GEP is a zero
11097 Indices.append(Src->op_begin()+1, Src->op_end());
11098 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11101 if (!Indices.empty()) {
11102 GetElementPtrInst *NewGEP =
11103 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11104 Indices.end(), GEP.getName());
11105 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
11106 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11111 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11112 if (Value *X = getBitCastOperand(PtrOp)) {
11113 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11115 if (HasZeroPointerIndex) {
11116 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11117 // into : GEP [10 x i8]* X, i32 0, ...
11119 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11120 // into : GEP i8* X, ...
11122 // This occurs when the program declares an array extern like "int X[];"
11123 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11124 const PointerType *XTy = cast<PointerType>(X->getType());
11125 if (const ArrayType *CATy =
11126 dyn_cast<ArrayType>(CPTy->getElementType())) {
11127 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11128 if (CATy->getElementType() == XTy->getElementType()) {
11129 // -> GEP i8* X, ...
11130 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11131 GetElementPtrInst *NewGEP =
11132 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11134 if (cast<GEPOperator>(&GEP)->isInBounds())
11135 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11137 } else if (const ArrayType *XATy =
11138 dyn_cast<ArrayType>(XTy->getElementType())) {
11139 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11140 if (CATy->getElementType() == XATy->getElementType()) {
11141 // -> GEP [10 x i8]* X, i32 0, ...
11142 // At this point, we know that the cast source type is a pointer
11143 // to an array of the same type as the destination pointer
11144 // array. Because the array type is never stepped over (there
11145 // is a leading zero) we can fold the cast into this GEP.
11146 GEP.setOperand(0, X);
11151 } else if (GEP.getNumOperands() == 2) {
11152 // Transform things like:
11153 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11154 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11155 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11156 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11157 if (TD && isa<ArrayType>(SrcElTy) &&
11158 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11159 TD->getTypeAllocSize(ResElTy)) {
11161 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11162 Idx[1] = GEP.getOperand(1);
11163 GetElementPtrInst *NewGEP =
11164 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11165 if (cast<GEPOperator>(&GEP)->isInBounds())
11166 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11167 Value *V = InsertNewInstBefore(NewGEP, GEP);
11168 // V and GEP are both pointer types --> BitCast
11169 return new BitCastInst(V, GEP.getType());
11172 // Transform things like:
11173 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11174 // (where tmp = 8*tmp2) into:
11175 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11177 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11178 uint64_t ArrayEltSize =
11179 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11181 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11182 // allow either a mul, shift, or constant here.
11184 ConstantInt *Scale = 0;
11185 if (ArrayEltSize == 1) {
11186 NewIdx = GEP.getOperand(1);
11187 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11188 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11189 NewIdx = ConstantInt::get(CI->getType(), 1);
11191 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11192 if (Inst->getOpcode() == Instruction::Shl &&
11193 isa<ConstantInt>(Inst->getOperand(1))) {
11194 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11195 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11196 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11198 NewIdx = Inst->getOperand(0);
11199 } else if (Inst->getOpcode() == Instruction::Mul &&
11200 isa<ConstantInt>(Inst->getOperand(1))) {
11201 Scale = cast<ConstantInt>(Inst->getOperand(1));
11202 NewIdx = Inst->getOperand(0);
11206 // If the index will be to exactly the right offset with the scale taken
11207 // out, perform the transformation. Note, we don't know whether Scale is
11208 // signed or not. We'll use unsigned version of division/modulo
11209 // operation after making sure Scale doesn't have the sign bit set.
11210 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11211 Scale->getZExtValue() % ArrayEltSize == 0) {
11212 Scale = ConstantInt::get(Scale->getType(),
11213 Scale->getZExtValue() / ArrayEltSize);
11214 if (Scale->getZExtValue() != 1) {
11215 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11217 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11218 NewIdx = InsertNewInstBefore(Sc, GEP);
11221 // Insert the new GEP instruction.
11223 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11225 Instruction *NewGEP =
11226 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11227 if (cast<GEPOperator>(&GEP)->isInBounds())
11228 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11229 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11230 // The NewGEP must be pointer typed, so must the old one -> BitCast
11231 return new BitCastInst(NewGEP, GEP.getType());
11237 /// See if we can simplify:
11238 /// X = bitcast A* to B*
11239 /// Y = gep X, <...constant indices...>
11240 /// into a gep of the original struct. This is important for SROA and alias
11241 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11242 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11244 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11245 // Determine how much the GEP moves the pointer. We are guaranteed to get
11246 // a constant back from EmitGEPOffset.
11247 ConstantInt *OffsetV =
11248 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11249 int64_t Offset = OffsetV->getSExtValue();
11251 // If this GEP instruction doesn't move the pointer, just replace the GEP
11252 // with a bitcast of the real input to the dest type.
11254 // If the bitcast is of an allocation, and the allocation will be
11255 // converted to match the type of the cast, don't touch this.
11256 if (isa<AllocationInst>(BCI->getOperand(0))) {
11257 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11258 if (Instruction *I = visitBitCast(*BCI)) {
11261 BCI->getParent()->getInstList().insert(BCI, I);
11262 ReplaceInstUsesWith(*BCI, I);
11267 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11270 // Otherwise, if the offset is non-zero, we need to find out if there is a
11271 // field at Offset in 'A's type. If so, we can pull the cast through the
11273 SmallVector<Value*, 8> NewIndices;
11275 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11276 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11277 Instruction *NGEP =
11278 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11280 if (NGEP->getType() == GEP.getType()) return NGEP;
11281 if (cast<GEPOperator>(&GEP)->isInBounds())
11282 cast<GEPOperator>(NGEP)->setIsInBounds(true);
11283 InsertNewInstBefore(NGEP, GEP);
11284 NGEP->takeName(&GEP);
11285 return new BitCastInst(NGEP, GEP.getType());
11293 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11294 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11295 if (AI.isArrayAllocation()) { // Check C != 1
11296 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11297 const Type *NewTy =
11298 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11299 AllocationInst *New = 0;
11301 // Create and insert the replacement instruction...
11302 if (isa<MallocInst>(AI))
11303 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11305 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11306 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11309 InsertNewInstBefore(New, AI);
11311 // Scan to the end of the allocation instructions, to skip over a block of
11312 // allocas if possible...also skip interleaved debug info
11314 BasicBlock::iterator It = New;
11315 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11317 // Now that I is pointing to the first non-allocation-inst in the block,
11318 // insert our getelementptr instruction...
11320 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11324 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11325 New->getName()+".sub", It);
11326 cast<GEPOperator>(V)->setIsInBounds(true);
11328 // Now make everything use the getelementptr instead of the original
11330 return ReplaceInstUsesWith(AI, V);
11331 } else if (isa<UndefValue>(AI.getArraySize())) {
11332 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11336 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11337 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11338 // Note that we only do this for alloca's, because malloc should allocate
11339 // and return a unique pointer, even for a zero byte allocation.
11340 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11341 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11343 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11344 if (AI.getAlignment() == 0)
11345 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11351 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11352 Value *Op = FI.getOperand(0);
11354 // free undef -> unreachable.
11355 if (isa<UndefValue>(Op)) {
11356 // Insert a new store to null because we cannot modify the CFG here.
11357 new StoreInst(ConstantInt::getTrue(*Context),
11358 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11359 return EraseInstFromFunction(FI);
11362 // If we have 'free null' delete the instruction. This can happen in stl code
11363 // when lots of inlining happens.
11364 if (isa<ConstantPointerNull>(Op))
11365 return EraseInstFromFunction(FI);
11367 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11368 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11369 FI.setOperand(0, CI->getOperand(0));
11373 // Change free (gep X, 0,0,0,0) into free(X)
11374 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11375 if (GEPI->hasAllZeroIndices()) {
11376 Worklist.Add(GEPI);
11377 FI.setOperand(0, GEPI->getOperand(0));
11382 // Change free(malloc) into nothing, if the malloc has a single use.
11383 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11384 if (MI->hasOneUse()) {
11385 EraseInstFromFunction(FI);
11386 return EraseInstFromFunction(*MI);
11393 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11394 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11395 const TargetData *TD) {
11396 User *CI = cast<User>(LI.getOperand(0));
11397 Value *CastOp = CI->getOperand(0);
11398 LLVMContext *Context = IC.getContext();
11401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11402 // Instead of loading constant c string, use corresponding integer value
11403 // directly if string length is small enough.
11405 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11406 unsigned len = Str.length();
11407 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11408 unsigned numBits = Ty->getPrimitiveSizeInBits();
11409 // Replace LI with immediate integer store.
11410 if ((numBits >> 3) == len + 1) {
11411 APInt StrVal(numBits, 0);
11412 APInt SingleChar(numBits, 0);
11413 if (TD->isLittleEndian()) {
11414 for (signed i = len-1; i >= 0; i--) {
11415 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11416 StrVal = (StrVal << 8) | SingleChar;
11419 for (unsigned i = 0; i < len; i++) {
11420 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11421 StrVal = (StrVal << 8) | SingleChar;
11423 // Append NULL at the end.
11425 StrVal = (StrVal << 8) | SingleChar;
11427 Value *NL = ConstantInt::get(*Context, StrVal);
11428 return IC.ReplaceInstUsesWith(LI, NL);
11434 const PointerType *DestTy = cast<PointerType>(CI->getType());
11435 const Type *DestPTy = DestTy->getElementType();
11436 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11438 // If the address spaces don't match, don't eliminate the cast.
11439 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11442 const Type *SrcPTy = SrcTy->getElementType();
11444 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11445 isa<VectorType>(DestPTy)) {
11446 // If the source is an array, the code below will not succeed. Check to
11447 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11449 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11450 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11451 if (ASrcTy->getNumElements() != 0) {
11453 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11454 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11455 SrcTy = cast<PointerType>(CastOp->getType());
11456 SrcPTy = SrcTy->getElementType();
11459 if (IC.getTargetData() &&
11460 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11461 isa<VectorType>(SrcPTy)) &&
11462 // Do not allow turning this into a load of an integer, which is then
11463 // casted to a pointer, this pessimizes pointer analysis a lot.
11464 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11465 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11466 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11468 // Okay, we are casting from one integer or pointer type to another of
11469 // the same size. Instead of casting the pointer before the load, cast
11470 // the result of the loaded value.
11471 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11473 LI.isVolatile()),LI);
11474 // Now cast the result of the load.
11475 return new BitCastInst(NewLoad, LI.getType());
11482 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11483 Value *Op = LI.getOperand(0);
11485 // Attempt to improve the alignment.
11487 unsigned KnownAlign =
11488 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11490 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11491 LI.getAlignment()))
11492 LI.setAlignment(KnownAlign);
11495 // load (cast X) --> cast (load X) iff safe
11496 if (isa<CastInst>(Op))
11497 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11500 // None of the following transforms are legal for volatile loads.
11501 if (LI.isVolatile()) return 0;
11503 // Do really simple store-to-load forwarding and load CSE, to catch cases
11504 // where there are several consequtive memory accesses to the same location,
11505 // separated by a few arithmetic operations.
11506 BasicBlock::iterator BBI = &LI;
11507 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11508 return ReplaceInstUsesWith(LI, AvailableVal);
11510 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11511 const Value *GEPI0 = GEPI->getOperand(0);
11512 // TODO: Consider a target hook for valid address spaces for this xform.
11513 if (isa<ConstantPointerNull>(GEPI0) &&
11514 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11515 // Insert a new store to null instruction before the load to indicate
11516 // that this code is not reachable. We do this instead of inserting
11517 // an unreachable instruction directly because we cannot modify the
11519 new StoreInst(UndefValue::get(LI.getType()),
11520 Constant::getNullValue(Op->getType()), &LI);
11521 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11525 if (Constant *C = dyn_cast<Constant>(Op)) {
11526 // load null/undef -> undef
11527 // TODO: Consider a target hook for valid address spaces for this xform.
11528 if (isa<UndefValue>(C) || (C->isNullValue() &&
11529 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11530 // Insert a new store to null instruction before the load to indicate that
11531 // this code is not reachable. We do this instead of inserting an
11532 // unreachable instruction directly because we cannot modify the CFG.
11533 new StoreInst(UndefValue::get(LI.getType()),
11534 Constant::getNullValue(Op->getType()), &LI);
11535 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11538 // Instcombine load (constant global) into the value loaded.
11539 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11540 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11541 return ReplaceInstUsesWith(LI, GV->getInitializer());
11543 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11544 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11545 if (CE->getOpcode() == Instruction::GetElementPtr) {
11546 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11547 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11549 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11551 return ReplaceInstUsesWith(LI, V);
11552 if (CE->getOperand(0)->isNullValue()) {
11553 // Insert a new store to null instruction before the load to indicate
11554 // that this code is not reachable. We do this instead of inserting
11555 // an unreachable instruction directly because we cannot modify the
11557 new StoreInst(UndefValue::get(LI.getType()),
11558 Constant::getNullValue(Op->getType()), &LI);
11559 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11562 } else if (CE->isCast()) {
11563 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11569 // If this load comes from anywhere in a constant global, and if the global
11570 // is all undef or zero, we know what it loads.
11571 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11572 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11573 if (GV->getInitializer()->isNullValue())
11574 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11575 else if (isa<UndefValue>(GV->getInitializer()))
11576 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11580 if (Op->hasOneUse()) {
11581 // Change select and PHI nodes to select values instead of addresses: this
11582 // helps alias analysis out a lot, allows many others simplifications, and
11583 // exposes redundancy in the code.
11585 // Note that we cannot do the transformation unless we know that the
11586 // introduced loads cannot trap! Something like this is valid as long as
11587 // the condition is always false: load (select bool %C, int* null, int* %G),
11588 // but it would not be valid if we transformed it to load from null
11589 // unconditionally.
11591 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11592 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11593 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11594 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11595 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11596 SI->getOperand(1)->getName()+".val"), LI);
11597 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11598 SI->getOperand(2)->getName()+".val"), LI);
11599 return SelectInst::Create(SI->getCondition(), V1, V2);
11602 // load (select (cond, null, P)) -> load P
11603 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11604 if (C->isNullValue()) {
11605 LI.setOperand(0, SI->getOperand(2));
11609 // load (select (cond, P, null)) -> load P
11610 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11611 if (C->isNullValue()) {
11612 LI.setOperand(0, SI->getOperand(1));
11620 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11621 /// when possible. This makes it generally easy to do alias analysis and/or
11622 /// SROA/mem2reg of the memory object.
11623 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11624 User *CI = cast<User>(SI.getOperand(1));
11625 Value *CastOp = CI->getOperand(0);
11627 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11628 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11629 if (SrcTy == 0) return 0;
11631 const Type *SrcPTy = SrcTy->getElementType();
11633 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11636 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11637 /// to its first element. This allows us to handle things like:
11638 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11639 /// on 32-bit hosts.
11640 SmallVector<Value*, 4> NewGEPIndices;
11642 // If the source is an array, the code below will not succeed. Check to
11643 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11645 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11646 // Index through pointer.
11647 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11648 NewGEPIndices.push_back(Zero);
11651 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11652 if (!STy->getNumElements()) /* Struct can be empty {} */
11654 NewGEPIndices.push_back(Zero);
11655 SrcPTy = STy->getElementType(0);
11656 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11657 NewGEPIndices.push_back(Zero);
11658 SrcPTy = ATy->getElementType();
11664 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11667 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11670 // If the pointers point into different address spaces or if they point to
11671 // values with different sizes, we can't do the transformation.
11672 if (!IC.getTargetData() ||
11673 SrcTy->getAddressSpace() !=
11674 cast<PointerType>(CI->getType())->getAddressSpace() ||
11675 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11676 IC.getTargetData()->getTypeSizeInBits(DestPTy))
11679 // Okay, we are casting from one integer or pointer type to another of
11680 // the same size. Instead of casting the pointer before
11681 // the store, cast the value to be stored.
11683 Value *SIOp0 = SI.getOperand(0);
11684 Instruction::CastOps opcode = Instruction::BitCast;
11685 const Type* CastSrcTy = SIOp0->getType();
11686 const Type* CastDstTy = SrcPTy;
11687 if (isa<PointerType>(CastDstTy)) {
11688 if (CastSrcTy->isInteger())
11689 opcode = Instruction::IntToPtr;
11690 } else if (isa<IntegerType>(CastDstTy)) {
11691 if (isa<PointerType>(SIOp0->getType()))
11692 opcode = Instruction::PtrToInt;
11695 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11696 // emit a GEP to index into its first field.
11697 if (!NewGEPIndices.empty()) {
11698 if (Constant *C = dyn_cast<Constant>(CastOp))
11699 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11700 NewGEPIndices.size());
11702 CastOp = IC.InsertNewInstBefore(
11703 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11704 NewGEPIndices.end()), SI);
11705 cast<GEPOperator>(CastOp)->setIsInBounds(true);
11708 if (Constant *C = dyn_cast<Constant>(SIOp0))
11709 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11711 NewCast = IC.InsertNewInstBefore(
11712 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11714 return new StoreInst(NewCast, CastOp);
11717 /// equivalentAddressValues - Test if A and B will obviously have the same
11718 /// value. This includes recognizing that %t0 and %t1 will have the same
11719 /// value in code like this:
11720 /// %t0 = getelementptr \@a, 0, 3
11721 /// store i32 0, i32* %t0
11722 /// %t1 = getelementptr \@a, 0, 3
11723 /// %t2 = load i32* %t1
11725 static bool equivalentAddressValues(Value *A, Value *B) {
11726 // Test if the values are trivially equivalent.
11727 if (A == B) return true;
11729 // Test if the values come form identical arithmetic instructions.
11730 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11731 // its only used to compare two uses within the same basic block, which
11732 // means that they'll always either have the same value or one of them
11733 // will have an undefined value.
11734 if (isa<BinaryOperator>(A) ||
11735 isa<CastInst>(A) ||
11737 isa<GetElementPtrInst>(A))
11738 if (Instruction *BI = dyn_cast<Instruction>(B))
11739 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11742 // Otherwise they may not be equivalent.
11746 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11747 // return the llvm.dbg.declare.
11748 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11749 if (!V->hasNUses(2))
11751 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11753 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11755 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11756 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11763 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11764 Value *Val = SI.getOperand(0);
11765 Value *Ptr = SI.getOperand(1);
11767 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11768 EraseInstFromFunction(SI);
11773 // If the RHS is an alloca with a single use, zapify the store, making the
11775 // If the RHS is an alloca with a two uses, the other one being a
11776 // llvm.dbg.declare, zapify the store and the declare, making the
11777 // alloca dead. We must do this to prevent declare's from affecting
11779 if (!SI.isVolatile()) {
11780 if (Ptr->hasOneUse()) {
11781 if (isa<AllocaInst>(Ptr)) {
11782 EraseInstFromFunction(SI);
11786 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11787 if (isa<AllocaInst>(GEP->getOperand(0))) {
11788 if (GEP->getOperand(0)->hasOneUse()) {
11789 EraseInstFromFunction(SI);
11793 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11794 EraseInstFromFunction(*DI);
11795 EraseInstFromFunction(SI);
11802 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11803 EraseInstFromFunction(*DI);
11804 EraseInstFromFunction(SI);
11810 // Attempt to improve the alignment.
11812 unsigned KnownAlign =
11813 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11815 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11816 SI.getAlignment()))
11817 SI.setAlignment(KnownAlign);
11820 // Do really simple DSE, to catch cases where there are several consecutive
11821 // stores to the same location, separated by a few arithmetic operations. This
11822 // situation often occurs with bitfield accesses.
11823 BasicBlock::iterator BBI = &SI;
11824 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11827 // Don't count debug info directives, lest they affect codegen,
11828 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11829 // It is necessary for correctness to skip those that feed into a
11830 // llvm.dbg.declare, as these are not present when debugging is off.
11831 if (isa<DbgInfoIntrinsic>(BBI) ||
11832 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11837 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11838 // Prev store isn't volatile, and stores to the same location?
11839 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11840 SI.getOperand(1))) {
11843 EraseInstFromFunction(*PrevSI);
11849 // If this is a load, we have to stop. However, if the loaded value is from
11850 // the pointer we're loading and is producing the pointer we're storing,
11851 // then *this* store is dead (X = load P; store X -> P).
11852 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11853 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11854 !SI.isVolatile()) {
11855 EraseInstFromFunction(SI);
11859 // Otherwise, this is a load from some other location. Stores before it
11860 // may not be dead.
11864 // Don't skip over loads or things that can modify memory.
11865 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11870 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11872 // store X, null -> turns into 'unreachable' in SimplifyCFG
11873 if (isa<ConstantPointerNull>(Ptr) &&
11874 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11875 if (!isa<UndefValue>(Val)) {
11876 SI.setOperand(0, UndefValue::get(Val->getType()));
11877 if (Instruction *U = dyn_cast<Instruction>(Val))
11878 Worklist.Add(U); // Dropped a use.
11881 return 0; // Do not modify these!
11884 // store undef, Ptr -> noop
11885 if (isa<UndefValue>(Val)) {
11886 EraseInstFromFunction(SI);
11891 // If the pointer destination is a cast, see if we can fold the cast into the
11893 if (isa<CastInst>(Ptr))
11894 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11896 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11898 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11902 // If this store is the last instruction in the basic block (possibly
11903 // excepting debug info instructions and the pointer bitcasts that feed
11904 // into them), and if the block ends with an unconditional branch, try
11905 // to move it to the successor block.
11909 } while (isa<DbgInfoIntrinsic>(BBI) ||
11910 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11911 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11912 if (BI->isUnconditional())
11913 if (SimplifyStoreAtEndOfBlock(SI))
11914 return 0; // xform done!
11919 /// SimplifyStoreAtEndOfBlock - Turn things like:
11920 /// if () { *P = v1; } else { *P = v2 }
11921 /// into a phi node with a store in the successor.
11923 /// Simplify things like:
11924 /// *P = v1; if () { *P = v2; }
11925 /// into a phi node with a store in the successor.
11927 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11928 BasicBlock *StoreBB = SI.getParent();
11930 // Check to see if the successor block has exactly two incoming edges. If
11931 // so, see if the other predecessor contains a store to the same location.
11932 // if so, insert a PHI node (if needed) and move the stores down.
11933 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11935 // Determine whether Dest has exactly two predecessors and, if so, compute
11936 // the other predecessor.
11937 pred_iterator PI = pred_begin(DestBB);
11938 BasicBlock *OtherBB = 0;
11939 if (*PI != StoreBB)
11942 if (PI == pred_end(DestBB))
11945 if (*PI != StoreBB) {
11950 if (++PI != pred_end(DestBB))
11953 // Bail out if all the relevant blocks aren't distinct (this can happen,
11954 // for example, if SI is in an infinite loop)
11955 if (StoreBB == DestBB || OtherBB == DestBB)
11958 // Verify that the other block ends in a branch and is not otherwise empty.
11959 BasicBlock::iterator BBI = OtherBB->getTerminator();
11960 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11961 if (!OtherBr || BBI == OtherBB->begin())
11964 // If the other block ends in an unconditional branch, check for the 'if then
11965 // else' case. there is an instruction before the branch.
11966 StoreInst *OtherStore = 0;
11967 if (OtherBr->isUnconditional()) {
11969 // Skip over debugging info.
11970 while (isa<DbgInfoIntrinsic>(BBI) ||
11971 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11972 if (BBI==OtherBB->begin())
11976 // If this isn't a store, or isn't a store to the same location, bail out.
11977 OtherStore = dyn_cast<StoreInst>(BBI);
11978 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11981 // Otherwise, the other block ended with a conditional branch. If one of the
11982 // destinations is StoreBB, then we have the if/then case.
11983 if (OtherBr->getSuccessor(0) != StoreBB &&
11984 OtherBr->getSuccessor(1) != StoreBB)
11987 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11988 // if/then triangle. See if there is a store to the same ptr as SI that
11989 // lives in OtherBB.
11991 // Check to see if we find the matching store.
11992 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11993 if (OtherStore->getOperand(1) != SI.getOperand(1))
11997 // If we find something that may be using or overwriting the stored
11998 // value, or if we run out of instructions, we can't do the xform.
11999 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12000 BBI == OtherBB->begin())
12004 // In order to eliminate the store in OtherBr, we have to
12005 // make sure nothing reads or overwrites the stored value in
12007 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12008 // FIXME: This should really be AA driven.
12009 if (I->mayReadFromMemory() || I->mayWriteToMemory())
12014 // Insert a PHI node now if we need it.
12015 Value *MergedVal = OtherStore->getOperand(0);
12016 if (MergedVal != SI.getOperand(0)) {
12017 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12018 PN->reserveOperandSpace(2);
12019 PN->addIncoming(SI.getOperand(0), SI.getParent());
12020 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12021 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12024 // Advance to a place where it is safe to insert the new store and
12026 BBI = DestBB->getFirstNonPHI();
12027 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12028 OtherStore->isVolatile()), *BBI);
12030 // Nuke the old stores.
12031 EraseInstFromFunction(SI);
12032 EraseInstFromFunction(*OtherStore);
12038 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12039 // Change br (not X), label True, label False to: br X, label False, True
12041 BasicBlock *TrueDest;
12042 BasicBlock *FalseDest;
12043 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12044 !isa<Constant>(X)) {
12045 // Swap Destinations and condition...
12046 BI.setCondition(X);
12047 BI.setSuccessor(0, FalseDest);
12048 BI.setSuccessor(1, TrueDest);
12052 // Cannonicalize fcmp_one -> fcmp_oeq
12053 FCmpInst::Predicate FPred; Value *Y;
12054 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12055 TrueDest, FalseDest)) &&
12056 BI.getCondition()->hasOneUse())
12057 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12058 FPred == FCmpInst::FCMP_OGE) {
12059 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12060 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12062 // Swap Destinations and condition.
12063 BI.setSuccessor(0, FalseDest);
12064 BI.setSuccessor(1, TrueDest);
12065 Worklist.Add(Cond);
12069 // Cannonicalize icmp_ne -> icmp_eq
12070 ICmpInst::Predicate IPred;
12071 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12072 TrueDest, FalseDest)) &&
12073 BI.getCondition()->hasOneUse())
12074 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12075 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12076 IPred == ICmpInst::ICMP_SGE) {
12077 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12078 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12079 // Swap Destinations and condition.
12080 BI.setSuccessor(0, FalseDest);
12081 BI.setSuccessor(1, TrueDest);
12082 Worklist.Add(Cond);
12089 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12090 Value *Cond = SI.getCondition();
12091 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12092 if (I->getOpcode() == Instruction::Add)
12093 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12094 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12095 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12097 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12099 SI.setOperand(0, I->getOperand(0));
12107 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12108 Value *Agg = EV.getAggregateOperand();
12110 if (!EV.hasIndices())
12111 return ReplaceInstUsesWith(EV, Agg);
12113 if (Constant *C = dyn_cast<Constant>(Agg)) {
12114 if (isa<UndefValue>(C))
12115 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12117 if (isa<ConstantAggregateZero>(C))
12118 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12120 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12121 // Extract the element indexed by the first index out of the constant
12122 Value *V = C->getOperand(*EV.idx_begin());
12123 if (EV.getNumIndices() > 1)
12124 // Extract the remaining indices out of the constant indexed by the
12126 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12128 return ReplaceInstUsesWith(EV, V);
12130 return 0; // Can't handle other constants
12132 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12133 // We're extracting from an insertvalue instruction, compare the indices
12134 const unsigned *exti, *exte, *insi, *inse;
12135 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12136 exte = EV.idx_end(), inse = IV->idx_end();
12137 exti != exte && insi != inse;
12139 if (*insi != *exti)
12140 // The insert and extract both reference distinctly different elements.
12141 // This means the extract is not influenced by the insert, and we can
12142 // replace the aggregate operand of the extract with the aggregate
12143 // operand of the insert. i.e., replace
12144 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12145 // %E = extractvalue { i32, { i32 } } %I, 0
12147 // %E = extractvalue { i32, { i32 } } %A, 0
12148 return ExtractValueInst::Create(IV->getAggregateOperand(),
12149 EV.idx_begin(), EV.idx_end());
12151 if (exti == exte && insi == inse)
12152 // Both iterators are at the end: Index lists are identical. Replace
12153 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12154 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12156 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12157 if (exti == exte) {
12158 // The extract list is a prefix of the insert list. i.e. replace
12159 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12160 // %E = extractvalue { i32, { i32 } } %I, 1
12162 // %X = extractvalue { i32, { i32 } } %A, 1
12163 // %E = insertvalue { i32 } %X, i32 42, 0
12164 // by switching the order of the insert and extract (though the
12165 // insertvalue should be left in, since it may have other uses).
12166 Value *NewEV = InsertNewInstBefore(
12167 ExtractValueInst::Create(IV->getAggregateOperand(),
12168 EV.idx_begin(), EV.idx_end()),
12170 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12174 // The insert list is a prefix of the extract list
12175 // We can simply remove the common indices from the extract and make it
12176 // operate on the inserted value instead of the insertvalue result.
12178 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12179 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12181 // %E extractvalue { i32 } { i32 42 }, 0
12182 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12185 // Can't simplify extracts from other values. Note that nested extracts are
12186 // already simplified implicitely by the above (extract ( extract (insert) )
12187 // will be translated into extract ( insert ( extract ) ) first and then just
12188 // the value inserted, if appropriate).
12192 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12193 /// is to leave as a vector operation.
12194 static bool CheapToScalarize(Value *V, bool isConstant) {
12195 if (isa<ConstantAggregateZero>(V))
12197 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12198 if (isConstant) return true;
12199 // If all elts are the same, we can extract.
12200 Constant *Op0 = C->getOperand(0);
12201 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12202 if (C->getOperand(i) != Op0)
12206 Instruction *I = dyn_cast<Instruction>(V);
12207 if (!I) return false;
12209 // Insert element gets simplified to the inserted element or is deleted if
12210 // this is constant idx extract element and its a constant idx insertelt.
12211 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12212 isa<ConstantInt>(I->getOperand(2)))
12214 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12216 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12217 if (BO->hasOneUse() &&
12218 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12219 CheapToScalarize(BO->getOperand(1), isConstant)))
12221 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12222 if (CI->hasOneUse() &&
12223 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12224 CheapToScalarize(CI->getOperand(1), isConstant)))
12230 /// Read and decode a shufflevector mask.
12232 /// It turns undef elements into values that are larger than the number of
12233 /// elements in the input.
12234 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12235 unsigned NElts = SVI->getType()->getNumElements();
12236 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12237 return std::vector<unsigned>(NElts, 0);
12238 if (isa<UndefValue>(SVI->getOperand(2)))
12239 return std::vector<unsigned>(NElts, 2*NElts);
12241 std::vector<unsigned> Result;
12242 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12243 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12244 if (isa<UndefValue>(*i))
12245 Result.push_back(NElts*2); // undef -> 8
12247 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12251 /// FindScalarElement - Given a vector and an element number, see if the scalar
12252 /// value is already around as a register, for example if it were inserted then
12253 /// extracted from the vector.
12254 static Value *FindScalarElement(Value *V, unsigned EltNo,
12255 LLVMContext *Context) {
12256 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12257 const VectorType *PTy = cast<VectorType>(V->getType());
12258 unsigned Width = PTy->getNumElements();
12259 if (EltNo >= Width) // Out of range access.
12260 return UndefValue::get(PTy->getElementType());
12262 if (isa<UndefValue>(V))
12263 return UndefValue::get(PTy->getElementType());
12264 else if (isa<ConstantAggregateZero>(V))
12265 return Constant::getNullValue(PTy->getElementType());
12266 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12267 return CP->getOperand(EltNo);
12268 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12269 // If this is an insert to a variable element, we don't know what it is.
12270 if (!isa<ConstantInt>(III->getOperand(2)))
12272 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12274 // If this is an insert to the element we are looking for, return the
12276 if (EltNo == IIElt)
12277 return III->getOperand(1);
12279 // Otherwise, the insertelement doesn't modify the value, recurse on its
12281 return FindScalarElement(III->getOperand(0), EltNo, Context);
12282 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12283 unsigned LHSWidth =
12284 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12285 unsigned InEl = getShuffleMask(SVI)[EltNo];
12286 if (InEl < LHSWidth)
12287 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12288 else if (InEl < LHSWidth*2)
12289 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12291 return UndefValue::get(PTy->getElementType());
12294 // Otherwise, we don't know.
12298 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12299 // If vector val is undef, replace extract with scalar undef.
12300 if (isa<UndefValue>(EI.getOperand(0)))
12301 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12303 // If vector val is constant 0, replace extract with scalar 0.
12304 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12305 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12307 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12308 // If vector val is constant with all elements the same, replace EI with
12309 // that element. When the elements are not identical, we cannot replace yet
12310 // (we do that below, but only when the index is constant).
12311 Constant *op0 = C->getOperand(0);
12312 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12313 if (C->getOperand(i) != op0) {
12318 return ReplaceInstUsesWith(EI, op0);
12321 // If extracting a specified index from the vector, see if we can recursively
12322 // find a previously computed scalar that was inserted into the vector.
12323 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12324 unsigned IndexVal = IdxC->getZExtValue();
12325 unsigned VectorWidth =
12326 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12328 // If this is extracting an invalid index, turn this into undef, to avoid
12329 // crashing the code below.
12330 if (IndexVal >= VectorWidth)
12331 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12333 // This instruction only demands the single element from the input vector.
12334 // If the input vector has a single use, simplify it based on this use
12336 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12337 APInt UndefElts(VectorWidth, 0);
12338 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12339 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12340 DemandedMask, UndefElts)) {
12341 EI.setOperand(0, V);
12346 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12347 return ReplaceInstUsesWith(EI, Elt);
12349 // If the this extractelement is directly using a bitcast from a vector of
12350 // the same number of elements, see if we can find the source element from
12351 // it. In this case, we will end up needing to bitcast the scalars.
12352 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12353 if (const VectorType *VT =
12354 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12355 if (VT->getNumElements() == VectorWidth)
12356 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12357 IndexVal, Context))
12358 return new BitCastInst(Elt, EI.getType());
12362 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12363 if (I->hasOneUse()) {
12364 // Push extractelement into predecessor operation if legal and
12365 // profitable to do so
12366 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12367 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12368 if (CheapToScalarize(BO, isConstantElt)) {
12369 ExtractElementInst *newEI0 =
12370 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
12371 EI.getName()+".lhs");
12372 ExtractElementInst *newEI1 =
12373 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
12374 EI.getName()+".rhs");
12375 InsertNewInstBefore(newEI0, EI);
12376 InsertNewInstBefore(newEI1, EI);
12377 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12379 } else if (isa<LoadInst>(I)) {
12381 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12382 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12383 PointerType::get(EI.getType(), AS),*I);
12384 GetElementPtrInst *GEP =
12385 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12386 cast<GEPOperator>(GEP)->setIsInBounds(true);
12387 InsertNewInstBefore(GEP, *I);
12388 LoadInst* Load = new LoadInst(GEP, "tmp");
12389 InsertNewInstBefore(Load, *I);
12390 return ReplaceInstUsesWith(EI, Load);
12393 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12394 // Extracting the inserted element?
12395 if (IE->getOperand(2) == EI.getOperand(1))
12396 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12397 // If the inserted and extracted elements are constants, they must not
12398 // be the same value, extract from the pre-inserted value instead.
12399 if (isa<Constant>(IE->getOperand(2)) &&
12400 isa<Constant>(EI.getOperand(1))) {
12401 Worklist.AddValue(EI.getOperand(0));
12402 EI.setOperand(0, IE->getOperand(0));
12405 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12406 // If this is extracting an element from a shufflevector, figure out where
12407 // it came from and extract from the appropriate input element instead.
12408 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12409 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12411 unsigned LHSWidth =
12412 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12414 if (SrcIdx < LHSWidth)
12415 Src = SVI->getOperand(0);
12416 else if (SrcIdx < LHSWidth*2) {
12417 SrcIdx -= LHSWidth;
12418 Src = SVI->getOperand(1);
12420 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12422 return ExtractElementInst::Create(Src,
12423 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
12426 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12431 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12432 /// elements from either LHS or RHS, return the shuffle mask and true.
12433 /// Otherwise, return false.
12434 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12435 std::vector<Constant*> &Mask,
12436 LLVMContext *Context) {
12437 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12438 "Invalid CollectSingleShuffleElements");
12439 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12441 if (isa<UndefValue>(V)) {
12442 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12444 } else if (V == LHS) {
12445 for (unsigned i = 0; i != NumElts; ++i)
12446 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12448 } else if (V == RHS) {
12449 for (unsigned i = 0; i != NumElts; ++i)
12450 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12452 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12453 // If this is an insert of an extract from some other vector, include it.
12454 Value *VecOp = IEI->getOperand(0);
12455 Value *ScalarOp = IEI->getOperand(1);
12456 Value *IdxOp = IEI->getOperand(2);
12458 if (!isa<ConstantInt>(IdxOp))
12460 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12462 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12463 // Okay, we can handle this if the vector we are insertinting into is
12464 // transitively ok.
12465 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12466 // If so, update the mask to reflect the inserted undef.
12467 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12470 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12471 if (isa<ConstantInt>(EI->getOperand(1)) &&
12472 EI->getOperand(0)->getType() == V->getType()) {
12473 unsigned ExtractedIdx =
12474 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12476 // This must be extracting from either LHS or RHS.
12477 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12478 // Okay, we can handle this if the vector we are insertinting into is
12479 // transitively ok.
12480 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12481 // If so, update the mask to reflect the inserted value.
12482 if (EI->getOperand(0) == LHS) {
12483 Mask[InsertedIdx % NumElts] =
12484 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12486 assert(EI->getOperand(0) == RHS);
12487 Mask[InsertedIdx % NumElts] =
12488 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12497 // TODO: Handle shufflevector here!
12502 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12503 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12504 /// that computes V and the LHS value of the shuffle.
12505 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12506 Value *&RHS, LLVMContext *Context) {
12507 assert(isa<VectorType>(V->getType()) &&
12508 (RHS == 0 || V->getType() == RHS->getType()) &&
12509 "Invalid shuffle!");
12510 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12512 if (isa<UndefValue>(V)) {
12513 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12515 } else if (isa<ConstantAggregateZero>(V)) {
12516 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12518 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12519 // If this is an insert of an extract from some other vector, include it.
12520 Value *VecOp = IEI->getOperand(0);
12521 Value *ScalarOp = IEI->getOperand(1);
12522 Value *IdxOp = IEI->getOperand(2);
12524 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12525 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12526 EI->getOperand(0)->getType() == V->getType()) {
12527 unsigned ExtractedIdx =
12528 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12529 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12531 // Either the extracted from or inserted into vector must be RHSVec,
12532 // otherwise we'd end up with a shuffle of three inputs.
12533 if (EI->getOperand(0) == RHS || RHS == 0) {
12534 RHS = EI->getOperand(0);
12535 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12536 Mask[InsertedIdx % NumElts] =
12537 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12541 if (VecOp == RHS) {
12542 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12544 // Everything but the extracted element is replaced with the RHS.
12545 for (unsigned i = 0; i != NumElts; ++i) {
12546 if (i != InsertedIdx)
12547 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12552 // If this insertelement is a chain that comes from exactly these two
12553 // vectors, return the vector and the effective shuffle.
12554 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12556 return EI->getOperand(0);
12561 // TODO: Handle shufflevector here!
12563 // Otherwise, can't do anything fancy. Return an identity vector.
12564 for (unsigned i = 0; i != NumElts; ++i)
12565 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12569 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12570 Value *VecOp = IE.getOperand(0);
12571 Value *ScalarOp = IE.getOperand(1);
12572 Value *IdxOp = IE.getOperand(2);
12574 // Inserting an undef or into an undefined place, remove this.
12575 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12576 ReplaceInstUsesWith(IE, VecOp);
12578 // If the inserted element was extracted from some other vector, and if the
12579 // indexes are constant, try to turn this into a shufflevector operation.
12580 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12581 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12582 EI->getOperand(0)->getType() == IE.getType()) {
12583 unsigned NumVectorElts = IE.getType()->getNumElements();
12584 unsigned ExtractedIdx =
12585 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12586 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12588 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12589 return ReplaceInstUsesWith(IE, VecOp);
12591 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12592 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12594 // If we are extracting a value from a vector, then inserting it right
12595 // back into the same place, just use the input vector.
12596 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12597 return ReplaceInstUsesWith(IE, VecOp);
12599 // We could theoretically do this for ANY input. However, doing so could
12600 // turn chains of insertelement instructions into a chain of shufflevector
12601 // instructions, and right now we do not merge shufflevectors. As such,
12602 // only do this in a situation where it is clear that there is benefit.
12603 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12604 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12605 // the values of VecOp, except then one read from EIOp0.
12606 // Build a new shuffle mask.
12607 std::vector<Constant*> Mask;
12608 if (isa<UndefValue>(VecOp))
12609 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12611 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12612 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12615 Mask[InsertedIdx] =
12616 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12617 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12618 ConstantVector::get(Mask));
12621 // If this insertelement isn't used by some other insertelement, turn it
12622 // (and any insertelements it points to), into one big shuffle.
12623 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12624 std::vector<Constant*> Mask;
12626 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12627 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12628 // We now have a shuffle of LHS, RHS, Mask.
12629 return new ShuffleVectorInst(LHS, RHS,
12630 ConstantVector::get(Mask));
12635 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12636 APInt UndefElts(VWidth, 0);
12637 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12638 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12645 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12646 Value *LHS = SVI.getOperand(0);
12647 Value *RHS = SVI.getOperand(1);
12648 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12650 bool MadeChange = false;
12652 // Undefined shuffle mask -> undefined value.
12653 if (isa<UndefValue>(SVI.getOperand(2)))
12654 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12656 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12658 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12661 APInt UndefElts(VWidth, 0);
12662 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12663 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12664 LHS = SVI.getOperand(0);
12665 RHS = SVI.getOperand(1);
12669 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12670 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12671 if (LHS == RHS || isa<UndefValue>(LHS)) {
12672 if (isa<UndefValue>(LHS) && LHS == RHS) {
12673 // shuffle(undef,undef,mask) -> undef.
12674 return ReplaceInstUsesWith(SVI, LHS);
12677 // Remap any references to RHS to use LHS.
12678 std::vector<Constant*> Elts;
12679 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12680 if (Mask[i] >= 2*e)
12681 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12683 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12684 (Mask[i] < e && isa<UndefValue>(LHS))) {
12685 Mask[i] = 2*e; // Turn into undef.
12686 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12688 Mask[i] = Mask[i] % e; // Force to LHS.
12689 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12693 SVI.setOperand(0, SVI.getOperand(1));
12694 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12695 SVI.setOperand(2, ConstantVector::get(Elts));
12696 LHS = SVI.getOperand(0);
12697 RHS = SVI.getOperand(1);
12701 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12702 bool isLHSID = true, isRHSID = true;
12704 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12705 if (Mask[i] >= e*2) continue; // Ignore undef values.
12706 // Is this an identity shuffle of the LHS value?
12707 isLHSID &= (Mask[i] == i);
12709 // Is this an identity shuffle of the RHS value?
12710 isRHSID &= (Mask[i]-e == i);
12713 // Eliminate identity shuffles.
12714 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12715 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12717 // If the LHS is a shufflevector itself, see if we can combine it with this
12718 // one without producing an unusual shuffle. Here we are really conservative:
12719 // we are absolutely afraid of producing a shuffle mask not in the input
12720 // program, because the code gen may not be smart enough to turn a merged
12721 // shuffle into two specific shuffles: it may produce worse code. As such,
12722 // we only merge two shuffles if the result is one of the two input shuffle
12723 // masks. In this case, merging the shuffles just removes one instruction,
12724 // which we know is safe. This is good for things like turning:
12725 // (splat(splat)) -> splat.
12726 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12727 if (isa<UndefValue>(RHS)) {
12728 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12730 std::vector<unsigned> NewMask;
12731 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12732 if (Mask[i] >= 2*e)
12733 NewMask.push_back(2*e);
12735 NewMask.push_back(LHSMask[Mask[i]]);
12737 // If the result mask is equal to the src shuffle or this shuffle mask, do
12738 // the replacement.
12739 if (NewMask == LHSMask || NewMask == Mask) {
12740 unsigned LHSInNElts =
12741 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12742 std::vector<Constant*> Elts;
12743 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12744 if (NewMask[i] >= LHSInNElts*2) {
12745 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12747 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12750 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12751 LHSSVI->getOperand(1),
12752 ConstantVector::get(Elts));
12757 return MadeChange ? &SVI : 0;
12763 /// TryToSinkInstruction - Try to move the specified instruction from its
12764 /// current block into the beginning of DestBlock, which can only happen if it's
12765 /// safe to move the instruction past all of the instructions between it and the
12766 /// end of its block.
12767 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12768 assert(I->hasOneUse() && "Invariants didn't hold!");
12770 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12771 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12774 // Do not sink alloca instructions out of the entry block.
12775 if (isa<AllocaInst>(I) && I->getParent() ==
12776 &DestBlock->getParent()->getEntryBlock())
12779 // We can only sink load instructions if there is nothing between the load and
12780 // the end of block that could change the value.
12781 if (I->mayReadFromMemory()) {
12782 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12784 if (Scan->mayWriteToMemory())
12788 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12790 CopyPrecedingStopPoint(I, InsertPos);
12791 I->moveBefore(InsertPos);
12797 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12798 /// all reachable code to the worklist.
12800 /// This has a couple of tricks to make the code faster and more powerful. In
12801 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12802 /// them to the worklist (this significantly speeds up instcombine on code where
12803 /// many instructions are dead or constant). Additionally, if we find a branch
12804 /// whose condition is a known constant, we only visit the reachable successors.
12806 static void AddReachableCodeToWorklist(BasicBlock *BB,
12807 SmallPtrSet<BasicBlock*, 64> &Visited,
12809 const TargetData *TD) {
12810 SmallVector<BasicBlock*, 256> Worklist;
12811 Worklist.push_back(BB);
12813 while (!Worklist.empty()) {
12814 BB = Worklist.back();
12815 Worklist.pop_back();
12817 // We have now visited this block! If we've already been here, ignore it.
12818 if (!Visited.insert(BB)) continue;
12820 DbgInfoIntrinsic *DBI_Prev = NULL;
12821 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12822 Instruction *Inst = BBI++;
12824 // DCE instruction if trivially dead.
12825 if (isInstructionTriviallyDead(Inst)) {
12827 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12828 Inst->eraseFromParent();
12832 // ConstantProp instruction if trivially constant.
12833 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12834 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12836 Inst->replaceAllUsesWith(C);
12838 Inst->eraseFromParent();
12842 // If there are two consecutive llvm.dbg.stoppoint calls then
12843 // it is likely that the optimizer deleted code in between these
12845 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12848 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12849 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12850 IC.Worklist.Remove(DBI_Prev);
12851 DBI_Prev->eraseFromParent();
12853 DBI_Prev = DBI_Next;
12858 IC.Worklist.Add(Inst);
12861 // Recursively visit successors. If this is a branch or switch on a
12862 // constant, only visit the reachable successor.
12863 TerminatorInst *TI = BB->getTerminator();
12864 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12865 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12866 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12867 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12868 Worklist.push_back(ReachableBB);
12871 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12872 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12873 // See if this is an explicit destination.
12874 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12875 if (SI->getCaseValue(i) == Cond) {
12876 BasicBlock *ReachableBB = SI->getSuccessor(i);
12877 Worklist.push_back(ReachableBB);
12881 // Otherwise it is the default destination.
12882 Worklist.push_back(SI->getSuccessor(0));
12887 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12888 Worklist.push_back(TI->getSuccessor(i));
12892 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12893 bool Changed = false;
12894 TD = getAnalysisIfAvailable<TargetData>();
12896 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12897 << F.getNameStr() << "\n");
12900 // Do a depth-first traversal of the function, populate the worklist with
12901 // the reachable instructions. Ignore blocks that are not reachable. Keep
12902 // track of which blocks we visit.
12903 SmallPtrSet<BasicBlock*, 64> Visited;
12904 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12906 // Do a quick scan over the function. If we find any blocks that are
12907 // unreachable, remove any instructions inside of them. This prevents
12908 // the instcombine code from having to deal with some bad special cases.
12909 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12910 if (!Visited.count(BB)) {
12911 Instruction *Term = BB->getTerminator();
12912 while (Term != BB->begin()) { // Remove instrs bottom-up
12913 BasicBlock::iterator I = Term; --I;
12915 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12916 // A debug intrinsic shouldn't force another iteration if we weren't
12917 // going to do one without it.
12918 if (!isa<DbgInfoIntrinsic>(I)) {
12922 if (!I->use_empty())
12923 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12924 I->eraseFromParent();
12929 while (!Worklist.isEmpty()) {
12930 Instruction *I = Worklist.RemoveOne();
12931 if (I == 0) continue; // skip null values.
12933 // Check to see if we can DCE the instruction.
12934 if (isInstructionTriviallyDead(I)) {
12935 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12936 EraseInstFromFunction(*I);
12942 // Instruction isn't dead, see if we can constant propagate it.
12943 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12944 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12946 // Add operands to the worklist.
12947 ReplaceInstUsesWith(*I, C);
12949 EraseInstFromFunction(*I);
12955 // See if we can constant fold its operands.
12956 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12957 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12958 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12959 F.getContext(), TD))
12966 // See if we can trivially sink this instruction to a successor basic block.
12967 if (I->hasOneUse()) {
12968 BasicBlock *BB = I->getParent();
12969 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12970 if (UserParent != BB) {
12971 bool UserIsSuccessor = false;
12972 // See if the user is one of our successors.
12973 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12974 if (*SI == UserParent) {
12975 UserIsSuccessor = true;
12979 // If the user is one of our immediate successors, and if that successor
12980 // only has us as a predecessors (we'd have to split the critical edge
12981 // otherwise), we can keep going.
12982 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12983 next(pred_begin(UserParent)) == pred_end(UserParent))
12984 // Okay, the CFG is simple enough, try to sink this instruction.
12985 Changed |= TryToSinkInstruction(I, UserParent);
12989 // Now that we have an instruction, try combining it to simplify it...
12993 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12994 if (Instruction *Result = visit(*I)) {
12996 // Should we replace the old instruction with a new one?
12998 DEBUG(errs() << "IC: Old = " << *I << '\n'
12999 << " New = " << *Result << '\n');
13001 // Everything uses the new instruction now.
13002 I->replaceAllUsesWith(Result);
13004 // Push the new instruction and any users onto the worklist.
13005 Worklist.Add(Result);
13006 Worklist.AddUsersToWorkList(*Result);
13008 // Move the name to the new instruction first.
13009 Result->takeName(I);
13011 // Insert the new instruction into the basic block...
13012 BasicBlock *InstParent = I->getParent();
13013 BasicBlock::iterator InsertPos = I;
13015 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13016 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13019 InstParent->getInstList().insert(InsertPos, Result);
13021 EraseInstFromFunction(*I);
13024 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13025 << " New = " << *I << '\n');
13028 // If the instruction was modified, it's possible that it is now dead.
13029 // if so, remove it.
13030 if (isInstructionTriviallyDead(I)) {
13031 EraseInstFromFunction(*I);
13034 Worklist.AddUsersToWorkList(*I);
13046 bool InstCombiner::runOnFunction(Function &F) {
13047 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13048 Context = &F.getContext();
13050 bool EverMadeChange = false;
13052 // Iterate while there is work to do.
13053 unsigned Iteration = 0;
13054 while (DoOneIteration(F, Iteration++))
13055 EverMadeChange = true;
13056 return EverMadeChange;
13059 FunctionPass *llvm::createInstructionCombiningPass() {
13060 return new InstCombiner();