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/IRBuilder.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/PatternMatch.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/ADT/DenseMap.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/Statistic.h"
64 #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 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
145 /// just like the normal insertion helper, but also adds any new instructions
146 /// to the instcombine worklist.
147 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
148 InstCombineWorklist &Worklist;
150 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
152 void InsertHelper(Instruction *I, const Twine &Name,
153 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
154 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
158 } // end anonymous namespace
162 class VISIBILITY_HIDDEN InstCombiner
163 : public FunctionPass,
164 public InstVisitor<InstCombiner, Instruction*> {
166 bool MustPreserveLCSSA;
169 /// Worklist - All of the instructions that need to be simplified.
170 InstCombineWorklist Worklist;
172 /// Builder - This is an IRBuilder that automatically inserts new
173 /// instructions into the worklist when they are created.
174 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
177 static char ID; // Pass identification, replacement for typeid
178 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
180 LLVMContext *Context;
181 LLVMContext *getContext() const { return Context; }
184 virtual bool runOnFunction(Function &F);
186 bool DoOneIteration(Function &F, unsigned ItNum);
188 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
189 AU.addPreservedID(LCSSAID);
190 AU.setPreservesCFG();
193 TargetData *getTargetData() const { return TD; }
195 // Visitation implementation - Implement instruction combining for different
196 // instruction types. The semantics are as follows:
198 // null - No change was made
199 // I - Change was made, I is still valid, I may be dead though
200 // otherwise - Change was made, replace I with returned instruction
202 Instruction *visitAdd(BinaryOperator &I);
203 Instruction *visitFAdd(BinaryOperator &I);
204 Instruction *visitSub(BinaryOperator &I);
205 Instruction *visitFSub(BinaryOperator &I);
206 Instruction *visitMul(BinaryOperator &I);
207 Instruction *visitFMul(BinaryOperator &I);
208 Instruction *visitURem(BinaryOperator &I);
209 Instruction *visitSRem(BinaryOperator &I);
210 Instruction *visitFRem(BinaryOperator &I);
211 bool SimplifyDivRemOfSelect(BinaryOperator &I);
212 Instruction *commonRemTransforms(BinaryOperator &I);
213 Instruction *commonIRemTransforms(BinaryOperator &I);
214 Instruction *commonDivTransforms(BinaryOperator &I);
215 Instruction *commonIDivTransforms(BinaryOperator &I);
216 Instruction *visitUDiv(BinaryOperator &I);
217 Instruction *visitSDiv(BinaryOperator &I);
218 Instruction *visitFDiv(BinaryOperator &I);
219 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
220 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
221 Instruction *visitAnd(BinaryOperator &I);
222 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
223 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
224 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
225 Value *A, Value *B, Value *C);
226 Instruction *visitOr (BinaryOperator &I);
227 Instruction *visitXor(BinaryOperator &I);
228 Instruction *visitShl(BinaryOperator &I);
229 Instruction *visitAShr(BinaryOperator &I);
230 Instruction *visitLShr(BinaryOperator &I);
231 Instruction *commonShiftTransforms(BinaryOperator &I);
232 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
234 Instruction *visitFCmpInst(FCmpInst &I);
235 Instruction *visitICmpInst(ICmpInst &I);
236 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
237 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
240 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
241 ConstantInt *DivRHS);
243 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
244 ICmpInst::Predicate Cond, Instruction &I);
245 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
247 Instruction *commonCastTransforms(CastInst &CI);
248 Instruction *commonIntCastTransforms(CastInst &CI);
249 Instruction *commonPointerCastTransforms(CastInst &CI);
250 Instruction *visitTrunc(TruncInst &CI);
251 Instruction *visitZExt(ZExtInst &CI);
252 Instruction *visitSExt(SExtInst &CI);
253 Instruction *visitFPTrunc(FPTruncInst &CI);
254 Instruction *visitFPExt(CastInst &CI);
255 Instruction *visitFPToUI(FPToUIInst &FI);
256 Instruction *visitFPToSI(FPToSIInst &FI);
257 Instruction *visitUIToFP(CastInst &CI);
258 Instruction *visitSIToFP(CastInst &CI);
259 Instruction *visitPtrToInt(PtrToIntInst &CI);
260 Instruction *visitIntToPtr(IntToPtrInst &CI);
261 Instruction *visitBitCast(BitCastInst &CI);
262 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
264 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
265 Instruction *visitSelectInst(SelectInst &SI);
266 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
267 Instruction *visitCallInst(CallInst &CI);
268 Instruction *visitInvokeInst(InvokeInst &II);
269 Instruction *visitPHINode(PHINode &PN);
270 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
271 Instruction *visitAllocationInst(AllocationInst &AI);
272 Instruction *visitFreeInst(FreeInst &FI);
273 Instruction *visitLoadInst(LoadInst &LI);
274 Instruction *visitStoreInst(StoreInst &SI);
275 Instruction *visitBranchInst(BranchInst &BI);
276 Instruction *visitSwitchInst(SwitchInst &SI);
277 Instruction *visitInsertElementInst(InsertElementInst &IE);
278 Instruction *visitExtractElementInst(ExtractElementInst &EI);
279 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
280 Instruction *visitExtractValueInst(ExtractValueInst &EV);
282 // visitInstruction - Specify what to return for unhandled instructions...
283 Instruction *visitInstruction(Instruction &I) { return 0; }
286 Instruction *visitCallSite(CallSite CS);
287 bool transformConstExprCastCall(CallSite CS);
288 Instruction *transformCallThroughTrampoline(CallSite CS);
289 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
290 bool DoXform = true);
291 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
292 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
296 // InsertNewInstBefore - insert an instruction New before instruction Old
297 // in the program. Add the new instruction to the worklist.
299 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
300 assert(New && New->getParent() == 0 &&
301 "New instruction already inserted into a basic block!");
302 BasicBlock *BB = Old.getParent();
303 BB->getInstList().insert(&Old, New); // Insert inst
308 // ReplaceInstUsesWith - This method is to be used when an instruction is
309 // found to be dead, replacable with another preexisting expression. Here
310 // we add all uses of I to the worklist, replace all uses of I with the new
311 // value, then return I, so that the inst combiner will know that I was
314 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
315 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
317 // If we are replacing the instruction with itself, this must be in a
318 // segment of unreachable code, so just clobber the instruction.
320 V = UndefValue::get(I.getType());
322 I.replaceAllUsesWith(V);
326 // EraseInstFromFunction - When dealing with an instruction that has side
327 // effects or produces a void value, we can't rely on DCE to delete the
328 // instruction. Instead, visit methods should return the value returned by
330 Instruction *EraseInstFromFunction(Instruction &I) {
331 DEBUG(errs() << "IC: erase " << I);
333 assert(I.use_empty() && "Cannot erase instruction that is used!");
334 // Make sure that we reprocess all operands now that we reduced their
336 if (I.getNumOperands() < 8) {
337 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
338 if (Instruction *Op = dyn_cast<Instruction>(*i))
344 return 0; // Don't do anything with FI
347 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
348 APInt &KnownOne, unsigned Depth = 0) const {
349 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
352 bool MaskedValueIsZero(Value *V, const APInt &Mask,
353 unsigned Depth = 0) const {
354 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
356 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
357 return llvm::ComputeNumSignBits(Op, TD, Depth);
362 /// SimplifyCommutative - This performs a few simplifications for
363 /// commutative operators.
364 bool SimplifyCommutative(BinaryOperator &I);
366 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
367 /// most-complex to least-complex order.
368 bool SimplifyCompare(CmpInst &I);
370 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
371 /// based on the demanded bits.
372 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
373 APInt& KnownZero, APInt& KnownOne,
375 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
376 APInt& KnownZero, APInt& KnownOne,
379 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
380 /// SimplifyDemandedBits knows about. See if the instruction has any
381 /// properties that allow us to simplify its operands.
382 bool SimplifyDemandedInstructionBits(Instruction &Inst);
384 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
385 APInt& UndefElts, unsigned Depth = 0);
387 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
388 // PHI node as operand #0, see if we can fold the instruction into the PHI
389 // (which is only possible if all operands to the PHI are constants).
390 Instruction *FoldOpIntoPhi(Instruction &I);
392 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
393 // operator and they all are only used by the PHI, PHI together their
394 // inputs, and do the operation once, to the result of the PHI.
395 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
396 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
397 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
400 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
401 ConstantInt *AndRHS, BinaryOperator &TheAnd);
403 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
404 bool isSub, Instruction &I);
405 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
406 bool isSigned, bool Inside, Instruction &IB);
407 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
408 Instruction *MatchBSwap(BinaryOperator &I);
409 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
410 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
411 Instruction *SimplifyMemSet(MemSetInst *MI);
414 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
416 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
417 unsigned CastOpc, int &NumCastsRemoved);
418 unsigned GetOrEnforceKnownAlignment(Value *V,
419 unsigned PrefAlign = 0);
422 } // end anonymous namespace
424 char InstCombiner::ID = 0;
425 static RegisterPass<InstCombiner>
426 X("instcombine", "Combine redundant instructions");
428 // getComplexity: Assign a complexity or rank value to LLVM Values...
429 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
430 static unsigned getComplexity(Value *V) {
431 if (isa<Instruction>(V)) {
432 if (BinaryOperator::isNeg(V) ||
433 BinaryOperator::isFNeg(V) ||
434 BinaryOperator::isNot(V))
438 if (isa<Argument>(V)) return 3;
439 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
442 // isOnlyUse - Return true if this instruction will be deleted if we stop using
444 static bool isOnlyUse(Value *V) {
445 return V->hasOneUse() || isa<Constant>(V);
448 // getPromotedType - Return the specified type promoted as it would be to pass
449 // though a va_arg area...
450 static const Type *getPromotedType(const Type *Ty) {
451 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
452 if (ITy->getBitWidth() < 32)
453 return Type::getInt32Ty(Ty->getContext());
458 /// getBitCastOperand - If the specified operand is a CastInst, a constant
459 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
460 /// operand value, otherwise return null.
461 static Value *getBitCastOperand(Value *V) {
462 if (Operator *O = dyn_cast<Operator>(V)) {
463 if (O->getOpcode() == Instruction::BitCast)
464 return O->getOperand(0);
465 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
466 if (GEP->hasAllZeroIndices())
467 return GEP->getPointerOperand();
472 /// This function is a wrapper around CastInst::isEliminableCastPair. It
473 /// simply extracts arguments and returns what that function returns.
474 static Instruction::CastOps
475 isEliminableCastPair(
476 const CastInst *CI, ///< The first cast instruction
477 unsigned opcode, ///< The opcode of the second cast instruction
478 const Type *DstTy, ///< The target type for the second cast instruction
479 TargetData *TD ///< The target data for pointer size
482 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
483 const Type *MidTy = CI->getType(); // B from above
485 // Get the opcodes of the two Cast instructions
486 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
487 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
489 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
491 TD ? TD->getIntPtrType(CI->getContext()) : 0);
493 // We don't want to form an inttoptr or ptrtoint that converts to an integer
494 // type that differs from the pointer size.
495 if ((Res == Instruction::IntToPtr &&
496 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
497 (Res == Instruction::PtrToInt &&
498 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
501 return Instruction::CastOps(Res);
504 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
505 /// in any code being generated. It does not require codegen if V is simple
506 /// enough or if the cast can be folded into other casts.
507 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
508 const Type *Ty, TargetData *TD) {
509 if (V->getType() == Ty || isa<Constant>(V)) return false;
511 // If this is another cast that can be eliminated, it isn't codegen either.
512 if (const CastInst *CI = dyn_cast<CastInst>(V))
513 if (isEliminableCastPair(CI, opcode, Ty, TD))
518 // SimplifyCommutative - This performs a few simplifications for commutative
521 // 1. Order operands such that they are listed from right (least complex) to
522 // left (most complex). This puts constants before unary operators before
525 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
526 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
528 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
529 bool Changed = false;
530 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
531 Changed = !I.swapOperands();
533 if (!I.isAssociative()) return Changed;
534 Instruction::BinaryOps Opcode = I.getOpcode();
535 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
536 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
537 if (isa<Constant>(I.getOperand(1))) {
538 Constant *Folded = ConstantExpr::get(I.getOpcode(),
539 cast<Constant>(I.getOperand(1)),
540 cast<Constant>(Op->getOperand(1)));
541 I.setOperand(0, Op->getOperand(0));
542 I.setOperand(1, Folded);
544 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
545 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
546 isOnlyUse(Op) && isOnlyUse(Op1)) {
547 Constant *C1 = cast<Constant>(Op->getOperand(1));
548 Constant *C2 = cast<Constant>(Op1->getOperand(1));
550 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
551 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
552 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
556 I.setOperand(0, New);
557 I.setOperand(1, Folded);
564 /// SimplifyCompare - For a CmpInst this function just orders the operands
565 /// so that theyare listed from right (least complex) to left (most complex).
566 /// This puts constants before unary operators before binary operators.
567 bool InstCombiner::SimplifyCompare(CmpInst &I) {
568 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
571 // Compare instructions are not associative so there's nothing else we can do.
575 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
576 // if the LHS is a constant zero (which is the 'negate' form).
578 static inline Value *dyn_castNegVal(Value *V) {
579 if (BinaryOperator::isNeg(V))
580 return BinaryOperator::getNegArgument(V);
582 // Constants can be considered to be negated values if they can be folded.
583 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
584 return ConstantExpr::getNeg(C);
586 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
587 if (C->getType()->getElementType()->isInteger())
588 return ConstantExpr::getNeg(C);
593 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
594 // instruction if the LHS is a constant negative zero (which is the 'negate'
597 static inline Value *dyn_castFNegVal(Value *V) {
598 if (BinaryOperator::isFNeg(V))
599 return BinaryOperator::getFNegArgument(V);
601 // Constants can be considered to be negated values if they can be folded.
602 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
603 return ConstantExpr::getFNeg(C);
605 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
606 if (C->getType()->getElementType()->isFloatingPoint())
607 return ConstantExpr::getFNeg(C);
612 static inline Value *dyn_castNotVal(Value *V) {
613 if (BinaryOperator::isNot(V))
614 return BinaryOperator::getNotArgument(V);
616 // Constants can be considered to be not'ed values...
617 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
618 return ConstantInt::get(C->getType(), ~C->getValue());
622 // dyn_castFoldableMul - If this value is a multiply that can be folded into
623 // other computations (because it has a constant operand), return the
624 // non-constant operand of the multiply, and set CST to point to the multiplier.
625 // Otherwise, return null.
627 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
628 if (V->hasOneUse() && V->getType()->isInteger())
629 if (Instruction *I = dyn_cast<Instruction>(V)) {
630 if (I->getOpcode() == Instruction::Mul)
631 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
632 return I->getOperand(0);
633 if (I->getOpcode() == Instruction::Shl)
634 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
635 // The multiplier is really 1 << CST.
636 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
637 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
638 CST = ConstantInt::get(V->getType()->getContext(),
639 APInt(BitWidth, 1).shl(CSTVal));
640 return I->getOperand(0);
646 /// AddOne - Add one to a ConstantInt
647 static Constant *AddOne(Constant *C) {
648 return ConstantExpr::getAdd(C,
649 ConstantInt::get(C->getType(), 1));
651 /// SubOne - Subtract one from a ConstantInt
652 static Constant *SubOne(ConstantInt *C) {
653 return ConstantExpr::getSub(C,
654 ConstantInt::get(C->getType(), 1));
656 /// MultiplyOverflows - True if the multiply can not be expressed in an int
658 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
659 uint32_t W = C1->getBitWidth();
660 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
669 APInt MulExt = LHSExt * RHSExt;
672 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
673 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
674 return MulExt.slt(Min) || MulExt.sgt(Max);
676 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
680 /// ShrinkDemandedConstant - Check to see if the specified operand of the
681 /// specified instruction is a constant integer. If so, check to see if there
682 /// are any bits set in the constant that are not demanded. If so, shrink the
683 /// constant and return true.
684 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
686 assert(I && "No instruction?");
687 assert(OpNo < I->getNumOperands() && "Operand index too large");
689 // If the operand is not a constant integer, nothing to do.
690 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
691 if (!OpC) return false;
693 // If there are no bits set that aren't demanded, nothing to do.
694 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
695 if ((~Demanded & OpC->getValue()) == 0)
698 // This instruction is producing bits that are not demanded. Shrink the RHS.
699 Demanded &= OpC->getValue();
700 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
704 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
705 // set of known zero and one bits, compute the maximum and minimum values that
706 // could have the specified known zero and known one bits, returning them in
708 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
709 const APInt& KnownOne,
710 APInt& Min, APInt& Max) {
711 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
712 KnownZero.getBitWidth() == Min.getBitWidth() &&
713 KnownZero.getBitWidth() == Max.getBitWidth() &&
714 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
715 APInt UnknownBits = ~(KnownZero|KnownOne);
717 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
718 // bit if it is unknown.
720 Max = KnownOne|UnknownBits;
722 if (UnknownBits.isNegative()) { // Sign bit is unknown
723 Min.set(Min.getBitWidth()-1);
724 Max.clear(Max.getBitWidth()-1);
728 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
729 // a set of known zero and one bits, compute the maximum and minimum values that
730 // could have the specified known zero and known one bits, returning them in
732 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
733 const APInt &KnownOne,
734 APInt &Min, APInt &Max) {
735 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
736 KnownZero.getBitWidth() == Min.getBitWidth() &&
737 KnownZero.getBitWidth() == Max.getBitWidth() &&
738 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
739 APInt UnknownBits = ~(KnownZero|KnownOne);
741 // The minimum value is when the unknown bits are all zeros.
743 // The maximum value is when the unknown bits are all ones.
744 Max = KnownOne|UnknownBits;
747 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
748 /// SimplifyDemandedBits knows about. See if the instruction has any
749 /// properties that allow us to simplify its operands.
750 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
751 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
752 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
753 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
755 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
756 KnownZero, KnownOne, 0);
757 if (V == 0) return false;
758 if (V == &Inst) return true;
759 ReplaceInstUsesWith(Inst, V);
763 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
764 /// specified instruction operand if possible, updating it in place. It returns
765 /// true if it made any change and false otherwise.
766 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
767 APInt &KnownZero, APInt &KnownOne,
769 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
770 KnownZero, KnownOne, Depth);
771 if (NewVal == 0) return false;
777 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
778 /// value based on the demanded bits. When this function is called, it is known
779 /// that only the bits set in DemandedMask of the result of V are ever used
780 /// downstream. Consequently, depending on the mask and V, it may be possible
781 /// to replace V with a constant or one of its operands. In such cases, this
782 /// function does the replacement and returns true. In all other cases, it
783 /// returns false after analyzing the expression and setting KnownOne and known
784 /// to be one in the expression. KnownZero contains all the bits that are known
785 /// to be zero in the expression. These are provided to potentially allow the
786 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
787 /// the expression. KnownOne and KnownZero always follow the invariant that
788 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
789 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
790 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
791 /// and KnownOne must all be the same.
793 /// This returns null if it did not change anything and it permits no
794 /// simplification. This returns V itself if it did some simplification of V's
795 /// operands based on the information about what bits are demanded. This returns
796 /// some other non-null value if it found out that V is equal to another value
797 /// in the context where the specified bits are demanded, but not for all users.
798 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
799 APInt &KnownZero, APInt &KnownOne,
801 assert(V != 0 && "Null pointer of Value???");
802 assert(Depth <= 6 && "Limit Search Depth");
803 uint32_t BitWidth = DemandedMask.getBitWidth();
804 const Type *VTy = V->getType();
805 assert((TD || !isa<PointerType>(VTy)) &&
806 "SimplifyDemandedBits needs to know bit widths!");
807 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
808 (!VTy->isIntOrIntVector() ||
809 VTy->getScalarSizeInBits() == BitWidth) &&
810 KnownZero.getBitWidth() == BitWidth &&
811 KnownOne.getBitWidth() == BitWidth &&
812 "Value *V, DemandedMask, KnownZero and KnownOne "
813 "must have same BitWidth");
814 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
815 // We know all of the bits for a constant!
816 KnownOne = CI->getValue() & DemandedMask;
817 KnownZero = ~KnownOne & DemandedMask;
820 if (isa<ConstantPointerNull>(V)) {
821 // We know all of the bits for a constant!
823 KnownZero = DemandedMask;
829 if (DemandedMask == 0) { // Not demanding any bits from V.
830 if (isa<UndefValue>(V))
832 return UndefValue::get(VTy);
835 if (Depth == 6) // Limit search depth.
838 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
839 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
841 Instruction *I = dyn_cast<Instruction>(V);
843 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
844 return 0; // Only analyze instructions.
847 // If there are multiple uses of this value and we aren't at the root, then
848 // we can't do any simplifications of the operands, because DemandedMask
849 // only reflects the bits demanded by *one* of the users.
850 if (Depth != 0 && !I->hasOneUse()) {
851 // Despite the fact that we can't simplify this instruction in all User's
852 // context, we can at least compute the knownzero/knownone bits, and we can
853 // do simplifications that apply to *just* the one user if we know that
854 // this instruction has a simpler value in that context.
855 if (I->getOpcode() == Instruction::And) {
856 // If either the LHS or the RHS are Zero, the result is zero.
857 ComputeMaskedBits(I->getOperand(1), DemandedMask,
858 RHSKnownZero, RHSKnownOne, Depth+1);
859 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
860 LHSKnownZero, LHSKnownOne, Depth+1);
862 // If all of the demanded bits are known 1 on one side, return the other.
863 // These bits cannot contribute to the result of the 'and' in this
865 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
866 (DemandedMask & ~LHSKnownZero))
867 return I->getOperand(0);
868 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
869 (DemandedMask & ~RHSKnownZero))
870 return I->getOperand(1);
872 // If all of the demanded bits in the inputs are known zeros, return zero.
873 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
874 return Constant::getNullValue(VTy);
876 } else if (I->getOpcode() == Instruction::Or) {
877 // We can simplify (X|Y) -> X or Y in the user's context if we know that
878 // only bits from X or Y are demanded.
880 // If either the LHS or the RHS are One, the result is One.
881 ComputeMaskedBits(I->getOperand(1), DemandedMask,
882 RHSKnownZero, RHSKnownOne, Depth+1);
883 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
884 LHSKnownZero, LHSKnownOne, Depth+1);
886 // If all of the demanded bits are known zero on one side, return the
887 // other. These bits cannot contribute to the result of the 'or' in this
889 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
890 (DemandedMask & ~LHSKnownOne))
891 return I->getOperand(0);
892 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
893 (DemandedMask & ~RHSKnownOne))
894 return I->getOperand(1);
896 // If all of the potentially set bits on one side are known to be set on
897 // the other side, just use the 'other' side.
898 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
899 (DemandedMask & (~RHSKnownZero)))
900 return I->getOperand(0);
901 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
902 (DemandedMask & (~LHSKnownZero)))
903 return I->getOperand(1);
906 // Compute the KnownZero/KnownOne bits to simplify things downstream.
907 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
911 // If this is the root being simplified, allow it to have multiple uses,
912 // just set the DemandedMask to all bits so that we can try to simplify the
913 // operands. This allows visitTruncInst (for example) to simplify the
914 // operand of a trunc without duplicating all the logic below.
915 if (Depth == 0 && !V->hasOneUse())
916 DemandedMask = APInt::getAllOnesValue(BitWidth);
918 switch (I->getOpcode()) {
920 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
922 case Instruction::And:
923 // If either the LHS or the RHS are Zero, the result is zero.
924 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
925 RHSKnownZero, RHSKnownOne, Depth+1) ||
926 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
927 LHSKnownZero, LHSKnownOne, Depth+1))
929 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
930 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
932 // If all of the demanded bits are known 1 on one side, return the other.
933 // These bits cannot contribute to the result of the 'and'.
934 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
935 (DemandedMask & ~LHSKnownZero))
936 return I->getOperand(0);
937 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
938 (DemandedMask & ~RHSKnownZero))
939 return I->getOperand(1);
941 // If all of the demanded bits in the inputs are known zeros, return zero.
942 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
943 return Constant::getNullValue(VTy);
945 // If the RHS is a constant, see if we can simplify it.
946 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
949 // Output known-1 bits are only known if set in both the LHS & RHS.
950 RHSKnownOne &= LHSKnownOne;
951 // Output known-0 are known to be clear if zero in either the LHS | RHS.
952 RHSKnownZero |= LHSKnownZero;
954 case Instruction::Or:
955 // If either the LHS or the RHS are One, the result is One.
956 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
957 RHSKnownZero, RHSKnownOne, Depth+1) ||
958 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
959 LHSKnownZero, LHSKnownOne, Depth+1))
961 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
962 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
964 // If all of the demanded bits are known zero on one side, return the other.
965 // These bits cannot contribute to the result of the 'or'.
966 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
967 (DemandedMask & ~LHSKnownOne))
968 return I->getOperand(0);
969 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
970 (DemandedMask & ~RHSKnownOne))
971 return I->getOperand(1);
973 // If all of the potentially set bits on one side are known to be set on
974 // the other side, just use the 'other' side.
975 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
976 (DemandedMask & (~RHSKnownZero)))
977 return I->getOperand(0);
978 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
979 (DemandedMask & (~LHSKnownZero)))
980 return I->getOperand(1);
982 // If the RHS is a constant, see if we can simplify it.
983 if (ShrinkDemandedConstant(I, 1, DemandedMask))
986 // Output known-0 bits are only known if clear in both the LHS & RHS.
987 RHSKnownZero &= LHSKnownZero;
988 // Output known-1 are known to be set if set in either the LHS | RHS.
989 RHSKnownOne |= LHSKnownOne;
991 case Instruction::Xor: {
992 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
993 RHSKnownZero, RHSKnownOne, Depth+1) ||
994 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
995 LHSKnownZero, LHSKnownOne, Depth+1))
997 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
998 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1000 // If all of the demanded bits are known zero on one side, return the other.
1001 // These bits cannot contribute to the result of the 'xor'.
1002 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1003 return I->getOperand(0);
1004 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1005 return I->getOperand(1);
1007 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1008 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1009 (RHSKnownOne & LHSKnownOne);
1010 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1011 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1012 (RHSKnownOne & LHSKnownZero);
1014 // If all of the demanded bits are known to be zero on one side or the
1015 // other, turn this into an *inclusive* or.
1016 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1017 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1019 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1021 return InsertNewInstBefore(Or, *I);
1024 // If all of the demanded bits on one side are known, and all of the set
1025 // bits on that side are also known to be set on the other side, turn this
1026 // into an AND, as we know the bits will be cleared.
1027 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1028 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1030 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1031 Constant *AndC = Constant::getIntegerValue(VTy,
1032 ~RHSKnownOne & DemandedMask);
1034 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1035 return InsertNewInstBefore(And, *I);
1039 // If the RHS is a constant, see if we can simplify it.
1040 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1041 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1044 RHSKnownZero = KnownZeroOut;
1045 RHSKnownOne = KnownOneOut;
1048 case Instruction::Select:
1049 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1050 RHSKnownZero, RHSKnownOne, Depth+1) ||
1051 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1052 LHSKnownZero, LHSKnownOne, Depth+1))
1054 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1055 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1057 // If the operands are constants, see if we can simplify them.
1058 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1059 ShrinkDemandedConstant(I, 2, DemandedMask))
1062 // Only known if known in both the LHS and RHS.
1063 RHSKnownOne &= LHSKnownOne;
1064 RHSKnownZero &= LHSKnownZero;
1066 case Instruction::Trunc: {
1067 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1068 DemandedMask.zext(truncBf);
1069 RHSKnownZero.zext(truncBf);
1070 RHSKnownOne.zext(truncBf);
1071 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1072 RHSKnownZero, RHSKnownOne, Depth+1))
1074 DemandedMask.trunc(BitWidth);
1075 RHSKnownZero.trunc(BitWidth);
1076 RHSKnownOne.trunc(BitWidth);
1077 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1080 case Instruction::BitCast:
1081 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1082 return false; // vector->int or fp->int?
1084 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1085 if (const VectorType *SrcVTy =
1086 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1087 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1088 // Don't touch a bitcast between vectors of different element counts.
1091 // Don't touch a scalar-to-vector bitcast.
1093 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1094 // Don't touch a vector-to-scalar bitcast.
1097 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1098 RHSKnownZero, RHSKnownOne, Depth+1))
1100 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1102 case Instruction::ZExt: {
1103 // Compute the bits in the result that are not present in the input.
1104 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1106 DemandedMask.trunc(SrcBitWidth);
1107 RHSKnownZero.trunc(SrcBitWidth);
1108 RHSKnownOne.trunc(SrcBitWidth);
1109 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1110 RHSKnownZero, RHSKnownOne, Depth+1))
1112 DemandedMask.zext(BitWidth);
1113 RHSKnownZero.zext(BitWidth);
1114 RHSKnownOne.zext(BitWidth);
1115 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1116 // The top bits are known to be zero.
1117 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1120 case Instruction::SExt: {
1121 // Compute the bits in the result that are not present in the input.
1122 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1124 APInt InputDemandedBits = DemandedMask &
1125 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1127 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1128 // If any of the sign extended bits are demanded, we know that the sign
1130 if ((NewBits & DemandedMask) != 0)
1131 InputDemandedBits.set(SrcBitWidth-1);
1133 InputDemandedBits.trunc(SrcBitWidth);
1134 RHSKnownZero.trunc(SrcBitWidth);
1135 RHSKnownOne.trunc(SrcBitWidth);
1136 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1137 RHSKnownZero, RHSKnownOne, Depth+1))
1139 InputDemandedBits.zext(BitWidth);
1140 RHSKnownZero.zext(BitWidth);
1141 RHSKnownOne.zext(BitWidth);
1142 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1144 // If the sign bit of the input is known set or clear, then we know the
1145 // top bits of the result.
1147 // If the input sign bit is known zero, or if the NewBits are not demanded
1148 // convert this into a zero extension.
1149 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1150 // Convert to ZExt cast
1151 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1152 return InsertNewInstBefore(NewCast, *I);
1153 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1154 RHSKnownOne |= NewBits;
1158 case Instruction::Add: {
1159 // Figure out what the input bits are. If the top bits of the and result
1160 // are not demanded, then the add doesn't demand them from its input
1162 unsigned NLZ = DemandedMask.countLeadingZeros();
1164 // If there is a constant on the RHS, there are a variety of xformations
1166 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1167 // If null, this should be simplified elsewhere. Some of the xforms here
1168 // won't work if the RHS is zero.
1172 // If the top bit of the output is demanded, demand everything from the
1173 // input. Otherwise, we demand all the input bits except NLZ top bits.
1174 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1176 // Find information about known zero/one bits in the input.
1177 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1178 LHSKnownZero, LHSKnownOne, Depth+1))
1181 // If the RHS of the add has bits set that can't affect the input, reduce
1183 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1186 // Avoid excess work.
1187 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1190 // Turn it into OR if input bits are zero.
1191 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1193 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1195 return InsertNewInstBefore(Or, *I);
1198 // We can say something about the output known-zero and known-one bits,
1199 // depending on potential carries from the input constant and the
1200 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1201 // bits set and the RHS constant is 0x01001, then we know we have a known
1202 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1204 // To compute this, we first compute the potential carry bits. These are
1205 // the bits which may be modified. I'm not aware of a better way to do
1207 const APInt &RHSVal = RHS->getValue();
1208 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1210 // Now that we know which bits have carries, compute the known-1/0 sets.
1212 // Bits are known one if they are known zero in one operand and one in the
1213 // other, and there is no input carry.
1214 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1215 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1217 // Bits are known zero if they are known zero in both operands and there
1218 // is no input carry.
1219 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1221 // If the high-bits of this ADD are not demanded, then it does not demand
1222 // the high bits of its LHS or RHS.
1223 if (DemandedMask[BitWidth-1] == 0) {
1224 // Right fill the mask of bits for this ADD to demand the most
1225 // significant bit and all those below it.
1226 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1227 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1228 LHSKnownZero, LHSKnownOne, Depth+1) ||
1229 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1230 LHSKnownZero, LHSKnownOne, Depth+1))
1236 case Instruction::Sub:
1237 // If the high-bits of this SUB are not demanded, then it does not demand
1238 // the high bits of its LHS or RHS.
1239 if (DemandedMask[BitWidth-1] == 0) {
1240 // Right fill the mask of bits for this SUB to demand the most
1241 // significant bit and all those below it.
1242 uint32_t NLZ = DemandedMask.countLeadingZeros();
1243 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1244 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1245 LHSKnownZero, LHSKnownOne, Depth+1) ||
1246 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1247 LHSKnownZero, LHSKnownOne, Depth+1))
1250 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1251 // the known zeros and ones.
1252 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1254 case Instruction::Shl:
1255 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1256 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1257 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1258 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1259 RHSKnownZero, RHSKnownOne, Depth+1))
1261 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1262 RHSKnownZero <<= ShiftAmt;
1263 RHSKnownOne <<= ShiftAmt;
1264 // low bits known zero.
1266 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1269 case Instruction::LShr:
1270 // For a logical shift right
1271 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1272 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1274 // Unsigned shift right.
1275 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1276 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1277 RHSKnownZero, RHSKnownOne, Depth+1))
1279 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1280 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1281 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1283 // Compute the new bits that are at the top now.
1284 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1285 RHSKnownZero |= HighBits; // high bits known zero.
1289 case Instruction::AShr:
1290 // If this is an arithmetic shift right and only the low-bit is set, we can
1291 // always convert this into a logical shr, even if the shift amount is
1292 // variable. The low bit of the shift cannot be an input sign bit unless
1293 // the shift amount is >= the size of the datatype, which is undefined.
1294 if (DemandedMask == 1) {
1295 // Perform the logical shift right.
1296 Instruction *NewVal = BinaryOperator::CreateLShr(
1297 I->getOperand(0), I->getOperand(1), I->getName());
1298 return InsertNewInstBefore(NewVal, *I);
1301 // If the sign bit is the only bit demanded by this ashr, then there is no
1302 // need to do it, the shift doesn't change the high bit.
1303 if (DemandedMask.isSignBit())
1304 return I->getOperand(0);
1306 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1307 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1309 // Signed shift right.
1310 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1311 // If any of the "high bits" are demanded, we should set the sign bit as
1313 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1314 DemandedMaskIn.set(BitWidth-1);
1315 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1316 RHSKnownZero, RHSKnownOne, Depth+1))
1318 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1319 // Compute the new bits that are at the top now.
1320 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1321 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1322 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1324 // Handle the sign bits.
1325 APInt SignBit(APInt::getSignBit(BitWidth));
1326 // Adjust to where it is now in the mask.
1327 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1329 // If the input sign bit is known to be zero, or if none of the top bits
1330 // are demanded, turn this into an unsigned shift right.
1331 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1332 (HighBits & ~DemandedMask) == HighBits) {
1333 // Perform the logical shift right.
1334 Instruction *NewVal = BinaryOperator::CreateLShr(
1335 I->getOperand(0), SA, I->getName());
1336 return InsertNewInstBefore(NewVal, *I);
1337 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1338 RHSKnownOne |= HighBits;
1342 case Instruction::SRem:
1343 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1344 APInt RA = Rem->getValue().abs();
1345 if (RA.isPowerOf2()) {
1346 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1347 return I->getOperand(0);
1349 APInt LowBits = RA - 1;
1350 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1351 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1352 LHSKnownZero, LHSKnownOne, Depth+1))
1355 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1356 LHSKnownZero |= ~LowBits;
1358 KnownZero |= LHSKnownZero & DemandedMask;
1360 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1364 case Instruction::URem: {
1365 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1366 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1367 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1368 KnownZero2, KnownOne2, Depth+1) ||
1369 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1370 KnownZero2, KnownOne2, Depth+1))
1373 unsigned Leaders = KnownZero2.countLeadingOnes();
1374 Leaders = std::max(Leaders,
1375 KnownZero2.countLeadingOnes());
1376 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1379 case Instruction::Call:
1380 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1381 switch (II->getIntrinsicID()) {
1383 case Intrinsic::bswap: {
1384 // If the only bits demanded come from one byte of the bswap result,
1385 // just shift the input byte into position to eliminate the bswap.
1386 unsigned NLZ = DemandedMask.countLeadingZeros();
1387 unsigned NTZ = DemandedMask.countTrailingZeros();
1389 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1390 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1391 // have 14 leading zeros, round to 8.
1394 // If we need exactly one byte, we can do this transformation.
1395 if (BitWidth-NLZ-NTZ == 8) {
1396 unsigned ResultBit = NTZ;
1397 unsigned InputBit = BitWidth-NTZ-8;
1399 // Replace this with either a left or right shift to get the byte into
1401 Instruction *NewVal;
1402 if (InputBit > ResultBit)
1403 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1404 ConstantInt::get(I->getType(), InputBit-ResultBit));
1406 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1407 ConstantInt::get(I->getType(), ResultBit-InputBit));
1408 NewVal->takeName(I);
1409 return InsertNewInstBefore(NewVal, *I);
1412 // TODO: Could compute known zero/one bits based on the input.
1417 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1421 // If the client is only demanding bits that we know, return the known
1423 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1424 return Constant::getIntegerValue(VTy, RHSKnownOne);
1429 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1430 /// any number of elements. DemandedElts contains the set of elements that are
1431 /// actually used by the caller. This method analyzes which elements of the
1432 /// operand are undef and returns that information in UndefElts.
1434 /// If the information about demanded elements can be used to simplify the
1435 /// operation, the operation is simplified, then the resultant value is
1436 /// returned. This returns null if no change was made.
1437 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1440 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1441 APInt EltMask(APInt::getAllOnesValue(VWidth));
1442 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1444 if (isa<UndefValue>(V)) {
1445 // If the entire vector is undefined, just return this info.
1446 UndefElts = EltMask;
1448 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1449 UndefElts = EltMask;
1450 return UndefValue::get(V->getType());
1454 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1455 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1456 Constant *Undef = UndefValue::get(EltTy);
1458 std::vector<Constant*> Elts;
1459 for (unsigned i = 0; i != VWidth; ++i)
1460 if (!DemandedElts[i]) { // If not demanded, set to undef.
1461 Elts.push_back(Undef);
1463 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1464 Elts.push_back(Undef);
1466 } else { // Otherwise, defined.
1467 Elts.push_back(CP->getOperand(i));
1470 // If we changed the constant, return it.
1471 Constant *NewCP = ConstantVector::get(Elts);
1472 return NewCP != CP ? NewCP : 0;
1473 } else if (isa<ConstantAggregateZero>(V)) {
1474 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1477 // Check if this is identity. If so, return 0 since we are not simplifying
1479 if (DemandedElts == ((1ULL << VWidth) -1))
1482 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1483 Constant *Zero = Constant::getNullValue(EltTy);
1484 Constant *Undef = UndefValue::get(EltTy);
1485 std::vector<Constant*> Elts;
1486 for (unsigned i = 0; i != VWidth; ++i) {
1487 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1488 Elts.push_back(Elt);
1490 UndefElts = DemandedElts ^ EltMask;
1491 return ConstantVector::get(Elts);
1494 // Limit search depth.
1498 // If multiple users are using the root value, procede with
1499 // simplification conservatively assuming that all elements
1501 if (!V->hasOneUse()) {
1502 // Quit if we find multiple users of a non-root value though.
1503 // They'll be handled when it's their turn to be visited by
1504 // the main instcombine process.
1506 // TODO: Just compute the UndefElts information recursively.
1509 // Conservatively assume that all elements are needed.
1510 DemandedElts = EltMask;
1513 Instruction *I = dyn_cast<Instruction>(V);
1514 if (!I) return 0; // Only analyze instructions.
1516 bool MadeChange = false;
1517 APInt UndefElts2(VWidth, 0);
1519 switch (I->getOpcode()) {
1522 case Instruction::InsertElement: {
1523 // If this is a variable index, we don't know which element it overwrites.
1524 // demand exactly the same input as we produce.
1525 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1527 // Note that we can't propagate undef elt info, because we don't know
1528 // which elt is getting updated.
1529 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1530 UndefElts2, Depth+1);
1531 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1535 // If this is inserting an element that isn't demanded, remove this
1537 unsigned IdxNo = Idx->getZExtValue();
1538 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1540 return I->getOperand(0);
1543 // Otherwise, the element inserted overwrites whatever was there, so the
1544 // input demanded set is simpler than the output set.
1545 APInt DemandedElts2 = DemandedElts;
1546 DemandedElts2.clear(IdxNo);
1547 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1548 UndefElts, Depth+1);
1549 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1551 // The inserted element is defined.
1552 UndefElts.clear(IdxNo);
1555 case Instruction::ShuffleVector: {
1556 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1557 uint64_t LHSVWidth =
1558 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1559 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1560 for (unsigned i = 0; i < VWidth; i++) {
1561 if (DemandedElts[i]) {
1562 unsigned MaskVal = Shuffle->getMaskValue(i);
1563 if (MaskVal != -1u) {
1564 assert(MaskVal < LHSVWidth * 2 &&
1565 "shufflevector mask index out of range!");
1566 if (MaskVal < LHSVWidth)
1567 LeftDemanded.set(MaskVal);
1569 RightDemanded.set(MaskVal - LHSVWidth);
1574 APInt UndefElts4(LHSVWidth, 0);
1575 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1576 UndefElts4, Depth+1);
1577 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1579 APInt UndefElts3(LHSVWidth, 0);
1580 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1581 UndefElts3, Depth+1);
1582 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1584 bool NewUndefElts = false;
1585 for (unsigned i = 0; i < VWidth; i++) {
1586 unsigned MaskVal = Shuffle->getMaskValue(i);
1587 if (MaskVal == -1u) {
1589 } else if (MaskVal < LHSVWidth) {
1590 if (UndefElts4[MaskVal]) {
1591 NewUndefElts = true;
1595 if (UndefElts3[MaskVal - LHSVWidth]) {
1596 NewUndefElts = true;
1603 // Add additional discovered undefs.
1604 std::vector<Constant*> Elts;
1605 for (unsigned i = 0; i < VWidth; ++i) {
1607 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1609 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1610 Shuffle->getMaskValue(i)));
1612 I->setOperand(2, ConstantVector::get(Elts));
1617 case Instruction::BitCast: {
1618 // Vector->vector casts only.
1619 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1621 unsigned InVWidth = VTy->getNumElements();
1622 APInt InputDemandedElts(InVWidth, 0);
1625 if (VWidth == InVWidth) {
1626 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1627 // elements as are demanded of us.
1629 InputDemandedElts = DemandedElts;
1630 } else if (VWidth > InVWidth) {
1634 // If there are more elements in the result than there are in the source,
1635 // then an input element is live if any of the corresponding output
1636 // elements are live.
1637 Ratio = VWidth/InVWidth;
1638 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1639 if (DemandedElts[OutIdx])
1640 InputDemandedElts.set(OutIdx/Ratio);
1646 // If there are more elements in the source than there are in the result,
1647 // then an input element is live if the corresponding output element is
1649 Ratio = InVWidth/VWidth;
1650 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1651 if (DemandedElts[InIdx/Ratio])
1652 InputDemandedElts.set(InIdx);
1655 // div/rem demand all inputs, because they don't want divide by zero.
1656 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1657 UndefElts2, Depth+1);
1659 I->setOperand(0, TmpV);
1663 UndefElts = UndefElts2;
1664 if (VWidth > InVWidth) {
1665 llvm_unreachable("Unimp");
1666 // If there are more elements in the result than there are in the source,
1667 // then an output element is undef if the corresponding input element is
1669 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1670 if (UndefElts2[OutIdx/Ratio])
1671 UndefElts.set(OutIdx);
1672 } else if (VWidth < InVWidth) {
1673 llvm_unreachable("Unimp");
1674 // If there are more elements in the source than there are in the result,
1675 // then a result element is undef if all of the corresponding input
1676 // elements are undef.
1677 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1678 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1679 if (!UndefElts2[InIdx]) // Not undef?
1680 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1684 case Instruction::And:
1685 case Instruction::Or:
1686 case Instruction::Xor:
1687 case Instruction::Add:
1688 case Instruction::Sub:
1689 case Instruction::Mul:
1690 // div/rem demand all inputs, because they don't want divide by zero.
1691 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1692 UndefElts, Depth+1);
1693 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1694 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1695 UndefElts2, Depth+1);
1696 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1698 // Output elements are undefined if both are undefined. Consider things
1699 // like undef&0. The result is known zero, not undef.
1700 UndefElts &= UndefElts2;
1703 case Instruction::Call: {
1704 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1706 switch (II->getIntrinsicID()) {
1709 // Binary vector operations that work column-wise. A dest element is a
1710 // function of the corresponding input elements from the two inputs.
1711 case Intrinsic::x86_sse_sub_ss:
1712 case Intrinsic::x86_sse_mul_ss:
1713 case Intrinsic::x86_sse_min_ss:
1714 case Intrinsic::x86_sse_max_ss:
1715 case Intrinsic::x86_sse2_sub_sd:
1716 case Intrinsic::x86_sse2_mul_sd:
1717 case Intrinsic::x86_sse2_min_sd:
1718 case Intrinsic::x86_sse2_max_sd:
1719 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1720 UndefElts, Depth+1);
1721 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1722 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1723 UndefElts2, Depth+1);
1724 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1726 // If only the low elt is demanded and this is a scalarizable intrinsic,
1727 // scalarize it now.
1728 if (DemandedElts == 1) {
1729 switch (II->getIntrinsicID()) {
1731 case Intrinsic::x86_sse_sub_ss:
1732 case Intrinsic::x86_sse_mul_ss:
1733 case Intrinsic::x86_sse2_sub_sd:
1734 case Intrinsic::x86_sse2_mul_sd:
1735 // TODO: Lower MIN/MAX/ABS/etc
1736 Value *LHS = II->getOperand(1);
1737 Value *RHS = II->getOperand(2);
1738 // Extract the element as scalars.
1739 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
1740 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1741 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1742 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1744 switch (II->getIntrinsicID()) {
1745 default: llvm_unreachable("Case stmts out of sync!");
1746 case Intrinsic::x86_sse_sub_ss:
1747 case Intrinsic::x86_sse2_sub_sd:
1748 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1749 II->getName()), *II);
1751 case Intrinsic::x86_sse_mul_ss:
1752 case Intrinsic::x86_sse2_mul_sd:
1753 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1754 II->getName()), *II);
1759 InsertElementInst::Create(
1760 UndefValue::get(II->getType()), TmpV,
1761 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1762 InsertNewInstBefore(New, *II);
1767 // Output elements are undefined if both are undefined. Consider things
1768 // like undef&0. The result is known zero, not undef.
1769 UndefElts &= UndefElts2;
1775 return MadeChange ? I : 0;
1779 /// AssociativeOpt - Perform an optimization on an associative operator. This
1780 /// function is designed to check a chain of associative operators for a
1781 /// potential to apply a certain optimization. Since the optimization may be
1782 /// applicable if the expression was reassociated, this checks the chain, then
1783 /// reassociates the expression as necessary to expose the optimization
1784 /// opportunity. This makes use of a special Functor, which must define
1785 /// 'shouldApply' and 'apply' methods.
1787 template<typename Functor>
1788 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1789 unsigned Opcode = Root.getOpcode();
1790 Value *LHS = Root.getOperand(0);
1792 // Quick check, see if the immediate LHS matches...
1793 if (F.shouldApply(LHS))
1794 return F.apply(Root);
1796 // Otherwise, if the LHS is not of the same opcode as the root, return.
1797 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1798 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1799 // Should we apply this transform to the RHS?
1800 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1802 // If not to the RHS, check to see if we should apply to the LHS...
1803 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1804 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1808 // If the functor wants to apply the optimization to the RHS of LHSI,
1809 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1811 // Now all of the instructions are in the current basic block, go ahead
1812 // and perform the reassociation.
1813 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1815 // First move the selected RHS to the LHS of the root...
1816 Root.setOperand(0, LHSI->getOperand(1));
1818 // Make what used to be the LHS of the root be the user of the root...
1819 Value *ExtraOperand = TmpLHSI->getOperand(1);
1820 if (&Root == TmpLHSI) {
1821 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1824 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1825 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1826 BasicBlock::iterator ARI = &Root; ++ARI;
1827 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1830 // Now propagate the ExtraOperand down the chain of instructions until we
1832 while (TmpLHSI != LHSI) {
1833 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1834 // Move the instruction to immediately before the chain we are
1835 // constructing to avoid breaking dominance properties.
1836 NextLHSI->moveBefore(ARI);
1839 Value *NextOp = NextLHSI->getOperand(1);
1840 NextLHSI->setOperand(1, ExtraOperand);
1842 ExtraOperand = NextOp;
1845 // Now that the instructions are reassociated, have the functor perform
1846 // the transformation...
1847 return F.apply(Root);
1850 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1857 // AddRHS - Implements: X + X --> X << 1
1860 explicit AddRHS(Value *rhs) : RHS(rhs) {}
1861 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1862 Instruction *apply(BinaryOperator &Add) const {
1863 return BinaryOperator::CreateShl(Add.getOperand(0),
1864 ConstantInt::get(Add.getType(), 1));
1868 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1870 struct AddMaskingAnd {
1872 explicit AddMaskingAnd(Constant *c) : C2(c) {}
1873 bool shouldApply(Value *LHS) const {
1875 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1876 ConstantExpr::getAnd(C1, C2)->isNullValue();
1878 Instruction *apply(BinaryOperator &Add) const {
1879 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1885 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1887 if (CastInst *CI = dyn_cast<CastInst>(&I))
1888 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1890 // Figure out if the constant is the left or the right argument.
1891 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1892 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1894 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1896 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1897 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1900 Value *Op0 = SO, *Op1 = ConstOperand;
1902 std::swap(Op0, Op1);
1904 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1905 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1906 SO->getName()+".op");
1907 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1908 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1909 SO->getName()+".cmp");
1910 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1911 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1912 SO->getName()+".cmp");
1913 llvm_unreachable("Unknown binary instruction type!");
1916 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1917 // constant as the other operand, try to fold the binary operator into the
1918 // select arguments. This also works for Cast instructions, which obviously do
1919 // not have a second operand.
1920 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1922 // Don't modify shared select instructions
1923 if (!SI->hasOneUse()) return 0;
1924 Value *TV = SI->getOperand(1);
1925 Value *FV = SI->getOperand(2);
1927 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1928 // Bool selects with constant operands can be folded to logical ops.
1929 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1931 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1932 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1934 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1941 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1942 /// node as operand #0, see if we can fold the instruction into the PHI (which
1943 /// is only possible if all operands to the PHI are constants).
1944 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1945 PHINode *PN = cast<PHINode>(I.getOperand(0));
1946 unsigned NumPHIValues = PN->getNumIncomingValues();
1947 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1949 // Check to see if all of the operands of the PHI are constants. If there is
1950 // one non-constant value, remember the BB it is. If there is more than one
1951 // or if *it* is a PHI, bail out.
1952 BasicBlock *NonConstBB = 0;
1953 for (unsigned i = 0; i != NumPHIValues; ++i)
1954 if (!isa<Constant>(PN->getIncomingValue(i))) {
1955 if (NonConstBB) return 0; // More than one non-const value.
1956 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1957 NonConstBB = PN->getIncomingBlock(i);
1959 // If the incoming non-constant value is in I's block, we have an infinite
1961 if (NonConstBB == I.getParent())
1965 // If there is exactly one non-constant value, we can insert a copy of the
1966 // operation in that block. However, if this is a critical edge, we would be
1967 // inserting the computation one some other paths (e.g. inside a loop). Only
1968 // do this if the pred block is unconditionally branching into the phi block.
1970 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1971 if (!BI || !BI->isUnconditional()) return 0;
1974 // Okay, we can do the transformation: create the new PHI node.
1975 PHINode *NewPN = PHINode::Create(I.getType(), "");
1976 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1977 InsertNewInstBefore(NewPN, *PN);
1978 NewPN->takeName(PN);
1980 // Next, add all of the operands to the PHI.
1981 if (I.getNumOperands() == 2) {
1982 Constant *C = cast<Constant>(I.getOperand(1));
1983 for (unsigned i = 0; i != NumPHIValues; ++i) {
1985 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1986 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1987 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1989 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1991 assert(PN->getIncomingBlock(i) == NonConstBB);
1992 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1993 InV = BinaryOperator::Create(BO->getOpcode(),
1994 PN->getIncomingValue(i), C, "phitmp",
1995 NonConstBB->getTerminator());
1996 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1997 InV = CmpInst::Create(CI->getOpcode(),
1999 PN->getIncomingValue(i), C, "phitmp",
2000 NonConstBB->getTerminator());
2002 llvm_unreachable("Unknown binop!");
2004 Worklist.Add(cast<Instruction>(InV));
2006 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2009 CastInst *CI = cast<CastInst>(&I);
2010 const Type *RetTy = CI->getType();
2011 for (unsigned i = 0; i != NumPHIValues; ++i) {
2013 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2014 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2016 assert(PN->getIncomingBlock(i) == NonConstBB);
2017 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2018 I.getType(), "phitmp",
2019 NonConstBB->getTerminator());
2020 Worklist.Add(cast<Instruction>(InV));
2022 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2025 return ReplaceInstUsesWith(I, NewPN);
2029 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2030 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2031 /// This basically requires proving that the add in the original type would not
2032 /// overflow to change the sign bit or have a carry out.
2033 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2034 // There are different heuristics we can use for this. Here are some simple
2037 // Add has the property that adding any two 2's complement numbers can only
2038 // have one carry bit which can change a sign. As such, if LHS and RHS each
2039 // have at least two sign bits, we know that the addition of the two values will
2040 // sign extend fine.
2041 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2045 // If one of the operands only has one non-zero bit, and if the other operand
2046 // has a known-zero bit in a more significant place than it (not including the
2047 // sign bit) the ripple may go up to and fill the zero, but won't change the
2048 // sign. For example, (X & ~4) + 1.
2056 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2057 bool Changed = SimplifyCommutative(I);
2058 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2060 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2061 // X + undef -> undef
2062 if (isa<UndefValue>(RHS))
2063 return ReplaceInstUsesWith(I, RHS);
2066 if (RHSC->isNullValue())
2067 return ReplaceInstUsesWith(I, LHS);
2069 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2070 // X + (signbit) --> X ^ signbit
2071 const APInt& Val = CI->getValue();
2072 uint32_t BitWidth = Val.getBitWidth();
2073 if (Val == APInt::getSignBit(BitWidth))
2074 return BinaryOperator::CreateXor(LHS, RHS);
2076 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2077 // (X & 254)+1 -> (X&254)|1
2078 if (SimplifyDemandedInstructionBits(I))
2081 // zext(bool) + C -> bool ? C + 1 : C
2082 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2083 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2084 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2087 if (isa<PHINode>(LHS))
2088 if (Instruction *NV = FoldOpIntoPhi(I))
2091 ConstantInt *XorRHS = 0;
2093 if (isa<ConstantInt>(RHSC) &&
2094 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2095 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2096 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2098 uint32_t Size = TySizeBits / 2;
2099 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2100 APInt CFF80Val(-C0080Val);
2102 if (TySizeBits > Size) {
2103 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2104 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2105 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2106 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2107 // This is a sign extend if the top bits are known zero.
2108 if (!MaskedValueIsZero(XorLHS,
2109 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2110 Size = 0; // Not a sign ext, but can't be any others either.
2115 C0080Val = APIntOps::lshr(C0080Val, Size);
2116 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2117 } while (Size >= 1);
2119 // FIXME: This shouldn't be necessary. When the backends can handle types
2120 // with funny bit widths then this switch statement should be removed. It
2121 // is just here to get the size of the "middle" type back up to something
2122 // that the back ends can handle.
2123 const Type *MiddleType = 0;
2126 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2127 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2128 case 8: MiddleType = Type::getInt8Ty(*Context); break;
2131 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2132 return new SExtInst(NewTrunc, I.getType(), I.getName());
2137 if (I.getType() == Type::getInt1Ty(*Context))
2138 return BinaryOperator::CreateXor(LHS, RHS);
2141 if (I.getType()->isInteger()) {
2142 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2145 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2146 if (RHSI->getOpcode() == Instruction::Sub)
2147 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2148 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2150 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2151 if (LHSI->getOpcode() == Instruction::Sub)
2152 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2153 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2158 // -A + -B --> -(A + B)
2159 if (Value *LHSV = dyn_castNegVal(LHS)) {
2160 if (LHS->getType()->isIntOrIntVector()) {
2161 if (Value *RHSV = dyn_castNegVal(RHS)) {
2162 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2163 return BinaryOperator::CreateNeg(NewAdd);
2167 return BinaryOperator::CreateSub(RHS, LHSV);
2171 if (!isa<Constant>(RHS))
2172 if (Value *V = dyn_castNegVal(RHS))
2173 return BinaryOperator::CreateSub(LHS, V);
2177 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2178 if (X == RHS) // X*C + X --> X * (C+1)
2179 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2181 // X*C1 + X*C2 --> X * (C1+C2)
2183 if (X == dyn_castFoldableMul(RHS, C1))
2184 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2187 // X + X*C --> X * (C+1)
2188 if (dyn_castFoldableMul(RHS, C2) == LHS)
2189 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2191 // X + ~X --> -1 since ~X = -X-1
2192 if (dyn_castNotVal(LHS) == RHS ||
2193 dyn_castNotVal(RHS) == LHS)
2194 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2197 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2198 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2199 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2202 // A+B --> A|B iff A and B have no bits set in common.
2203 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2204 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2205 APInt LHSKnownOne(IT->getBitWidth(), 0);
2206 APInt LHSKnownZero(IT->getBitWidth(), 0);
2207 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2208 if (LHSKnownZero != 0) {
2209 APInt RHSKnownOne(IT->getBitWidth(), 0);
2210 APInt RHSKnownZero(IT->getBitWidth(), 0);
2211 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2213 // No bits in common -> bitwise or.
2214 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2215 return BinaryOperator::CreateOr(LHS, RHS);
2219 // W*X + Y*Z --> W * (X+Z) iff W == Y
2220 if (I.getType()->isIntOrIntVector()) {
2221 Value *W, *X, *Y, *Z;
2222 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2223 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2227 } else if (Y == X) {
2229 } else if (X == Z) {
2236 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2237 return BinaryOperator::CreateMul(W, NewAdd);
2242 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2244 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2245 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2247 // (X & FF00) + xx00 -> (X+xx00) & FF00
2248 if (LHS->hasOneUse() &&
2249 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2250 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2251 if (Anded == CRHS) {
2252 // See if all bits from the first bit set in the Add RHS up are included
2253 // in the mask. First, get the rightmost bit.
2254 const APInt& AddRHSV = CRHS->getValue();
2256 // Form a mask of all bits from the lowest bit added through the top.
2257 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2259 // See if the and mask includes all of these bits.
2260 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2262 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2263 // Okay, the xform is safe. Insert the new add pronto.
2264 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2265 return BinaryOperator::CreateAnd(NewAdd, C2);
2270 // Try to fold constant add into select arguments.
2271 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2272 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2276 // add (select X 0 (sub n A)) A --> select X A n
2278 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2281 SI = dyn_cast<SelectInst>(RHS);
2284 if (SI && SI->hasOneUse()) {
2285 Value *TV = SI->getTrueValue();
2286 Value *FV = SI->getFalseValue();
2289 // Can we fold the add into the argument of the select?
2290 // We check both true and false select arguments for a matching subtract.
2291 if (match(FV, m_Zero()) &&
2292 match(TV, m_Sub(m_Value(N), m_Specific(A))))
2293 // Fold the add into the true select value.
2294 return SelectInst::Create(SI->getCondition(), N, A);
2295 if (match(TV, m_Zero()) &&
2296 match(FV, m_Sub(m_Value(N), m_Specific(A))))
2297 // Fold the add into the false select value.
2298 return SelectInst::Create(SI->getCondition(), A, N);
2302 // Check for (add (sext x), y), see if we can merge this into an
2303 // integer add followed by a sext.
2304 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2305 // (add (sext x), cst) --> (sext (add x, cst'))
2306 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2308 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2309 if (LHSConv->hasOneUse() &&
2310 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2311 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2312 // Insert the new, smaller add.
2313 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2315 return new SExtInst(NewAdd, I.getType());
2319 // (add (sext x), (sext y)) --> (sext (add int x, y))
2320 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2321 // Only do this if x/y have the same type, if at last one of them has a
2322 // single use (so we don't increase the number of sexts), and if the
2323 // integer add will not overflow.
2324 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2325 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2326 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2327 RHSConv->getOperand(0))) {
2328 // Insert the new integer add.
2329 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2330 RHSConv->getOperand(0), "addconv");
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 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2388 return new SIToFPInst(NewAdd, I.getType());
2392 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2393 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2394 // Only do this if x/y have the same type, if at last one of them has a
2395 // single use (so we don't increase the number of int->fp conversions),
2396 // and if the integer add will not overflow.
2397 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2398 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2399 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2400 RHSConv->getOperand(0))) {
2401 // Insert the new integer add.
2402 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2403 RHSConv->getOperand(0), "addconv");
2404 return new SIToFPInst(NewAdd, I.getType());
2409 return Changed ? &I : 0;
2412 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2413 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2415 if (Op0 == Op1) // sub X, X -> 0
2416 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2418 // If this is a 'B = x-(-A)', change to B = x+A...
2419 if (Value *V = dyn_castNegVal(Op1))
2420 return BinaryOperator::CreateAdd(Op0, V);
2422 if (isa<UndefValue>(Op0))
2423 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2424 if (isa<UndefValue>(Op1))
2425 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2427 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2428 // Replace (-1 - A) with (~A)...
2429 if (C->isAllOnesValue())
2430 return BinaryOperator::CreateNot(Op1);
2432 // C - ~X == X + (1+C)
2434 if (match(Op1, m_Not(m_Value(X))))
2435 return BinaryOperator::CreateAdd(X, AddOne(C));
2437 // -(X >>u 31) -> (X >>s 31)
2438 // -(X >>s 31) -> (X >>u 31)
2440 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2441 if (SI->getOpcode() == Instruction::LShr) {
2442 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2443 // Check to see if we are shifting out everything but the sign bit.
2444 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2445 SI->getType()->getPrimitiveSizeInBits()-1) {
2446 // Ok, the transformation is safe. Insert AShr.
2447 return BinaryOperator::Create(Instruction::AShr,
2448 SI->getOperand(0), CU, SI->getName());
2452 else if (SI->getOpcode() == Instruction::AShr) {
2453 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2454 // Check to see if we are shifting out everything but the sign bit.
2455 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2456 SI->getType()->getPrimitiveSizeInBits()-1) {
2457 // Ok, the transformation is safe. Insert LShr.
2458 return BinaryOperator::CreateLShr(
2459 SI->getOperand(0), CU, SI->getName());
2466 // Try to fold constant sub into select arguments.
2467 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2468 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2471 // C - zext(bool) -> bool ? C - 1 : C
2472 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2473 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2474 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2477 if (I.getType() == Type::getInt1Ty(*Context))
2478 return BinaryOperator::CreateXor(Op0, Op1);
2480 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2481 if (Op1I->getOpcode() == Instruction::Add) {
2482 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2483 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2485 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2486 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2488 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2489 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2490 // C1-(X+C2) --> (C1-C2)-X
2491 return BinaryOperator::CreateSub(
2492 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2496 if (Op1I->hasOneUse()) {
2497 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2498 // is not used by anyone else...
2500 if (Op1I->getOpcode() == Instruction::Sub) {
2501 // Swap the two operands of the subexpr...
2502 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2503 Op1I->setOperand(0, IIOp1);
2504 Op1I->setOperand(1, IIOp0);
2506 // Create the new top level add instruction...
2507 return BinaryOperator::CreateAdd(Op0, Op1);
2510 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2512 if (Op1I->getOpcode() == Instruction::And &&
2513 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2514 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2516 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2517 return BinaryOperator::CreateAnd(Op0, NewNot);
2520 // 0 - (X sdiv C) -> (X sdiv -C)
2521 if (Op1I->getOpcode() == Instruction::SDiv)
2522 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2524 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2525 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2526 ConstantExpr::getNeg(DivRHS));
2528 // X - X*C --> X * (1-C)
2529 ConstantInt *C2 = 0;
2530 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2532 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2534 return BinaryOperator::CreateMul(Op0, CP1);
2539 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2540 if (Op0I->getOpcode() == Instruction::Add) {
2541 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2542 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2543 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2544 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2545 } else if (Op0I->getOpcode() == Instruction::Sub) {
2546 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2547 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2553 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2554 if (X == Op1) // X*C - X --> X * (C-1)
2555 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2557 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2558 if (X == dyn_castFoldableMul(Op1, C2))
2559 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2564 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2565 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2567 // If this is a 'B = x-(-A)', change to B = x+A...
2568 if (Value *V = dyn_castFNegVal(Op1))
2569 return BinaryOperator::CreateFAdd(Op0, V);
2571 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2572 if (Op1I->getOpcode() == Instruction::FAdd) {
2573 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2574 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2576 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2577 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2585 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2586 /// comparison only checks the sign bit. If it only checks the sign bit, set
2587 /// TrueIfSigned if the result of the comparison is true when the input value is
2589 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2590 bool &TrueIfSigned) {
2592 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2593 TrueIfSigned = true;
2594 return RHS->isZero();
2595 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2596 TrueIfSigned = true;
2597 return RHS->isAllOnesValue();
2598 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2599 TrueIfSigned = false;
2600 return RHS->isAllOnesValue();
2601 case ICmpInst::ICMP_UGT:
2602 // True if LHS u> RHS and RHS == high-bit-mask - 1
2603 TrueIfSigned = true;
2604 return RHS->getValue() ==
2605 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2606 case ICmpInst::ICMP_UGE:
2607 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2608 TrueIfSigned = true;
2609 return RHS->getValue().isSignBit();
2615 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2616 bool Changed = SimplifyCommutative(I);
2617 Value *Op0 = I.getOperand(0);
2619 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2620 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2622 // Simplify mul instructions with a constant RHS...
2623 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2624 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2626 // ((X << C1)*C2) == (X * (C2 << C1))
2627 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2628 if (SI->getOpcode() == Instruction::Shl)
2629 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2630 return BinaryOperator::CreateMul(SI->getOperand(0),
2631 ConstantExpr::getShl(CI, ShOp));
2634 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2635 if (CI->equalsInt(1)) // X * 1 == X
2636 return ReplaceInstUsesWith(I, Op0);
2637 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2638 return BinaryOperator::CreateNeg(Op0, I.getName());
2640 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2641 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2642 return BinaryOperator::CreateShl(Op0,
2643 ConstantInt::get(Op0->getType(), Val.logBase2()));
2645 } else if (isa<VectorType>(Op1->getType())) {
2646 if (Op1->isNullValue())
2647 return ReplaceInstUsesWith(I, Op1);
2649 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2650 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2651 return BinaryOperator::CreateNeg(Op0, I.getName());
2653 // As above, vector X*splat(1.0) -> X in all defined cases.
2654 if (Constant *Splat = Op1V->getSplatValue()) {
2655 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2656 if (CI->equalsInt(1))
2657 return ReplaceInstUsesWith(I, Op0);
2662 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2663 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2664 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2665 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2666 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2667 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
2668 return BinaryOperator::CreateAdd(Add, C1C2);
2672 // Try to fold constant mul into select arguments.
2673 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2674 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2677 if (isa<PHINode>(Op0))
2678 if (Instruction *NV = FoldOpIntoPhi(I))
2682 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2683 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2684 return BinaryOperator::CreateMul(Op0v, Op1v);
2686 // (X / Y) * Y = X - (X % Y)
2687 // (X / Y) * -Y = (X % Y) - X
2689 Value *Op1 = I.getOperand(1);
2690 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2692 (BO->getOpcode() != Instruction::UDiv &&
2693 BO->getOpcode() != Instruction::SDiv)) {
2695 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2697 Value *Neg = dyn_castNegVal(Op1);
2698 if (BO && BO->hasOneUse() &&
2699 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2700 (BO->getOpcode() == Instruction::UDiv ||
2701 BO->getOpcode() == Instruction::SDiv)) {
2702 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2704 // If the division is exact, X % Y is zero.
2705 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2706 if (SDiv->isExact()) {
2708 return ReplaceInstUsesWith(I, Op0BO);
2710 return BinaryOperator::CreateNeg(Op0BO);
2714 if (BO->getOpcode() == Instruction::UDiv)
2715 Rem = Builder->CreateURem(Op0BO, Op1BO);
2717 Rem = Builder->CreateSRem(Op0BO, Op1BO);
2721 return BinaryOperator::CreateSub(Op0BO, Rem);
2722 return BinaryOperator::CreateSub(Rem, Op0BO);
2726 if (I.getType() == Type::getInt1Ty(*Context))
2727 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2729 // If one of the operands of the multiply is a cast from a boolean value, then
2730 // we know the bool is either zero or one, so this is a 'masking' multiply.
2731 // See if we can simplify things based on how the boolean was originally
2733 CastInst *BoolCast = 0;
2734 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2735 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2738 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2739 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2742 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2743 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2744 const Type *SCOpTy = SCIOp0->getType();
2747 // If the icmp is true iff the sign bit of X is set, then convert this
2748 // multiply into a shift/and combination.
2749 if (isa<ConstantInt>(SCIOp1) &&
2750 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2752 // Shift the X value right to turn it into "all signbits".
2753 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2754 SCOpTy->getPrimitiveSizeInBits()-1);
2755 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2756 BoolCast->getOperand(0)->getName()+".mask");
2758 // If the multiply type is not the same as the source type, sign extend
2759 // or truncate to the multiply type.
2760 if (I.getType() != V->getType())
2761 V = Builder->CreateIntCast(V, I.getType(), true);
2763 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2764 return BinaryOperator::CreateAnd(V, OtherOp);
2769 return Changed ? &I : 0;
2772 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2773 bool Changed = SimplifyCommutative(I);
2774 Value *Op0 = I.getOperand(0);
2776 // Simplify mul instructions with a constant RHS...
2777 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2778 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2779 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2780 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2781 if (Op1F->isExactlyValue(1.0))
2782 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2783 } else if (isa<VectorType>(Op1->getType())) {
2784 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2785 // As above, vector X*splat(1.0) -> X in all defined cases.
2786 if (Constant *Splat = Op1V->getSplatValue()) {
2787 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2788 if (F->isExactlyValue(1.0))
2789 return ReplaceInstUsesWith(I, Op0);
2794 // Try to fold constant mul into select arguments.
2795 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2796 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2799 if (isa<PHINode>(Op0))
2800 if (Instruction *NV = FoldOpIntoPhi(I))
2804 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2805 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2806 return BinaryOperator::CreateFMul(Op0v, Op1v);
2808 return Changed ? &I : 0;
2811 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2813 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2814 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2816 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2817 int NonNullOperand = -1;
2818 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2819 if (ST->isNullValue())
2821 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2822 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2823 if (ST->isNullValue())
2826 if (NonNullOperand == -1)
2829 Value *SelectCond = SI->getOperand(0);
2831 // Change the div/rem to use 'Y' instead of the select.
2832 I.setOperand(1, SI->getOperand(NonNullOperand));
2834 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2835 // problem. However, the select, or the condition of the select may have
2836 // multiple uses. Based on our knowledge that the operand must be non-zero,
2837 // propagate the known value for the select into other uses of it, and
2838 // propagate a known value of the condition into its other users.
2840 // If the select and condition only have a single use, don't bother with this,
2842 if (SI->use_empty() && SelectCond->hasOneUse())
2845 // Scan the current block backward, looking for other uses of SI.
2846 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2848 while (BBI != BBFront) {
2850 // If we found a call to a function, we can't assume it will return, so
2851 // information from below it cannot be propagated above it.
2852 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2855 // Replace uses of the select or its condition with the known values.
2856 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2859 *I = SI->getOperand(NonNullOperand);
2861 } else if (*I == SelectCond) {
2862 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2863 ConstantInt::getFalse(*Context);
2868 // If we past the instruction, quit looking for it.
2871 if (&*BBI == SelectCond)
2874 // If we ran out of things to eliminate, break out of the loop.
2875 if (SelectCond == 0 && SI == 0)
2883 /// This function implements the transforms on div instructions that work
2884 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2885 /// used by the visitors to those instructions.
2886 /// @brief Transforms common to all three div instructions
2887 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2888 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2890 // undef / X -> 0 for integer.
2891 // undef / X -> undef for FP (the undef could be a snan).
2892 if (isa<UndefValue>(Op0)) {
2893 if (Op0->getType()->isFPOrFPVector())
2894 return ReplaceInstUsesWith(I, Op0);
2895 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2898 // X / undef -> undef
2899 if (isa<UndefValue>(Op1))
2900 return ReplaceInstUsesWith(I, Op1);
2905 /// This function implements the transforms common to both integer division
2906 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2907 /// division instructions.
2908 /// @brief Common integer divide transforms
2909 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2910 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2912 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2914 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2915 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2916 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2917 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2920 Constant *CI = ConstantInt::get(I.getType(), 1);
2921 return ReplaceInstUsesWith(I, CI);
2924 if (Instruction *Common = commonDivTransforms(I))
2927 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2928 // This does not apply for fdiv.
2929 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2932 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2934 if (RHS->equalsInt(1))
2935 return ReplaceInstUsesWith(I, Op0);
2937 // (X / C1) / C2 -> X / (C1*C2)
2938 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2939 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2940 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2941 if (MultiplyOverflows(RHS, LHSRHS,
2942 I.getOpcode()==Instruction::SDiv))
2943 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2945 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2946 ConstantExpr::getMul(RHS, LHSRHS));
2949 if (!RHS->isZero()) { // avoid X udiv 0
2950 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2951 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2953 if (isa<PHINode>(Op0))
2954 if (Instruction *NV = FoldOpIntoPhi(I))
2959 // 0 / X == 0, we don't need to preserve faults!
2960 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2961 if (LHS->equalsInt(0))
2962 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2964 // It can't be division by zero, hence it must be division by one.
2965 if (I.getType() == Type::getInt1Ty(*Context))
2966 return ReplaceInstUsesWith(I, Op0);
2968 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2969 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2972 return ReplaceInstUsesWith(I, Op0);
2978 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2979 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2981 // Handle the integer div common cases
2982 if (Instruction *Common = commonIDivTransforms(I))
2985 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2986 // X udiv C^2 -> X >> C
2987 // Check to see if this is an unsigned division with an exact power of 2,
2988 // if so, convert to a right shift.
2989 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2990 return BinaryOperator::CreateLShr(Op0,
2991 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2993 // X udiv C, where C >= signbit
2994 if (C->getValue().isNegative()) {
2995 Value *IC = Builder->CreateICmpULT( Op0, C);
2996 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2997 ConstantInt::get(I.getType(), 1));
3001 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3002 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3003 if (RHSI->getOpcode() == Instruction::Shl &&
3004 isa<ConstantInt>(RHSI->getOperand(0))) {
3005 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3006 if (C1.isPowerOf2()) {
3007 Value *N = RHSI->getOperand(1);
3008 const Type *NTy = N->getType();
3009 if (uint32_t C2 = C1.logBase2())
3010 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3011 return BinaryOperator::CreateLShr(Op0, N);
3016 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3017 // where C1&C2 are powers of two.
3018 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3019 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3020 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3021 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3022 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3023 // Compute the shift amounts
3024 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3025 // Construct the "on true" case of the select
3026 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3027 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3029 // Construct the "on false" case of the select
3030 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3031 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3033 // construct the select instruction and return it.
3034 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3040 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3043 // Handle the integer div common cases
3044 if (Instruction *Common = commonIDivTransforms(I))
3047 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3049 if (RHS->isAllOnesValue())
3050 return BinaryOperator::CreateNeg(Op0);
3052 // sdiv X, C --> ashr X, log2(C)
3053 if (cast<SDivOperator>(&I)->isExact() &&
3054 RHS->getValue().isNonNegative() &&
3055 RHS->getValue().isPowerOf2()) {
3056 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3057 RHS->getValue().exactLogBase2());
3058 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3061 // -X/C --> X/-C provided the negation doesn't overflow.
3062 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3063 if (isa<Constant>(Sub->getOperand(0)) &&
3064 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3065 Sub->hasNoSignedWrap())
3066 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3067 ConstantExpr::getNeg(RHS));
3070 // If the sign bits of both operands are zero (i.e. we can prove they are
3071 // unsigned inputs), turn this into a udiv.
3072 if (I.getType()->isInteger()) {
3073 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3074 if (MaskedValueIsZero(Op0, Mask)) {
3075 if (MaskedValueIsZero(Op1, Mask)) {
3076 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3077 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3079 ConstantInt *ShiftedInt;
3080 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3081 ShiftedInt->getValue().isPowerOf2()) {
3082 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3083 // Safe because the only negative value (1 << Y) can take on is
3084 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3085 // the sign bit set.
3086 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3094 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3095 return commonDivTransforms(I);
3098 /// This function implements the transforms on rem instructions that work
3099 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3100 /// is used by the visitors to those instructions.
3101 /// @brief Transforms common to all three rem instructions
3102 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3103 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3105 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3106 if (I.getType()->isFPOrFPVector())
3107 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3108 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3110 if (isa<UndefValue>(Op1))
3111 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3113 // Handle cases involving: rem X, (select Cond, Y, Z)
3114 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3120 /// This function implements the transforms common to both integer remainder
3121 /// instructions (urem and srem). It is called by the visitors to those integer
3122 /// remainder instructions.
3123 /// @brief Common integer remainder transforms
3124 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3125 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3127 if (Instruction *common = commonRemTransforms(I))
3130 // 0 % X == 0 for integer, we don't need to preserve faults!
3131 if (Constant *LHS = dyn_cast<Constant>(Op0))
3132 if (LHS->isNullValue())
3133 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3135 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3136 // X % 0 == undef, we don't need to preserve faults!
3137 if (RHS->equalsInt(0))
3138 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3140 if (RHS->equalsInt(1)) // X % 1 == 0
3141 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3143 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3144 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3145 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3147 } else if (isa<PHINode>(Op0I)) {
3148 if (Instruction *NV = FoldOpIntoPhi(I))
3152 // See if we can fold away this rem instruction.
3153 if (SimplifyDemandedInstructionBits(I))
3161 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3162 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3164 if (Instruction *common = commonIRemTransforms(I))
3167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3168 // X urem C^2 -> X and C
3169 // Check to see if this is an unsigned remainder with an exact power of 2,
3170 // if so, convert to a bitwise and.
3171 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3172 if (C->getValue().isPowerOf2())
3173 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3176 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3177 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3178 if (RHSI->getOpcode() == Instruction::Shl &&
3179 isa<ConstantInt>(RHSI->getOperand(0))) {
3180 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3181 Constant *N1 = Constant::getAllOnesValue(I.getType());
3182 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3183 return BinaryOperator::CreateAnd(Op0, Add);
3188 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3189 // where C1&C2 are powers of two.
3190 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3191 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3192 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3193 // STO == 0 and SFO == 0 handled above.
3194 if ((STO->getValue().isPowerOf2()) &&
3195 (SFO->getValue().isPowerOf2())) {
3196 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3197 SI->getName()+".t");
3198 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3199 SI->getName()+".f");
3200 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3208 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3211 // Handle the integer rem common cases
3212 if (Instruction *Common = commonIRemTransforms(I))
3215 if (Value *RHSNeg = dyn_castNegVal(Op1))
3216 if (!isa<Constant>(RHSNeg) ||
3217 (isa<ConstantInt>(RHSNeg) &&
3218 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3220 Worklist.AddValue(I.getOperand(1));
3221 I.setOperand(1, RHSNeg);
3225 // If the sign bits of both operands are zero (i.e. we can prove they are
3226 // unsigned inputs), turn this into a urem.
3227 if (I.getType()->isInteger()) {
3228 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3229 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3230 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3231 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3235 // If it's a constant vector, flip any negative values positive.
3236 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3237 unsigned VWidth = RHSV->getNumOperands();
3239 bool hasNegative = false;
3240 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3241 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3242 if (RHS->getValue().isNegative())
3246 std::vector<Constant *> Elts(VWidth);
3247 for (unsigned i = 0; i != VWidth; ++i) {
3248 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3249 if (RHS->getValue().isNegative())
3250 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3256 Constant *NewRHSV = ConstantVector::get(Elts);
3257 if (NewRHSV != RHSV) {
3258 Worklist.AddValue(I.getOperand(1));
3259 I.setOperand(1, NewRHSV);
3268 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3269 return commonRemTransforms(I);
3272 // isOneBitSet - Return true if there is exactly one bit set in the specified
3274 static bool isOneBitSet(const ConstantInt *CI) {
3275 return CI->getValue().isPowerOf2();
3278 // isHighOnes - Return true if the constant is of the form 1+0+.
3279 // This is the same as lowones(~X).
3280 static bool isHighOnes(const ConstantInt *CI) {
3281 return (~CI->getValue() + 1).isPowerOf2();
3284 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3285 /// are carefully arranged to allow folding of expressions such as:
3287 /// (A < B) | (A > B) --> (A != B)
3289 /// Note that this is only valid if the first and second predicates have the
3290 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3292 /// Three bits are used to represent the condition, as follows:
3297 /// <=> Value Definition
3298 /// 000 0 Always false
3305 /// 111 7 Always true
3307 static unsigned getICmpCode(const ICmpInst *ICI) {
3308 switch (ICI->getPredicate()) {
3310 case ICmpInst::ICMP_UGT: return 1; // 001
3311 case ICmpInst::ICMP_SGT: return 1; // 001
3312 case ICmpInst::ICMP_EQ: return 2; // 010
3313 case ICmpInst::ICMP_UGE: return 3; // 011
3314 case ICmpInst::ICMP_SGE: return 3; // 011
3315 case ICmpInst::ICMP_ULT: return 4; // 100
3316 case ICmpInst::ICMP_SLT: return 4; // 100
3317 case ICmpInst::ICMP_NE: return 5; // 101
3318 case ICmpInst::ICMP_ULE: return 6; // 110
3319 case ICmpInst::ICMP_SLE: return 6; // 110
3322 llvm_unreachable("Invalid ICmp predicate!");
3327 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3328 /// predicate into a three bit mask. It also returns whether it is an ordered
3329 /// predicate by reference.
3330 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3333 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3334 case FCmpInst::FCMP_UNO: return 0; // 000
3335 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3336 case FCmpInst::FCMP_UGT: return 1; // 001
3337 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3338 case FCmpInst::FCMP_UEQ: return 2; // 010
3339 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3340 case FCmpInst::FCMP_UGE: return 3; // 011
3341 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3342 case FCmpInst::FCMP_ULT: return 4; // 100
3343 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3344 case FCmpInst::FCMP_UNE: return 5; // 101
3345 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3346 case FCmpInst::FCMP_ULE: return 6; // 110
3349 // Not expecting FCMP_FALSE and FCMP_TRUE;
3350 llvm_unreachable("Unexpected FCmp predicate!");
3355 /// getICmpValue - This is the complement of getICmpCode, which turns an
3356 /// opcode and two operands into either a constant true or false, or a brand
3357 /// new ICmp instruction. The sign is passed in to determine which kind
3358 /// of predicate to use in the new icmp instruction.
3359 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3360 LLVMContext *Context) {
3362 default: llvm_unreachable("Illegal ICmp code!");
3363 case 0: return ConstantInt::getFalse(*Context);
3366 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3368 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3369 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3372 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3374 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3377 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3379 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3380 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3383 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3385 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3386 case 7: return ConstantInt::getTrue(*Context);
3390 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3391 /// opcode and two operands into either a FCmp instruction. isordered is passed
3392 /// in to determine which kind of predicate to use in the new fcmp instruction.
3393 static Value *getFCmpValue(bool isordered, unsigned code,
3394 Value *LHS, Value *RHS, LLVMContext *Context) {
3396 default: llvm_unreachable("Illegal FCmp code!");
3399 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3401 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3404 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3406 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3409 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3411 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3414 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3416 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3419 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3421 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3424 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3426 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3429 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3431 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3432 case 7: return ConstantInt::getTrue(*Context);
3436 /// PredicatesFoldable - Return true if both predicates match sign or if at
3437 /// least one of them is an equality comparison (which is signless).
3438 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3439 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3440 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3441 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3445 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3446 struct FoldICmpLogical {
3449 ICmpInst::Predicate pred;
3450 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3451 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3452 pred(ICI->getPredicate()) {}
3453 bool shouldApply(Value *V) const {
3454 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3455 if (PredicatesFoldable(pred, ICI->getPredicate()))
3456 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3457 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3460 Instruction *apply(Instruction &Log) const {
3461 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3462 if (ICI->getOperand(0) != LHS) {
3463 assert(ICI->getOperand(1) == LHS);
3464 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3467 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3468 unsigned LHSCode = getICmpCode(ICI);
3469 unsigned RHSCode = getICmpCode(RHSICI);
3471 switch (Log.getOpcode()) {
3472 case Instruction::And: Code = LHSCode & RHSCode; break;
3473 case Instruction::Or: Code = LHSCode | RHSCode; break;
3474 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3475 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3478 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3479 ICmpInst::isSignedPredicate(ICI->getPredicate());
3481 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3482 if (Instruction *I = dyn_cast<Instruction>(RV))
3484 // Otherwise, it's a constant boolean value...
3485 return IC.ReplaceInstUsesWith(Log, RV);
3488 } // end anonymous namespace
3490 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3491 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3492 // guaranteed to be a binary operator.
3493 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3495 ConstantInt *AndRHS,
3496 BinaryOperator &TheAnd) {
3497 Value *X = Op->getOperand(0);
3498 Constant *Together = 0;
3500 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3502 switch (Op->getOpcode()) {
3503 case Instruction::Xor:
3504 if (Op->hasOneUse()) {
3505 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3506 Value *And = Builder->CreateAnd(X, AndRHS);
3508 return BinaryOperator::CreateXor(And, Together);
3511 case Instruction::Or:
3512 if (Together == AndRHS) // (X | C) & C --> C
3513 return ReplaceInstUsesWith(TheAnd, AndRHS);
3515 if (Op->hasOneUse() && Together != OpRHS) {
3516 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3517 Value *Or = Builder->CreateOr(X, Together);
3519 return BinaryOperator::CreateAnd(Or, AndRHS);
3522 case Instruction::Add:
3523 if (Op->hasOneUse()) {
3524 // Adding a one to a single bit bit-field should be turned into an XOR
3525 // of the bit. First thing to check is to see if this AND is with a
3526 // single bit constant.
3527 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3529 // If there is only one bit set...
3530 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3531 // Ok, at this point, we know that we are masking the result of the
3532 // ADD down to exactly one bit. If the constant we are adding has
3533 // no bits set below this bit, then we can eliminate the ADD.
3534 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3536 // Check to see if any bits below the one bit set in AndRHSV are set.
3537 if ((AddRHS & (AndRHSV-1)) == 0) {
3538 // If not, the only thing that can effect the output of the AND is
3539 // the bit specified by AndRHSV. If that bit is set, the effect of
3540 // the XOR is to toggle the bit. If it is clear, then the ADD has
3542 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3543 TheAnd.setOperand(0, X);
3546 // Pull the XOR out of the AND.
3547 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3548 NewAnd->takeName(Op);
3549 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3556 case Instruction::Shl: {
3557 // We know that the AND will not produce any of the bits shifted in, so if
3558 // the anded constant includes them, clear them now!
3560 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3561 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3562 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3563 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3565 if (CI->getValue() == ShlMask) {
3566 // Masking out bits that the shift already masks
3567 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3568 } else if (CI != AndRHS) { // Reducing bits set in and.
3569 TheAnd.setOperand(1, CI);
3574 case Instruction::LShr:
3576 // We know that the AND will not produce any of the bits shifted in, so if
3577 // the anded constant includes them, clear them now! This only applies to
3578 // unsigned shifts, because a signed shr may bring in set bits!
3580 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3581 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3582 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3583 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3585 if (CI->getValue() == ShrMask) {
3586 // Masking out bits that the shift already masks.
3587 return ReplaceInstUsesWith(TheAnd, Op);
3588 } else if (CI != AndRHS) {
3589 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3594 case Instruction::AShr:
3596 // See if this is shifting in some sign extension, then masking it out
3598 if (Op->hasOneUse()) {
3599 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3600 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3601 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3602 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3603 if (C == AndRHS) { // Masking out bits shifted in.
3604 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3605 // Make the argument unsigned.
3606 Value *ShVal = Op->getOperand(0);
3607 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3608 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3617 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3618 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3619 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3620 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3621 /// insert new instructions.
3622 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3623 bool isSigned, bool Inside,
3625 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3626 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3627 "Lo is not <= Hi in range emission code!");
3630 if (Lo == Hi) // Trivially false.
3631 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3633 // V >= Min && V < Hi --> V < Hi
3634 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3635 ICmpInst::Predicate pred = (isSigned ?
3636 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3637 return new ICmpInst(pred, V, Hi);
3640 // Emit V-Lo <u Hi-Lo
3641 Constant *NegLo = ConstantExpr::getNeg(Lo);
3642 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3643 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3644 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3647 if (Lo == Hi) // Trivially true.
3648 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3650 // V < Min || V >= Hi -> V > Hi-1
3651 Hi = SubOne(cast<ConstantInt>(Hi));
3652 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3653 ICmpInst::Predicate pred = (isSigned ?
3654 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3655 return new ICmpInst(pred, V, Hi);
3658 // Emit V-Lo >u Hi-1-Lo
3659 // Note that Hi has already had one subtracted from it, above.
3660 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3661 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3662 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3663 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3666 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3667 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3668 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3669 // not, since all 1s are not contiguous.
3670 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3671 const APInt& V = Val->getValue();
3672 uint32_t BitWidth = Val->getType()->getBitWidth();
3673 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3675 // look for the first zero bit after the run of ones
3676 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3677 // look for the first non-zero bit
3678 ME = V.getActiveBits();
3682 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3683 /// where isSub determines whether the operator is a sub. If we can fold one of
3684 /// the following xforms:
3686 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3687 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3688 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3690 /// return (A +/- B).
3692 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3693 ConstantInt *Mask, bool isSub,
3695 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3696 if (!LHSI || LHSI->getNumOperands() != 2 ||
3697 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3699 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3701 switch (LHSI->getOpcode()) {
3703 case Instruction::And:
3704 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3705 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3706 if ((Mask->getValue().countLeadingZeros() +
3707 Mask->getValue().countPopulation()) ==
3708 Mask->getValue().getBitWidth())
3711 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3712 // part, we don't need any explicit masks to take them out of A. If that
3713 // is all N is, ignore it.
3714 uint32_t MB = 0, ME = 0;
3715 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3716 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3717 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3718 if (MaskedValueIsZero(RHS, Mask))
3723 case Instruction::Or:
3724 case Instruction::Xor:
3725 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3726 if ((Mask->getValue().countLeadingZeros() +
3727 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3728 && ConstantExpr::getAnd(N, Mask)->isNullValue())
3734 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3735 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3738 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3739 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3740 ICmpInst *LHS, ICmpInst *RHS) {
3742 ConstantInt *LHSCst, *RHSCst;
3743 ICmpInst::Predicate LHSCC, RHSCC;
3745 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3746 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3747 m_ConstantInt(LHSCst))) ||
3748 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3749 m_ConstantInt(RHSCst))))
3752 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3753 // where C is a power of 2
3754 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3755 LHSCst->getValue().isPowerOf2()) {
3756 Value *NewOr = Builder->CreateOr(Val, Val2);
3757 return new ICmpInst(LHSCC, NewOr, LHSCst);
3760 // From here on, we only handle:
3761 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3762 if (Val != Val2) return 0;
3764 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3765 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3766 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3767 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3768 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3771 // We can't fold (ugt x, C) & (sgt x, C2).
3772 if (!PredicatesFoldable(LHSCC, RHSCC))
3775 // Ensure that the larger constant is on the RHS.
3777 if (ICmpInst::isSignedPredicate(LHSCC) ||
3778 (ICmpInst::isEquality(LHSCC) &&
3779 ICmpInst::isSignedPredicate(RHSCC)))
3780 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3782 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3785 std::swap(LHS, RHS);
3786 std::swap(LHSCst, RHSCst);
3787 std::swap(LHSCC, RHSCC);
3790 // At this point, we know we have have two icmp instructions
3791 // comparing a value against two constants and and'ing the result
3792 // together. Because of the above check, we know that we only have
3793 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3794 // (from the FoldICmpLogical check above), that the two constants
3795 // are not equal and that the larger constant is on the RHS
3796 assert(LHSCst != RHSCst && "Compares not folded above?");
3799 default: llvm_unreachable("Unknown integer condition code!");
3800 case ICmpInst::ICMP_EQ:
3802 default: llvm_unreachable("Unknown integer condition code!");
3803 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3804 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3805 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3806 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3807 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3808 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3809 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3810 return ReplaceInstUsesWith(I, LHS);
3812 case ICmpInst::ICMP_NE:
3814 default: llvm_unreachable("Unknown integer condition code!");
3815 case ICmpInst::ICMP_ULT:
3816 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3817 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3818 break; // (X != 13 & X u< 15) -> no change
3819 case ICmpInst::ICMP_SLT:
3820 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3821 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3822 break; // (X != 13 & X s< 15) -> no change
3823 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3824 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3825 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3826 return ReplaceInstUsesWith(I, RHS);
3827 case ICmpInst::ICMP_NE:
3828 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3829 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3830 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3831 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3832 ConstantInt::get(Add->getType(), 1));
3834 break; // (X != 13 & X != 15) -> no change
3837 case ICmpInst::ICMP_ULT:
3839 default: llvm_unreachable("Unknown integer condition code!");
3840 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3841 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3842 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3843 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3845 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3846 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3847 return ReplaceInstUsesWith(I, LHS);
3848 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3852 case ICmpInst::ICMP_SLT:
3854 default: llvm_unreachable("Unknown integer condition code!");
3855 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3856 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3857 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3858 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3860 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3861 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3862 return ReplaceInstUsesWith(I, LHS);
3863 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3867 case ICmpInst::ICMP_UGT:
3869 default: llvm_unreachable("Unknown integer condition code!");
3870 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3871 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3872 return ReplaceInstUsesWith(I, RHS);
3873 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3875 case ICmpInst::ICMP_NE:
3876 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3877 return new ICmpInst(LHSCC, Val, RHSCst);
3878 break; // (X u> 13 & X != 15) -> no change
3879 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3880 return InsertRangeTest(Val, AddOne(LHSCst),
3881 RHSCst, false, true, I);
3882 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3886 case ICmpInst::ICMP_SGT:
3888 default: llvm_unreachable("Unknown integer condition code!");
3889 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3890 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3891 return ReplaceInstUsesWith(I, RHS);
3892 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3894 case ICmpInst::ICMP_NE:
3895 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3896 return new ICmpInst(LHSCC, Val, RHSCst);
3897 break; // (X s> 13 & X != 15) -> no change
3898 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3899 return InsertRangeTest(Val, AddOne(LHSCst),
3900 RHSCst, true, true, I);
3901 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3910 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3913 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3914 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3915 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3916 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3917 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3918 // If either of the constants are nans, then the whole thing returns
3920 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3921 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3922 return new FCmpInst(FCmpInst::FCMP_ORD,
3923 LHS->getOperand(0), RHS->getOperand(0));
3926 // Handle vector zeros. This occurs because the canonical form of
3927 // "fcmp ord x,x" is "fcmp ord x, 0".
3928 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3929 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3930 return new FCmpInst(FCmpInst::FCMP_ORD,
3931 LHS->getOperand(0), RHS->getOperand(0));
3935 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3936 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3937 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3940 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3941 // Swap RHS operands to match LHS.
3942 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3943 std::swap(Op1LHS, Op1RHS);
3946 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3947 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3949 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3951 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3952 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3953 if (Op0CC == FCmpInst::FCMP_TRUE)
3954 return ReplaceInstUsesWith(I, RHS);
3955 if (Op1CC == FCmpInst::FCMP_TRUE)
3956 return ReplaceInstUsesWith(I, LHS);
3960 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3961 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3963 std::swap(LHS, RHS);
3964 std::swap(Op0Pred, Op1Pred);
3965 std::swap(Op0Ordered, Op1Ordered);
3968 // uno && ueq -> uno && (uno || eq) -> ueq
3969 // ord && olt -> ord && (ord && lt) -> olt
3970 if (Op0Ordered == Op1Ordered)
3971 return ReplaceInstUsesWith(I, RHS);
3973 // uno && oeq -> uno && (ord && eq) -> false
3974 // uno && ord -> false
3976 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3977 // ord && ueq -> ord && (uno || eq) -> oeq
3978 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3979 Op0LHS, Op0RHS, Context));
3987 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3988 bool Changed = SimplifyCommutative(I);
3989 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3991 if (isa<UndefValue>(Op1)) // X & undef -> 0
3992 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3996 return ReplaceInstUsesWith(I, Op1);
3998 // See if we can simplify any instructions used by the instruction whose sole
3999 // purpose is to compute bits we don't care about.
4000 if (SimplifyDemandedInstructionBits(I))
4002 if (isa<VectorType>(I.getType())) {
4003 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4004 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4005 return ReplaceInstUsesWith(I, I.getOperand(0));
4006 } else if (isa<ConstantAggregateZero>(Op1)) {
4007 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4011 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4012 const APInt& AndRHSMask = AndRHS->getValue();
4013 APInt NotAndRHS(~AndRHSMask);
4015 // Optimize a variety of ((val OP C1) & C2) combinations...
4016 if (isa<BinaryOperator>(Op0)) {
4017 Instruction *Op0I = cast<Instruction>(Op0);
4018 Value *Op0LHS = Op0I->getOperand(0);
4019 Value *Op0RHS = Op0I->getOperand(1);
4020 switch (Op0I->getOpcode()) {
4021 case Instruction::Xor:
4022 case Instruction::Or:
4023 // If the mask is only needed on one incoming arm, push it up.
4024 if (Op0I->hasOneUse()) {
4025 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4026 // Not masking anything out for the LHS, move to RHS.
4027 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4028 Op0RHS->getName()+".masked");
4029 return BinaryOperator::Create(
4030 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4032 if (!isa<Constant>(Op0RHS) &&
4033 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4034 // Not masking anything out for the RHS, move to LHS.
4035 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4036 Op0LHS->getName()+".masked");
4037 return BinaryOperator::Create(
4038 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4043 case Instruction::Add:
4044 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4045 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4046 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4047 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4048 return BinaryOperator::CreateAnd(V, AndRHS);
4049 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4050 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4053 case Instruction::Sub:
4054 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4055 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4056 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4057 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4058 return BinaryOperator::CreateAnd(V, AndRHS);
4060 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4061 // has 1's for all bits that the subtraction with A might affect.
4062 if (Op0I->hasOneUse()) {
4063 uint32_t BitWidth = AndRHSMask.getBitWidth();
4064 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4065 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4067 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4068 if (!(A && A->isZero()) && // avoid infinite recursion.
4069 MaskedValueIsZero(Op0LHS, Mask)) {
4070 Value *NewNeg = Builder->CreateNeg(Op0RHS);
4071 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4076 case Instruction::Shl:
4077 case Instruction::LShr:
4078 // (1 << x) & 1 --> zext(x == 0)
4079 // (1 >> x) & 1 --> zext(x == 0)
4080 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4082 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4083 return new ZExtInst(NewICmp, I.getType());
4088 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4089 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4091 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4092 // If this is an integer truncation or change from signed-to-unsigned, and
4093 // if the source is an and/or with immediate, transform it. This
4094 // frequently occurs for bitfield accesses.
4095 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4096 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4097 CastOp->getNumOperands() == 2)
4098 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4099 if (CastOp->getOpcode() == Instruction::And) {
4100 // Change: and (cast (and X, C1) to T), C2
4101 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4102 // This will fold the two constants together, which may allow
4103 // other simplifications.
4104 Value *NewCast = Builder->CreateTruncOrBitCast(
4105 CastOp->getOperand(0), I.getType(),
4106 CastOp->getName()+".shrunk");
4107 // trunc_or_bitcast(C1)&C2
4108 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4109 C3 = ConstantExpr::getAnd(C3, AndRHS);
4110 return BinaryOperator::CreateAnd(NewCast, C3);
4111 } else if (CastOp->getOpcode() == Instruction::Or) {
4112 // Change: and (cast (or X, C1) to T), C2
4113 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4114 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4115 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4117 return ReplaceInstUsesWith(I, AndRHS);
4123 // Try to fold constant and into select arguments.
4124 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4125 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4127 if (isa<PHINode>(Op0))
4128 if (Instruction *NV = FoldOpIntoPhi(I))
4132 Value *Op0NotVal = dyn_castNotVal(Op0);
4133 Value *Op1NotVal = dyn_castNotVal(Op1);
4135 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4136 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4138 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4139 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4140 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4141 I.getName()+".demorgan");
4142 return BinaryOperator::CreateNot(Or);
4146 Value *A = 0, *B = 0, *C = 0, *D = 0;
4147 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4148 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4149 return ReplaceInstUsesWith(I, Op1);
4151 // (A|B) & ~(A&B) -> A^B
4152 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4153 if ((A == C && B == D) || (A == D && B == C))
4154 return BinaryOperator::CreateXor(A, B);
4158 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4159 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4160 return ReplaceInstUsesWith(I, Op0);
4162 // ~(A&B) & (A|B) -> A^B
4163 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4164 if ((A == C && B == D) || (A == D && B == C))
4165 return BinaryOperator::CreateXor(A, B);
4169 if (Op0->hasOneUse() &&
4170 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4171 if (A == Op1) { // (A^B)&A -> A&(A^B)
4172 I.swapOperands(); // Simplify below
4173 std::swap(Op0, Op1);
4174 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4175 cast<BinaryOperator>(Op0)->swapOperands();
4176 I.swapOperands(); // Simplify below
4177 std::swap(Op0, Op1);
4181 if (Op1->hasOneUse() &&
4182 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4183 if (B == Op0) { // B&(A^B) -> B&(B^A)
4184 cast<BinaryOperator>(Op1)->swapOperands();
4187 if (A == Op0) // A&(A^B) -> A & ~B
4188 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4191 // (A&((~A)|B)) -> A&B
4192 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4193 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4194 return BinaryOperator::CreateAnd(A, Op1);
4195 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4196 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4197 return BinaryOperator::CreateAnd(A, Op0);
4200 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4201 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4202 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4205 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4206 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4210 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4211 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4212 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4213 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4214 const Type *SrcTy = Op0C->getOperand(0)->getType();
4215 if (SrcTy == Op1C->getOperand(0)->getType() &&
4216 SrcTy->isIntOrIntVector() &&
4217 // Only do this if the casts both really cause code to be generated.
4218 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4220 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4222 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4223 Op1C->getOperand(0), I.getName());
4224 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4228 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4229 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4230 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4231 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4232 SI0->getOperand(1) == SI1->getOperand(1) &&
4233 (SI0->hasOneUse() || SI1->hasOneUse())) {
4235 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4237 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4238 SI1->getOperand(1));
4242 // If and'ing two fcmp, try combine them into one.
4243 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4244 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4245 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4249 return Changed ? &I : 0;
4252 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4253 /// capable of providing pieces of a bswap. The subexpression provides pieces
4254 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4255 /// the expression came from the corresponding "byte swapped" byte in some other
4256 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4257 /// we know that the expression deposits the low byte of %X into the high byte
4258 /// of the bswap result and that all other bytes are zero. This expression is
4259 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4262 /// This function returns true if the match was unsuccessful and false if so.
4263 /// On entry to the function the "OverallLeftShift" is a signed integer value
4264 /// indicating the number of bytes that the subexpression is later shifted. For
4265 /// example, if the expression is later right shifted by 16 bits, the
4266 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4267 /// byte of ByteValues is actually being set.
4269 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4270 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4271 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4272 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4273 /// always in the local (OverallLeftShift) coordinate space.
4275 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4276 SmallVector<Value*, 8> &ByteValues) {
4277 if (Instruction *I = dyn_cast<Instruction>(V)) {
4278 // If this is an or instruction, it may be an inner node of the bswap.
4279 if (I->getOpcode() == Instruction::Or) {
4280 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4282 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4286 // If this is a logical shift by a constant multiple of 8, recurse with
4287 // OverallLeftShift and ByteMask adjusted.
4288 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4290 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4291 // Ensure the shift amount is defined and of a byte value.
4292 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4295 unsigned ByteShift = ShAmt >> 3;
4296 if (I->getOpcode() == Instruction::Shl) {
4297 // X << 2 -> collect(X, +2)
4298 OverallLeftShift += ByteShift;
4299 ByteMask >>= ByteShift;
4301 // X >>u 2 -> collect(X, -2)
4302 OverallLeftShift -= ByteShift;
4303 ByteMask <<= ByteShift;
4304 ByteMask &= (~0U >> (32-ByteValues.size()));
4307 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4308 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4310 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4314 // If this is a logical 'and' with a mask that clears bytes, clear the
4315 // corresponding bytes in ByteMask.
4316 if (I->getOpcode() == Instruction::And &&
4317 isa<ConstantInt>(I->getOperand(1))) {
4318 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4319 unsigned NumBytes = ByteValues.size();
4320 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4321 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4323 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4324 // If this byte is masked out by a later operation, we don't care what
4326 if ((ByteMask & (1 << i)) == 0)
4329 // If the AndMask is all zeros for this byte, clear the bit.
4330 APInt MaskB = AndMask & Byte;
4332 ByteMask &= ~(1U << i);
4336 // If the AndMask is not all ones for this byte, it's not a bytezap.
4340 // Otherwise, this byte is kept.
4343 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4348 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4349 // the input value to the bswap. Some observations: 1) if more than one byte
4350 // is demanded from this input, then it could not be successfully assembled
4351 // into a byteswap. At least one of the two bytes would not be aligned with
4352 // their ultimate destination.
4353 if (!isPowerOf2_32(ByteMask)) return true;
4354 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4356 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4357 // is demanded, it needs to go into byte 0 of the result. This means that the
4358 // byte needs to be shifted until it lands in the right byte bucket. The
4359 // shift amount depends on the position: if the byte is coming from the high
4360 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4361 // low part, it must be shifted left.
4362 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4363 if (InputByteNo < ByteValues.size()/2) {
4364 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4367 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4371 // If the destination byte value is already defined, the values are or'd
4372 // together, which isn't a bswap (unless it's an or of the same bits).
4373 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4375 ByteValues[DestByteNo] = V;
4379 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4380 /// If so, insert the new bswap intrinsic and return it.
4381 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4382 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4383 if (!ITy || ITy->getBitWidth() % 16 ||
4384 // ByteMask only allows up to 32-byte values.
4385 ITy->getBitWidth() > 32*8)
4386 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4388 /// ByteValues - For each byte of the result, we keep track of which value
4389 /// defines each byte.
4390 SmallVector<Value*, 8> ByteValues;
4391 ByteValues.resize(ITy->getBitWidth()/8);
4393 // Try to find all the pieces corresponding to the bswap.
4394 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4395 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4398 // Check to see if all of the bytes come from the same value.
4399 Value *V = ByteValues[0];
4400 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4402 // Check to make sure that all of the bytes come from the same value.
4403 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4404 if (ByteValues[i] != V)
4406 const Type *Tys[] = { ITy };
4407 Module *M = I.getParent()->getParent()->getParent();
4408 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4409 return CallInst::Create(F, V);
4412 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4413 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4414 /// we can simplify this expression to "cond ? C : D or B".
4415 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4417 LLVMContext *Context) {
4418 // If A is not a select of -1/0, this cannot match.
4420 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4423 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4424 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4425 return SelectInst::Create(Cond, C, B);
4426 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4427 return SelectInst::Create(Cond, C, B);
4428 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4429 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4430 return SelectInst::Create(Cond, C, D);
4431 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4432 return SelectInst::Create(Cond, C, D);
4436 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4437 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4438 ICmpInst *LHS, ICmpInst *RHS) {
4440 ConstantInt *LHSCst, *RHSCst;
4441 ICmpInst::Predicate LHSCC, RHSCC;
4443 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4444 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4445 m_ConstantInt(LHSCst))) ||
4446 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4447 m_ConstantInt(RHSCst))))
4450 // From here on, we only handle:
4451 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4452 if (Val != Val2) return 0;
4454 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4455 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4456 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4457 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4458 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4461 // We can't fold (ugt x, C) | (sgt x, C2).
4462 if (!PredicatesFoldable(LHSCC, RHSCC))
4465 // Ensure that the larger constant is on the RHS.
4467 if (ICmpInst::isSignedPredicate(LHSCC) ||
4468 (ICmpInst::isEquality(LHSCC) &&
4469 ICmpInst::isSignedPredicate(RHSCC)))
4470 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4472 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4475 std::swap(LHS, RHS);
4476 std::swap(LHSCst, RHSCst);
4477 std::swap(LHSCC, RHSCC);
4480 // At this point, we know we have have two icmp instructions
4481 // comparing a value against two constants and or'ing the result
4482 // together. Because of the above check, we know that we only have
4483 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4484 // FoldICmpLogical check above), that the two constants are not
4486 assert(LHSCst != RHSCst && "Compares not folded above?");
4489 default: llvm_unreachable("Unknown integer condition code!");
4490 case ICmpInst::ICMP_EQ:
4492 default: llvm_unreachable("Unknown integer condition code!");
4493 case ICmpInst::ICMP_EQ:
4494 if (LHSCst == SubOne(RHSCst)) {
4495 // (X == 13 | X == 14) -> X-13 <u 2
4496 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4497 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4498 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4499 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4501 break; // (X == 13 | X == 15) -> no change
4502 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4503 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4505 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4506 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4507 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4508 return ReplaceInstUsesWith(I, RHS);
4511 case ICmpInst::ICMP_NE:
4513 default: llvm_unreachable("Unknown integer condition code!");
4514 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4515 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4516 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4517 return ReplaceInstUsesWith(I, LHS);
4518 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4519 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4520 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4521 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4524 case ICmpInst::ICMP_ULT:
4526 default: llvm_unreachable("Unknown integer condition code!");
4527 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4529 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4530 // If RHSCst is [us]MAXINT, it is always false. Not handling
4531 // this can cause overflow.
4532 if (RHSCst->isMaxValue(false))
4533 return ReplaceInstUsesWith(I, LHS);
4534 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4536 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4538 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4539 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4540 return ReplaceInstUsesWith(I, RHS);
4541 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4545 case ICmpInst::ICMP_SLT:
4547 default: llvm_unreachable("Unknown integer condition code!");
4548 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4550 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4551 // If RHSCst is [us]MAXINT, it is always false. Not handling
4552 // this can cause overflow.
4553 if (RHSCst->isMaxValue(true))
4554 return ReplaceInstUsesWith(I, LHS);
4555 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4557 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4559 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4560 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4561 return ReplaceInstUsesWith(I, RHS);
4562 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4566 case ICmpInst::ICMP_UGT:
4568 default: llvm_unreachable("Unknown integer condition code!");
4569 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4570 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4571 return ReplaceInstUsesWith(I, LHS);
4572 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4574 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4575 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4576 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4577 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4581 case ICmpInst::ICMP_SGT:
4583 default: llvm_unreachable("Unknown integer condition code!");
4584 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4585 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4586 return ReplaceInstUsesWith(I, LHS);
4587 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4589 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4590 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4591 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4592 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4600 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4602 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4603 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4604 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4605 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4606 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4607 // If either of the constants are nans, then the whole thing returns
4609 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4610 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4612 // Otherwise, no need to compare the two constants, compare the
4614 return new FCmpInst(FCmpInst::FCMP_UNO,
4615 LHS->getOperand(0), RHS->getOperand(0));
4618 // Handle vector zeros. This occurs because the canonical form of
4619 // "fcmp uno x,x" is "fcmp uno x, 0".
4620 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4621 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4622 return new FCmpInst(FCmpInst::FCMP_UNO,
4623 LHS->getOperand(0), RHS->getOperand(0));
4628 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4629 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4630 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4632 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4633 // Swap RHS operands to match LHS.
4634 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4635 std::swap(Op1LHS, Op1RHS);
4637 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4638 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4640 return new FCmpInst((FCmpInst::Predicate)Op0CC,
4642 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4643 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4644 if (Op0CC == FCmpInst::FCMP_FALSE)
4645 return ReplaceInstUsesWith(I, RHS);
4646 if (Op1CC == FCmpInst::FCMP_FALSE)
4647 return ReplaceInstUsesWith(I, LHS);
4650 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4651 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4652 if (Op0Ordered == Op1Ordered) {
4653 // If both are ordered or unordered, return a new fcmp with
4654 // or'ed predicates.
4655 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4656 Op0LHS, Op0RHS, Context);
4657 if (Instruction *I = dyn_cast<Instruction>(RV))
4659 // Otherwise, it's a constant boolean value...
4660 return ReplaceInstUsesWith(I, RV);
4666 /// FoldOrWithConstants - This helper function folds:
4668 /// ((A | B) & C1) | (B & C2)
4674 /// when the XOR of the two constants is "all ones" (-1).
4675 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4676 Value *A, Value *B, Value *C) {
4677 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4681 ConstantInt *CI2 = 0;
4682 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4684 APInt Xor = CI1->getValue() ^ CI2->getValue();
4685 if (!Xor.isAllOnesValue()) return 0;
4687 if (V1 == A || V1 == B) {
4688 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4689 return BinaryOperator::CreateOr(NewOp, V1);
4695 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4696 bool Changed = SimplifyCommutative(I);
4697 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4699 if (isa<UndefValue>(Op1)) // X | undef -> -1
4700 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4704 return ReplaceInstUsesWith(I, Op0);
4706 // See if we can simplify any instructions used by the instruction whose sole
4707 // purpose is to compute bits we don't care about.
4708 if (SimplifyDemandedInstructionBits(I))
4710 if (isa<VectorType>(I.getType())) {
4711 if (isa<ConstantAggregateZero>(Op1)) {
4712 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4713 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4714 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4715 return ReplaceInstUsesWith(I, I.getOperand(1));
4720 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4721 ConstantInt *C1 = 0; Value *X = 0;
4722 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4723 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4725 Value *Or = Builder->CreateOr(X, RHS);
4727 return BinaryOperator::CreateAnd(Or,
4728 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4731 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4732 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4734 Value *Or = Builder->CreateOr(X, RHS);
4736 return BinaryOperator::CreateXor(Or,
4737 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4740 // Try to fold constant and into select arguments.
4741 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4742 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4744 if (isa<PHINode>(Op0))
4745 if (Instruction *NV = FoldOpIntoPhi(I))
4749 Value *A = 0, *B = 0;
4750 ConstantInt *C1 = 0, *C2 = 0;
4752 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4753 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4754 return ReplaceInstUsesWith(I, Op1);
4755 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4756 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4757 return ReplaceInstUsesWith(I, Op0);
4759 // (A | B) | C and A | (B | C) -> bswap if possible.
4760 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4761 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4762 match(Op1, m_Or(m_Value(), m_Value())) ||
4763 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4764 match(Op1, m_Shift(m_Value(), m_Value())))) {
4765 if (Instruction *BSwap = MatchBSwap(I))
4769 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4770 if (Op0->hasOneUse() &&
4771 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4772 MaskedValueIsZero(Op1, C1->getValue())) {
4773 Value *NOr = Builder->CreateOr(A, Op1);
4775 return BinaryOperator::CreateXor(NOr, C1);
4778 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4779 if (Op1->hasOneUse() &&
4780 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4781 MaskedValueIsZero(Op0, C1->getValue())) {
4782 Value *NOr = Builder->CreateOr(A, Op0);
4784 return BinaryOperator::CreateXor(NOr, C1);
4788 Value *C = 0, *D = 0;
4789 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4790 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4791 Value *V1 = 0, *V2 = 0, *V3 = 0;
4792 C1 = dyn_cast<ConstantInt>(C);
4793 C2 = dyn_cast<ConstantInt>(D);
4794 if (C1 && C2) { // (A & C1)|(B & C2)
4795 // If we have: ((V + N) & C1) | (V & C2)
4796 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4797 // replace with V+N.
4798 if (C1->getValue() == ~C2->getValue()) {
4799 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4800 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4801 // Add commutes, try both ways.
4802 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4803 return ReplaceInstUsesWith(I, A);
4804 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4805 return ReplaceInstUsesWith(I, A);
4807 // Or commutes, try both ways.
4808 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4809 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4810 // Add commutes, try both ways.
4811 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4812 return ReplaceInstUsesWith(I, B);
4813 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4814 return ReplaceInstUsesWith(I, B);
4817 V1 = 0; V2 = 0; V3 = 0;
4820 // Check to see if we have any common things being and'ed. If so, find the
4821 // terms for V1 & (V2|V3).
4822 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4823 if (A == B) // (A & C)|(A & D) == A & (C|D)
4824 V1 = A, V2 = C, V3 = D;
4825 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4826 V1 = A, V2 = B, V3 = C;
4827 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4828 V1 = C, V2 = A, V3 = D;
4829 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4830 V1 = C, V2 = A, V3 = B;
4833 Value *Or = Builder->CreateOr(V2, V3, "tmp");
4834 return BinaryOperator::CreateAnd(V1, Or);
4838 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4839 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4841 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4843 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4845 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4848 // ((A&~B)|(~A&B)) -> A^B
4849 if ((match(C, m_Not(m_Specific(D))) &&
4850 match(B, m_Not(m_Specific(A)))))
4851 return BinaryOperator::CreateXor(A, D);
4852 // ((~B&A)|(~A&B)) -> A^B
4853 if ((match(A, m_Not(m_Specific(D))) &&
4854 match(B, m_Not(m_Specific(C)))))
4855 return BinaryOperator::CreateXor(C, D);
4856 // ((A&~B)|(B&~A)) -> A^B
4857 if ((match(C, m_Not(m_Specific(B))) &&
4858 match(D, m_Not(m_Specific(A)))))
4859 return BinaryOperator::CreateXor(A, B);
4860 // ((~B&A)|(B&~A)) -> A^B
4861 if ((match(A, m_Not(m_Specific(B))) &&
4862 match(D, m_Not(m_Specific(C)))))
4863 return BinaryOperator::CreateXor(C, B);
4866 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4867 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4868 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4869 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4870 SI0->getOperand(1) == SI1->getOperand(1) &&
4871 (SI0->hasOneUse() || SI1->hasOneUse())) {
4872 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4874 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4875 SI1->getOperand(1));
4879 // ((A|B)&1)|(B&-2) -> (A&1) | B
4880 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4881 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4882 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4883 if (Ret) return Ret;
4885 // (B&-2)|((A|B)&1) -> (A&1) | B
4886 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4887 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4888 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4889 if (Ret) return Ret;
4892 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4893 if (A == Op1) // ~A | A == -1
4894 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4898 // Note, A is still live here!
4899 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4901 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4903 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4904 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4905 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4906 return BinaryOperator::CreateNot(And);
4910 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4911 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4912 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4915 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4916 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4920 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4921 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4922 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4923 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4924 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4925 !isa<ICmpInst>(Op1C->getOperand(0))) {
4926 const Type *SrcTy = Op0C->getOperand(0)->getType();
4927 if (SrcTy == Op1C->getOperand(0)->getType() &&
4928 SrcTy->isIntOrIntVector() &&
4929 // Only do this if the casts both really cause code to be
4931 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4933 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4935 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4936 Op1C->getOperand(0), I.getName());
4937 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4944 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4945 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4946 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4947 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4951 return Changed ? &I : 0;
4956 // XorSelf - Implements: X ^ X --> 0
4959 XorSelf(Value *rhs) : RHS(rhs) {}
4960 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4961 Instruction *apply(BinaryOperator &Xor) const {
4968 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4969 bool Changed = SimplifyCommutative(I);
4970 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4972 if (isa<UndefValue>(Op1)) {
4973 if (isa<UndefValue>(Op0))
4974 // Handle undef ^ undef -> 0 special case. This is a common
4976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4977 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4980 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4981 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4982 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4983 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4986 // See if we can simplify any instructions used by the instruction whose sole
4987 // purpose is to compute bits we don't care about.
4988 if (SimplifyDemandedInstructionBits(I))
4990 if (isa<VectorType>(I.getType()))
4991 if (isa<ConstantAggregateZero>(Op1))
4992 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4994 // Is this a ~ operation?
4995 if (Value *NotOp = dyn_castNotVal(&I)) {
4996 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4997 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4998 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4999 if (Op0I->getOpcode() == Instruction::And ||
5000 Op0I->getOpcode() == Instruction::Or) {
5001 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5002 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5004 Builder->CreateNot(Op0I->getOperand(1),
5005 Op0I->getOperand(1)->getName()+".not");
5006 if (Op0I->getOpcode() == Instruction::And)
5007 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5008 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5015 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5016 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5017 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5018 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5019 return new ICmpInst(ICI->getInversePredicate(),
5020 ICI->getOperand(0), ICI->getOperand(1));
5022 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5023 return new FCmpInst(FCI->getInversePredicate(),
5024 FCI->getOperand(0), FCI->getOperand(1));
5027 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5028 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5029 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5030 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5031 Instruction::CastOps Opcode = Op0C->getOpcode();
5032 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5033 (RHS == ConstantExpr::getCast(Opcode,
5034 ConstantInt::getTrue(*Context),
5035 Op0C->getDestTy()))) {
5036 CI->setPredicate(CI->getInversePredicate());
5037 return CastInst::Create(Opcode, CI, Op0C->getType());
5043 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5044 // ~(c-X) == X-c-1 == X+(-c-1)
5045 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5046 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5047 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5048 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5049 ConstantInt::get(I.getType(), 1));
5050 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5053 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5054 if (Op0I->getOpcode() == Instruction::Add) {
5055 // ~(X-c) --> (-c-1)-X
5056 if (RHS->isAllOnesValue()) {
5057 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5058 return BinaryOperator::CreateSub(
5059 ConstantExpr::getSub(NegOp0CI,
5060 ConstantInt::get(I.getType(), 1)),
5061 Op0I->getOperand(0));
5062 } else if (RHS->getValue().isSignBit()) {
5063 // (X + C) ^ signbit -> (X + C + signbit)
5064 Constant *C = ConstantInt::get(*Context,
5065 RHS->getValue() + Op0CI->getValue());
5066 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5069 } else if (Op0I->getOpcode() == Instruction::Or) {
5070 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5071 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5072 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5073 // Anything in both C1 and C2 is known to be zero, remove it from
5075 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5076 NewRHS = ConstantExpr::getAnd(NewRHS,
5077 ConstantExpr::getNot(CommonBits));
5079 I.setOperand(0, Op0I->getOperand(0));
5080 I.setOperand(1, NewRHS);
5087 // Try to fold constant and into select arguments.
5088 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5089 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5091 if (isa<PHINode>(Op0))
5092 if (Instruction *NV = FoldOpIntoPhi(I))
5096 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5098 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5100 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5102 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5105 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5108 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5109 if (A == Op0) { // B^(B|A) == (A|B)^B
5110 Op1I->swapOperands();
5112 std::swap(Op0, Op1);
5113 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5114 I.swapOperands(); // Simplified below.
5115 std::swap(Op0, Op1);
5117 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5118 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5119 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5120 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5121 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
5123 if (A == Op0) { // A^(A&B) -> A^(B&A)
5124 Op1I->swapOperands();
5127 if (B == Op0) { // A^(B&A) -> (B&A)^A
5128 I.swapOperands(); // Simplified below.
5129 std::swap(Op0, Op1);
5134 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5137 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5138 Op0I->hasOneUse()) {
5139 if (A == Op1) // (B|A)^B == (A|B)^B
5141 if (B == Op1) // (A|B)^B == A & ~B
5142 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5143 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5144 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5145 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5146 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5147 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5149 if (A == Op1) // (A&B)^A -> (B&A)^A
5151 if (B == Op1 && // (B&A)^A == ~B & A
5152 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5153 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5158 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5159 if (Op0I && Op1I && Op0I->isShift() &&
5160 Op0I->getOpcode() == Op1I->getOpcode() &&
5161 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5162 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5164 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5166 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5167 Op1I->getOperand(1));
5171 Value *A, *B, *C, *D;
5172 // (A & B)^(A | B) -> A ^ B
5173 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5174 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5175 if ((A == C && B == D) || (A == D && B == C))
5176 return BinaryOperator::CreateXor(A, B);
5178 // (A | B)^(A & B) -> A ^ B
5179 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5180 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5181 if ((A == C && B == D) || (A == D && B == C))
5182 return BinaryOperator::CreateXor(A, B);
5186 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5187 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5188 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5189 // (X & Y)^(X & Y) -> (Y^Z) & X
5190 Value *X = 0, *Y = 0, *Z = 0;
5192 X = A, Y = B, Z = D;
5194 X = A, Y = B, Z = C;
5196 X = B, Y = A, Z = D;
5198 X = B, Y = A, Z = C;
5201 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5202 return BinaryOperator::CreateAnd(NewOp, X);
5207 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5208 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5209 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5212 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5213 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5214 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5215 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5216 const Type *SrcTy = Op0C->getOperand(0)->getType();
5217 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5218 // Only do this if the casts both really cause code to be generated.
5219 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5221 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5223 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5224 Op1C->getOperand(0), I.getName());
5225 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5230 return Changed ? &I : 0;
5233 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5234 LLVMContext *Context) {
5235 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5238 static bool HasAddOverflow(ConstantInt *Result,
5239 ConstantInt *In1, ConstantInt *In2,
5242 if (In2->getValue().isNegative())
5243 return Result->getValue().sgt(In1->getValue());
5245 return Result->getValue().slt(In1->getValue());
5247 return Result->getValue().ult(In1->getValue());
5250 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5251 /// overflowed for this type.
5252 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5253 Constant *In2, LLVMContext *Context,
5254 bool IsSigned = false) {
5255 Result = ConstantExpr::getAdd(In1, In2);
5257 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5258 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5259 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5260 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5261 ExtractElement(In1, Idx, Context),
5262 ExtractElement(In2, Idx, Context),
5269 return HasAddOverflow(cast<ConstantInt>(Result),
5270 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5274 static bool HasSubOverflow(ConstantInt *Result,
5275 ConstantInt *In1, ConstantInt *In2,
5278 if (In2->getValue().isNegative())
5279 return Result->getValue().slt(In1->getValue());
5281 return Result->getValue().sgt(In1->getValue());
5283 return Result->getValue().ugt(In1->getValue());
5286 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5287 /// overflowed for this type.
5288 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5289 Constant *In2, LLVMContext *Context,
5290 bool IsSigned = false) {
5291 Result = ConstantExpr::getSub(In1, In2);
5293 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5294 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5295 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5296 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5297 ExtractElement(In1, Idx, Context),
5298 ExtractElement(In2, Idx, Context),
5305 return HasSubOverflow(cast<ConstantInt>(Result),
5306 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5310 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5311 /// code necessary to compute the offset from the base pointer (without adding
5312 /// in the base pointer). Return the result as a signed integer of intptr size.
5313 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5314 TargetData &TD = *IC.getTargetData();
5315 gep_type_iterator GTI = gep_type_begin(GEP);
5316 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5317 Value *Result = Constant::getNullValue(IntPtrTy);
5319 // Build a mask for high order bits.
5320 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5321 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5323 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5326 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5327 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5328 if (OpC->isZero()) continue;
5330 // Handle a struct index, which adds its field offset to the pointer.
5331 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5332 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5334 Result = IC.Builder->CreateAdd(Result,
5335 ConstantInt::get(IntPtrTy, Size),
5336 GEP->getName()+".offs");
5340 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5342 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5343 Scale = ConstantExpr::getMul(OC, Scale);
5344 // Emit an add instruction.
5345 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5348 // Convert to correct type.
5349 if (Op->getType() != IntPtrTy)
5350 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5352 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5353 // We'll let instcombine(mul) convert this to a shl if possible.
5354 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5357 // Emit an add instruction.
5358 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5364 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5365 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5366 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5367 /// be complex, and scales are involved. The above expression would also be
5368 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5369 /// This later form is less amenable to optimization though, and we are allowed
5370 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5372 /// If we can't emit an optimized form for this expression, this returns null.
5374 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5376 TargetData &TD = *IC.getTargetData();
5377 gep_type_iterator GTI = gep_type_begin(GEP);
5379 // Check to see if this gep only has a single variable index. If so, and if
5380 // any constant indices are a multiple of its scale, then we can compute this
5381 // in terms of the scale of the variable index. For example, if the GEP
5382 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5383 // because the expression will cross zero at the same point.
5384 unsigned i, e = GEP->getNumOperands();
5386 for (i = 1; i != e; ++i, ++GTI) {
5387 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5388 // Compute the aggregate offset of constant indices.
5389 if (CI->isZero()) continue;
5391 // Handle a struct index, which adds its field offset to the pointer.
5392 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5393 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5395 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5396 Offset += Size*CI->getSExtValue();
5399 // Found our variable index.
5404 // If there are no variable indices, we must have a constant offset, just
5405 // evaluate it the general way.
5406 if (i == e) return 0;
5408 Value *VariableIdx = GEP->getOperand(i);
5409 // Determine the scale factor of the variable element. For example, this is
5410 // 4 if the variable index is into an array of i32.
5411 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5413 // Verify that there are no other variable indices. If so, emit the hard way.
5414 for (++i, ++GTI; i != e; ++i, ++GTI) {
5415 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5418 // Compute the aggregate offset of constant indices.
5419 if (CI->isZero()) continue;
5421 // Handle a struct index, which adds its field offset to the pointer.
5422 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5423 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5425 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5426 Offset += Size*CI->getSExtValue();
5430 // Okay, we know we have a single variable index, which must be a
5431 // pointer/array/vector index. If there is no offset, life is simple, return
5433 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5435 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5436 // we don't need to bother extending: the extension won't affect where the
5437 // computation crosses zero.
5438 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5439 VariableIdx = new TruncInst(VariableIdx,
5440 TD.getIntPtrType(VariableIdx->getContext()),
5441 VariableIdx->getName(), &I);
5445 // Otherwise, there is an index. The computation we will do will be modulo
5446 // the pointer size, so get it.
5447 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5449 Offset &= PtrSizeMask;
5450 VariableScale &= PtrSizeMask;
5452 // To do this transformation, any constant index must be a multiple of the
5453 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5454 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5455 // multiple of the variable scale.
5456 int64_t NewOffs = Offset / (int64_t)VariableScale;
5457 if (Offset != NewOffs*(int64_t)VariableScale)
5460 // Okay, we can do this evaluation. Start by converting the index to intptr.
5461 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5462 if (VariableIdx->getType() != IntPtrTy)
5463 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5465 VariableIdx->getName(), &I);
5466 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5467 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5471 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5472 /// else. At this point we know that the GEP is on the LHS of the comparison.
5473 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5474 ICmpInst::Predicate Cond,
5476 // Look through bitcasts.
5477 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5478 RHS = BCI->getOperand(0);
5480 Value *PtrBase = GEPLHS->getOperand(0);
5481 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5482 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5483 // This transformation (ignoring the base and scales) is valid because we
5484 // know pointers can't overflow since the gep is inbounds. See if we can
5485 // output an optimized form.
5486 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5488 // If not, synthesize the offset the hard way.
5490 Offset = EmitGEPOffset(GEPLHS, I, *this);
5491 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5492 Constant::getNullValue(Offset->getType()));
5493 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5494 // If the base pointers are different, but the indices are the same, just
5495 // compare the base pointer.
5496 if (PtrBase != GEPRHS->getOperand(0)) {
5497 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5498 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5499 GEPRHS->getOperand(0)->getType();
5501 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5502 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5503 IndicesTheSame = false;
5507 // If all indices are the same, just compare the base pointers.
5509 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5510 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5512 // Otherwise, the base pointers are different and the indices are
5513 // different, bail out.
5517 // If one of the GEPs has all zero indices, recurse.
5518 bool AllZeros = true;
5519 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5520 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5521 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5526 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5527 ICmpInst::getSwappedPredicate(Cond), I);
5529 // If the other GEP has all zero indices, recurse.
5531 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5532 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5533 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5538 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5540 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5541 // If the GEPs only differ by one index, compare it.
5542 unsigned NumDifferences = 0; // Keep track of # differences.
5543 unsigned DiffOperand = 0; // The operand that differs.
5544 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5545 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5546 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5547 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5548 // Irreconcilable differences.
5552 if (NumDifferences++) break;
5557 if (NumDifferences == 0) // SAME GEP?
5558 return ReplaceInstUsesWith(I, // No comparison is needed here.
5559 ConstantInt::get(Type::getInt1Ty(*Context),
5560 ICmpInst::isTrueWhenEqual(Cond)));
5562 else if (NumDifferences == 1) {
5563 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5564 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5565 // Make sure we do a signed comparison here.
5566 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5570 // Only lower this if the icmp is the only user of the GEP or if we expect
5571 // the result to fold to a constant!
5573 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5574 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5575 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5576 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5577 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5578 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5584 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5586 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5589 if (!isa<ConstantFP>(RHSC)) return 0;
5590 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5592 // Get the width of the mantissa. We don't want to hack on conversions that
5593 // might lose information from the integer, e.g. "i64 -> float"
5594 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5595 if (MantissaWidth == -1) return 0; // Unknown.
5597 // Check to see that the input is converted from an integer type that is small
5598 // enough that preserves all bits. TODO: check here for "known" sign bits.
5599 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5600 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5602 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5603 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5607 // If the conversion would lose info, don't hack on this.
5608 if ((int)InputSize > MantissaWidth)
5611 // Otherwise, we can potentially simplify the comparison. We know that it
5612 // will always come through as an integer value and we know the constant is
5613 // not a NAN (it would have been previously simplified).
5614 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5616 ICmpInst::Predicate Pred;
5617 switch (I.getPredicate()) {
5618 default: llvm_unreachable("Unexpected predicate!");
5619 case FCmpInst::FCMP_UEQ:
5620 case FCmpInst::FCMP_OEQ:
5621 Pred = ICmpInst::ICMP_EQ;
5623 case FCmpInst::FCMP_UGT:
5624 case FCmpInst::FCMP_OGT:
5625 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5627 case FCmpInst::FCMP_UGE:
5628 case FCmpInst::FCMP_OGE:
5629 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5631 case FCmpInst::FCMP_ULT:
5632 case FCmpInst::FCMP_OLT:
5633 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5635 case FCmpInst::FCMP_ULE:
5636 case FCmpInst::FCMP_OLE:
5637 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5639 case FCmpInst::FCMP_UNE:
5640 case FCmpInst::FCMP_ONE:
5641 Pred = ICmpInst::ICMP_NE;
5643 case FCmpInst::FCMP_ORD:
5644 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5645 case FCmpInst::FCMP_UNO:
5646 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5649 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5651 // Now we know that the APFloat is a normal number, zero or inf.
5653 // See if the FP constant is too large for the integer. For example,
5654 // comparing an i8 to 300.0.
5655 unsigned IntWidth = IntTy->getScalarSizeInBits();
5658 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5659 // and large values.
5660 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5661 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5662 APFloat::rmNearestTiesToEven);
5663 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5664 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5665 Pred == ICmpInst::ICMP_SLE)
5666 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5667 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5670 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5671 // +INF and large values.
5672 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5673 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5674 APFloat::rmNearestTiesToEven);
5675 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5676 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5677 Pred == ICmpInst::ICMP_ULE)
5678 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5679 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5684 // See if the RHS value is < SignedMin.
5685 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5686 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5687 APFloat::rmNearestTiesToEven);
5688 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5689 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5690 Pred == ICmpInst::ICMP_SGE)
5691 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5692 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5696 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5697 // [0, UMAX], but it may still be fractional. See if it is fractional by
5698 // casting the FP value to the integer value and back, checking for equality.
5699 // Don't do this for zero, because -0.0 is not fractional.
5700 Constant *RHSInt = LHSUnsigned
5701 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5702 : ConstantExpr::getFPToSI(RHSC, IntTy);
5703 if (!RHS.isZero()) {
5704 bool Equal = LHSUnsigned
5705 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5706 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5708 // If we had a comparison against a fractional value, we have to adjust
5709 // the compare predicate and sometimes the value. RHSC is rounded towards
5710 // zero at this point.
5712 default: llvm_unreachable("Unexpected integer comparison!");
5713 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5714 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5715 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5716 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5717 case ICmpInst::ICMP_ULE:
5718 // (float)int <= 4.4 --> int <= 4
5719 // (float)int <= -4.4 --> false
5720 if (RHS.isNegative())
5721 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5723 case ICmpInst::ICMP_SLE:
5724 // (float)int <= 4.4 --> int <= 4
5725 // (float)int <= -4.4 --> int < -4
5726 if (RHS.isNegative())
5727 Pred = ICmpInst::ICMP_SLT;
5729 case ICmpInst::ICMP_ULT:
5730 // (float)int < -4.4 --> false
5731 // (float)int < 4.4 --> int <= 4
5732 if (RHS.isNegative())
5733 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5734 Pred = ICmpInst::ICMP_ULE;
5736 case ICmpInst::ICMP_SLT:
5737 // (float)int < -4.4 --> int < -4
5738 // (float)int < 4.4 --> int <= 4
5739 if (!RHS.isNegative())
5740 Pred = ICmpInst::ICMP_SLE;
5742 case ICmpInst::ICMP_UGT:
5743 // (float)int > 4.4 --> int > 4
5744 // (float)int > -4.4 --> true
5745 if (RHS.isNegative())
5746 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5748 case ICmpInst::ICMP_SGT:
5749 // (float)int > 4.4 --> int > 4
5750 // (float)int > -4.4 --> int >= -4
5751 if (RHS.isNegative())
5752 Pred = ICmpInst::ICMP_SGE;
5754 case ICmpInst::ICMP_UGE:
5755 // (float)int >= -4.4 --> true
5756 // (float)int >= 4.4 --> int > 4
5757 if (!RHS.isNegative())
5758 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5759 Pred = ICmpInst::ICMP_UGT;
5761 case ICmpInst::ICMP_SGE:
5762 // (float)int >= -4.4 --> int >= -4
5763 // (float)int >= 4.4 --> int > 4
5764 if (!RHS.isNegative())
5765 Pred = ICmpInst::ICMP_SGT;
5771 // Lower this FP comparison into an appropriate integer version of the
5773 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5776 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5777 bool Changed = SimplifyCompare(I);
5778 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5780 // Fold trivial predicates.
5781 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5782 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5783 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5784 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5786 // Simplify 'fcmp pred X, X'
5788 switch (I.getPredicate()) {
5789 default: llvm_unreachable("Unknown predicate!");
5790 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5791 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5792 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5793 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5794 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5795 case FCmpInst::FCMP_OLT: // True if ordered and less than
5796 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5797 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5799 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5800 case FCmpInst::FCMP_ULT: // True if unordered or less than
5801 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5802 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5803 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5804 I.setPredicate(FCmpInst::FCMP_UNO);
5805 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5808 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5809 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5810 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5811 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5812 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5813 I.setPredicate(FCmpInst::FCMP_ORD);
5814 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5819 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5820 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5822 // Handle fcmp with constant RHS
5823 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5824 // If the constant is a nan, see if we can fold the comparison based on it.
5825 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5826 if (CFP->getValueAPF().isNaN()) {
5827 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5828 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5829 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5830 "Comparison must be either ordered or unordered!");
5831 // True if unordered.
5832 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5836 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5837 switch (LHSI->getOpcode()) {
5838 case Instruction::PHI:
5839 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5840 // block. If in the same block, we're encouraging jump threading. If
5841 // not, we are just pessimizing the code by making an i1 phi.
5842 if (LHSI->getParent() == I.getParent())
5843 if (Instruction *NV = FoldOpIntoPhi(I))
5846 case Instruction::SIToFP:
5847 case Instruction::UIToFP:
5848 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5851 case Instruction::Select:
5852 // If either operand of the select is a constant, we can fold the
5853 // comparison into the select arms, which will cause one to be
5854 // constant folded and the select turned into a bitwise or.
5855 Value *Op1 = 0, *Op2 = 0;
5856 if (LHSI->hasOneUse()) {
5857 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5858 // Fold the known value into the constant operand.
5859 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5860 // Insert a new FCmp of the other select operand.
5861 Op2 = Builder->CreateFCmp(I.getPredicate(),
5862 LHSI->getOperand(2), RHSC, I.getName());
5863 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5864 // Fold the known value into the constant operand.
5865 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5866 // Insert a new FCmp of the other select operand.
5867 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5873 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5878 return Changed ? &I : 0;
5881 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5882 bool Changed = SimplifyCompare(I);
5883 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5884 const Type *Ty = Op0->getType();
5888 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
5889 I.isTrueWhenEqual()));
5891 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5892 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5894 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5895 // addresses never equal each other! We already know that Op0 != Op1.
5896 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5897 isa<ConstantPointerNull>(Op0)) &&
5898 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5899 isa<ConstantPointerNull>(Op1)))
5900 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
5901 !I.isTrueWhenEqual()));
5903 // icmp's with boolean values can always be turned into bitwise operations
5904 if (Ty == Type::getInt1Ty(*Context)) {
5905 switch (I.getPredicate()) {
5906 default: llvm_unreachable("Invalid icmp instruction!");
5907 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5908 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5909 return BinaryOperator::CreateNot(Xor);
5911 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5912 return BinaryOperator::CreateXor(Op0, Op1);
5914 case ICmpInst::ICMP_UGT:
5915 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5917 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5918 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5919 return BinaryOperator::CreateAnd(Not, Op1);
5921 case ICmpInst::ICMP_SGT:
5922 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5924 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5925 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5926 return BinaryOperator::CreateAnd(Not, Op0);
5928 case ICmpInst::ICMP_UGE:
5929 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5931 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
5932 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5933 return BinaryOperator::CreateOr(Not, Op1);
5935 case ICmpInst::ICMP_SGE:
5936 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5938 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5939 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5940 return BinaryOperator::CreateOr(Not, Op0);
5945 unsigned BitWidth = 0;
5947 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5948 else if (Ty->isIntOrIntVector())
5949 BitWidth = Ty->getScalarSizeInBits();
5951 bool isSignBit = false;
5953 // See if we are doing a comparison with a constant.
5954 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5955 Value *A = 0, *B = 0;
5957 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5958 if (I.isEquality() && CI->isNullValue() &&
5959 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5960 // (icmp cond A B) if cond is equality
5961 return new ICmpInst(I.getPredicate(), A, B);
5964 // If we have an icmp le or icmp ge instruction, turn it into the
5965 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5966 // them being folded in the code below.
5967 switch (I.getPredicate()) {
5969 case ICmpInst::ICMP_ULE:
5970 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5971 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5972 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
5974 case ICmpInst::ICMP_SLE:
5975 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5976 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5977 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5979 case ICmpInst::ICMP_UGE:
5980 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5981 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5982 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
5984 case ICmpInst::ICMP_SGE:
5985 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5986 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5987 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5991 // If this comparison is a normal comparison, it demands all
5992 // bits, if it is a sign bit comparison, it only demands the sign bit.
5994 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5997 // See if we can fold the comparison based on range information we can get
5998 // by checking whether bits are known to be zero or one in the input.
5999 if (BitWidth != 0) {
6000 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6001 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6003 if (SimplifyDemandedBits(I.getOperandUse(0),
6004 isSignBit ? APInt::getSignBit(BitWidth)
6005 : APInt::getAllOnesValue(BitWidth),
6006 Op0KnownZero, Op0KnownOne, 0))
6008 if (SimplifyDemandedBits(I.getOperandUse(1),
6009 APInt::getAllOnesValue(BitWidth),
6010 Op1KnownZero, Op1KnownOne, 0))
6013 // Given the known and unknown bits, compute a range that the LHS could be
6014 // in. Compute the Min, Max and RHS values based on the known bits. For the
6015 // EQ and NE we use unsigned values.
6016 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6017 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6018 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6019 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6021 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6024 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6026 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6030 // If Min and Max are known to be the same, then SimplifyDemandedBits
6031 // figured out that the LHS is a constant. Just constant fold this now so
6032 // that code below can assume that Min != Max.
6033 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6034 return new ICmpInst(I.getPredicate(),
6035 ConstantInt::get(*Context, Op0Min), Op1);
6036 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6037 return new ICmpInst(I.getPredicate(), Op0,
6038 ConstantInt::get(*Context, Op1Min));
6040 // Based on the range information we know about the LHS, see if we can
6041 // simplify this comparison. For example, (x&4) < 8 is always true.
6042 switch (I.getPredicate()) {
6043 default: llvm_unreachable("Unknown icmp opcode!");
6044 case ICmpInst::ICMP_EQ:
6045 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6046 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6048 case ICmpInst::ICMP_NE:
6049 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6050 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6052 case ICmpInst::ICMP_ULT:
6053 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6054 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6055 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6056 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6057 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6058 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6059 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6060 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6061 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6064 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6065 if (CI->isMinValue(true))
6066 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6067 Constant::getAllOnesValue(Op0->getType()));
6070 case ICmpInst::ICMP_UGT:
6071 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6072 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6073 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6074 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6076 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6077 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6078 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6079 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6080 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6083 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6084 if (CI->isMaxValue(true))
6085 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6086 Constant::getNullValue(Op0->getType()));
6089 case ICmpInst::ICMP_SLT:
6090 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6091 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6092 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6093 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6094 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6095 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6096 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6097 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6098 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6102 case ICmpInst::ICMP_SGT:
6103 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6104 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6105 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6106 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6108 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6109 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6111 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6112 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6116 case ICmpInst::ICMP_SGE:
6117 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6118 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6119 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6120 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6121 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6123 case ICmpInst::ICMP_SLE:
6124 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6125 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6126 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6127 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6128 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6130 case ICmpInst::ICMP_UGE:
6131 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6132 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6133 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6134 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6135 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6137 case ICmpInst::ICMP_ULE:
6138 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6139 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6140 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6141 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6142 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6146 // Turn a signed comparison into an unsigned one if both operands
6147 // are known to have the same sign.
6148 if (I.isSignedPredicate() &&
6149 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6150 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6151 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6154 // Test if the ICmpInst instruction is used exclusively by a select as
6155 // part of a minimum or maximum operation. If so, refrain from doing
6156 // any other folding. This helps out other analyses which understand
6157 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6158 // and CodeGen. And in this case, at least one of the comparison
6159 // operands has at least one user besides the compare (the select),
6160 // which would often largely negate the benefit of folding anyway.
6162 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6163 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6164 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6167 // See if we are doing a comparison between a constant and an instruction that
6168 // can be folded into the comparison.
6169 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6170 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6171 // instruction, see if that instruction also has constants so that the
6172 // instruction can be folded into the icmp
6173 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6174 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6178 // Handle icmp with constant (but not simple integer constant) RHS
6179 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6180 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6181 switch (LHSI->getOpcode()) {
6182 case Instruction::GetElementPtr:
6183 if (RHSC->isNullValue()) {
6184 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6185 bool isAllZeros = true;
6186 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6187 if (!isa<Constant>(LHSI->getOperand(i)) ||
6188 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6193 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6194 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6198 case Instruction::PHI:
6199 // Only fold icmp into the PHI if the phi and fcmp are in the same
6200 // block. If in the same block, we're encouraging jump threading. If
6201 // not, we are just pessimizing the code by making an i1 phi.
6202 if (LHSI->getParent() == I.getParent())
6203 if (Instruction *NV = FoldOpIntoPhi(I))
6206 case Instruction::Select: {
6207 // If either operand of the select is a constant, we can fold the
6208 // comparison into the select arms, which will cause one to be
6209 // constant folded and the select turned into a bitwise or.
6210 Value *Op1 = 0, *Op2 = 0;
6211 if (LHSI->hasOneUse()) {
6212 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6213 // Fold the known value into the constant operand.
6214 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6215 // Insert a new ICmp of the other select operand.
6216 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6218 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6219 // Fold the known value into the constant operand.
6220 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6221 // Insert a new ICmp of the other select operand.
6222 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6228 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6231 case Instruction::Malloc:
6232 // If we have (malloc != null), and if the malloc has a single use, we
6233 // can assume it is successful and remove the malloc.
6234 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6236 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6237 !I.isTrueWhenEqual()));
6243 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6244 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6245 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6247 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6248 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6249 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6252 // Test to see if the operands of the icmp are casted versions of other
6253 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6255 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6256 if (isa<PointerType>(Op0->getType()) &&
6257 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6258 // We keep moving the cast from the left operand over to the right
6259 // operand, where it can often be eliminated completely.
6260 Op0 = CI->getOperand(0);
6262 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6263 // so eliminate it as well.
6264 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6265 Op1 = CI2->getOperand(0);
6267 // If Op1 is a constant, we can fold the cast into the constant.
6268 if (Op0->getType() != Op1->getType()) {
6269 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6270 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6272 // Otherwise, cast the RHS right before the icmp
6273 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6276 return new ICmpInst(I.getPredicate(), Op0, Op1);
6280 if (isa<CastInst>(Op0)) {
6281 // Handle the special case of: icmp (cast bool to X), <cst>
6282 // This comes up when you have code like
6285 // For generality, we handle any zero-extension of any operand comparison
6286 // with a constant or another cast from the same type.
6287 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6288 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6292 // See if it's the same type of instruction on the left and right.
6293 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6294 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6295 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6296 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6297 switch (Op0I->getOpcode()) {
6299 case Instruction::Add:
6300 case Instruction::Sub:
6301 case Instruction::Xor:
6302 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6303 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6304 Op1I->getOperand(0));
6305 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6306 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6307 if (CI->getValue().isSignBit()) {
6308 ICmpInst::Predicate Pred = I.isSignedPredicate()
6309 ? I.getUnsignedPredicate()
6310 : I.getSignedPredicate();
6311 return new ICmpInst(Pred, Op0I->getOperand(0),
6312 Op1I->getOperand(0));
6315 if (CI->getValue().isMaxSignedValue()) {
6316 ICmpInst::Predicate Pred = I.isSignedPredicate()
6317 ? I.getUnsignedPredicate()
6318 : I.getSignedPredicate();
6319 Pred = I.getSwappedPredicate(Pred);
6320 return new ICmpInst(Pred, Op0I->getOperand(0),
6321 Op1I->getOperand(0));
6325 case Instruction::Mul:
6326 if (!I.isEquality())
6329 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6330 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6331 // Mask = -1 >> count-trailing-zeros(Cst).
6332 if (!CI->isZero() && !CI->isOne()) {
6333 const APInt &AP = CI->getValue();
6334 ConstantInt *Mask = ConstantInt::get(*Context,
6335 APInt::getLowBitsSet(AP.getBitWidth(),
6337 AP.countTrailingZeros()));
6338 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6339 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6340 return new ICmpInst(I.getPredicate(), And1, And2);
6349 // ~x < ~y --> y < x
6351 if (match(Op0, m_Not(m_Value(A))) &&
6352 match(Op1, m_Not(m_Value(B))))
6353 return new ICmpInst(I.getPredicate(), B, A);
6356 if (I.isEquality()) {
6357 Value *A, *B, *C, *D;
6359 // -x == -y --> x == y
6360 if (match(Op0, m_Neg(m_Value(A))) &&
6361 match(Op1, m_Neg(m_Value(B))))
6362 return new ICmpInst(I.getPredicate(), A, B);
6364 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6365 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6366 Value *OtherVal = A == Op1 ? B : A;
6367 return new ICmpInst(I.getPredicate(), OtherVal,
6368 Constant::getNullValue(A->getType()));
6371 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6372 // A^c1 == C^c2 --> A == C^(c1^c2)
6373 ConstantInt *C1, *C2;
6374 if (match(B, m_ConstantInt(C1)) &&
6375 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6377 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6378 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6379 return new ICmpInst(I.getPredicate(), A, Xor);
6382 // A^B == A^D -> B == D
6383 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6384 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6385 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6386 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6390 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6391 (A == Op0 || B == Op0)) {
6392 // A == (A^B) -> B == 0
6393 Value *OtherVal = A == Op0 ? B : A;
6394 return new ICmpInst(I.getPredicate(), OtherVal,
6395 Constant::getNullValue(A->getType()));
6398 // (A-B) == A -> B == 0
6399 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6400 return new ICmpInst(I.getPredicate(), B,
6401 Constant::getNullValue(B->getType()));
6403 // A == (A-B) -> B == 0
6404 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6405 return new ICmpInst(I.getPredicate(), B,
6406 Constant::getNullValue(B->getType()));
6408 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6409 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6410 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6411 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6412 Value *X = 0, *Y = 0, *Z = 0;
6415 X = B; Y = D; Z = A;
6416 } else if (A == D) {
6417 X = B; Y = C; Z = A;
6418 } else if (B == C) {
6419 X = A; Y = D; Z = B;
6420 } else if (B == D) {
6421 X = A; Y = C; Z = B;
6424 if (X) { // Build (X^Y) & Z
6425 Op1 = Builder->CreateXor(X, Y, "tmp");
6426 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6427 I.setOperand(0, Op1);
6428 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6433 return Changed ? &I : 0;
6437 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6438 /// and CmpRHS are both known to be integer constants.
6439 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6440 ConstantInt *DivRHS) {
6441 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6442 const APInt &CmpRHSV = CmpRHS->getValue();
6444 // FIXME: If the operand types don't match the type of the divide
6445 // then don't attempt this transform. The code below doesn't have the
6446 // logic to deal with a signed divide and an unsigned compare (and
6447 // vice versa). This is because (x /s C1) <s C2 produces different
6448 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6449 // (x /u C1) <u C2. Simply casting the operands and result won't
6450 // work. :( The if statement below tests that condition and bails
6452 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6453 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6455 if (DivRHS->isZero())
6456 return 0; // The ProdOV computation fails on divide by zero.
6457 if (DivIsSigned && DivRHS->isAllOnesValue())
6458 return 0; // The overflow computation also screws up here
6459 if (DivRHS->isOne())
6460 return 0; // Not worth bothering, and eliminates some funny cases
6463 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6464 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6465 // C2 (CI). By solving for X we can turn this into a range check
6466 // instead of computing a divide.
6467 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6469 // Determine if the product overflows by seeing if the product is
6470 // not equal to the divide. Make sure we do the same kind of divide
6471 // as in the LHS instruction that we're folding.
6472 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6473 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6475 // Get the ICmp opcode
6476 ICmpInst::Predicate Pred = ICI.getPredicate();
6478 // Figure out the interval that is being checked. For example, a comparison
6479 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6480 // Compute this interval based on the constants involved and the signedness of
6481 // the compare/divide. This computes a half-open interval, keeping track of
6482 // whether either value in the interval overflows. After analysis each
6483 // overflow variable is set to 0 if it's corresponding bound variable is valid
6484 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6485 int LoOverflow = 0, HiOverflow = 0;
6486 Constant *LoBound = 0, *HiBound = 0;
6488 if (!DivIsSigned) { // udiv
6489 // e.g. X/5 op 3 --> [15, 20)
6491 HiOverflow = LoOverflow = ProdOV;
6493 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6494 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6495 if (CmpRHSV == 0) { // (X / pos) op 0
6496 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6497 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6499 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6500 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6501 HiOverflow = LoOverflow = ProdOV;
6503 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6504 } else { // (X / pos) op neg
6505 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6506 HiBound = AddOne(Prod);
6507 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6509 ConstantInt* DivNeg =
6510 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6511 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6515 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6516 if (CmpRHSV == 0) { // (X / neg) op 0
6517 // e.g. X/-5 op 0 --> [-4, 5)
6518 LoBound = AddOne(DivRHS);
6519 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6520 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6521 HiOverflow = 1; // [INTMIN+1, overflow)
6522 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6524 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6525 // e.g. X/-5 op 3 --> [-19, -14)
6526 HiBound = AddOne(Prod);
6527 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6529 LoOverflow = AddWithOverflow(LoBound, HiBound,
6530 DivRHS, Context, true) ? -1 : 0;
6531 } else { // (X / neg) op neg
6532 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6533 LoOverflow = HiOverflow = ProdOV;
6535 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6538 // Dividing by a negative swaps the condition. LT <-> GT
6539 Pred = ICmpInst::getSwappedPredicate(Pred);
6542 Value *X = DivI->getOperand(0);
6544 default: llvm_unreachable("Unhandled icmp opcode!");
6545 case ICmpInst::ICMP_EQ:
6546 if (LoOverflow && HiOverflow)
6547 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6548 else if (HiOverflow)
6549 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6550 ICmpInst::ICMP_UGE, X, LoBound);
6551 else if (LoOverflow)
6552 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6553 ICmpInst::ICMP_ULT, X, HiBound);
6555 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6556 case ICmpInst::ICMP_NE:
6557 if (LoOverflow && HiOverflow)
6558 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6559 else if (HiOverflow)
6560 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6561 ICmpInst::ICMP_ULT, X, LoBound);
6562 else if (LoOverflow)
6563 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6564 ICmpInst::ICMP_UGE, X, HiBound);
6566 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6567 case ICmpInst::ICMP_ULT:
6568 case ICmpInst::ICMP_SLT:
6569 if (LoOverflow == +1) // Low bound is greater than input range.
6570 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6571 if (LoOverflow == -1) // Low bound is less than input range.
6572 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6573 return new ICmpInst(Pred, X, LoBound);
6574 case ICmpInst::ICMP_UGT:
6575 case ICmpInst::ICMP_SGT:
6576 if (HiOverflow == +1) // High bound greater than input range.
6577 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6578 else if (HiOverflow == -1) // High bound less than input range.
6579 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6580 if (Pred == ICmpInst::ICMP_UGT)
6581 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6583 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6588 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6590 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6593 const APInt &RHSV = RHS->getValue();
6595 switch (LHSI->getOpcode()) {
6596 case Instruction::Trunc:
6597 if (ICI.isEquality() && LHSI->hasOneUse()) {
6598 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6599 // of the high bits truncated out of x are known.
6600 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6601 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6602 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6603 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6604 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6606 // If all the high bits are known, we can do this xform.
6607 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6608 // Pull in the high bits from known-ones set.
6609 APInt NewRHS(RHS->getValue());
6610 NewRHS.zext(SrcBits);
6612 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6613 ConstantInt::get(*Context, NewRHS));
6618 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6619 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6620 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6622 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6623 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6624 Value *CompareVal = LHSI->getOperand(0);
6626 // If the sign bit of the XorCST is not set, there is no change to
6627 // the operation, just stop using the Xor.
6628 if (!XorCST->getValue().isNegative()) {
6629 ICI.setOperand(0, CompareVal);
6634 // Was the old condition true if the operand is positive?
6635 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6637 // If so, the new one isn't.
6638 isTrueIfPositive ^= true;
6640 if (isTrueIfPositive)
6641 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6644 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6648 if (LHSI->hasOneUse()) {
6649 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6650 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6651 const APInt &SignBit = XorCST->getValue();
6652 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6653 ? ICI.getUnsignedPredicate()
6654 : ICI.getSignedPredicate();
6655 return new ICmpInst(Pred, LHSI->getOperand(0),
6656 ConstantInt::get(*Context, RHSV ^ SignBit));
6659 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6660 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6661 const APInt &NotSignBit = XorCST->getValue();
6662 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6663 ? ICI.getUnsignedPredicate()
6664 : ICI.getSignedPredicate();
6665 Pred = ICI.getSwappedPredicate(Pred);
6666 return new ICmpInst(Pred, LHSI->getOperand(0),
6667 ConstantInt::get(*Context, RHSV ^ NotSignBit));
6672 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6673 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6674 LHSI->getOperand(0)->hasOneUse()) {
6675 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6677 // If the LHS is an AND of a truncating cast, we can widen the
6678 // and/compare to be the input width without changing the value
6679 // produced, eliminating a cast.
6680 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6681 // We can do this transformation if either the AND constant does not
6682 // have its sign bit set or if it is an equality comparison.
6683 // Extending a relational comparison when we're checking the sign
6684 // bit would not work.
6685 if (Cast->hasOneUse() &&
6686 (ICI.isEquality() ||
6687 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6689 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6690 APInt NewCST = AndCST->getValue();
6691 NewCST.zext(BitWidth);
6693 NewCI.zext(BitWidth);
6695 Builder->CreateAnd(Cast->getOperand(0),
6696 ConstantInt::get(*Context, NewCST), LHSI->getName());
6697 return new ICmpInst(ICI.getPredicate(), NewAnd,
6698 ConstantInt::get(*Context, NewCI));
6702 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6703 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6704 // happens a LOT in code produced by the C front-end, for bitfield
6706 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6707 if (Shift && !Shift->isShift())
6711 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6712 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6713 const Type *AndTy = AndCST->getType(); // Type of the and.
6715 // We can fold this as long as we can't shift unknown bits
6716 // into the mask. This can only happen with signed shift
6717 // rights, as they sign-extend.
6719 bool CanFold = Shift->isLogicalShift();
6721 // To test for the bad case of the signed shr, see if any
6722 // of the bits shifted in could be tested after the mask.
6723 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6724 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6726 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6727 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6728 AndCST->getValue()) == 0)
6734 if (Shift->getOpcode() == Instruction::Shl)
6735 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6737 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6739 // Check to see if we are shifting out any of the bits being
6741 if (ConstantExpr::get(Shift->getOpcode(),
6742 NewCst, ShAmt) != RHS) {
6743 // If we shifted bits out, the fold is not going to work out.
6744 // As a special case, check to see if this means that the
6745 // result is always true or false now.
6746 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6747 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6748 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6749 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6751 ICI.setOperand(1, NewCst);
6752 Constant *NewAndCST;
6753 if (Shift->getOpcode() == Instruction::Shl)
6754 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6756 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6757 LHSI->setOperand(1, NewAndCST);
6758 LHSI->setOperand(0, Shift->getOperand(0));
6759 Worklist.Add(Shift); // Shift is dead.
6765 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6766 // preferable because it allows the C<<Y expression to be hoisted out
6767 // of a loop if Y is invariant and X is not.
6768 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6769 ICI.isEquality() && !Shift->isArithmeticShift() &&
6770 !isa<Constant>(Shift->getOperand(0))) {
6773 if (Shift->getOpcode() == Instruction::LShr) {
6774 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6776 // Insert a logical shift.
6777 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6780 // Compute X & (C << Y).
6782 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6784 ICI.setOperand(0, NewAnd);
6790 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6791 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6794 uint32_t TypeBits = RHSV.getBitWidth();
6796 // Check that the shift amount is in range. If not, don't perform
6797 // undefined shifts. When the shift is visited it will be
6799 if (ShAmt->uge(TypeBits))
6802 if (ICI.isEquality()) {
6803 // If we are comparing against bits always shifted out, the
6804 // comparison cannot succeed.
6806 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6808 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6809 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6810 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6811 return ReplaceInstUsesWith(ICI, Cst);
6814 if (LHSI->hasOneUse()) {
6815 // Otherwise strength reduce the shift into an and.
6816 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6818 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
6819 TypeBits-ShAmtVal));
6822 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6823 return new ICmpInst(ICI.getPredicate(), And,
6824 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6828 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6829 bool TrueIfSigned = false;
6830 if (LHSI->hasOneUse() &&
6831 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6832 // (X << 31) <s 0 --> (X&1) != 0
6833 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6834 (TypeBits-ShAmt->getZExtValue()-1));
6836 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6837 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6838 And, Constant::getNullValue(And->getType()));
6843 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6844 case Instruction::AShr: {
6845 // Only handle equality comparisons of shift-by-constant.
6846 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6847 if (!ShAmt || !ICI.isEquality()) break;
6849 // Check that the shift amount is in range. If not, don't perform
6850 // undefined shifts. When the shift is visited it will be
6852 uint32_t TypeBits = RHSV.getBitWidth();
6853 if (ShAmt->uge(TypeBits))
6856 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6858 // If we are comparing against bits always shifted out, the
6859 // comparison cannot succeed.
6860 APInt Comp = RHSV << ShAmtVal;
6861 if (LHSI->getOpcode() == Instruction::LShr)
6862 Comp = Comp.lshr(ShAmtVal);
6864 Comp = Comp.ashr(ShAmtVal);
6866 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6867 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6868 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6869 return ReplaceInstUsesWith(ICI, Cst);
6872 // Otherwise, check to see if the bits shifted out are known to be zero.
6873 // If so, we can compare against the unshifted value:
6874 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6875 if (LHSI->hasOneUse() &&
6876 MaskedValueIsZero(LHSI->getOperand(0),
6877 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6878 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6879 ConstantExpr::getShl(RHS, ShAmt));
6882 if (LHSI->hasOneUse()) {
6883 // Otherwise strength reduce the shift into an and.
6884 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6885 Constant *Mask = ConstantInt::get(*Context, Val);
6887 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6888 Mask, LHSI->getName()+".mask");
6889 return new ICmpInst(ICI.getPredicate(), And,
6890 ConstantExpr::getShl(RHS, ShAmt));
6895 case Instruction::SDiv:
6896 case Instruction::UDiv:
6897 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6898 // Fold this div into the comparison, producing a range check.
6899 // Determine, based on the divide type, what the range is being
6900 // checked. If there is an overflow on the low or high side, remember
6901 // it, otherwise compute the range [low, hi) bounding the new value.
6902 // See: InsertRangeTest above for the kinds of replacements possible.
6903 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6904 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6909 case Instruction::Add:
6910 // Fold: icmp pred (add, X, C1), C2
6912 if (!ICI.isEquality()) {
6913 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6915 const APInt &LHSV = LHSC->getValue();
6917 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6920 if (ICI.isSignedPredicate()) {
6921 if (CR.getLower().isSignBit()) {
6922 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6923 ConstantInt::get(*Context, CR.getUpper()));
6924 } else if (CR.getUpper().isSignBit()) {
6925 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6926 ConstantInt::get(*Context, CR.getLower()));
6929 if (CR.getLower().isMinValue()) {
6930 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6931 ConstantInt::get(*Context, CR.getUpper()));
6932 } else if (CR.getUpper().isMinValue()) {
6933 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6934 ConstantInt::get(*Context, CR.getLower()));
6941 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6942 if (ICI.isEquality()) {
6943 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6945 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6946 // the second operand is a constant, simplify a bit.
6947 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6948 switch (BO->getOpcode()) {
6949 case Instruction::SRem:
6950 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6951 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6952 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6953 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6955 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6957 return new ICmpInst(ICI.getPredicate(), NewRem,
6958 Constant::getNullValue(BO->getType()));
6962 case Instruction::Add:
6963 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6964 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6965 if (BO->hasOneUse())
6966 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6967 ConstantExpr::getSub(RHS, BOp1C));
6968 } else if (RHSV == 0) {
6969 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6970 // efficiently invertible, or if the add has just this one use.
6971 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6973 if (Value *NegVal = dyn_castNegVal(BOp1))
6974 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6975 else if (Value *NegVal = dyn_castNegVal(BOp0))
6976 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6977 else if (BO->hasOneUse()) {
6978 Value *Neg = Builder->CreateNeg(BOp1);
6980 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6984 case Instruction::Xor:
6985 // For the xor case, we can xor two constants together, eliminating
6986 // the explicit xor.
6987 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6988 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6989 ConstantExpr::getXor(RHS, BOC));
6992 case Instruction::Sub:
6993 // Replace (([sub|xor] A, B) != 0) with (A != B)
6995 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6999 case Instruction::Or:
7000 // If bits are being or'd in that are not present in the constant we
7001 // are comparing against, then the comparison could never succeed!
7002 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7003 Constant *NotCI = ConstantExpr::getNot(RHS);
7004 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7005 return ReplaceInstUsesWith(ICI,
7006 ConstantInt::get(Type::getInt1Ty(*Context),
7011 case Instruction::And:
7012 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7013 // If bits are being compared against that are and'd out, then the
7014 // comparison can never succeed!
7015 if ((RHSV & ~BOC->getValue()) != 0)
7016 return ReplaceInstUsesWith(ICI,
7017 ConstantInt::get(Type::getInt1Ty(*Context),
7020 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7021 if (RHS == BOC && RHSV.isPowerOf2())
7022 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7023 ICmpInst::ICMP_NE, LHSI,
7024 Constant::getNullValue(RHS->getType()));
7026 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7027 if (BOC->getValue().isSignBit()) {
7028 Value *X = BO->getOperand(0);
7029 Constant *Zero = Constant::getNullValue(X->getType());
7030 ICmpInst::Predicate pred = isICMP_NE ?
7031 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7032 return new ICmpInst(pred, X, Zero);
7035 // ((X & ~7) == 0) --> X < 8
7036 if (RHSV == 0 && isHighOnes(BOC)) {
7037 Value *X = BO->getOperand(0);
7038 Constant *NegX = ConstantExpr::getNeg(BOC);
7039 ICmpInst::Predicate pred = isICMP_NE ?
7040 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7041 return new ICmpInst(pred, X, NegX);
7046 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7047 // Handle icmp {eq|ne} <intrinsic>, intcst.
7048 if (II->getIntrinsicID() == Intrinsic::bswap) {
7050 ICI.setOperand(0, II->getOperand(1));
7051 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7059 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7060 /// We only handle extending casts so far.
7062 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7063 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7064 Value *LHSCIOp = LHSCI->getOperand(0);
7065 const Type *SrcTy = LHSCIOp->getType();
7066 const Type *DestTy = LHSCI->getType();
7069 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7070 // integer type is the same size as the pointer type.
7071 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7072 TD->getPointerSizeInBits() ==
7073 cast<IntegerType>(DestTy)->getBitWidth()) {
7075 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7076 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7077 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7078 RHSOp = RHSC->getOperand(0);
7079 // If the pointer types don't match, insert a bitcast.
7080 if (LHSCIOp->getType() != RHSOp->getType())
7081 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7085 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7088 // The code below only handles extension cast instructions, so far.
7090 if (LHSCI->getOpcode() != Instruction::ZExt &&
7091 LHSCI->getOpcode() != Instruction::SExt)
7094 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7095 bool isSignedCmp = ICI.isSignedPredicate();
7097 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7098 // Not an extension from the same type?
7099 RHSCIOp = CI->getOperand(0);
7100 if (RHSCIOp->getType() != LHSCIOp->getType())
7103 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7104 // and the other is a zext), then we can't handle this.
7105 if (CI->getOpcode() != LHSCI->getOpcode())
7108 // Deal with equality cases early.
7109 if (ICI.isEquality())
7110 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7112 // A signed comparison of sign extended values simplifies into a
7113 // signed comparison.
7114 if (isSignedCmp && isSignedExt)
7115 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7117 // The other three cases all fold into an unsigned comparison.
7118 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7121 // If we aren't dealing with a constant on the RHS, exit early
7122 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7126 // Compute the constant that would happen if we truncated to SrcTy then
7127 // reextended to DestTy.
7128 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7129 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7132 // If the re-extended constant didn't change...
7134 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7135 // For example, we might have:
7136 // %A = sext i16 %X to i32
7137 // %B = icmp ugt i32 %A, 1330
7138 // It is incorrect to transform this into
7139 // %B = icmp ugt i16 %X, 1330
7140 // because %A may have negative value.
7142 // However, we allow this when the compare is EQ/NE, because they are
7144 if (isSignedExt == isSignedCmp || ICI.isEquality())
7145 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7149 // The re-extended constant changed so the constant cannot be represented
7150 // in the shorter type. Consequently, we cannot emit a simple comparison.
7152 // First, handle some easy cases. We know the result cannot be equal at this
7153 // point so handle the ICI.isEquality() cases
7154 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7155 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7156 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7157 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7159 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7160 // should have been folded away previously and not enter in here.
7163 // We're performing a signed comparison.
7164 if (cast<ConstantInt>(CI)->getValue().isNegative())
7165 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
7167 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
7169 // We're performing an unsigned comparison.
7171 // We're performing an unsigned comp with a sign extended value.
7172 // This is true if the input is >= 0. [aka >s -1]
7173 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7174 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7176 // Unsigned extend & unsigned compare -> always true.
7177 Result = ConstantInt::getTrue(*Context);
7181 // Finally, return the value computed.
7182 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7183 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7184 return ReplaceInstUsesWith(ICI, Result);
7186 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7187 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7188 "ICmp should be folded!");
7189 if (Constant *CI = dyn_cast<Constant>(Result))
7190 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7191 return BinaryOperator::CreateNot(Result);
7194 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7195 return commonShiftTransforms(I);
7198 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7199 return commonShiftTransforms(I);
7202 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7203 if (Instruction *R = commonShiftTransforms(I))
7206 Value *Op0 = I.getOperand(0);
7208 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7209 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7210 if (CSI->isAllOnesValue())
7211 return ReplaceInstUsesWith(I, CSI);
7213 // See if we can turn a signed shr into an unsigned shr.
7214 if (MaskedValueIsZero(Op0,
7215 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7216 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7218 // Arithmetic shifting an all-sign-bit value is a no-op.
7219 unsigned NumSignBits = ComputeNumSignBits(Op0);
7220 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7221 return ReplaceInstUsesWith(I, Op0);
7226 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7227 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7230 // shl X, 0 == X and shr X, 0 == X
7231 // shl 0, X == 0 and shr 0, X == 0
7232 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7233 Op0 == Constant::getNullValue(Op0->getType()))
7234 return ReplaceInstUsesWith(I, Op0);
7236 if (isa<UndefValue>(Op0)) {
7237 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7238 return ReplaceInstUsesWith(I, Op0);
7239 else // undef << X -> 0, undef >>u X -> 0
7240 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7242 if (isa<UndefValue>(Op1)) {
7243 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7244 return ReplaceInstUsesWith(I, Op0);
7245 else // X << undef, X >>u undef -> 0
7246 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7249 // See if we can fold away this shift.
7250 if (SimplifyDemandedInstructionBits(I))
7253 // Try to fold constant and into select arguments.
7254 if (isa<Constant>(Op0))
7255 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7256 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7259 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7260 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7265 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7266 BinaryOperator &I) {
7267 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7269 // See if we can simplify any instructions used by the instruction whose sole
7270 // purpose is to compute bits we don't care about.
7271 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7273 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7276 if (Op1->uge(TypeBits)) {
7277 if (I.getOpcode() != Instruction::AShr)
7278 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7280 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7285 // ((X*C1) << C2) == (X * (C1 << C2))
7286 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7287 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7288 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7289 return BinaryOperator::CreateMul(BO->getOperand(0),
7290 ConstantExpr::getShl(BOOp, Op1));
7292 // Try to fold constant and into select arguments.
7293 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7294 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7296 if (isa<PHINode>(Op0))
7297 if (Instruction *NV = FoldOpIntoPhi(I))
7300 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7301 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7302 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7303 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7304 // place. Don't try to do this transformation in this case. Also, we
7305 // require that the input operand is a shift-by-constant so that we have
7306 // confidence that the shifts will get folded together. We could do this
7307 // xform in more cases, but it is unlikely to be profitable.
7308 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7309 isa<ConstantInt>(TrOp->getOperand(1))) {
7310 // Okay, we'll do this xform. Make the shift of shift.
7311 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7312 // (shift2 (shift1 & 0x00FF), c2)
7313 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7315 // For logical shifts, the truncation has the effect of making the high
7316 // part of the register be zeros. Emulate this by inserting an AND to
7317 // clear the top bits as needed. This 'and' will usually be zapped by
7318 // other xforms later if dead.
7319 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7320 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7321 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7323 // The mask we constructed says what the trunc would do if occurring
7324 // between the shifts. We want to know the effect *after* the second
7325 // shift. We know that it is a logical shift by a constant, so adjust the
7326 // mask as appropriate.
7327 if (I.getOpcode() == Instruction::Shl)
7328 MaskV <<= Op1->getZExtValue();
7330 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7331 MaskV = MaskV.lshr(Op1->getZExtValue());
7335 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7338 // Return the value truncated to the interesting size.
7339 return new TruncInst(And, I.getType());
7343 if (Op0->hasOneUse()) {
7344 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7345 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7348 switch (Op0BO->getOpcode()) {
7350 case Instruction::Add:
7351 case Instruction::And:
7352 case Instruction::Or:
7353 case Instruction::Xor: {
7354 // These operators commute.
7355 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7356 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7357 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7358 m_Specific(Op1)))) {
7359 Value *YS = // (Y << C)
7360 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7362 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7363 Op0BO->getOperand(1)->getName());
7364 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7365 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7366 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7369 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7370 Value *Op0BOOp1 = Op0BO->getOperand(1);
7371 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7373 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7374 m_ConstantInt(CC))) &&
7375 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7376 Value *YS = // (Y << C)
7377 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7380 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7381 V1->getName()+".mask");
7382 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7387 case Instruction::Sub: {
7388 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7389 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7390 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7391 m_Specific(Op1)))) {
7392 Value *YS = // (Y << C)
7393 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7395 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7396 Op0BO->getOperand(0)->getName());
7397 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7398 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7399 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7402 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7403 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7404 match(Op0BO->getOperand(0),
7405 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7406 m_ConstantInt(CC))) && V2 == Op1 &&
7407 cast<BinaryOperator>(Op0BO->getOperand(0))
7408 ->getOperand(0)->hasOneUse()) {
7409 Value *YS = // (Y << C)
7410 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7412 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7413 V1->getName()+".mask");
7415 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7423 // If the operand is an bitwise operator with a constant RHS, and the
7424 // shift is the only use, we can pull it out of the shift.
7425 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7426 bool isValid = true; // Valid only for And, Or, Xor
7427 bool highBitSet = false; // Transform if high bit of constant set?
7429 switch (Op0BO->getOpcode()) {
7430 default: isValid = false; break; // Do not perform transform!
7431 case Instruction::Add:
7432 isValid = isLeftShift;
7434 case Instruction::Or:
7435 case Instruction::Xor:
7438 case Instruction::And:
7443 // If this is a signed shift right, and the high bit is modified
7444 // by the logical operation, do not perform the transformation.
7445 // The highBitSet boolean indicates the value of the high bit of
7446 // the constant which would cause it to be modified for this
7449 if (isValid && I.getOpcode() == Instruction::AShr)
7450 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7453 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7456 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7457 NewShift->takeName(Op0BO);
7459 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7466 // Find out if this is a shift of a shift by a constant.
7467 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7468 if (ShiftOp && !ShiftOp->isShift())
7471 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7472 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7473 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7474 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7475 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7476 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7477 Value *X = ShiftOp->getOperand(0);
7479 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7481 const IntegerType *Ty = cast<IntegerType>(I.getType());
7483 // Check for (X << c1) << c2 and (X >> c1) >> c2
7484 if (I.getOpcode() == ShiftOp->getOpcode()) {
7485 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7487 if (AmtSum >= TypeBits) {
7488 if (I.getOpcode() != Instruction::AShr)
7489 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7490 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7493 return BinaryOperator::Create(I.getOpcode(), X,
7494 ConstantInt::get(Ty, AmtSum));
7497 if (ShiftOp->getOpcode() == Instruction::LShr &&
7498 I.getOpcode() == Instruction::AShr) {
7499 if (AmtSum >= TypeBits)
7500 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7502 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7503 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7506 if (ShiftOp->getOpcode() == Instruction::AShr &&
7507 I.getOpcode() == Instruction::LShr) {
7508 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7509 if (AmtSum >= TypeBits)
7510 AmtSum = TypeBits-1;
7512 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7514 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7515 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7518 // Okay, if we get here, one shift must be left, and the other shift must be
7519 // right. See if the amounts are equal.
7520 if (ShiftAmt1 == ShiftAmt2) {
7521 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7522 if (I.getOpcode() == Instruction::Shl) {
7523 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7524 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7526 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7527 if (I.getOpcode() == Instruction::LShr) {
7528 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7529 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7531 // We can simplify ((X << C) >>s C) into a trunc + sext.
7532 // NOTE: we could do this for any C, but that would make 'unusual' integer
7533 // types. For now, just stick to ones well-supported by the code
7535 const Type *SExtType = 0;
7536 switch (Ty->getBitWidth() - ShiftAmt1) {
7543 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7548 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7549 // Otherwise, we can't handle it yet.
7550 } else if (ShiftAmt1 < ShiftAmt2) {
7551 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7553 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7554 if (I.getOpcode() == Instruction::Shl) {
7555 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7556 ShiftOp->getOpcode() == Instruction::AShr);
7557 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7559 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7560 return BinaryOperator::CreateAnd(Shift,
7561 ConstantInt::get(*Context, Mask));
7564 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7565 if (I.getOpcode() == Instruction::LShr) {
7566 assert(ShiftOp->getOpcode() == Instruction::Shl);
7567 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7569 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7570 return BinaryOperator::CreateAnd(Shift,
7571 ConstantInt::get(*Context, Mask));
7574 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7576 assert(ShiftAmt2 < ShiftAmt1);
7577 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7579 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7580 if (I.getOpcode() == Instruction::Shl) {
7581 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7582 ShiftOp->getOpcode() == Instruction::AShr);
7583 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7584 ConstantInt::get(Ty, ShiftDiff));
7586 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7587 return BinaryOperator::CreateAnd(Shift,
7588 ConstantInt::get(*Context, Mask));
7591 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7592 if (I.getOpcode() == Instruction::LShr) {
7593 assert(ShiftOp->getOpcode() == Instruction::Shl);
7594 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7596 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7597 return BinaryOperator::CreateAnd(Shift,
7598 ConstantInt::get(*Context, Mask));
7601 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7608 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7609 /// expression. If so, decompose it, returning some value X, such that Val is
7612 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7613 int &Offset, LLVMContext *Context) {
7614 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7615 "Unexpected allocation size type!");
7616 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7617 Offset = CI->getZExtValue();
7619 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7620 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7621 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7622 if (I->getOpcode() == Instruction::Shl) {
7623 // This is a value scaled by '1 << the shift amt'.
7624 Scale = 1U << RHS->getZExtValue();
7626 return I->getOperand(0);
7627 } else if (I->getOpcode() == Instruction::Mul) {
7628 // This value is scaled by 'RHS'.
7629 Scale = RHS->getZExtValue();
7631 return I->getOperand(0);
7632 } else if (I->getOpcode() == Instruction::Add) {
7633 // We have X+C. Check to see if we really have (X*C2)+C1,
7634 // where C1 is divisible by C2.
7637 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7639 Offset += RHS->getZExtValue();
7646 // Otherwise, we can't look past this.
7653 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7654 /// try to eliminate the cast by moving the type information into the alloc.
7655 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7656 AllocationInst &AI) {
7657 const PointerType *PTy = cast<PointerType>(CI.getType());
7659 BuilderTy AllocaBuilder(*Builder);
7660 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7662 // Remove any uses of AI that are dead.
7663 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7665 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7666 Instruction *User = cast<Instruction>(*UI++);
7667 if (isInstructionTriviallyDead(User)) {
7668 while (UI != E && *UI == User)
7669 ++UI; // If this instruction uses AI more than once, don't break UI.
7672 DEBUG(errs() << "IC: DCE: " << *User << '\n');
7673 EraseInstFromFunction(*User);
7677 // This requires TargetData to get the alloca alignment and size information.
7680 // Get the type really allocated and the type casted to.
7681 const Type *AllocElTy = AI.getAllocatedType();
7682 const Type *CastElTy = PTy->getElementType();
7683 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7685 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7686 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7687 if (CastElTyAlign < AllocElTyAlign) return 0;
7689 // If the allocation has multiple uses, only promote it if we are strictly
7690 // increasing the alignment of the resultant allocation. If we keep it the
7691 // same, we open the door to infinite loops of various kinds. (A reference
7692 // from a dbg.declare doesn't count as a use for this purpose.)
7693 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7694 CastElTyAlign == AllocElTyAlign) return 0;
7696 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7697 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7698 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7700 // See if we can satisfy the modulus by pulling a scale out of the array
7702 unsigned ArraySizeScale;
7704 Value *NumElements = // See if the array size is a decomposable linear expr.
7705 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7706 ArrayOffset, Context);
7708 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7710 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7711 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7713 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7718 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7719 // Insert before the alloca, not before the cast.
7720 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7723 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7724 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7725 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7728 AllocationInst *New;
7729 if (isa<MallocInst>(AI))
7730 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7732 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7733 New->setAlignment(AI.getAlignment());
7736 // If the allocation has one real use plus a dbg.declare, just remove the
7738 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7739 EraseInstFromFunction(*DI);
7741 // If the allocation has multiple real uses, insert a cast and change all
7742 // things that used it to use the new cast. This will also hack on CI, but it
7744 else if (!AI.hasOneUse()) {
7745 // New is the allocation instruction, pointer typed. AI is the original
7746 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7747 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7748 AI.replaceAllUsesWith(NewCast);
7750 return ReplaceInstUsesWith(CI, New);
7753 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7754 /// and return it as type Ty without inserting any new casts and without
7755 /// changing the computed value. This is used by code that tries to decide
7756 /// whether promoting or shrinking integer operations to wider or smaller types
7757 /// will allow us to eliminate a truncate or extend.
7759 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7760 /// extension operation if Ty is larger.
7762 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7763 /// should return true if trunc(V) can be computed by computing V in the smaller
7764 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7765 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7766 /// efficiently truncated.
7768 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7769 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7770 /// the final result.
7771 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7773 int &NumCastsRemoved){
7774 // We can always evaluate constants in another type.
7775 if (isa<Constant>(V))
7778 Instruction *I = dyn_cast<Instruction>(V);
7779 if (!I) return false;
7781 const Type *OrigTy = V->getType();
7783 // If this is an extension or truncate, we can often eliminate it.
7784 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7785 // If this is a cast from the destination type, we can trivially eliminate
7786 // it, and this will remove a cast overall.
7787 if (I->getOperand(0)->getType() == Ty) {
7788 // If the first operand is itself a cast, and is eliminable, do not count
7789 // this as an eliminable cast. We would prefer to eliminate those two
7791 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7797 // We can't extend or shrink something that has multiple uses: doing so would
7798 // require duplicating the instruction in general, which isn't profitable.
7799 if (!I->hasOneUse()) return false;
7801 unsigned Opc = I->getOpcode();
7803 case Instruction::Add:
7804 case Instruction::Sub:
7805 case Instruction::Mul:
7806 case Instruction::And:
7807 case Instruction::Or:
7808 case Instruction::Xor:
7809 // These operators can all arbitrarily be extended or truncated.
7810 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7812 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7815 case Instruction::UDiv:
7816 case Instruction::URem: {
7817 // UDiv and URem can be truncated if all the truncated bits are zero.
7818 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7819 uint32_t BitWidth = Ty->getScalarSizeInBits();
7820 if (BitWidth < OrigBitWidth) {
7821 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7822 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7823 MaskedValueIsZero(I->getOperand(1), Mask)) {
7824 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7826 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7832 case Instruction::Shl:
7833 // If we are truncating the result of this SHL, and if it's a shift of a
7834 // constant amount, we can always perform a SHL in a smaller type.
7835 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7836 uint32_t BitWidth = Ty->getScalarSizeInBits();
7837 if (BitWidth < OrigTy->getScalarSizeInBits() &&
7838 CI->getLimitedValue(BitWidth) < BitWidth)
7839 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7843 case Instruction::LShr:
7844 // If this is a truncate of a logical shr, we can truncate it to a smaller
7845 // lshr iff we know that the bits we would otherwise be shifting in are
7847 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7848 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7849 uint32_t BitWidth = Ty->getScalarSizeInBits();
7850 if (BitWidth < OrigBitWidth &&
7851 MaskedValueIsZero(I->getOperand(0),
7852 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7853 CI->getLimitedValue(BitWidth) < BitWidth) {
7854 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7859 case Instruction::ZExt:
7860 case Instruction::SExt:
7861 case Instruction::Trunc:
7862 // If this is the same kind of case as our original (e.g. zext+zext), we
7863 // can safely replace it. Note that replacing it does not reduce the number
7864 // of casts in the input.
7868 // sext (zext ty1), ty2 -> zext ty2
7869 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7872 case Instruction::Select: {
7873 SelectInst *SI = cast<SelectInst>(I);
7874 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7876 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7879 case Instruction::PHI: {
7880 // We can change a phi if we can change all operands.
7881 PHINode *PN = cast<PHINode>(I);
7882 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7883 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7889 // TODO: Can handle more cases here.
7896 /// EvaluateInDifferentType - Given an expression that
7897 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7898 /// evaluate the expression.
7899 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7901 if (Constant *C = dyn_cast<Constant>(V))
7902 return ConstantExpr::getIntegerCast(C, Ty,
7903 isSigned /*Sext or ZExt*/);
7905 // Otherwise, it must be an instruction.
7906 Instruction *I = cast<Instruction>(V);
7907 Instruction *Res = 0;
7908 unsigned Opc = I->getOpcode();
7910 case Instruction::Add:
7911 case Instruction::Sub:
7912 case Instruction::Mul:
7913 case Instruction::And:
7914 case Instruction::Or:
7915 case Instruction::Xor:
7916 case Instruction::AShr:
7917 case Instruction::LShr:
7918 case Instruction::Shl:
7919 case Instruction::UDiv:
7920 case Instruction::URem: {
7921 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7922 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7923 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7926 case Instruction::Trunc:
7927 case Instruction::ZExt:
7928 case Instruction::SExt:
7929 // If the source type of the cast is the type we're trying for then we can
7930 // just return the source. There's no need to insert it because it is not
7932 if (I->getOperand(0)->getType() == Ty)
7933 return I->getOperand(0);
7935 // Otherwise, must be the same type of cast, so just reinsert a new one.
7936 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7939 case Instruction::Select: {
7940 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7941 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7942 Res = SelectInst::Create(I->getOperand(0), True, False);
7945 case Instruction::PHI: {
7946 PHINode *OPN = cast<PHINode>(I);
7947 PHINode *NPN = PHINode::Create(Ty);
7948 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7949 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7950 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7956 // TODO: Can handle more cases here.
7957 llvm_unreachable("Unreachable!");
7962 return InsertNewInstBefore(Res, *I);
7965 /// @brief Implement the transforms common to all CastInst visitors.
7966 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7967 Value *Src = CI.getOperand(0);
7969 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7970 // eliminate it now.
7971 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7972 if (Instruction::CastOps opc =
7973 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7974 // The first cast (CSrc) is eliminable so we need to fix up or replace
7975 // the second cast (CI). CSrc will then have a good chance of being dead.
7976 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7980 // If we are casting a select then fold the cast into the select
7981 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7982 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7985 // If we are casting a PHI then fold the cast into the PHI
7986 if (isa<PHINode>(Src))
7987 if (Instruction *NV = FoldOpIntoPhi(CI))
7993 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7994 /// or not there is a sequence of GEP indices into the type that will land us at
7995 /// the specified offset. If so, fill them into NewIndices and return the
7996 /// resultant element type, otherwise return null.
7997 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7998 SmallVectorImpl<Value*> &NewIndices,
7999 const TargetData *TD,
8000 LLVMContext *Context) {
8002 if (!Ty->isSized()) return 0;
8004 // Start with the index over the outer type. Note that the type size
8005 // might be zero (even if the offset isn't zero) if the indexed type
8006 // is something like [0 x {int, int}]
8007 const Type *IntPtrTy = TD->getIntPtrType(*Context);
8008 int64_t FirstIdx = 0;
8009 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8010 FirstIdx = Offset/TySize;
8011 Offset -= FirstIdx*TySize;
8013 // Handle hosts where % returns negative instead of values [0..TySize).
8017 assert(Offset >= 0);
8019 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8022 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8024 // Index into the types. If we fail, set OrigBase to null.
8026 // Indexing into tail padding between struct/array elements.
8027 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8030 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8031 const StructLayout *SL = TD->getStructLayout(STy);
8032 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8033 "Offset must stay within the indexed type");
8035 unsigned Elt = SL->getElementContainingOffset(Offset);
8036 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8038 Offset -= SL->getElementOffset(Elt);
8039 Ty = STy->getElementType(Elt);
8040 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8041 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8042 assert(EltSize && "Cannot index into a zero-sized array");
8043 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8045 Ty = AT->getElementType();
8047 // Otherwise, we can't index into the middle of this atomic type, bail.
8055 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8056 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8057 Value *Src = CI.getOperand(0);
8059 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8060 // If casting the result of a getelementptr instruction with no offset, turn
8061 // this into a cast of the original pointer!
8062 if (GEP->hasAllZeroIndices()) {
8063 // Changing the cast operand is usually not a good idea but it is safe
8064 // here because the pointer operand is being replaced with another
8065 // pointer operand so the opcode doesn't need to change.
8067 CI.setOperand(0, GEP->getOperand(0));
8071 // If the GEP has a single use, and the base pointer is a bitcast, and the
8072 // GEP computes a constant offset, see if we can convert these three
8073 // instructions into fewer. This typically happens with unions and other
8074 // non-type-safe code.
8075 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8076 if (GEP->hasAllConstantIndices()) {
8077 // We are guaranteed to get a constant from EmitGEPOffset.
8078 ConstantInt *OffsetV =
8079 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8080 int64_t Offset = OffsetV->getSExtValue();
8082 // Get the base pointer input of the bitcast, and the type it points to.
8083 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8084 const Type *GEPIdxTy =
8085 cast<PointerType>(OrigBase->getType())->getElementType();
8086 SmallVector<Value*, 8> NewIndices;
8087 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8088 // If we were able to index down into an element, create the GEP
8089 // and bitcast the result. This eliminates one bitcast, potentially
8091 Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8093 NGEP->takeName(GEP);
8094 if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
8095 cast<GEPOperator>(NGEP)->setIsInBounds(true);
8097 if (isa<BitCastInst>(CI))
8098 return new BitCastInst(NGEP, CI.getType());
8099 assert(isa<PtrToIntInst>(CI));
8100 return new PtrToIntInst(NGEP, CI.getType());
8106 return commonCastTransforms(CI);
8109 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8110 /// type like i42. We don't want to introduce operations on random non-legal
8111 /// integer types where they don't already exist in the code. In the future,
8112 /// we should consider making this based off target-data, so that 32-bit targets
8113 /// won't get i64 operations etc.
8114 static bool isSafeIntegerType(const Type *Ty) {
8115 switch (Ty->getPrimitiveSizeInBits()) {
8126 /// commonIntCastTransforms - This function implements the common transforms
8127 /// for trunc, zext, and sext.
8128 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8129 if (Instruction *Result = commonCastTransforms(CI))
8132 Value *Src = CI.getOperand(0);
8133 const Type *SrcTy = Src->getType();
8134 const Type *DestTy = CI.getType();
8135 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8136 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8138 // See if we can simplify any instructions used by the LHS whose sole
8139 // purpose is to compute bits we don't care about.
8140 if (SimplifyDemandedInstructionBits(CI))
8143 // If the source isn't an instruction or has more than one use then we
8144 // can't do anything more.
8145 Instruction *SrcI = dyn_cast<Instruction>(Src);
8146 if (!SrcI || !Src->hasOneUse())
8149 // Attempt to propagate the cast into the instruction for int->int casts.
8150 int NumCastsRemoved = 0;
8151 // Only do this if the dest type is a simple type, don't convert the
8152 // expression tree to something weird like i93 unless the source is also
8154 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8155 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8156 CanEvaluateInDifferentType(SrcI, DestTy,
8157 CI.getOpcode(), NumCastsRemoved)) {
8158 // If this cast is a truncate, evaluting in a different type always
8159 // eliminates the cast, so it is always a win. If this is a zero-extension,
8160 // we need to do an AND to maintain the clear top-part of the computation,
8161 // so we require that the input have eliminated at least one cast. If this
8162 // is a sign extension, we insert two new casts (to do the extension) so we
8163 // require that two casts have been eliminated.
8164 bool DoXForm = false;
8165 bool JustReplace = false;
8166 switch (CI.getOpcode()) {
8168 // All the others use floating point so we shouldn't actually
8169 // get here because of the check above.
8170 llvm_unreachable("Unknown cast type");
8171 case Instruction::Trunc:
8174 case Instruction::ZExt: {
8175 DoXForm = NumCastsRemoved >= 1;
8176 if (!DoXForm && 0) {
8177 // If it's unnecessary to issue an AND to clear the high bits, it's
8178 // always profitable to do this xform.
8179 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8180 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8181 if (MaskedValueIsZero(TryRes, Mask))
8182 return ReplaceInstUsesWith(CI, TryRes);
8184 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8185 if (TryI->use_empty())
8186 EraseInstFromFunction(*TryI);
8190 case Instruction::SExt: {
8191 DoXForm = NumCastsRemoved >= 2;
8192 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8193 // If we do not have to emit the truncate + sext pair, then it's always
8194 // profitable to do this xform.
8196 // It's not safe to eliminate the trunc + sext pair if one of the
8197 // eliminated cast is a truncate. e.g.
8198 // t2 = trunc i32 t1 to i16
8199 // t3 = sext i16 t2 to i32
8202 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8203 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8204 if (NumSignBits > (DestBitSize - SrcBitSize))
8205 return ReplaceInstUsesWith(CI, TryRes);
8207 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8208 if (TryI->use_empty())
8209 EraseInstFromFunction(*TryI);
8216 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8217 " to avoid cast: " << CI);
8218 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8219 CI.getOpcode() == Instruction::SExt);
8221 // Just replace this cast with the result.
8222 return ReplaceInstUsesWith(CI, Res);
8224 assert(Res->getType() == DestTy);
8225 switch (CI.getOpcode()) {
8226 default: llvm_unreachable("Unknown cast type!");
8227 case Instruction::Trunc:
8228 // Just replace this cast with the result.
8229 return ReplaceInstUsesWith(CI, Res);
8230 case Instruction::ZExt: {
8231 assert(SrcBitSize < DestBitSize && "Not a zext?");
8233 // If the high bits are already zero, just replace this cast with the
8235 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8236 if (MaskedValueIsZero(Res, Mask))
8237 return ReplaceInstUsesWith(CI, Res);
8239 // We need to emit an AND to clear the high bits.
8240 Constant *C = ConstantInt::get(*Context,
8241 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8242 return BinaryOperator::CreateAnd(Res, C);
8244 case Instruction::SExt: {
8245 // If the high bits are already filled with sign bit, just replace this
8246 // cast with the result.
8247 unsigned NumSignBits = ComputeNumSignBits(Res);
8248 if (NumSignBits > (DestBitSize - SrcBitSize))
8249 return ReplaceInstUsesWith(CI, Res);
8251 // We need to emit a cast to truncate, then a cast to sext.
8252 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8258 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8259 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8261 switch (SrcI->getOpcode()) {
8262 case Instruction::Add:
8263 case Instruction::Mul:
8264 case Instruction::And:
8265 case Instruction::Or:
8266 case Instruction::Xor:
8267 // If we are discarding information, rewrite.
8268 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8269 // Don't insert two casts unless at least one can be eliminated.
8270 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8271 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8272 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8273 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8274 return BinaryOperator::Create(
8275 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8279 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8280 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8281 SrcI->getOpcode() == Instruction::Xor &&
8282 Op1 == ConstantInt::getTrue(*Context) &&
8283 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8284 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8285 return BinaryOperator::CreateXor(New,
8286 ConstantInt::get(CI.getType(), 1));
8290 case Instruction::Shl: {
8291 // Canonicalize trunc inside shl, if we can.
8292 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8293 if (CI && DestBitSize < SrcBitSize &&
8294 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8295 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8296 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8297 return BinaryOperator::CreateShl(Op0c, Op1c);
8305 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8306 if (Instruction *Result = commonIntCastTransforms(CI))
8309 Value *Src = CI.getOperand(0);
8310 const Type *Ty = CI.getType();
8311 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8312 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8314 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8315 if (DestBitWidth == 1) {
8316 Constant *One = ConstantInt::get(Src->getType(), 1);
8317 Src = Builder->CreateAnd(Src, One, "tmp");
8318 Value *Zero = Constant::getNullValue(Src->getType());
8319 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8322 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8323 ConstantInt *ShAmtV = 0;
8325 if (Src->hasOneUse() &&
8326 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8327 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8329 // Get a mask for the bits shifting in.
8330 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8331 if (MaskedValueIsZero(ShiftOp, Mask)) {
8332 if (ShAmt >= DestBitWidth) // All zeros.
8333 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8335 // Okay, we can shrink this. Truncate the input, then return a new
8337 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8338 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8339 return BinaryOperator::CreateLShr(V1, V2);
8346 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8347 /// in order to eliminate the icmp.
8348 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8350 // If we are just checking for a icmp eq of a single bit and zext'ing it
8351 // to an integer, then shift the bit to the appropriate place and then
8352 // cast to integer to avoid the comparison.
8353 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8354 const APInt &Op1CV = Op1C->getValue();
8356 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8357 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8358 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8359 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8360 if (!DoXform) return ICI;
8362 Value *In = ICI->getOperand(0);
8363 Value *Sh = ConstantInt::get(In->getType(),
8364 In->getType()->getScalarSizeInBits()-1);
8365 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8366 if (In->getType() != CI.getType())
8367 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8369 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8370 Constant *One = ConstantInt::get(In->getType(), 1);
8371 In = Builder->CreateXor(In, One, In->getName()+".not");
8374 return ReplaceInstUsesWith(CI, In);
8379 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8380 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8381 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8382 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8383 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8384 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8385 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8386 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8387 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8388 // This only works for EQ and NE
8389 ICI->isEquality()) {
8390 // If Op1C some other power of two, convert:
8391 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8392 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8393 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8394 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8396 APInt KnownZeroMask(~KnownZero);
8397 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8398 if (!DoXform) return ICI;
8400 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8401 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8402 // (X&4) == 2 --> false
8403 // (X&4) != 2 --> true
8404 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8405 Res = ConstantExpr::getZExt(Res, CI.getType());
8406 return ReplaceInstUsesWith(CI, Res);
8409 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8410 Value *In = ICI->getOperand(0);
8412 // Perform a logical shr by shiftamt.
8413 // Insert the shift to put the result in the low bit.
8414 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8415 In->getName()+".lobit");
8418 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8419 Constant *One = ConstantInt::get(In->getType(), 1);
8420 In = Builder->CreateXor(In, One, "tmp");
8423 if (CI.getType() == In->getType())
8424 return ReplaceInstUsesWith(CI, In);
8426 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8434 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8435 // If one of the common conversion will work ..
8436 if (Instruction *Result = commonIntCastTransforms(CI))
8439 Value *Src = CI.getOperand(0);
8441 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8442 // types and if the sizes are just right we can convert this into a logical
8443 // 'and' which will be much cheaper than the pair of casts.
8444 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8445 // Get the sizes of the types involved. We know that the intermediate type
8446 // will be smaller than A or C, but don't know the relation between A and C.
8447 Value *A = CSrc->getOperand(0);
8448 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8449 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8450 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8451 // If we're actually extending zero bits, then if
8452 // SrcSize < DstSize: zext(a & mask)
8453 // SrcSize == DstSize: a & mask
8454 // SrcSize > DstSize: trunc(a) & mask
8455 if (SrcSize < DstSize) {
8456 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8457 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8458 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8459 return new ZExtInst(And, CI.getType());
8462 if (SrcSize == DstSize) {
8463 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8464 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8467 if (SrcSize > DstSize) {
8468 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8469 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8470 return BinaryOperator::CreateAnd(Trunc,
8471 ConstantInt::get(Trunc->getType(),
8476 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8477 return transformZExtICmp(ICI, CI);
8479 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8480 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8481 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8482 // of the (zext icmp) will be transformed.
8483 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8484 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8485 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8486 (transformZExtICmp(LHS, CI, false) ||
8487 transformZExtICmp(RHS, CI, false))) {
8488 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8489 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8490 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8494 // zext(trunc(t) & C) -> (t & zext(C)).
8495 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8496 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8497 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8498 Value *TI0 = TI->getOperand(0);
8499 if (TI0->getType() == CI.getType())
8501 BinaryOperator::CreateAnd(TI0,
8502 ConstantExpr::getZExt(C, CI.getType()));
8505 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8506 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8507 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8508 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8509 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8510 And->getOperand(1) == C)
8511 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8512 Value *TI0 = TI->getOperand(0);
8513 if (TI0->getType() == CI.getType()) {
8514 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8515 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8516 return BinaryOperator::CreateXor(NewAnd, ZC);
8523 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8524 if (Instruction *I = commonIntCastTransforms(CI))
8527 Value *Src = CI.getOperand(0);
8529 // Canonicalize sign-extend from i1 to a select.
8530 if (Src->getType() == Type::getInt1Ty(*Context))
8531 return SelectInst::Create(Src,
8532 Constant::getAllOnesValue(CI.getType()),
8533 Constant::getNullValue(CI.getType()));
8535 // See if the value being truncated is already sign extended. If so, just
8536 // eliminate the trunc/sext pair.
8537 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8538 Value *Op = cast<User>(Src)->getOperand(0);
8539 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8540 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8541 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8542 unsigned NumSignBits = ComputeNumSignBits(Op);
8544 if (OpBits == DestBits) {
8545 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8546 // bits, it is already ready.
8547 if (NumSignBits > DestBits-MidBits)
8548 return ReplaceInstUsesWith(CI, Op);
8549 } else if (OpBits < DestBits) {
8550 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8551 // bits, just sext from i32.
8552 if (NumSignBits > OpBits-MidBits)
8553 return new SExtInst(Op, CI.getType(), "tmp");
8555 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8556 // bits, just truncate to i32.
8557 if (NumSignBits > OpBits-MidBits)
8558 return new TruncInst(Op, CI.getType(), "tmp");
8562 // If the input is a shl/ashr pair of a same constant, then this is a sign
8563 // extension from a smaller value. If we could trust arbitrary bitwidth
8564 // integers, we could turn this into a truncate to the smaller bit and then
8565 // use a sext for the whole extension. Since we don't, look deeper and check
8566 // for a truncate. If the source and dest are the same type, eliminate the
8567 // trunc and extend and just do shifts. For example, turn:
8568 // %a = trunc i32 %i to i8
8569 // %b = shl i8 %a, 6
8570 // %c = ashr i8 %b, 6
8571 // %d = sext i8 %c to i32
8573 // %a = shl i32 %i, 30
8574 // %d = ashr i32 %a, 30
8576 ConstantInt *BA = 0, *CA = 0;
8577 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8578 m_ConstantInt(CA))) &&
8579 BA == CA && isa<TruncInst>(A)) {
8580 Value *I = cast<TruncInst>(A)->getOperand(0);
8581 if (I->getType() == CI.getType()) {
8582 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8583 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8584 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8585 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8586 I = Builder->CreateShl(I, ShAmtV, CI.getName());
8587 return BinaryOperator::CreateAShr(I, ShAmtV);
8594 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8595 /// in the specified FP type without changing its value.
8596 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8597 LLVMContext *Context) {
8599 APFloat F = CFP->getValueAPF();
8600 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8602 return ConstantFP::get(*Context, F);
8606 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8607 /// through it until we get the source value.
8608 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8609 if (Instruction *I = dyn_cast<Instruction>(V))
8610 if (I->getOpcode() == Instruction::FPExt)
8611 return LookThroughFPExtensions(I->getOperand(0), Context);
8613 // If this value is a constant, return the constant in the smallest FP type
8614 // that can accurately represent it. This allows us to turn
8615 // (float)((double)X+2.0) into x+2.0f.
8616 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8617 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8618 return V; // No constant folding of this.
8619 // See if the value can be truncated to float and then reextended.
8620 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8622 if (CFP->getType() == Type::getDoubleTy(*Context))
8623 return V; // Won't shrink.
8624 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8626 // Don't try to shrink to various long double types.
8632 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8633 if (Instruction *I = commonCastTransforms(CI))
8636 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8637 // smaller than the destination type, we can eliminate the truncate by doing
8638 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8639 // many builtins (sqrt, etc).
8640 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8641 if (OpI && OpI->hasOneUse()) {
8642 switch (OpI->getOpcode()) {
8644 case Instruction::FAdd:
8645 case Instruction::FSub:
8646 case Instruction::FMul:
8647 case Instruction::FDiv:
8648 case Instruction::FRem:
8649 const Type *SrcTy = OpI->getType();
8650 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8651 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8652 if (LHSTrunc->getType() != SrcTy &&
8653 RHSTrunc->getType() != SrcTy) {
8654 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8655 // If the source types were both smaller than the destination type of
8656 // the cast, do this xform.
8657 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8658 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8659 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8660 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8661 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8670 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8671 return commonCastTransforms(CI);
8674 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8675 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8677 return commonCastTransforms(FI);
8679 // fptoui(uitofp(X)) --> X
8680 // fptoui(sitofp(X)) --> X
8681 // This is safe if the intermediate type has enough bits in its mantissa to
8682 // accurately represent all values of X. For example, do not do this with
8683 // i64->float->i64. This is also safe for sitofp case, because any negative
8684 // 'X' value would cause an undefined result for the fptoui.
8685 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8686 OpI->getOperand(0)->getType() == FI.getType() &&
8687 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8688 OpI->getType()->getFPMantissaWidth())
8689 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8691 return commonCastTransforms(FI);
8694 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8695 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8697 return commonCastTransforms(FI);
8699 // fptosi(sitofp(X)) --> X
8700 // fptosi(uitofp(X)) --> X
8701 // This is safe if the intermediate type has enough bits in its mantissa to
8702 // accurately represent all values of X. For example, do not do this with
8703 // i64->float->i64. This is also safe for sitofp case, because any negative
8704 // 'X' value would cause an undefined result for the fptoui.
8705 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8706 OpI->getOperand(0)->getType() == FI.getType() &&
8707 (int)FI.getType()->getScalarSizeInBits() <=
8708 OpI->getType()->getFPMantissaWidth())
8709 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8711 return commonCastTransforms(FI);
8714 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8715 return commonCastTransforms(CI);
8718 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8719 return commonCastTransforms(CI);
8722 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8723 // If the destination integer type is smaller than the intptr_t type for
8724 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8725 // trunc to be exposed to other transforms. Don't do this for extending
8726 // ptrtoint's, because we don't know if the target sign or zero extends its
8729 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8730 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8731 TD->getIntPtrType(CI.getContext()),
8733 return new TruncInst(P, CI.getType());
8736 return commonPointerCastTransforms(CI);
8739 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8740 // If the source integer type is larger than the intptr_t type for
8741 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8742 // allows the trunc to be exposed to other transforms. Don't do this for
8743 // extending inttoptr's, because we don't know if the target sign or zero
8744 // extends to pointers.
8745 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8746 TD->getPointerSizeInBits()) {
8747 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8748 TD->getIntPtrType(CI.getContext()), "tmp");
8749 return new IntToPtrInst(P, CI.getType());
8752 if (Instruction *I = commonCastTransforms(CI))
8758 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8759 // If the operands are integer typed then apply the integer transforms,
8760 // otherwise just apply the common ones.
8761 Value *Src = CI.getOperand(0);
8762 const Type *SrcTy = Src->getType();
8763 const Type *DestTy = CI.getType();
8765 if (isa<PointerType>(SrcTy)) {
8766 if (Instruction *I = commonPointerCastTransforms(CI))
8769 if (Instruction *Result = commonCastTransforms(CI))
8774 // Get rid of casts from one type to the same type. These are useless and can
8775 // be replaced by the operand.
8776 if (DestTy == Src->getType())
8777 return ReplaceInstUsesWith(CI, Src);
8779 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8780 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8781 const Type *DstElTy = DstPTy->getElementType();
8782 const Type *SrcElTy = SrcPTy->getElementType();
8784 // If the address spaces don't match, don't eliminate the bitcast, which is
8785 // required for changing types.
8786 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8789 // If we are casting a malloc or alloca to a pointer to a type of the same
8790 // size, rewrite the allocation instruction to allocate the "right" type.
8791 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8792 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8795 // If the source and destination are pointers, and this cast is equivalent
8796 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8797 // This can enhance SROA and other transforms that want type-safe pointers.
8798 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8799 unsigned NumZeros = 0;
8800 while (SrcElTy != DstElTy &&
8801 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8802 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8803 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8807 // If we found a path from the src to dest, create the getelementptr now.
8808 if (SrcElTy == DstElTy) {
8809 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8810 Instruction *GEP = GetElementPtrInst::Create(Src,
8811 Idxs.begin(), Idxs.end(), "",
8812 ((Instruction*) NULL));
8813 cast<GEPOperator>(GEP)->setIsInBounds(true);
8818 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8819 if (DestVTy->getNumElements() == 1) {
8820 if (!isa<VectorType>(SrcTy)) {
8821 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8822 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8823 Constant::getNullValue(Type::getInt32Ty(*Context)));
8825 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8829 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8830 if (SrcVTy->getNumElements() == 1) {
8831 if (!isa<VectorType>(DestTy)) {
8833 Builder->CreateExtractElement(Src,
8834 Constant::getNullValue(Type::getInt32Ty(*Context)));
8835 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8840 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8841 if (SVI->hasOneUse()) {
8842 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8843 // a bitconvert to a vector with the same # elts.
8844 if (isa<VectorType>(DestTy) &&
8845 cast<VectorType>(DestTy)->getNumElements() ==
8846 SVI->getType()->getNumElements() &&
8847 SVI->getType()->getNumElements() ==
8848 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8850 // If either of the operands is a cast from CI.getType(), then
8851 // evaluating the shuffle in the casted destination's type will allow
8852 // us to eliminate at least one cast.
8853 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8854 Tmp->getOperand(0)->getType() == DestTy) ||
8855 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8856 Tmp->getOperand(0)->getType() == DestTy)) {
8857 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8858 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8859 // Return a new shuffle vector. Use the same element ID's, as we
8860 // know the vector types match #elts.
8861 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8869 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8871 /// %D = select %cond, %C, %A
8873 /// %C = select %cond, %B, 0
8876 /// Assuming that the specified instruction is an operand to the select, return
8877 /// a bitmask indicating which operands of this instruction are foldable if they
8878 /// equal the other incoming value of the select.
8880 static unsigned GetSelectFoldableOperands(Instruction *I) {
8881 switch (I->getOpcode()) {
8882 case Instruction::Add:
8883 case Instruction::Mul:
8884 case Instruction::And:
8885 case Instruction::Or:
8886 case Instruction::Xor:
8887 return 3; // Can fold through either operand.
8888 case Instruction::Sub: // Can only fold on the amount subtracted.
8889 case Instruction::Shl: // Can only fold on the shift amount.
8890 case Instruction::LShr:
8891 case Instruction::AShr:
8894 return 0; // Cannot fold
8898 /// GetSelectFoldableConstant - For the same transformation as the previous
8899 /// function, return the identity constant that goes into the select.
8900 static Constant *GetSelectFoldableConstant(Instruction *I,
8901 LLVMContext *Context) {
8902 switch (I->getOpcode()) {
8903 default: llvm_unreachable("This cannot happen!");
8904 case Instruction::Add:
8905 case Instruction::Sub:
8906 case Instruction::Or:
8907 case Instruction::Xor:
8908 case Instruction::Shl:
8909 case Instruction::LShr:
8910 case Instruction::AShr:
8911 return Constant::getNullValue(I->getType());
8912 case Instruction::And:
8913 return Constant::getAllOnesValue(I->getType());
8914 case Instruction::Mul:
8915 return ConstantInt::get(I->getType(), 1);
8919 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8920 /// have the same opcode and only one use each. Try to simplify this.
8921 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8923 if (TI->getNumOperands() == 1) {
8924 // If this is a non-volatile load or a cast from the same type,
8927 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8930 return 0; // unknown unary op.
8933 // Fold this by inserting a select from the input values.
8934 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8935 FI->getOperand(0), SI.getName()+".v");
8936 InsertNewInstBefore(NewSI, SI);
8937 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
8941 // Only handle binary operators here.
8942 if (!isa<BinaryOperator>(TI))
8945 // Figure out if the operations have any operands in common.
8946 Value *MatchOp, *OtherOpT, *OtherOpF;
8948 if (TI->getOperand(0) == FI->getOperand(0)) {
8949 MatchOp = TI->getOperand(0);
8950 OtherOpT = TI->getOperand(1);
8951 OtherOpF = FI->getOperand(1);
8952 MatchIsOpZero = true;
8953 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8954 MatchOp = TI->getOperand(1);
8955 OtherOpT = TI->getOperand(0);
8956 OtherOpF = FI->getOperand(0);
8957 MatchIsOpZero = false;
8958 } else if (!TI->isCommutative()) {
8960 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8961 MatchOp = TI->getOperand(0);
8962 OtherOpT = TI->getOperand(1);
8963 OtherOpF = FI->getOperand(0);
8964 MatchIsOpZero = true;
8965 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8966 MatchOp = TI->getOperand(1);
8967 OtherOpT = TI->getOperand(0);
8968 OtherOpF = FI->getOperand(1);
8969 MatchIsOpZero = true;
8974 // If we reach here, they do have operations in common.
8975 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8976 OtherOpF, SI.getName()+".v");
8977 InsertNewInstBefore(NewSI, SI);
8979 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8981 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8983 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8985 llvm_unreachable("Shouldn't get here");
8989 static bool isSelect01(Constant *C1, Constant *C2) {
8990 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8993 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8996 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8999 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9000 /// facilitate further optimization.
9001 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9003 // See the comment above GetSelectFoldableOperands for a description of the
9004 // transformation we are doing here.
9005 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9006 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9007 !isa<Constant>(FalseVal)) {
9008 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9009 unsigned OpToFold = 0;
9010 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9012 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9017 Constant *C = GetSelectFoldableConstant(TVI, Context);
9018 Value *OOp = TVI->getOperand(2-OpToFold);
9019 // Avoid creating select between 2 constants unless it's selecting
9021 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9022 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9023 InsertNewInstBefore(NewSel, SI);
9024 NewSel->takeName(TVI);
9025 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9026 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9027 llvm_unreachable("Unknown instruction!!");
9034 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9035 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9036 !isa<Constant>(TrueVal)) {
9037 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9038 unsigned OpToFold = 0;
9039 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9041 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9046 Constant *C = GetSelectFoldableConstant(FVI, Context);
9047 Value *OOp = FVI->getOperand(2-OpToFold);
9048 // Avoid creating select between 2 constants unless it's selecting
9050 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9051 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9052 InsertNewInstBefore(NewSel, SI);
9053 NewSel->takeName(FVI);
9054 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9055 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9056 llvm_unreachable("Unknown instruction!!");
9066 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9067 /// ICmpInst as its first operand.
9069 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9071 bool Changed = false;
9072 ICmpInst::Predicate Pred = ICI->getPredicate();
9073 Value *CmpLHS = ICI->getOperand(0);
9074 Value *CmpRHS = ICI->getOperand(1);
9075 Value *TrueVal = SI.getTrueValue();
9076 Value *FalseVal = SI.getFalseValue();
9078 // Check cases where the comparison is with a constant that
9079 // can be adjusted to fit the min/max idiom. We may edit ICI in
9080 // place here, so make sure the select is the only user.
9081 if (ICI->hasOneUse())
9082 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9085 case ICmpInst::ICMP_ULT:
9086 case ICmpInst::ICMP_SLT: {
9087 // X < MIN ? T : F --> F
9088 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9089 return ReplaceInstUsesWith(SI, FalseVal);
9090 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9091 Constant *AdjustedRHS = SubOne(CI);
9092 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9093 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9094 Pred = ICmpInst::getSwappedPredicate(Pred);
9095 CmpRHS = AdjustedRHS;
9096 std::swap(FalseVal, TrueVal);
9097 ICI->setPredicate(Pred);
9098 ICI->setOperand(1, CmpRHS);
9099 SI.setOperand(1, TrueVal);
9100 SI.setOperand(2, FalseVal);
9105 case ICmpInst::ICMP_UGT:
9106 case ICmpInst::ICMP_SGT: {
9107 // X > MAX ? T : F --> F
9108 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9109 return ReplaceInstUsesWith(SI, FalseVal);
9110 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9111 Constant *AdjustedRHS = AddOne(CI);
9112 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9113 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9114 Pred = ICmpInst::getSwappedPredicate(Pred);
9115 CmpRHS = AdjustedRHS;
9116 std::swap(FalseVal, TrueVal);
9117 ICI->setPredicate(Pred);
9118 ICI->setOperand(1, CmpRHS);
9119 SI.setOperand(1, TrueVal);
9120 SI.setOperand(2, FalseVal);
9127 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9128 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9129 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9130 if (match(TrueVal, m_ConstantInt<-1>()) &&
9131 match(FalseVal, m_ConstantInt<0>()))
9132 Pred = ICI->getPredicate();
9133 else if (match(TrueVal, m_ConstantInt<0>()) &&
9134 match(FalseVal, m_ConstantInt<-1>()))
9135 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9137 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9138 // If we are just checking for a icmp eq of a single bit and zext'ing it
9139 // to an integer, then shift the bit to the appropriate place and then
9140 // cast to integer to avoid the comparison.
9141 const APInt &Op1CV = CI->getValue();
9143 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9144 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9145 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9146 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9147 Value *In = ICI->getOperand(0);
9148 Value *Sh = ConstantInt::get(In->getType(),
9149 In->getType()->getScalarSizeInBits()-1);
9150 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9151 In->getName()+".lobit"),
9153 if (In->getType() != SI.getType())
9154 In = CastInst::CreateIntegerCast(In, SI.getType(),
9155 true/*SExt*/, "tmp", ICI);
9157 if (Pred == ICmpInst::ICMP_SGT)
9158 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9159 In->getName()+".not"), *ICI);
9161 return ReplaceInstUsesWith(SI, In);
9166 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9167 // Transform (X == Y) ? X : Y -> Y
9168 if (Pred == ICmpInst::ICMP_EQ)
9169 return ReplaceInstUsesWith(SI, FalseVal);
9170 // Transform (X != Y) ? X : Y -> X
9171 if (Pred == ICmpInst::ICMP_NE)
9172 return ReplaceInstUsesWith(SI, TrueVal);
9173 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9175 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9176 // Transform (X == Y) ? Y : X -> X
9177 if (Pred == ICmpInst::ICMP_EQ)
9178 return ReplaceInstUsesWith(SI, FalseVal);
9179 // Transform (X != Y) ? Y : X -> Y
9180 if (Pred == ICmpInst::ICMP_NE)
9181 return ReplaceInstUsesWith(SI, TrueVal);
9182 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9185 /// NOTE: if we wanted to, this is where to detect integer ABS
9187 return Changed ? &SI : 0;
9190 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9191 Value *CondVal = SI.getCondition();
9192 Value *TrueVal = SI.getTrueValue();
9193 Value *FalseVal = SI.getFalseValue();
9195 // select true, X, Y -> X
9196 // select false, X, Y -> Y
9197 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9198 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9200 // select C, X, X -> X
9201 if (TrueVal == FalseVal)
9202 return ReplaceInstUsesWith(SI, TrueVal);
9204 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9205 return ReplaceInstUsesWith(SI, FalseVal);
9206 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9207 return ReplaceInstUsesWith(SI, TrueVal);
9208 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9209 if (isa<Constant>(TrueVal))
9210 return ReplaceInstUsesWith(SI, TrueVal);
9212 return ReplaceInstUsesWith(SI, FalseVal);
9215 if (SI.getType() == Type::getInt1Ty(*Context)) {
9216 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9217 if (C->getZExtValue()) {
9218 // Change: A = select B, true, C --> A = or B, C
9219 return BinaryOperator::CreateOr(CondVal, FalseVal);
9221 // Change: A = select B, false, C --> A = and !B, C
9223 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9224 "not."+CondVal->getName()), SI);
9225 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9227 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9228 if (C->getZExtValue() == false) {
9229 // Change: A = select B, C, false --> A = and B, C
9230 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9232 // Change: A = select B, C, true --> A = or !B, C
9234 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9235 "not."+CondVal->getName()), SI);
9236 return BinaryOperator::CreateOr(NotCond, TrueVal);
9240 // select a, b, a -> a&b
9241 // select a, a, b -> a|b
9242 if (CondVal == TrueVal)
9243 return BinaryOperator::CreateOr(CondVal, FalseVal);
9244 else if (CondVal == FalseVal)
9245 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9248 // Selecting between two integer constants?
9249 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9250 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9251 // select C, 1, 0 -> zext C to int
9252 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9253 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9254 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9255 // select C, 0, 1 -> zext !C to int
9257 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9258 "not."+CondVal->getName()), SI);
9259 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9262 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9263 // If one of the constants is zero (we know they can't both be) and we
9264 // have an icmp instruction with zero, and we have an 'and' with the
9265 // non-constant value, eliminate this whole mess. This corresponds to
9266 // cases like this: ((X & 27) ? 27 : 0)
9267 if (TrueValC->isZero() || FalseValC->isZero())
9268 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9269 cast<Constant>(IC->getOperand(1))->isNullValue())
9270 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9271 if (ICA->getOpcode() == Instruction::And &&
9272 isa<ConstantInt>(ICA->getOperand(1)) &&
9273 (ICA->getOperand(1) == TrueValC ||
9274 ICA->getOperand(1) == FalseValC) &&
9275 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9276 // Okay, now we know that everything is set up, we just don't
9277 // know whether we have a icmp_ne or icmp_eq and whether the
9278 // true or false val is the zero.
9279 bool ShouldNotVal = !TrueValC->isZero();
9280 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9283 V = InsertNewInstBefore(BinaryOperator::Create(
9284 Instruction::Xor, V, ICA->getOperand(1)), SI);
9285 return ReplaceInstUsesWith(SI, V);
9290 // See if we are selecting two values based on a comparison of the two values.
9291 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9292 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9293 // Transform (X == Y) ? X : Y -> Y
9294 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9295 // This is not safe in general for floating point:
9296 // consider X== -0, Y== +0.
9297 // It becomes safe if either operand is a nonzero constant.
9298 ConstantFP *CFPt, *CFPf;
9299 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9300 !CFPt->getValueAPF().isZero()) ||
9301 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9302 !CFPf->getValueAPF().isZero()))
9303 return ReplaceInstUsesWith(SI, FalseVal);
9305 // Transform (X != Y) ? X : Y -> X
9306 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9307 return ReplaceInstUsesWith(SI, TrueVal);
9308 // NOTE: if we wanted to, this is where to detect MIN/MAX
9310 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9311 // Transform (X == Y) ? Y : X -> X
9312 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9313 // This is not safe in general for floating point:
9314 // consider X== -0, Y== +0.
9315 // It becomes safe if either operand is a nonzero constant.
9316 ConstantFP *CFPt, *CFPf;
9317 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9318 !CFPt->getValueAPF().isZero()) ||
9319 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9320 !CFPf->getValueAPF().isZero()))
9321 return ReplaceInstUsesWith(SI, FalseVal);
9323 // Transform (X != Y) ? Y : X -> Y
9324 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9325 return ReplaceInstUsesWith(SI, TrueVal);
9326 // NOTE: if we wanted to, this is where to detect MIN/MAX
9328 // NOTE: if we wanted to, this is where to detect ABS
9331 // See if we are selecting two values based on a comparison of the two values.
9332 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9333 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9336 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9337 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9338 if (TI->hasOneUse() && FI->hasOneUse()) {
9339 Instruction *AddOp = 0, *SubOp = 0;
9341 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9342 if (TI->getOpcode() == FI->getOpcode())
9343 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9346 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9347 // even legal for FP.
9348 if ((TI->getOpcode() == Instruction::Sub &&
9349 FI->getOpcode() == Instruction::Add) ||
9350 (TI->getOpcode() == Instruction::FSub &&
9351 FI->getOpcode() == Instruction::FAdd)) {
9352 AddOp = FI; SubOp = TI;
9353 } else if ((FI->getOpcode() == Instruction::Sub &&
9354 TI->getOpcode() == Instruction::Add) ||
9355 (FI->getOpcode() == Instruction::FSub &&
9356 TI->getOpcode() == Instruction::FAdd)) {
9357 AddOp = TI; SubOp = FI;
9361 Value *OtherAddOp = 0;
9362 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9363 OtherAddOp = AddOp->getOperand(1);
9364 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9365 OtherAddOp = AddOp->getOperand(0);
9369 // So at this point we know we have (Y -> OtherAddOp):
9370 // select C, (add X, Y), (sub X, Z)
9371 Value *NegVal; // Compute -Z
9372 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9373 NegVal = ConstantExpr::getNeg(C);
9375 NegVal = InsertNewInstBefore(
9376 BinaryOperator::CreateNeg(SubOp->getOperand(1),
9380 Value *NewTrueOp = OtherAddOp;
9381 Value *NewFalseOp = NegVal;
9383 std::swap(NewTrueOp, NewFalseOp);
9384 Instruction *NewSel =
9385 SelectInst::Create(CondVal, NewTrueOp,
9386 NewFalseOp, SI.getName() + ".p");
9388 NewSel = InsertNewInstBefore(NewSel, SI);
9389 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9394 // See if we can fold the select into one of our operands.
9395 if (SI.getType()->isInteger()) {
9396 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9401 if (BinaryOperator::isNot(CondVal)) {
9402 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9403 SI.setOperand(1, FalseVal);
9404 SI.setOperand(2, TrueVal);
9411 /// EnforceKnownAlignment - If the specified pointer points to an object that
9412 /// we control, modify the object's alignment to PrefAlign. This isn't
9413 /// often possible though. If alignment is important, a more reliable approach
9414 /// is to simply align all global variables and allocation instructions to
9415 /// their preferred alignment from the beginning.
9417 static unsigned EnforceKnownAlignment(Value *V,
9418 unsigned Align, unsigned PrefAlign) {
9420 User *U = dyn_cast<User>(V);
9421 if (!U) return Align;
9423 switch (Operator::getOpcode(U)) {
9425 case Instruction::BitCast:
9426 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9427 case Instruction::GetElementPtr: {
9428 // If all indexes are zero, it is just the alignment of the base pointer.
9429 bool AllZeroOperands = true;
9430 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9431 if (!isa<Constant>(*i) ||
9432 !cast<Constant>(*i)->isNullValue()) {
9433 AllZeroOperands = false;
9437 if (AllZeroOperands) {
9438 // Treat this like a bitcast.
9439 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9445 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9446 // If there is a large requested alignment and we can, bump up the alignment
9448 if (!GV->isDeclaration()) {
9449 if (GV->getAlignment() >= PrefAlign)
9450 Align = GV->getAlignment();
9452 GV->setAlignment(PrefAlign);
9456 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9457 // If there is a requested alignment and if this is an alloca, round up. We
9458 // don't do this for malloc, because some systems can't respect the request.
9459 if (isa<AllocaInst>(AI)) {
9460 if (AI->getAlignment() >= PrefAlign)
9461 Align = AI->getAlignment();
9463 AI->setAlignment(PrefAlign);
9472 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9473 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9474 /// and it is more than the alignment of the ultimate object, see if we can
9475 /// increase the alignment of the ultimate object, making this check succeed.
9476 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9477 unsigned PrefAlign) {
9478 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9479 sizeof(PrefAlign) * CHAR_BIT;
9480 APInt Mask = APInt::getAllOnesValue(BitWidth);
9481 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9482 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9483 unsigned TrailZ = KnownZero.countTrailingOnes();
9484 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9486 if (PrefAlign > Align)
9487 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9489 // We don't need to make any adjustment.
9493 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9494 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9495 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9496 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9497 unsigned CopyAlign = MI->getAlignment();
9499 if (CopyAlign < MinAlign) {
9500 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9505 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9507 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9508 if (MemOpLength == 0) return 0;
9510 // Source and destination pointer types are always "i8*" for intrinsic. See
9511 // if the size is something we can handle with a single primitive load/store.
9512 // A single load+store correctly handles overlapping memory in the memmove
9514 unsigned Size = MemOpLength->getZExtValue();
9515 if (Size == 0) return MI; // Delete this mem transfer.
9517 if (Size > 8 || (Size&(Size-1)))
9518 return 0; // If not 1/2/4/8 bytes, exit.
9520 // Use an integer load+store unless we can find something better.
9522 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9524 // Memcpy forces the use of i8* for the source and destination. That means
9525 // that if you're using memcpy to move one double around, you'll get a cast
9526 // from double* to i8*. We'd much rather use a double load+store rather than
9527 // an i64 load+store, here because this improves the odds that the source or
9528 // dest address will be promotable. See if we can find a better type than the
9529 // integer datatype.
9530 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9531 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9532 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9533 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9534 // down through these levels if so.
9535 while (!SrcETy->isSingleValueType()) {
9536 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9537 if (STy->getNumElements() == 1)
9538 SrcETy = STy->getElementType(0);
9541 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9542 if (ATy->getNumElements() == 1)
9543 SrcETy = ATy->getElementType();
9550 if (SrcETy->isSingleValueType())
9551 NewPtrTy = PointerType::getUnqual(SrcETy);
9556 // If the memcpy/memmove provides better alignment info than we can
9558 SrcAlign = std::max(SrcAlign, CopyAlign);
9559 DstAlign = std::max(DstAlign, CopyAlign);
9561 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9562 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9563 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9564 InsertNewInstBefore(L, *MI);
9565 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9567 // Set the size of the copy to 0, it will be deleted on the next iteration.
9568 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9572 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9573 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9574 if (MI->getAlignment() < Alignment) {
9575 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9580 // Extract the length and alignment and fill if they are constant.
9581 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9582 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9583 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9585 uint64_t Len = LenC->getZExtValue();
9586 Alignment = MI->getAlignment();
9588 // If the length is zero, this is a no-op
9589 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9591 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9592 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9593 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
9595 Value *Dest = MI->getDest();
9596 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9598 // Alignment 0 is identity for alignment 1 for memset, but not store.
9599 if (Alignment == 0) Alignment = 1;
9601 // Extract the fill value and store.
9602 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9603 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9604 Dest, false, Alignment), *MI);
9606 // Set the size of the copy to 0, it will be deleted on the next iteration.
9607 MI->setLength(Constant::getNullValue(LenC->getType()));
9615 /// visitCallInst - CallInst simplification. This mostly only handles folding
9616 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9617 /// the heavy lifting.
9619 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9620 // If the caller function is nounwind, mark the call as nounwind, even if the
9622 if (CI.getParent()->getParent()->doesNotThrow() &&
9623 !CI.doesNotThrow()) {
9624 CI.setDoesNotThrow();
9628 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9629 if (!II) return visitCallSite(&CI);
9631 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9633 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9634 bool Changed = false;
9636 // memmove/cpy/set of zero bytes is a noop.
9637 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9638 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9640 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9641 if (CI->getZExtValue() == 1) {
9642 // Replace the instruction with just byte operations. We would
9643 // transform other cases to loads/stores, but we don't know if
9644 // alignment is sufficient.
9648 // If we have a memmove and the source operation is a constant global,
9649 // then the source and dest pointers can't alias, so we can change this
9650 // into a call to memcpy.
9651 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9652 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9653 if (GVSrc->isConstant()) {
9654 Module *M = CI.getParent()->getParent()->getParent();
9655 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9657 Tys[0] = CI.getOperand(3)->getType();
9659 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9663 // memmove(x,x,size) -> noop.
9664 if (MMI->getSource() == MMI->getDest())
9665 return EraseInstFromFunction(CI);
9668 // If we can determine a pointer alignment that is bigger than currently
9669 // set, update the alignment.
9670 if (isa<MemTransferInst>(MI)) {
9671 if (Instruction *I = SimplifyMemTransfer(MI))
9673 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9674 if (Instruction *I = SimplifyMemSet(MSI))
9678 if (Changed) return II;
9681 switch (II->getIntrinsicID()) {
9683 case Intrinsic::bswap:
9684 // bswap(bswap(x)) -> x
9685 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9686 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9687 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9689 case Intrinsic::ppc_altivec_lvx:
9690 case Intrinsic::ppc_altivec_lvxl:
9691 case Intrinsic::x86_sse_loadu_ps:
9692 case Intrinsic::x86_sse2_loadu_pd:
9693 case Intrinsic::x86_sse2_loadu_dq:
9694 // Turn PPC lvx -> load if the pointer is known aligned.
9695 // Turn X86 loadups -> load if the pointer is known aligned.
9696 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9697 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9698 PointerType::getUnqual(II->getType()));
9699 return new LoadInst(Ptr);
9702 case Intrinsic::ppc_altivec_stvx:
9703 case Intrinsic::ppc_altivec_stvxl:
9704 // Turn stvx -> store if the pointer is known aligned.
9705 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9706 const Type *OpPtrTy =
9707 PointerType::getUnqual(II->getOperand(1)->getType());
9708 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9709 return new StoreInst(II->getOperand(1), Ptr);
9712 case Intrinsic::x86_sse_storeu_ps:
9713 case Intrinsic::x86_sse2_storeu_pd:
9714 case Intrinsic::x86_sse2_storeu_dq:
9715 // Turn X86 storeu -> store if the pointer is known aligned.
9716 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9717 const Type *OpPtrTy =
9718 PointerType::getUnqual(II->getOperand(2)->getType());
9719 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9720 return new StoreInst(II->getOperand(2), Ptr);
9724 case Intrinsic::x86_sse_cvttss2si: {
9725 // These intrinsics only demands the 0th element of its input vector. If
9726 // we can simplify the input based on that, do so now.
9728 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9729 APInt DemandedElts(VWidth, 1);
9730 APInt UndefElts(VWidth, 0);
9731 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9733 II->setOperand(1, V);
9739 case Intrinsic::ppc_altivec_vperm:
9740 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9741 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9742 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9744 // Check that all of the elements are integer constants or undefs.
9745 bool AllEltsOk = true;
9746 for (unsigned i = 0; i != 16; ++i) {
9747 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9748 !isa<UndefValue>(Mask->getOperand(i))) {
9755 // Cast the input vectors to byte vectors.
9756 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9757 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9758 Value *Result = UndefValue::get(Op0->getType());
9760 // Only extract each element once.
9761 Value *ExtractedElts[32];
9762 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9764 for (unsigned i = 0; i != 16; ++i) {
9765 if (isa<UndefValue>(Mask->getOperand(i)))
9767 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9768 Idx &= 31; // Match the hardware behavior.
9770 if (ExtractedElts[Idx] == 0) {
9771 ExtractedElts[Idx] =
9772 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9773 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9777 // Insert this value into the result vector.
9778 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9779 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9782 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9787 case Intrinsic::stackrestore: {
9788 // If the save is right next to the restore, remove the restore. This can
9789 // happen when variable allocas are DCE'd.
9790 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9791 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9792 BasicBlock::iterator BI = SS;
9794 return EraseInstFromFunction(CI);
9798 // Scan down this block to see if there is another stack restore in the
9799 // same block without an intervening call/alloca.
9800 BasicBlock::iterator BI = II;
9801 TerminatorInst *TI = II->getParent()->getTerminator();
9802 bool CannotRemove = false;
9803 for (++BI; &*BI != TI; ++BI) {
9804 if (isa<AllocaInst>(BI)) {
9805 CannotRemove = true;
9808 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9809 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9810 // If there is a stackrestore below this one, remove this one.
9811 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9812 return EraseInstFromFunction(CI);
9813 // Otherwise, ignore the intrinsic.
9815 // If we found a non-intrinsic call, we can't remove the stack
9817 CannotRemove = true;
9823 // If the stack restore is in a return/unwind block and if there are no
9824 // allocas or calls between the restore and the return, nuke the restore.
9825 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9826 return EraseInstFromFunction(CI);
9831 return visitCallSite(II);
9834 // InvokeInst simplification
9836 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9837 return visitCallSite(&II);
9840 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9841 /// passed through the varargs area, we can eliminate the use of the cast.
9842 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9843 const CastInst * const CI,
9844 const TargetData * const TD,
9846 if (!CI->isLosslessCast())
9849 // The size of ByVal arguments is derived from the type, so we
9850 // can't change to a type with a different size. If the size were
9851 // passed explicitly we could avoid this check.
9852 if (!CS.paramHasAttr(ix, Attribute::ByVal))
9856 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9857 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9858 if (!SrcTy->isSized() || !DstTy->isSized())
9860 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9865 // visitCallSite - Improvements for call and invoke instructions.
9867 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9868 bool Changed = false;
9870 // If the callee is a constexpr cast of a function, attempt to move the cast
9871 // to the arguments of the call/invoke.
9872 if (transformConstExprCastCall(CS)) return 0;
9874 Value *Callee = CS.getCalledValue();
9876 if (Function *CalleeF = dyn_cast<Function>(Callee))
9877 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9878 Instruction *OldCall = CS.getInstruction();
9879 // If the call and callee calling conventions don't match, this call must
9880 // be unreachable, as the call is undefined.
9881 new StoreInst(ConstantInt::getTrue(*Context),
9882 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9884 if (!OldCall->use_empty())
9885 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9886 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9887 return EraseInstFromFunction(*OldCall);
9891 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9892 // This instruction is not reachable, just remove it. We insert a store to
9893 // undef so that we know that this code is not reachable, despite the fact
9894 // that we can't modify the CFG here.
9895 new StoreInst(ConstantInt::getTrue(*Context),
9896 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9897 CS.getInstruction());
9899 if (!CS.getInstruction()->use_empty())
9900 CS.getInstruction()->
9901 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9903 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9904 // Don't break the CFG, insert a dummy cond branch.
9905 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9906 ConstantInt::getTrue(*Context), II);
9908 return EraseInstFromFunction(*CS.getInstruction());
9911 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9912 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9913 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9914 return transformCallThroughTrampoline(CS);
9916 const PointerType *PTy = cast<PointerType>(Callee->getType());
9917 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9918 if (FTy->isVarArg()) {
9919 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9920 // See if we can optimize any arguments passed through the varargs area of
9922 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9923 E = CS.arg_end(); I != E; ++I, ++ix) {
9924 CastInst *CI = dyn_cast<CastInst>(*I);
9925 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9926 *I = CI->getOperand(0);
9932 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9933 // Inline asm calls cannot throw - mark them 'nounwind'.
9934 CS.setDoesNotThrow();
9938 return Changed ? CS.getInstruction() : 0;
9941 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9942 // attempt to move the cast to the arguments of the call/invoke.
9944 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9945 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9946 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9947 if (CE->getOpcode() != Instruction::BitCast ||
9948 !isa<Function>(CE->getOperand(0)))
9950 Function *Callee = cast<Function>(CE->getOperand(0));
9951 Instruction *Caller = CS.getInstruction();
9952 const AttrListPtr &CallerPAL = CS.getAttributes();
9954 // Okay, this is a cast from a function to a different type. Unless doing so
9955 // would cause a type conversion of one of our arguments, change this call to
9956 // be a direct call with arguments casted to the appropriate types.
9958 const FunctionType *FT = Callee->getFunctionType();
9959 const Type *OldRetTy = Caller->getType();
9960 const Type *NewRetTy = FT->getReturnType();
9962 if (isa<StructType>(NewRetTy))
9963 return false; // TODO: Handle multiple return values.
9965 // Check to see if we are changing the return type...
9966 if (OldRetTy != NewRetTy) {
9967 if (Callee->isDeclaration() &&
9968 // Conversion is ok if changing from one pointer type to another or from
9969 // a pointer to an integer of the same size.
9970 !((isa<PointerType>(OldRetTy) || !TD ||
9971 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
9972 (isa<PointerType>(NewRetTy) || !TD ||
9973 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
9974 return false; // Cannot transform this return value.
9976 if (!Caller->use_empty() &&
9977 // void -> non-void is handled specially
9978 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
9979 return false; // Cannot transform this return value.
9981 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9982 Attributes RAttrs = CallerPAL.getRetAttributes();
9983 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9984 return false; // Attribute not compatible with transformed value.
9987 // If the callsite is an invoke instruction, and the return value is used by
9988 // a PHI node in a successor, we cannot change the return type of the call
9989 // because there is no place to put the cast instruction (without breaking
9990 // the critical edge). Bail out in this case.
9991 if (!Caller->use_empty())
9992 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9993 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9995 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9996 if (PN->getParent() == II->getNormalDest() ||
9997 PN->getParent() == II->getUnwindDest())
10001 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10002 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10004 CallSite::arg_iterator AI = CS.arg_begin();
10005 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10006 const Type *ParamTy = FT->getParamType(i);
10007 const Type *ActTy = (*AI)->getType();
10009 if (!CastInst::isCastable(ActTy, ParamTy))
10010 return false; // Cannot transform this parameter value.
10012 if (CallerPAL.getParamAttributes(i + 1)
10013 & Attribute::typeIncompatible(ParamTy))
10014 return false; // Attribute not compatible with transformed value.
10016 // Converting from one pointer type to another or between a pointer and an
10017 // integer of the same size is safe even if we do not have a body.
10018 bool isConvertible = ActTy == ParamTy ||
10019 (TD && ((isa<PointerType>(ParamTy) ||
10020 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10021 (isa<PointerType>(ActTy) ||
10022 ActTy == TD->getIntPtrType(Caller->getContext()))));
10023 if (Callee->isDeclaration() && !isConvertible) return false;
10026 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10027 Callee->isDeclaration())
10028 return false; // Do not delete arguments unless we have a function body.
10030 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10031 !CallerPAL.isEmpty())
10032 // In this case we have more arguments than the new function type, but we
10033 // won't be dropping them. Check that these extra arguments have attributes
10034 // that are compatible with being a vararg call argument.
10035 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10036 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10038 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10039 if (PAttrs & Attribute::VarArgsIncompatible)
10043 // Okay, we decided that this is a safe thing to do: go ahead and start
10044 // inserting cast instructions as necessary...
10045 std::vector<Value*> Args;
10046 Args.reserve(NumActualArgs);
10047 SmallVector<AttributeWithIndex, 8> attrVec;
10048 attrVec.reserve(NumCommonArgs);
10050 // Get any return attributes.
10051 Attributes RAttrs = CallerPAL.getRetAttributes();
10053 // If the return value is not being used, the type may not be compatible
10054 // with the existing attributes. Wipe out any problematic attributes.
10055 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10057 // Add the new return attributes.
10059 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10061 AI = CS.arg_begin();
10062 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10063 const Type *ParamTy = FT->getParamType(i);
10064 if ((*AI)->getType() == ParamTy) {
10065 Args.push_back(*AI);
10067 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10068 false, ParamTy, false);
10069 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10072 // Add any parameter attributes.
10073 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10074 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10077 // If the function takes more arguments than the call was taking, add them
10079 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10080 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10082 // If we are removing arguments to the function, emit an obnoxious warning.
10083 if (FT->getNumParams() < NumActualArgs) {
10084 if (!FT->isVarArg()) {
10085 errs() << "WARNING: While resolving call to function '"
10086 << Callee->getName() << "' arguments were dropped!\n";
10088 // Add all of the arguments in their promoted form to the arg list.
10089 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10090 const Type *PTy = getPromotedType((*AI)->getType());
10091 if (PTy != (*AI)->getType()) {
10092 // Must promote to pass through va_arg area!
10093 Instruction::CastOps opcode =
10094 CastInst::getCastOpcode(*AI, false, PTy, false);
10095 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10097 Args.push_back(*AI);
10100 // Add any parameter attributes.
10101 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10102 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10107 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10108 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10110 if (NewRetTy == Type::getVoidTy(*Context))
10111 Caller->setName(""); // Void type should not have a name.
10113 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10117 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10118 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10119 Args.begin(), Args.end(),
10120 Caller->getName(), Caller);
10121 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10122 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10124 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10125 Caller->getName(), Caller);
10126 CallInst *CI = cast<CallInst>(Caller);
10127 if (CI->isTailCall())
10128 cast<CallInst>(NC)->setTailCall();
10129 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10130 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10133 // Insert a cast of the return type as necessary.
10135 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10136 if (NV->getType() != Type::getVoidTy(*Context)) {
10137 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10139 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10141 // If this is an invoke instruction, we should insert it after the first
10142 // non-phi, instruction in the normal successor block.
10143 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10144 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10145 InsertNewInstBefore(NC, *I);
10147 // Otherwise, it's a call, just insert cast right after the call instr
10148 InsertNewInstBefore(NC, *Caller);
10150 Worklist.AddUsersToWorkList(*Caller);
10152 NV = UndefValue::get(Caller->getType());
10157 if (!Caller->use_empty())
10158 Caller->replaceAllUsesWith(NV);
10160 EraseInstFromFunction(*Caller);
10164 // transformCallThroughTrampoline - Turn a call to a function created by the
10165 // init_trampoline intrinsic into a direct call to the underlying function.
10167 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10168 Value *Callee = CS.getCalledValue();
10169 const PointerType *PTy = cast<PointerType>(Callee->getType());
10170 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10171 const AttrListPtr &Attrs = CS.getAttributes();
10173 // If the call already has the 'nest' attribute somewhere then give up -
10174 // otherwise 'nest' would occur twice after splicing in the chain.
10175 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10178 IntrinsicInst *Tramp =
10179 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10181 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10182 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10183 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10185 const AttrListPtr &NestAttrs = NestF->getAttributes();
10186 if (!NestAttrs.isEmpty()) {
10187 unsigned NestIdx = 1;
10188 const Type *NestTy = 0;
10189 Attributes NestAttr = Attribute::None;
10191 // Look for a parameter marked with the 'nest' attribute.
10192 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10193 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10194 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10195 // Record the parameter type and any other attributes.
10197 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10202 Instruction *Caller = CS.getInstruction();
10203 std::vector<Value*> NewArgs;
10204 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10206 SmallVector<AttributeWithIndex, 8> NewAttrs;
10207 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10209 // Insert the nest argument into the call argument list, which may
10210 // mean appending it. Likewise for attributes.
10212 // Add any result attributes.
10213 if (Attributes Attr = Attrs.getRetAttributes())
10214 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10218 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10220 if (Idx == NestIdx) {
10221 // Add the chain argument and attributes.
10222 Value *NestVal = Tramp->getOperand(3);
10223 if (NestVal->getType() != NestTy)
10224 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10225 NewArgs.push_back(NestVal);
10226 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10232 // Add the original argument and attributes.
10233 NewArgs.push_back(*I);
10234 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10236 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10242 // Add any function attributes.
10243 if (Attributes Attr = Attrs.getFnAttributes())
10244 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10246 // The trampoline may have been bitcast to a bogus type (FTy).
10247 // Handle this by synthesizing a new function type, equal to FTy
10248 // with the chain parameter inserted.
10250 std::vector<const Type*> NewTypes;
10251 NewTypes.reserve(FTy->getNumParams()+1);
10253 // Insert the chain's type into the list of parameter types, which may
10254 // mean appending it.
10257 FunctionType::param_iterator I = FTy->param_begin(),
10258 E = FTy->param_end();
10261 if (Idx == NestIdx)
10262 // Add the chain's type.
10263 NewTypes.push_back(NestTy);
10268 // Add the original type.
10269 NewTypes.push_back(*I);
10275 // Replace the trampoline call with a direct call. Let the generic
10276 // code sort out any function type mismatches.
10277 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
10279 Constant *NewCallee =
10280 NestF->getType() == PointerType::getUnqual(NewFTy) ?
10281 NestF : ConstantExpr::getBitCast(NestF,
10282 PointerType::getUnqual(NewFTy));
10283 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10286 Instruction *NewCaller;
10287 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10288 NewCaller = InvokeInst::Create(NewCallee,
10289 II->getNormalDest(), II->getUnwindDest(),
10290 NewArgs.begin(), NewArgs.end(),
10291 Caller->getName(), Caller);
10292 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10293 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10295 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10296 Caller->getName(), Caller);
10297 if (cast<CallInst>(Caller)->isTailCall())
10298 cast<CallInst>(NewCaller)->setTailCall();
10299 cast<CallInst>(NewCaller)->
10300 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10301 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10303 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10304 Caller->replaceAllUsesWith(NewCaller);
10305 Caller->eraseFromParent();
10306 Worklist.Remove(Caller);
10311 // Replace the trampoline call with a direct call. Since there is no 'nest'
10312 // parameter, there is no need to adjust the argument list. Let the generic
10313 // code sort out any function type mismatches.
10314 Constant *NewCallee =
10315 NestF->getType() == PTy ? NestF :
10316 ConstantExpr::getBitCast(NestF, PTy);
10317 CS.setCalledFunction(NewCallee);
10318 return CS.getInstruction();
10321 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10322 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10323 /// and a single binop.
10324 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10325 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10326 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10327 unsigned Opc = FirstInst->getOpcode();
10328 Value *LHSVal = FirstInst->getOperand(0);
10329 Value *RHSVal = FirstInst->getOperand(1);
10331 const Type *LHSType = LHSVal->getType();
10332 const Type *RHSType = RHSVal->getType();
10334 // Scan to see if all operands are the same opcode, all have one use, and all
10335 // kill their operands (i.e. the operands have one use).
10336 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10337 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10338 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10339 // Verify type of the LHS matches so we don't fold cmp's of different
10340 // types or GEP's with different index types.
10341 I->getOperand(0)->getType() != LHSType ||
10342 I->getOperand(1)->getType() != RHSType)
10345 // If they are CmpInst instructions, check their predicates
10346 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10347 if (cast<CmpInst>(I)->getPredicate() !=
10348 cast<CmpInst>(FirstInst)->getPredicate())
10351 // Keep track of which operand needs a phi node.
10352 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10353 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10356 // Otherwise, this is safe to transform!
10358 Value *InLHS = FirstInst->getOperand(0);
10359 Value *InRHS = FirstInst->getOperand(1);
10360 PHINode *NewLHS = 0, *NewRHS = 0;
10362 NewLHS = PHINode::Create(LHSType,
10363 FirstInst->getOperand(0)->getName() + ".pn");
10364 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10365 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10366 InsertNewInstBefore(NewLHS, PN);
10371 NewRHS = PHINode::Create(RHSType,
10372 FirstInst->getOperand(1)->getName() + ".pn");
10373 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10374 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10375 InsertNewInstBefore(NewRHS, PN);
10379 // Add all operands to the new PHIs.
10380 if (NewLHS || NewRHS) {
10381 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10382 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10384 Value *NewInLHS = InInst->getOperand(0);
10385 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10388 Value *NewInRHS = InInst->getOperand(1);
10389 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10394 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10395 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10396 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10397 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10401 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10402 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10404 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10405 FirstInst->op_end());
10406 // This is true if all GEP bases are allocas and if all indices into them are
10408 bool AllBasePointersAreAllocas = true;
10410 // Scan to see if all operands are the same opcode, all have one use, and all
10411 // kill their operands (i.e. the operands have one use).
10412 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10413 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10414 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10415 GEP->getNumOperands() != FirstInst->getNumOperands())
10418 // Keep track of whether or not all GEPs are of alloca pointers.
10419 if (AllBasePointersAreAllocas &&
10420 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10421 !GEP->hasAllConstantIndices()))
10422 AllBasePointersAreAllocas = false;
10424 // Compare the operand lists.
10425 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10426 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10429 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10430 // if one of the PHIs has a constant for the index. The index may be
10431 // substantially cheaper to compute for the constants, so making it a
10432 // variable index could pessimize the path. This also handles the case
10433 // for struct indices, which must always be constant.
10434 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10435 isa<ConstantInt>(GEP->getOperand(op)))
10438 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10440 FixedOperands[op] = 0; // Needs a PHI.
10444 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10445 // bother doing this transformation. At best, this will just save a bit of
10446 // offset calculation, but all the predecessors will have to materialize the
10447 // stack address into a register anyway. We'd actually rather *clone* the
10448 // load up into the predecessors so that we have a load of a gep of an alloca,
10449 // which can usually all be folded into the load.
10450 if (AllBasePointersAreAllocas)
10453 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10454 // that is variable.
10455 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10457 bool HasAnyPHIs = false;
10458 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10459 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10460 Value *FirstOp = FirstInst->getOperand(i);
10461 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10462 FirstOp->getName()+".pn");
10463 InsertNewInstBefore(NewPN, PN);
10465 NewPN->reserveOperandSpace(e);
10466 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10467 OperandPhis[i] = NewPN;
10468 FixedOperands[i] = NewPN;
10473 // Add all operands to the new PHIs.
10475 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10476 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10477 BasicBlock *InBB = PN.getIncomingBlock(i);
10479 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10480 if (PHINode *OpPhi = OperandPhis[op])
10481 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10485 Value *Base = FixedOperands[0];
10486 GetElementPtrInst *GEP =
10487 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10488 FixedOperands.end());
10489 if (cast<GEPOperator>(FirstInst)->isInBounds())
10490 cast<GEPOperator>(GEP)->setIsInBounds(true);
10495 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10496 /// sink the load out of the block that defines it. This means that it must be
10497 /// obvious the value of the load is not changed from the point of the load to
10498 /// the end of the block it is in.
10500 /// Finally, it is safe, but not profitable, to sink a load targetting a
10501 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10503 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10504 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10506 for (++BBI; BBI != E; ++BBI)
10507 if (BBI->mayWriteToMemory())
10510 // Check for non-address taken alloca. If not address-taken already, it isn't
10511 // profitable to do this xform.
10512 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10513 bool isAddressTaken = false;
10514 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10516 if (isa<LoadInst>(UI)) continue;
10517 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10518 // If storing TO the alloca, then the address isn't taken.
10519 if (SI->getOperand(1) == AI) continue;
10521 isAddressTaken = true;
10525 if (!isAddressTaken && AI->isStaticAlloca())
10529 // If this load is a load from a GEP with a constant offset from an alloca,
10530 // then we don't want to sink it. In its present form, it will be
10531 // load [constant stack offset]. Sinking it will cause us to have to
10532 // materialize the stack addresses in each predecessor in a register only to
10533 // do a shared load from register in the successor.
10534 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10535 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10536 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10543 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10544 // operator and they all are only used by the PHI, PHI together their
10545 // inputs, and do the operation once, to the result of the PHI.
10546 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10547 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10549 // Scan the instruction, looking for input operations that can be folded away.
10550 // If all input operands to the phi are the same instruction (e.g. a cast from
10551 // the same type or "+42") we can pull the operation through the PHI, reducing
10552 // code size and simplifying code.
10553 Constant *ConstantOp = 0;
10554 const Type *CastSrcTy = 0;
10555 bool isVolatile = false;
10556 if (isa<CastInst>(FirstInst)) {
10557 CastSrcTy = FirstInst->getOperand(0)->getType();
10558 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10559 // Can fold binop, compare or shift here if the RHS is a constant,
10560 // otherwise call FoldPHIArgBinOpIntoPHI.
10561 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10562 if (ConstantOp == 0)
10563 return FoldPHIArgBinOpIntoPHI(PN);
10564 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10565 isVolatile = LI->isVolatile();
10566 // We can't sink the load if the loaded value could be modified between the
10567 // load and the PHI.
10568 if (LI->getParent() != PN.getIncomingBlock(0) ||
10569 !isSafeAndProfitableToSinkLoad(LI))
10572 // If the PHI is of volatile loads and the load block has multiple
10573 // successors, sinking it would remove a load of the volatile value from
10574 // the path through the other successor.
10576 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10579 } else if (isa<GetElementPtrInst>(FirstInst)) {
10580 return FoldPHIArgGEPIntoPHI(PN);
10582 return 0; // Cannot fold this operation.
10585 // Check to see if all arguments are the same operation.
10586 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10587 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10588 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10589 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10592 if (I->getOperand(0)->getType() != CastSrcTy)
10593 return 0; // Cast operation must match.
10594 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10595 // We can't sink the load if the loaded value could be modified between
10596 // the load and the PHI.
10597 if (LI->isVolatile() != isVolatile ||
10598 LI->getParent() != PN.getIncomingBlock(i) ||
10599 !isSafeAndProfitableToSinkLoad(LI))
10602 // If the PHI is of volatile loads and the load block has multiple
10603 // successors, sinking it would remove a load of the volatile value from
10604 // the path through the other successor.
10606 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10609 } else if (I->getOperand(1) != ConstantOp) {
10614 // Okay, they are all the same operation. Create a new PHI node of the
10615 // correct type, and PHI together all of the LHS's of the instructions.
10616 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10617 PN.getName()+".in");
10618 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10620 Value *InVal = FirstInst->getOperand(0);
10621 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10623 // Add all operands to the new PHI.
10624 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10625 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10626 if (NewInVal != InVal)
10628 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10633 // The new PHI unions all of the same values together. This is really
10634 // common, so we handle it intelligently here for compile-time speed.
10638 InsertNewInstBefore(NewPN, PN);
10642 // Insert and return the new operation.
10643 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10644 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10645 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10646 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10647 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10648 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10649 PhiVal, ConstantOp);
10650 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10652 // If this was a volatile load that we are merging, make sure to loop through
10653 // and mark all the input loads as non-volatile. If we don't do this, we will
10654 // insert a new volatile load and the old ones will not be deletable.
10656 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10657 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10659 return new LoadInst(PhiVal, "", isVolatile);
10662 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10664 static bool DeadPHICycle(PHINode *PN,
10665 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10666 if (PN->use_empty()) return true;
10667 if (!PN->hasOneUse()) return false;
10669 // Remember this node, and if we find the cycle, return.
10670 if (!PotentiallyDeadPHIs.insert(PN))
10673 // Don't scan crazily complex things.
10674 if (PotentiallyDeadPHIs.size() == 16)
10677 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10678 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10683 /// PHIsEqualValue - Return true if this phi node is always equal to
10684 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10685 /// z = some value; x = phi (y, z); y = phi (x, z)
10686 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10687 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10688 // See if we already saw this PHI node.
10689 if (!ValueEqualPHIs.insert(PN))
10692 // Don't scan crazily complex things.
10693 if (ValueEqualPHIs.size() == 16)
10696 // Scan the operands to see if they are either phi nodes or are equal to
10698 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10699 Value *Op = PN->getIncomingValue(i);
10700 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10701 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10703 } else if (Op != NonPhiInVal)
10711 // PHINode simplification
10713 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10714 // If LCSSA is around, don't mess with Phi nodes
10715 if (MustPreserveLCSSA) return 0;
10717 if (Value *V = PN.hasConstantValue())
10718 return ReplaceInstUsesWith(PN, V);
10720 // If all PHI operands are the same operation, pull them through the PHI,
10721 // reducing code size.
10722 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10723 isa<Instruction>(PN.getIncomingValue(1)) &&
10724 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10725 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10726 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10727 // than themselves more than once.
10728 PN.getIncomingValue(0)->hasOneUse())
10729 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10732 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10733 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10734 // PHI)... break the cycle.
10735 if (PN.hasOneUse()) {
10736 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10737 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10738 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10739 PotentiallyDeadPHIs.insert(&PN);
10740 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10741 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10744 // If this phi has a single use, and if that use just computes a value for
10745 // the next iteration of a loop, delete the phi. This occurs with unused
10746 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10747 // common case here is good because the only other things that catch this
10748 // are induction variable analysis (sometimes) and ADCE, which is only run
10750 if (PHIUser->hasOneUse() &&
10751 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10752 PHIUser->use_back() == &PN) {
10753 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10757 // We sometimes end up with phi cycles that non-obviously end up being the
10758 // same value, for example:
10759 // z = some value; x = phi (y, z); y = phi (x, z)
10760 // where the phi nodes don't necessarily need to be in the same block. Do a
10761 // quick check to see if the PHI node only contains a single non-phi value, if
10762 // so, scan to see if the phi cycle is actually equal to that value.
10764 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10765 // Scan for the first non-phi operand.
10766 while (InValNo != NumOperandVals &&
10767 isa<PHINode>(PN.getIncomingValue(InValNo)))
10770 if (InValNo != NumOperandVals) {
10771 Value *NonPhiInVal = PN.getOperand(InValNo);
10773 // Scan the rest of the operands to see if there are any conflicts, if so
10774 // there is no need to recursively scan other phis.
10775 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10776 Value *OpVal = PN.getIncomingValue(InValNo);
10777 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10781 // If we scanned over all operands, then we have one unique value plus
10782 // phi values. Scan PHI nodes to see if they all merge in each other or
10784 if (InValNo == NumOperandVals) {
10785 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10786 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10787 return ReplaceInstUsesWith(PN, NonPhiInVal);
10794 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10795 Value *PtrOp = GEP.getOperand(0);
10796 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10797 if (GEP.getNumOperands() == 1)
10798 return ReplaceInstUsesWith(GEP, PtrOp);
10800 if (isa<UndefValue>(GEP.getOperand(0)))
10801 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10803 bool HasZeroPointerIndex = false;
10804 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10805 HasZeroPointerIndex = C->isNullValue();
10807 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10808 return ReplaceInstUsesWith(GEP, PtrOp);
10810 // Eliminate unneeded casts for indices.
10812 bool MadeChange = false;
10813 unsigned PtrSize = TD->getPointerSizeInBits();
10815 gep_type_iterator GTI = gep_type_begin(GEP);
10816 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10817 I != E; ++I, ++GTI) {
10818 if (!isa<SequentialType>(*GTI)) continue;
10820 // If we are using a wider index than needed for this platform, shrink it
10821 // to what we need. If narrower, sign-extend it to what we need. This
10822 // explicit cast can make subsequent optimizations more obvious.
10823 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10824 if (OpBits == PtrSize)
10827 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10830 if (MadeChange) return &GEP;
10833 // Combine Indices - If the source pointer to this getelementptr instruction
10834 // is a getelementptr instruction, combine the indices of the two
10835 // getelementptr instructions into a single instruction.
10837 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10838 // Note that if our source is a gep chain itself that we wait for that
10839 // chain to be resolved before we perform this transformation. This
10840 // avoids us creating a TON of code in some cases.
10842 if (GetElementPtrInst *SrcGEP =
10843 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10844 if (SrcGEP->getNumOperands() == 2)
10845 return 0; // Wait until our source is folded to completion.
10847 SmallVector<Value*, 8> Indices;
10849 // Find out whether the last index in the source GEP is a sequential idx.
10850 bool EndsWithSequential = false;
10851 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10853 EndsWithSequential = !isa<StructType>(*I);
10855 // Can we combine the two pointer arithmetics offsets?
10856 if (EndsWithSequential) {
10857 // Replace: gep (gep %P, long B), long A, ...
10858 // With: T = long A+B; gep %P, T, ...
10861 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10862 Value *GO1 = GEP.getOperand(1);
10863 if (SO1 == Constant::getNullValue(SO1->getType())) {
10865 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10868 // If they aren't the same type, then the input hasn't been processed
10869 // by the loop above yet (which canonicalizes sequential index types to
10870 // intptr_t). Just avoid transforming this until the input has been
10872 if (SO1->getType() != GO1->getType())
10874 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10877 // Update the GEP in place if possible.
10878 if (Src->getNumOperands() == 2) {
10879 GEP.setOperand(0, Src->getOperand(0));
10880 GEP.setOperand(1, Sum);
10883 Indices.append(Src->op_begin()+1, Src->op_end()-1);
10884 Indices.push_back(Sum);
10885 Indices.append(GEP.op_begin()+2, GEP.op_end());
10886 } else if (isa<Constant>(*GEP.idx_begin()) &&
10887 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10888 Src->getNumOperands() != 1) {
10889 // Otherwise we can do the fold if the first index of the GEP is a zero
10890 Indices.append(Src->op_begin()+1, Src->op_end());
10891 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10894 if (!Indices.empty()) {
10895 GetElementPtrInst *NewGEP =
10896 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
10897 Indices.end(), GEP.getName());
10898 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
10899 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10904 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10905 if (Value *X = getBitCastOperand(PtrOp)) {
10906 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10908 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10909 // want to change the gep until the bitcasts are eliminated.
10910 if (getBitCastOperand(X)) {
10911 Worklist.AddValue(PtrOp);
10915 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10916 // into : GEP [10 x i8]* X, i32 0, ...
10918 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10919 // into : GEP i8* X, ...
10921 // This occurs when the program declares an array extern like "int X[];"
10922 if (HasZeroPointerIndex) {
10923 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10924 const PointerType *XTy = cast<PointerType>(X->getType());
10925 if (const ArrayType *CATy =
10926 dyn_cast<ArrayType>(CPTy->getElementType())) {
10927 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10928 if (CATy->getElementType() == XTy->getElementType()) {
10929 // -> GEP i8* X, ...
10930 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10931 GetElementPtrInst *NewGEP =
10932 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10934 if (cast<GEPOperator>(&GEP)->isInBounds())
10935 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10939 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
10940 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10941 if (CATy->getElementType() == XATy->getElementType()) {
10942 // -> GEP [10 x i8]* X, i32 0, ...
10943 // At this point, we know that the cast source type is a pointer
10944 // to an array of the same type as the destination pointer
10945 // array. Because the array type is never stepped over (there
10946 // is a leading zero) we can fold the cast into this GEP.
10947 GEP.setOperand(0, X);
10952 } else if (GEP.getNumOperands() == 2) {
10953 // Transform things like:
10954 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10955 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10956 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10957 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10958 if (TD && isa<ArrayType>(SrcElTy) &&
10959 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10960 TD->getTypeAllocSize(ResElTy)) {
10962 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
10963 Idx[1] = GEP.getOperand(1);
10965 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
10966 if (cast<GEPOperator>(&GEP)->isInBounds())
10967 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10968 // V and GEP are both pointer types --> BitCast
10969 return new BitCastInst(NewGEP, GEP.getType());
10972 // Transform things like:
10973 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10974 // (where tmp = 8*tmp2) into:
10975 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10977 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
10978 uint64_t ArrayEltSize =
10979 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
10981 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10982 // allow either a mul, shift, or constant here.
10984 ConstantInt *Scale = 0;
10985 if (ArrayEltSize == 1) {
10986 NewIdx = GEP.getOperand(1);
10987 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
10988 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10989 NewIdx = ConstantInt::get(CI->getType(), 1);
10991 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10992 if (Inst->getOpcode() == Instruction::Shl &&
10993 isa<ConstantInt>(Inst->getOperand(1))) {
10994 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10995 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10996 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
10998 NewIdx = Inst->getOperand(0);
10999 } else if (Inst->getOpcode() == Instruction::Mul &&
11000 isa<ConstantInt>(Inst->getOperand(1))) {
11001 Scale = cast<ConstantInt>(Inst->getOperand(1));
11002 NewIdx = Inst->getOperand(0);
11006 // If the index will be to exactly the right offset with the scale taken
11007 // out, perform the transformation. Note, we don't know whether Scale is
11008 // signed or not. We'll use unsigned version of division/modulo
11009 // operation after making sure Scale doesn't have the sign bit set.
11010 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11011 Scale->getZExtValue() % ArrayEltSize == 0) {
11012 Scale = ConstantInt::get(Scale->getType(),
11013 Scale->getZExtValue() / ArrayEltSize);
11014 if (Scale->getZExtValue() != 1) {
11015 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11017 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11020 // Insert the new GEP instruction.
11022 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11024 Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11025 if (cast<GEPOperator>(&GEP)->isInBounds())
11026 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11027 // The NewGEP must be pointer typed, so must the old one -> BitCast
11028 return new BitCastInst(NewGEP, GEP.getType());
11034 /// See if we can simplify:
11035 /// X = bitcast A* to B*
11036 /// Y = gep X, <...constant indices...>
11037 /// into a gep of the original struct. This is important for SROA and alias
11038 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11039 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11041 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11042 // Determine how much the GEP moves the pointer. We are guaranteed to get
11043 // a constant back from EmitGEPOffset.
11044 ConstantInt *OffsetV =
11045 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11046 int64_t Offset = OffsetV->getSExtValue();
11048 // If this GEP instruction doesn't move the pointer, just replace the GEP
11049 // with a bitcast of the real input to the dest type.
11051 // If the bitcast is of an allocation, and the allocation will be
11052 // converted to match the type of the cast, don't touch this.
11053 if (isa<AllocationInst>(BCI->getOperand(0))) {
11054 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11055 if (Instruction *I = visitBitCast(*BCI)) {
11058 BCI->getParent()->getInstList().insert(BCI, I);
11059 ReplaceInstUsesWith(*BCI, I);
11064 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11067 // Otherwise, if the offset is non-zero, we need to find out if there is a
11068 // field at Offset in 'A's type. If so, we can pull the cast through the
11070 SmallVector<Value*, 8> NewIndices;
11072 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11073 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11074 Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11076 if (cast<GEPOperator>(&GEP)->isInBounds())
11077 cast<GEPOperator>(NGEP)->setIsInBounds(true);
11079 if (NGEP->getType() == GEP.getType())
11080 return ReplaceInstUsesWith(GEP, NGEP);
11081 NGEP->takeName(&GEP);
11082 return new BitCastInst(NGEP, GEP.getType());
11090 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11091 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11092 if (AI.isArrayAllocation()) { // Check C != 1
11093 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11094 const Type *NewTy =
11095 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11096 AllocationInst *New = 0;
11098 // Create and insert the replacement instruction...
11099 if (isa<MallocInst>(AI))
11100 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11102 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11103 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11105 New->setAlignment(AI.getAlignment());
11107 // Scan to the end of the allocation instructions, to skip over a block of
11108 // allocas if possible...also skip interleaved debug info
11110 BasicBlock::iterator It = New;
11111 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11113 // Now that I is pointing to the first non-allocation-inst in the block,
11114 // insert our getelementptr instruction...
11116 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11120 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11121 New->getName()+".sub", It);
11122 cast<GEPOperator>(V)->setIsInBounds(true);
11124 // Now make everything use the getelementptr instead of the original
11126 return ReplaceInstUsesWith(AI, V);
11127 } else if (isa<UndefValue>(AI.getArraySize())) {
11128 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11132 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11133 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11134 // Note that we only do this for alloca's, because malloc should allocate
11135 // and return a unique pointer, even for a zero byte allocation.
11136 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11137 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11139 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11140 if (AI.getAlignment() == 0)
11141 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11147 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11148 Value *Op = FI.getOperand(0);
11150 // free undef -> unreachable.
11151 if (isa<UndefValue>(Op)) {
11152 // Insert a new store to null because we cannot modify the CFG here.
11153 new StoreInst(ConstantInt::getTrue(*Context),
11154 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11155 return EraseInstFromFunction(FI);
11158 // If we have 'free null' delete the instruction. This can happen in stl code
11159 // when lots of inlining happens.
11160 if (isa<ConstantPointerNull>(Op))
11161 return EraseInstFromFunction(FI);
11163 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11164 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11165 FI.setOperand(0, CI->getOperand(0));
11169 // Change free (gep X, 0,0,0,0) into free(X)
11170 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11171 if (GEPI->hasAllZeroIndices()) {
11172 Worklist.Add(GEPI);
11173 FI.setOperand(0, GEPI->getOperand(0));
11178 // Change free(malloc) into nothing, if the malloc has a single use.
11179 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11180 if (MI->hasOneUse()) {
11181 EraseInstFromFunction(FI);
11182 return EraseInstFromFunction(*MI);
11189 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11190 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11191 const TargetData *TD) {
11192 User *CI = cast<User>(LI.getOperand(0));
11193 Value *CastOp = CI->getOperand(0);
11194 LLVMContext *Context = IC.getContext();
11197 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11198 // Instead of loading constant c string, use corresponding integer value
11199 // directly if string length is small enough.
11201 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11202 unsigned len = Str.length();
11203 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11204 unsigned numBits = Ty->getPrimitiveSizeInBits();
11205 // Replace LI with immediate integer store.
11206 if ((numBits >> 3) == len + 1) {
11207 APInt StrVal(numBits, 0);
11208 APInt SingleChar(numBits, 0);
11209 if (TD->isLittleEndian()) {
11210 for (signed i = len-1; i >= 0; i--) {
11211 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11212 StrVal = (StrVal << 8) | SingleChar;
11215 for (unsigned i = 0; i < len; i++) {
11216 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11217 StrVal = (StrVal << 8) | SingleChar;
11219 // Append NULL at the end.
11221 StrVal = (StrVal << 8) | SingleChar;
11223 Value *NL = ConstantInt::get(*Context, StrVal);
11224 return IC.ReplaceInstUsesWith(LI, NL);
11230 const PointerType *DestTy = cast<PointerType>(CI->getType());
11231 const Type *DestPTy = DestTy->getElementType();
11232 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11234 // If the address spaces don't match, don't eliminate the cast.
11235 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11238 const Type *SrcPTy = SrcTy->getElementType();
11240 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11241 isa<VectorType>(DestPTy)) {
11242 // If the source is an array, the code below will not succeed. Check to
11243 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11245 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11246 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11247 if (ASrcTy->getNumElements() != 0) {
11249 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11250 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11251 SrcTy = cast<PointerType>(CastOp->getType());
11252 SrcPTy = SrcTy->getElementType();
11255 if (IC.getTargetData() &&
11256 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11257 isa<VectorType>(SrcPTy)) &&
11258 // Do not allow turning this into a load of an integer, which is then
11259 // casted to a pointer, this pessimizes pointer analysis a lot.
11260 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11261 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11262 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11264 // Okay, we are casting from one integer or pointer type to another of
11265 // the same size. Instead of casting the pointer before the load, cast
11266 // the result of the loaded value.
11268 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11269 // Now cast the result of the load.
11270 return new BitCastInst(NewLoad, LI.getType());
11277 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11278 Value *Op = LI.getOperand(0);
11280 // Attempt to improve the alignment.
11282 unsigned KnownAlign =
11283 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11285 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11286 LI.getAlignment()))
11287 LI.setAlignment(KnownAlign);
11290 // load (cast X) --> cast (load X) iff safe.
11291 if (isa<CastInst>(Op))
11292 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11295 // None of the following transforms are legal for volatile loads.
11296 if (LI.isVolatile()) return 0;
11298 // Do really simple store-to-load forwarding and load CSE, to catch cases
11299 // where there are several consequtive memory accesses to the same location,
11300 // separated by a few arithmetic operations.
11301 BasicBlock::iterator BBI = &LI;
11302 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11303 return ReplaceInstUsesWith(LI, AvailableVal);
11305 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11306 const Value *GEPI0 = GEPI->getOperand(0);
11307 // TODO: Consider a target hook for valid address spaces for this xform.
11308 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11309 // Insert a new store to null instruction before the load to indicate
11310 // that this code is not reachable. We do this instead of inserting
11311 // an unreachable instruction directly because we cannot modify the
11313 new StoreInst(UndefValue::get(LI.getType()),
11314 Constant::getNullValue(Op->getType()), &LI);
11315 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11319 if (Constant *C = dyn_cast<Constant>(Op)) {
11320 // load null/undef -> undef
11321 // TODO: Consider a target hook for valid address spaces for this xform.
11322 if (isa<UndefValue>(C) ||
11323 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11324 // Insert a new store to null instruction before the load to indicate that
11325 // this code is not reachable. We do this instead of inserting an
11326 // unreachable instruction directly because we cannot modify the CFG.
11327 new StoreInst(UndefValue::get(LI.getType()),
11328 Constant::getNullValue(Op->getType()), &LI);
11329 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11332 // Instcombine load (constant global) into the value loaded.
11333 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11334 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11335 return ReplaceInstUsesWith(LI, GV->getInitializer());
11337 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11338 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11339 if (CE->getOpcode() == Instruction::GetElementPtr) {
11340 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11341 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11343 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11345 return ReplaceInstUsesWith(LI, V);
11346 if (CE->getOperand(0)->isNullValue()) {
11347 // Insert a new store to null instruction before the load to indicate
11348 // that this code is not reachable. We do this instead of inserting
11349 // an unreachable instruction directly because we cannot modify the
11351 new StoreInst(UndefValue::get(LI.getType()),
11352 Constant::getNullValue(Op->getType()), &LI);
11353 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11356 } else if (CE->isCast()) {
11357 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11363 // If this load comes from anywhere in a constant global, and if the global
11364 // is all undef or zero, we know what it loads.
11365 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11366 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11367 if (GV->getInitializer()->isNullValue())
11368 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11369 else if (isa<UndefValue>(GV->getInitializer()))
11370 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11374 if (Op->hasOneUse()) {
11375 // Change select and PHI nodes to select values instead of addresses: this
11376 // helps alias analysis out a lot, allows many others simplifications, and
11377 // exposes redundancy in the code.
11379 // Note that we cannot do the transformation unless we know that the
11380 // introduced loads cannot trap! Something like this is valid as long as
11381 // the condition is always false: load (select bool %C, int* null, int* %G),
11382 // but it would not be valid if we transformed it to load from null
11383 // unconditionally.
11385 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11386 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11387 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11388 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11389 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11390 SI->getOperand(1)->getName()+".val");
11391 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11392 SI->getOperand(2)->getName()+".val");
11393 return SelectInst::Create(SI->getCondition(), V1, V2);
11396 // load (select (cond, null, P)) -> load P
11397 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11398 if (C->isNullValue()) {
11399 LI.setOperand(0, SI->getOperand(2));
11403 // load (select (cond, P, null)) -> load P
11404 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11405 if (C->isNullValue()) {
11406 LI.setOperand(0, SI->getOperand(1));
11414 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11415 /// when possible. This makes it generally easy to do alias analysis and/or
11416 /// SROA/mem2reg of the memory object.
11417 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11418 User *CI = cast<User>(SI.getOperand(1));
11419 Value *CastOp = CI->getOperand(0);
11421 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11422 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11423 if (SrcTy == 0) return 0;
11425 const Type *SrcPTy = SrcTy->getElementType();
11427 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11430 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11431 /// to its first element. This allows us to handle things like:
11432 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11433 /// on 32-bit hosts.
11434 SmallVector<Value*, 4> NewGEPIndices;
11436 // If the source is an array, the code below will not succeed. Check to
11437 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11439 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11440 // Index through pointer.
11441 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11442 NewGEPIndices.push_back(Zero);
11445 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11446 if (!STy->getNumElements()) /* Struct can be empty {} */
11448 NewGEPIndices.push_back(Zero);
11449 SrcPTy = STy->getElementType(0);
11450 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11451 NewGEPIndices.push_back(Zero);
11452 SrcPTy = ATy->getElementType();
11458 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11461 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11464 // If the pointers point into different address spaces or if they point to
11465 // values with different sizes, we can't do the transformation.
11466 if (!IC.getTargetData() ||
11467 SrcTy->getAddressSpace() !=
11468 cast<PointerType>(CI->getType())->getAddressSpace() ||
11469 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11470 IC.getTargetData()->getTypeSizeInBits(DestPTy))
11473 // Okay, we are casting from one integer or pointer type to another of
11474 // the same size. Instead of casting the pointer before
11475 // the store, cast the value to be stored.
11477 Value *SIOp0 = SI.getOperand(0);
11478 Instruction::CastOps opcode = Instruction::BitCast;
11479 const Type* CastSrcTy = SIOp0->getType();
11480 const Type* CastDstTy = SrcPTy;
11481 if (isa<PointerType>(CastDstTy)) {
11482 if (CastSrcTy->isInteger())
11483 opcode = Instruction::IntToPtr;
11484 } else if (isa<IntegerType>(CastDstTy)) {
11485 if (isa<PointerType>(SIOp0->getType()))
11486 opcode = Instruction::PtrToInt;
11489 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11490 // emit a GEP to index into its first field.
11491 if (!NewGEPIndices.empty()) {
11492 CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11493 NewGEPIndices.end());
11494 cast<GEPOperator>(CastOp)->setIsInBounds(true);
11497 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11498 SIOp0->getName()+".c");
11499 return new StoreInst(NewCast, CastOp);
11502 /// equivalentAddressValues - Test if A and B will obviously have the same
11503 /// value. This includes recognizing that %t0 and %t1 will have the same
11504 /// value in code like this:
11505 /// %t0 = getelementptr \@a, 0, 3
11506 /// store i32 0, i32* %t0
11507 /// %t1 = getelementptr \@a, 0, 3
11508 /// %t2 = load i32* %t1
11510 static bool equivalentAddressValues(Value *A, Value *B) {
11511 // Test if the values are trivially equivalent.
11512 if (A == B) return true;
11514 // Test if the values come form identical arithmetic instructions.
11515 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11516 // its only used to compare two uses within the same basic block, which
11517 // means that they'll always either have the same value or one of them
11518 // will have an undefined value.
11519 if (isa<BinaryOperator>(A) ||
11520 isa<CastInst>(A) ||
11522 isa<GetElementPtrInst>(A))
11523 if (Instruction *BI = dyn_cast<Instruction>(B))
11524 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11527 // Otherwise they may not be equivalent.
11531 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11532 // return the llvm.dbg.declare.
11533 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11534 if (!V->hasNUses(2))
11536 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11538 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11540 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11541 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11548 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11549 Value *Val = SI.getOperand(0);
11550 Value *Ptr = SI.getOperand(1);
11552 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11553 EraseInstFromFunction(SI);
11558 // If the RHS is an alloca with a single use, zapify the store, making the
11560 // If the RHS is an alloca with a two uses, the other one being a
11561 // llvm.dbg.declare, zapify the store and the declare, making the
11562 // alloca dead. We must do this to prevent declare's from affecting
11564 if (!SI.isVolatile()) {
11565 if (Ptr->hasOneUse()) {
11566 if (isa<AllocaInst>(Ptr)) {
11567 EraseInstFromFunction(SI);
11571 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11572 if (isa<AllocaInst>(GEP->getOperand(0))) {
11573 if (GEP->getOperand(0)->hasOneUse()) {
11574 EraseInstFromFunction(SI);
11578 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11579 EraseInstFromFunction(*DI);
11580 EraseInstFromFunction(SI);
11587 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11588 EraseInstFromFunction(*DI);
11589 EraseInstFromFunction(SI);
11595 // Attempt to improve the alignment.
11597 unsigned KnownAlign =
11598 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11600 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11601 SI.getAlignment()))
11602 SI.setAlignment(KnownAlign);
11605 // Do really simple DSE, to catch cases where there are several consecutive
11606 // stores to the same location, separated by a few arithmetic operations. This
11607 // situation often occurs with bitfield accesses.
11608 BasicBlock::iterator BBI = &SI;
11609 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11612 // Don't count debug info directives, lest they affect codegen,
11613 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11614 // It is necessary for correctness to skip those that feed into a
11615 // llvm.dbg.declare, as these are not present when debugging is off.
11616 if (isa<DbgInfoIntrinsic>(BBI) ||
11617 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11622 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11623 // Prev store isn't volatile, and stores to the same location?
11624 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11625 SI.getOperand(1))) {
11628 EraseInstFromFunction(*PrevSI);
11634 // If this is a load, we have to stop. However, if the loaded value is from
11635 // the pointer we're loading and is producing the pointer we're storing,
11636 // then *this* store is dead (X = load P; store X -> P).
11637 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11638 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11639 !SI.isVolatile()) {
11640 EraseInstFromFunction(SI);
11644 // Otherwise, this is a load from some other location. Stores before it
11645 // may not be dead.
11649 // Don't skip over loads or things that can modify memory.
11650 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11655 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11657 // store X, null -> turns into 'unreachable' in SimplifyCFG
11658 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11659 if (!isa<UndefValue>(Val)) {
11660 SI.setOperand(0, UndefValue::get(Val->getType()));
11661 if (Instruction *U = dyn_cast<Instruction>(Val))
11662 Worklist.Add(U); // Dropped a use.
11665 return 0; // Do not modify these!
11668 // store undef, Ptr -> noop
11669 if (isa<UndefValue>(Val)) {
11670 EraseInstFromFunction(SI);
11675 // If the pointer destination is a cast, see if we can fold the cast into the
11677 if (isa<CastInst>(Ptr))
11678 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11680 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11682 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11686 // If this store is the last instruction in the basic block (possibly
11687 // excepting debug info instructions and the pointer bitcasts that feed
11688 // into them), and if the block ends with an unconditional branch, try
11689 // to move it to the successor block.
11693 } while (isa<DbgInfoIntrinsic>(BBI) ||
11694 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11695 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11696 if (BI->isUnconditional())
11697 if (SimplifyStoreAtEndOfBlock(SI))
11698 return 0; // xform done!
11703 /// SimplifyStoreAtEndOfBlock - Turn things like:
11704 /// if () { *P = v1; } else { *P = v2 }
11705 /// into a phi node with a store in the successor.
11707 /// Simplify things like:
11708 /// *P = v1; if () { *P = v2; }
11709 /// into a phi node with a store in the successor.
11711 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11712 BasicBlock *StoreBB = SI.getParent();
11714 // Check to see if the successor block has exactly two incoming edges. If
11715 // so, see if the other predecessor contains a store to the same location.
11716 // if so, insert a PHI node (if needed) and move the stores down.
11717 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11719 // Determine whether Dest has exactly two predecessors and, if so, compute
11720 // the other predecessor.
11721 pred_iterator PI = pred_begin(DestBB);
11722 BasicBlock *OtherBB = 0;
11723 if (*PI != StoreBB)
11726 if (PI == pred_end(DestBB))
11729 if (*PI != StoreBB) {
11734 if (++PI != pred_end(DestBB))
11737 // Bail out if all the relevant blocks aren't distinct (this can happen,
11738 // for example, if SI is in an infinite loop)
11739 if (StoreBB == DestBB || OtherBB == DestBB)
11742 // Verify that the other block ends in a branch and is not otherwise empty.
11743 BasicBlock::iterator BBI = OtherBB->getTerminator();
11744 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11745 if (!OtherBr || BBI == OtherBB->begin())
11748 // If the other block ends in an unconditional branch, check for the 'if then
11749 // else' case. there is an instruction before the branch.
11750 StoreInst *OtherStore = 0;
11751 if (OtherBr->isUnconditional()) {
11753 // Skip over debugging info.
11754 while (isa<DbgInfoIntrinsic>(BBI) ||
11755 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11756 if (BBI==OtherBB->begin())
11760 // If this isn't a store, or isn't a store to the same location, bail out.
11761 OtherStore = dyn_cast<StoreInst>(BBI);
11762 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11765 // Otherwise, the other block ended with a conditional branch. If one of the
11766 // destinations is StoreBB, then we have the if/then case.
11767 if (OtherBr->getSuccessor(0) != StoreBB &&
11768 OtherBr->getSuccessor(1) != StoreBB)
11771 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11772 // if/then triangle. See if there is a store to the same ptr as SI that
11773 // lives in OtherBB.
11775 // Check to see if we find the matching store.
11776 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11777 if (OtherStore->getOperand(1) != SI.getOperand(1))
11781 // If we find something that may be using or overwriting the stored
11782 // value, or if we run out of instructions, we can't do the xform.
11783 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11784 BBI == OtherBB->begin())
11788 // In order to eliminate the store in OtherBr, we have to
11789 // make sure nothing reads or overwrites the stored value in
11791 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11792 // FIXME: This should really be AA driven.
11793 if (I->mayReadFromMemory() || I->mayWriteToMemory())
11798 // Insert a PHI node now if we need it.
11799 Value *MergedVal = OtherStore->getOperand(0);
11800 if (MergedVal != SI.getOperand(0)) {
11801 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11802 PN->reserveOperandSpace(2);
11803 PN->addIncoming(SI.getOperand(0), SI.getParent());
11804 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11805 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11808 // Advance to a place where it is safe to insert the new store and
11810 BBI = DestBB->getFirstNonPHI();
11811 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11812 OtherStore->isVolatile()), *BBI);
11814 // Nuke the old stores.
11815 EraseInstFromFunction(SI);
11816 EraseInstFromFunction(*OtherStore);
11822 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11823 // Change br (not X), label True, label False to: br X, label False, True
11825 BasicBlock *TrueDest;
11826 BasicBlock *FalseDest;
11827 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11828 !isa<Constant>(X)) {
11829 // Swap Destinations and condition...
11830 BI.setCondition(X);
11831 BI.setSuccessor(0, FalseDest);
11832 BI.setSuccessor(1, TrueDest);
11836 // Cannonicalize fcmp_one -> fcmp_oeq
11837 FCmpInst::Predicate FPred; Value *Y;
11838 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11839 TrueDest, FalseDest)) &&
11840 BI.getCondition()->hasOneUse())
11841 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11842 FPred == FCmpInst::FCMP_OGE) {
11843 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11844 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11846 // Swap Destinations and condition.
11847 BI.setSuccessor(0, FalseDest);
11848 BI.setSuccessor(1, TrueDest);
11849 Worklist.Add(Cond);
11853 // Cannonicalize icmp_ne -> icmp_eq
11854 ICmpInst::Predicate IPred;
11855 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11856 TrueDest, FalseDest)) &&
11857 BI.getCondition()->hasOneUse())
11858 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11859 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11860 IPred == ICmpInst::ICMP_SGE) {
11861 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11862 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11863 // Swap Destinations and condition.
11864 BI.setSuccessor(0, FalseDest);
11865 BI.setSuccessor(1, TrueDest);
11866 Worklist.Add(Cond);
11873 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11874 Value *Cond = SI.getCondition();
11875 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11876 if (I->getOpcode() == Instruction::Add)
11877 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11878 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11879 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11881 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11883 SI.setOperand(0, I->getOperand(0));
11891 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11892 Value *Agg = EV.getAggregateOperand();
11894 if (!EV.hasIndices())
11895 return ReplaceInstUsesWith(EV, Agg);
11897 if (Constant *C = dyn_cast<Constant>(Agg)) {
11898 if (isa<UndefValue>(C))
11899 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11901 if (isa<ConstantAggregateZero>(C))
11902 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11904 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11905 // Extract the element indexed by the first index out of the constant
11906 Value *V = C->getOperand(*EV.idx_begin());
11907 if (EV.getNumIndices() > 1)
11908 // Extract the remaining indices out of the constant indexed by the
11910 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11912 return ReplaceInstUsesWith(EV, V);
11914 return 0; // Can't handle other constants
11916 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11917 // We're extracting from an insertvalue instruction, compare the indices
11918 const unsigned *exti, *exte, *insi, *inse;
11919 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11920 exte = EV.idx_end(), inse = IV->idx_end();
11921 exti != exte && insi != inse;
11923 if (*insi != *exti)
11924 // The insert and extract both reference distinctly different elements.
11925 // This means the extract is not influenced by the insert, and we can
11926 // replace the aggregate operand of the extract with the aggregate
11927 // operand of the insert. i.e., replace
11928 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11929 // %E = extractvalue { i32, { i32 } } %I, 0
11931 // %E = extractvalue { i32, { i32 } } %A, 0
11932 return ExtractValueInst::Create(IV->getAggregateOperand(),
11933 EV.idx_begin(), EV.idx_end());
11935 if (exti == exte && insi == inse)
11936 // Both iterators are at the end: Index lists are identical. Replace
11937 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11938 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11940 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11941 if (exti == exte) {
11942 // The extract list is a prefix of the insert list. i.e. replace
11943 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11944 // %E = extractvalue { i32, { i32 } } %I, 1
11946 // %X = extractvalue { i32, { i32 } } %A, 1
11947 // %E = insertvalue { i32 } %X, i32 42, 0
11948 // by switching the order of the insert and extract (though the
11949 // insertvalue should be left in, since it may have other uses).
11950 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11951 EV.idx_begin(), EV.idx_end());
11952 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11956 // The insert list is a prefix of the extract list
11957 // We can simply remove the common indices from the extract and make it
11958 // operate on the inserted value instead of the insertvalue result.
11960 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11961 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11963 // %E extractvalue { i32 } { i32 42 }, 0
11964 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11967 // Can't simplify extracts from other values. Note that nested extracts are
11968 // already simplified implicitely by the above (extract ( extract (insert) )
11969 // will be translated into extract ( insert ( extract ) ) first and then just
11970 // the value inserted, if appropriate).
11974 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11975 /// is to leave as a vector operation.
11976 static bool CheapToScalarize(Value *V, bool isConstant) {
11977 if (isa<ConstantAggregateZero>(V))
11979 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11980 if (isConstant) return true;
11981 // If all elts are the same, we can extract.
11982 Constant *Op0 = C->getOperand(0);
11983 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11984 if (C->getOperand(i) != Op0)
11988 Instruction *I = dyn_cast<Instruction>(V);
11989 if (!I) return false;
11991 // Insert element gets simplified to the inserted element or is deleted if
11992 // this is constant idx extract element and its a constant idx insertelt.
11993 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11994 isa<ConstantInt>(I->getOperand(2)))
11996 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11998 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11999 if (BO->hasOneUse() &&
12000 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12001 CheapToScalarize(BO->getOperand(1), isConstant)))
12003 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12004 if (CI->hasOneUse() &&
12005 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12006 CheapToScalarize(CI->getOperand(1), isConstant)))
12012 /// Read and decode a shufflevector mask.
12014 /// It turns undef elements into values that are larger than the number of
12015 /// elements in the input.
12016 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12017 unsigned NElts = SVI->getType()->getNumElements();
12018 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12019 return std::vector<unsigned>(NElts, 0);
12020 if (isa<UndefValue>(SVI->getOperand(2)))
12021 return std::vector<unsigned>(NElts, 2*NElts);
12023 std::vector<unsigned> Result;
12024 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12025 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12026 if (isa<UndefValue>(*i))
12027 Result.push_back(NElts*2); // undef -> 8
12029 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12033 /// FindScalarElement - Given a vector and an element number, see if the scalar
12034 /// value is already around as a register, for example if it were inserted then
12035 /// extracted from the vector.
12036 static Value *FindScalarElement(Value *V, unsigned EltNo,
12037 LLVMContext *Context) {
12038 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12039 const VectorType *PTy = cast<VectorType>(V->getType());
12040 unsigned Width = PTy->getNumElements();
12041 if (EltNo >= Width) // Out of range access.
12042 return UndefValue::get(PTy->getElementType());
12044 if (isa<UndefValue>(V))
12045 return UndefValue::get(PTy->getElementType());
12046 else if (isa<ConstantAggregateZero>(V))
12047 return Constant::getNullValue(PTy->getElementType());
12048 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12049 return CP->getOperand(EltNo);
12050 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12051 // If this is an insert to a variable element, we don't know what it is.
12052 if (!isa<ConstantInt>(III->getOperand(2)))
12054 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12056 // If this is an insert to the element we are looking for, return the
12058 if (EltNo == IIElt)
12059 return III->getOperand(1);
12061 // Otherwise, the insertelement doesn't modify the value, recurse on its
12063 return FindScalarElement(III->getOperand(0), EltNo, Context);
12064 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12065 unsigned LHSWidth =
12066 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12067 unsigned InEl = getShuffleMask(SVI)[EltNo];
12068 if (InEl < LHSWidth)
12069 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12070 else if (InEl < LHSWidth*2)
12071 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12073 return UndefValue::get(PTy->getElementType());
12076 // Otherwise, we don't know.
12080 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12081 // If vector val is undef, replace extract with scalar undef.
12082 if (isa<UndefValue>(EI.getOperand(0)))
12083 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12085 // If vector val is constant 0, replace extract with scalar 0.
12086 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12087 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12089 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12090 // If vector val is constant with all elements the same, replace EI with
12091 // that element. When the elements are not identical, we cannot replace yet
12092 // (we do that below, but only when the index is constant).
12093 Constant *op0 = C->getOperand(0);
12094 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12095 if (C->getOperand(i) != op0) {
12100 return ReplaceInstUsesWith(EI, op0);
12103 // If extracting a specified index from the vector, see if we can recursively
12104 // find a previously computed scalar that was inserted into the vector.
12105 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12106 unsigned IndexVal = IdxC->getZExtValue();
12107 unsigned VectorWidth =
12108 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12110 // If this is extracting an invalid index, turn this into undef, to avoid
12111 // crashing the code below.
12112 if (IndexVal >= VectorWidth)
12113 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12115 // This instruction only demands the single element from the input vector.
12116 // If the input vector has a single use, simplify it based on this use
12118 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12119 APInt UndefElts(VectorWidth, 0);
12120 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12121 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12122 DemandedMask, UndefElts)) {
12123 EI.setOperand(0, V);
12128 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12129 return ReplaceInstUsesWith(EI, Elt);
12131 // If the this extractelement is directly using a bitcast from a vector of
12132 // the same number of elements, see if we can find the source element from
12133 // it. In this case, we will end up needing to bitcast the scalars.
12134 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12135 if (const VectorType *VT =
12136 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12137 if (VT->getNumElements() == VectorWidth)
12138 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12139 IndexVal, Context))
12140 return new BitCastInst(Elt, EI.getType());
12144 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12145 if (I->hasOneUse()) {
12146 // Push extractelement into predecessor operation if legal and
12147 // profitable to do so
12148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12149 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12150 if (CheapToScalarize(BO, isConstantElt)) {
12152 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12153 EI.getName()+".lhs");
12155 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12156 EI.getName()+".rhs");
12157 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12159 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12160 unsigned AS = LI->getPointerAddressSpace();
12161 Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12162 PointerType::get(EI.getType(), AS),
12163 I->getOperand(0)->getName());
12165 Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
12166 cast<GEPOperator>(GEP)->setIsInBounds(true);
12168 LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12170 // Make sure the Load goes before the load instruction in the source,
12171 // not wherever the extract happens to be.
12172 if (Instruction *P = dyn_cast<Instruction>(Ptr))
12174 if (Instruction *G = dyn_cast<Instruction>(GEP))
12176 Load->moveBefore(I);
12178 return ReplaceInstUsesWith(EI, Load);
12181 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12182 // Extracting the inserted element?
12183 if (IE->getOperand(2) == EI.getOperand(1))
12184 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12185 // If the inserted and extracted elements are constants, they must not
12186 // be the same value, extract from the pre-inserted value instead.
12187 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12188 Worklist.AddValue(EI.getOperand(0));
12189 EI.setOperand(0, IE->getOperand(0));
12192 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12193 // If this is extracting an element from a shufflevector, figure out where
12194 // it came from and extract from the appropriate input element instead.
12195 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12196 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12198 unsigned LHSWidth =
12199 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12201 if (SrcIdx < LHSWidth)
12202 Src = SVI->getOperand(0);
12203 else if (SrcIdx < LHSWidth*2) {
12204 SrcIdx -= LHSWidth;
12205 Src = SVI->getOperand(1);
12207 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12209 return ExtractElementInst::Create(Src,
12210 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12214 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12219 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12220 /// elements from either LHS or RHS, return the shuffle mask and true.
12221 /// Otherwise, return false.
12222 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12223 std::vector<Constant*> &Mask,
12224 LLVMContext *Context) {
12225 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12226 "Invalid CollectSingleShuffleElements");
12227 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12229 if (isa<UndefValue>(V)) {
12230 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12232 } else if (V == LHS) {
12233 for (unsigned i = 0; i != NumElts; ++i)
12234 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12236 } else if (V == RHS) {
12237 for (unsigned i = 0; i != NumElts; ++i)
12238 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12240 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12241 // If this is an insert of an extract from some other vector, include it.
12242 Value *VecOp = IEI->getOperand(0);
12243 Value *ScalarOp = IEI->getOperand(1);
12244 Value *IdxOp = IEI->getOperand(2);
12246 if (!isa<ConstantInt>(IdxOp))
12248 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12250 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12251 // Okay, we can handle this if the vector we are insertinting into is
12252 // transitively ok.
12253 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12254 // If so, update the mask to reflect the inserted undef.
12255 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12258 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12259 if (isa<ConstantInt>(EI->getOperand(1)) &&
12260 EI->getOperand(0)->getType() == V->getType()) {
12261 unsigned ExtractedIdx =
12262 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12264 // This must be extracting from either LHS or RHS.
12265 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12266 // Okay, we can handle this if the vector we are insertinting into is
12267 // transitively ok.
12268 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12269 // If so, update the mask to reflect the inserted value.
12270 if (EI->getOperand(0) == LHS) {
12271 Mask[InsertedIdx % NumElts] =
12272 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12274 assert(EI->getOperand(0) == RHS);
12275 Mask[InsertedIdx % NumElts] =
12276 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12285 // TODO: Handle shufflevector here!
12290 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12291 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12292 /// that computes V and the LHS value of the shuffle.
12293 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12294 Value *&RHS, LLVMContext *Context) {
12295 assert(isa<VectorType>(V->getType()) &&
12296 (RHS == 0 || V->getType() == RHS->getType()) &&
12297 "Invalid shuffle!");
12298 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12300 if (isa<UndefValue>(V)) {
12301 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12303 } else if (isa<ConstantAggregateZero>(V)) {
12304 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12306 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12307 // If this is an insert of an extract from some other vector, include it.
12308 Value *VecOp = IEI->getOperand(0);
12309 Value *ScalarOp = IEI->getOperand(1);
12310 Value *IdxOp = IEI->getOperand(2);
12312 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12313 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12314 EI->getOperand(0)->getType() == V->getType()) {
12315 unsigned ExtractedIdx =
12316 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12317 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12319 // Either the extracted from or inserted into vector must be RHSVec,
12320 // otherwise we'd end up with a shuffle of three inputs.
12321 if (EI->getOperand(0) == RHS || RHS == 0) {
12322 RHS = EI->getOperand(0);
12323 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12324 Mask[InsertedIdx % NumElts] =
12325 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12329 if (VecOp == RHS) {
12330 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12332 // Everything but the extracted element is replaced with the RHS.
12333 for (unsigned i = 0; i != NumElts; ++i) {
12334 if (i != InsertedIdx)
12335 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12340 // If this insertelement is a chain that comes from exactly these two
12341 // vectors, return the vector and the effective shuffle.
12342 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12344 return EI->getOperand(0);
12349 // TODO: Handle shufflevector here!
12351 // Otherwise, can't do anything fancy. Return an identity vector.
12352 for (unsigned i = 0; i != NumElts; ++i)
12353 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12357 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12358 Value *VecOp = IE.getOperand(0);
12359 Value *ScalarOp = IE.getOperand(1);
12360 Value *IdxOp = IE.getOperand(2);
12362 // Inserting an undef or into an undefined place, remove this.
12363 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12364 ReplaceInstUsesWith(IE, VecOp);
12366 // If the inserted element was extracted from some other vector, and if the
12367 // indexes are constant, try to turn this into a shufflevector operation.
12368 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12369 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12370 EI->getOperand(0)->getType() == IE.getType()) {
12371 unsigned NumVectorElts = IE.getType()->getNumElements();
12372 unsigned ExtractedIdx =
12373 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12374 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12376 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12377 return ReplaceInstUsesWith(IE, VecOp);
12379 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12380 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12382 // If we are extracting a value from a vector, then inserting it right
12383 // back into the same place, just use the input vector.
12384 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12385 return ReplaceInstUsesWith(IE, VecOp);
12387 // We could theoretically do this for ANY input. However, doing so could
12388 // turn chains of insertelement instructions into a chain of shufflevector
12389 // instructions, and right now we do not merge shufflevectors. As such,
12390 // only do this in a situation where it is clear that there is benefit.
12391 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12392 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12393 // the values of VecOp, except then one read from EIOp0.
12394 // Build a new shuffle mask.
12395 std::vector<Constant*> Mask;
12396 if (isa<UndefValue>(VecOp))
12397 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12399 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12400 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12403 Mask[InsertedIdx] =
12404 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12405 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12406 ConstantVector::get(Mask));
12409 // If this insertelement isn't used by some other insertelement, turn it
12410 // (and any insertelements it points to), into one big shuffle.
12411 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12412 std::vector<Constant*> Mask;
12414 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12415 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12416 // We now have a shuffle of LHS, RHS, Mask.
12417 return new ShuffleVectorInst(LHS, RHS,
12418 ConstantVector::get(Mask));
12423 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12424 APInt UndefElts(VWidth, 0);
12425 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12426 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12433 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12434 Value *LHS = SVI.getOperand(0);
12435 Value *RHS = SVI.getOperand(1);
12436 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12438 bool MadeChange = false;
12440 // Undefined shuffle mask -> undefined value.
12441 if (isa<UndefValue>(SVI.getOperand(2)))
12442 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12444 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12446 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12449 APInt UndefElts(VWidth, 0);
12450 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12451 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12452 LHS = SVI.getOperand(0);
12453 RHS = SVI.getOperand(1);
12457 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12458 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12459 if (LHS == RHS || isa<UndefValue>(LHS)) {
12460 if (isa<UndefValue>(LHS) && LHS == RHS) {
12461 // shuffle(undef,undef,mask) -> undef.
12462 return ReplaceInstUsesWith(SVI, LHS);
12465 // Remap any references to RHS to use LHS.
12466 std::vector<Constant*> Elts;
12467 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12468 if (Mask[i] >= 2*e)
12469 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12471 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12472 (Mask[i] < e && isa<UndefValue>(LHS))) {
12473 Mask[i] = 2*e; // Turn into undef.
12474 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12476 Mask[i] = Mask[i] % e; // Force to LHS.
12477 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12481 SVI.setOperand(0, SVI.getOperand(1));
12482 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12483 SVI.setOperand(2, ConstantVector::get(Elts));
12484 LHS = SVI.getOperand(0);
12485 RHS = SVI.getOperand(1);
12489 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12490 bool isLHSID = true, isRHSID = true;
12492 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12493 if (Mask[i] >= e*2) continue; // Ignore undef values.
12494 // Is this an identity shuffle of the LHS value?
12495 isLHSID &= (Mask[i] == i);
12497 // Is this an identity shuffle of the RHS value?
12498 isRHSID &= (Mask[i]-e == i);
12501 // Eliminate identity shuffles.
12502 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12503 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12505 // If the LHS is a shufflevector itself, see if we can combine it with this
12506 // one without producing an unusual shuffle. Here we are really conservative:
12507 // we are absolutely afraid of producing a shuffle mask not in the input
12508 // program, because the code gen may not be smart enough to turn a merged
12509 // shuffle into two specific shuffles: it may produce worse code. As such,
12510 // we only merge two shuffles if the result is one of the two input shuffle
12511 // masks. In this case, merging the shuffles just removes one instruction,
12512 // which we know is safe. This is good for things like turning:
12513 // (splat(splat)) -> splat.
12514 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12515 if (isa<UndefValue>(RHS)) {
12516 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12518 std::vector<unsigned> NewMask;
12519 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12520 if (Mask[i] >= 2*e)
12521 NewMask.push_back(2*e);
12523 NewMask.push_back(LHSMask[Mask[i]]);
12525 // If the result mask is equal to the src shuffle or this shuffle mask, do
12526 // the replacement.
12527 if (NewMask == LHSMask || NewMask == Mask) {
12528 unsigned LHSInNElts =
12529 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12530 std::vector<Constant*> Elts;
12531 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12532 if (NewMask[i] >= LHSInNElts*2) {
12533 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12535 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12538 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12539 LHSSVI->getOperand(1),
12540 ConstantVector::get(Elts));
12545 return MadeChange ? &SVI : 0;
12551 /// TryToSinkInstruction - Try to move the specified instruction from its
12552 /// current block into the beginning of DestBlock, which can only happen if it's
12553 /// safe to move the instruction past all of the instructions between it and the
12554 /// end of its block.
12555 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12556 assert(I->hasOneUse() && "Invariants didn't hold!");
12558 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12559 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12562 // Do not sink alloca instructions out of the entry block.
12563 if (isa<AllocaInst>(I) && I->getParent() ==
12564 &DestBlock->getParent()->getEntryBlock())
12567 // We can only sink load instructions if there is nothing between the load and
12568 // the end of block that could change the value.
12569 if (I->mayReadFromMemory()) {
12570 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12572 if (Scan->mayWriteToMemory())
12576 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12578 CopyPrecedingStopPoint(I, InsertPos);
12579 I->moveBefore(InsertPos);
12585 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12586 /// all reachable code to the worklist.
12588 /// This has a couple of tricks to make the code faster and more powerful. In
12589 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12590 /// them to the worklist (this significantly speeds up instcombine on code where
12591 /// many instructions are dead or constant). Additionally, if we find a branch
12592 /// whose condition is a known constant, we only visit the reachable successors.
12594 static void AddReachableCodeToWorklist(BasicBlock *BB,
12595 SmallPtrSet<BasicBlock*, 64> &Visited,
12597 const TargetData *TD) {
12598 SmallVector<BasicBlock*, 256> Worklist;
12599 Worklist.push_back(BB);
12601 while (!Worklist.empty()) {
12602 BB = Worklist.back();
12603 Worklist.pop_back();
12605 // We have now visited this block! If we've already been here, ignore it.
12606 if (!Visited.insert(BB)) continue;
12608 DbgInfoIntrinsic *DBI_Prev = NULL;
12609 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12610 Instruction *Inst = BBI++;
12612 // DCE instruction if trivially dead.
12613 if (isInstructionTriviallyDead(Inst)) {
12615 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12616 Inst->eraseFromParent();
12620 // ConstantProp instruction if trivially constant.
12621 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12622 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12624 Inst->replaceAllUsesWith(C);
12626 Inst->eraseFromParent();
12630 // If there are two consecutive llvm.dbg.stoppoint calls then
12631 // it is likely that the optimizer deleted code in between these
12633 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12636 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12637 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12638 IC.Worklist.Remove(DBI_Prev);
12639 DBI_Prev->eraseFromParent();
12641 DBI_Prev = DBI_Next;
12646 IC.Worklist.Add(Inst);
12649 // Recursively visit successors. If this is a branch or switch on a
12650 // constant, only visit the reachable successor.
12651 TerminatorInst *TI = BB->getTerminator();
12652 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12653 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12654 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12655 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12656 Worklist.push_back(ReachableBB);
12659 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12660 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12661 // See if this is an explicit destination.
12662 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12663 if (SI->getCaseValue(i) == Cond) {
12664 BasicBlock *ReachableBB = SI->getSuccessor(i);
12665 Worklist.push_back(ReachableBB);
12669 // Otherwise it is the default destination.
12670 Worklist.push_back(SI->getSuccessor(0));
12675 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12676 Worklist.push_back(TI->getSuccessor(i));
12680 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12681 MadeIRChange = false;
12682 TD = getAnalysisIfAvailable<TargetData>();
12684 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12685 << F.getNameStr() << "\n");
12688 // Do a depth-first traversal of the function, populate the worklist with
12689 // the reachable instructions. Ignore blocks that are not reachable. Keep
12690 // track of which blocks we visit.
12691 SmallPtrSet<BasicBlock*, 64> Visited;
12692 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12694 // Do a quick scan over the function. If we find any blocks that are
12695 // unreachable, remove any instructions inside of them. This prevents
12696 // the instcombine code from having to deal with some bad special cases.
12697 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12698 if (!Visited.count(BB)) {
12699 Instruction *Term = BB->getTerminator();
12700 while (Term != BB->begin()) { // Remove instrs bottom-up
12701 BasicBlock::iterator I = Term; --I;
12703 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12704 // A debug intrinsic shouldn't force another iteration if we weren't
12705 // going to do one without it.
12706 if (!isa<DbgInfoIntrinsic>(I)) {
12708 MadeIRChange = true;
12710 if (!I->use_empty())
12711 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12712 I->eraseFromParent();
12717 while (!Worklist.isEmpty()) {
12718 Instruction *I = Worklist.RemoveOne();
12719 if (I == 0) continue; // skip null values.
12721 // Check to see if we can DCE the instruction.
12722 if (isInstructionTriviallyDead(I)) {
12723 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12724 EraseInstFromFunction(*I);
12726 MadeIRChange = true;
12730 // Instruction isn't dead, see if we can constant propagate it.
12731 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12732 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12734 // Add operands to the worklist.
12735 ReplaceInstUsesWith(*I, C);
12737 EraseInstFromFunction(*I);
12738 MadeIRChange = true;
12743 // See if we can constant fold its operands.
12744 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12745 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12746 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12747 F.getContext(), TD))
12750 MadeIRChange = true;
12754 // See if we can trivially sink this instruction to a successor basic block.
12755 if (I->hasOneUse()) {
12756 BasicBlock *BB = I->getParent();
12757 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12758 if (UserParent != BB) {
12759 bool UserIsSuccessor = false;
12760 // See if the user is one of our successors.
12761 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12762 if (*SI == UserParent) {
12763 UserIsSuccessor = true;
12767 // If the user is one of our immediate successors, and if that successor
12768 // only has us as a predecessors (we'd have to split the critical edge
12769 // otherwise), we can keep going.
12770 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12771 next(pred_begin(UserParent)) == pred_end(UserParent))
12772 // Okay, the CFG is simple enough, try to sink this instruction.
12773 MadeIRChange |= TryToSinkInstruction(I, UserParent);
12777 // Now that we have an instruction, try combining it to simplify it.
12778 Builder->SetInsertPoint(I->getParent(), I);
12783 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12785 if (Instruction *Result = visit(*I)) {
12787 // Should we replace the old instruction with a new one?
12789 DEBUG(errs() << "IC: Old = " << *I << '\n'
12790 << " New = " << *Result << '\n');
12792 // Everything uses the new instruction now.
12793 I->replaceAllUsesWith(Result);
12795 // Push the new instruction and any users onto the worklist.
12796 Worklist.Add(Result);
12797 Worklist.AddUsersToWorkList(*Result);
12799 // Move the name to the new instruction first.
12800 Result->takeName(I);
12802 // Insert the new instruction into the basic block...
12803 BasicBlock *InstParent = I->getParent();
12804 BasicBlock::iterator InsertPos = I;
12806 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12807 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12810 InstParent->getInstList().insert(InsertPos, Result);
12812 EraseInstFromFunction(*I);
12815 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12816 << " New = " << *I << '\n');
12819 // If the instruction was modified, it's possible that it is now dead.
12820 // if so, remove it.
12821 if (isInstructionTriviallyDead(I)) {
12822 EraseInstFromFunction(*I);
12825 Worklist.AddUsersToWorkList(*I);
12828 MadeIRChange = true;
12833 return MadeIRChange;
12837 bool InstCombiner::runOnFunction(Function &F) {
12838 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12839 Context = &F.getContext();
12842 /// Builder - This is an IRBuilder that automatically inserts new
12843 /// instructions into the worklist when they are created.
12844 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12845 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12846 InstCombineIRInserter(Worklist));
12847 Builder = &TheBuilder;
12849 bool EverMadeChange = false;
12851 // Iterate while there is work to do.
12852 unsigned Iteration = 0;
12853 while (DoOneIteration(F, Iteration++))
12854 EverMadeChange = true;
12857 return EverMadeChange;
12860 FunctionPass *llvm::createInstructionCombiningPass() {
12861 return new InstCombiner();